refactor: migrate remaining routes to modules and enforce auto-discovery
MIGRATION: - Delete app/api/v1/vendor/analytics.py (duplicate - analytics module already auto-discovered) - Move usage routes from app/api/v1/vendor/usage.py to billing module - Move onboarding routes from app/api/v1/vendor/onboarding.py to marketplace module - Move features routes to billing module (admin + vendor) - Move inventory routes to inventory module (admin + vendor) - Move marketplace/letzshop routes to marketplace module - Move orders routes to orders module - Delete legacy letzshop service files (moved to marketplace module) DOCUMENTATION: - Add docs/development/migration/module-autodiscovery-migration.md with full migration history - Update docs/architecture/module-system.md with Entity Auto-Discovery Reference section - Add detailed sections for each entity type: routes, services, models, schemas, tasks, exceptions, templates, static files, locales, configuration ARCHITECTURE VALIDATION: - Add MOD-016: Routes must be in modules, not app/api/v1/ - Add MOD-017: Services must be in modules, not app/services/ - Add MOD-018: Tasks must be in modules, not app/tasks/ - Add MOD-019: Schemas must be in modules, not models/schema/ - Update scripts/validate_architecture.py with _validate_legacy_locations method - Update .architecture-rules/module.yaml with legacy location rules These rules enforce that all entities must be in self-contained modules. Legacy locations now trigger ERROR severity violations. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
@@ -47,7 +47,6 @@ from . import (
|
||||
companies,
|
||||
dashboard,
|
||||
email_templates,
|
||||
features,
|
||||
images,
|
||||
logs,
|
||||
media,
|
||||
@@ -60,7 +59,6 @@ from . import (
|
||||
platform_health,
|
||||
platforms,
|
||||
settings,
|
||||
subscriptions, # Legacy - will be replaced by billing module router
|
||||
tests,
|
||||
users,
|
||||
vendor_domains,
|
||||
@@ -179,9 +177,6 @@ router.include_router(
|
||||
# Include test runner endpoints
|
||||
router.include_router(tests.router, prefix="/tests", tags=["admin-tests"])
|
||||
|
||||
# Include feature management endpoints
|
||||
router.include_router(features.router, tags=["admin-features"])
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Auto-discovered Module Routes
|
||||
|
||||
@@ -1,308 +0,0 @@
|
||||
# app/api/v1/admin/features.py
|
||||
"""
|
||||
Admin feature management endpoints.
|
||||
|
||||
Provides endpoints for:
|
||||
- Listing all features with their tier assignments
|
||||
- Updating tier feature assignments
|
||||
- Managing feature metadata
|
||||
- Viewing feature usage statistics
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.api.deps import get_current_admin_api
|
||||
from app.core.database import get_db
|
||||
from app.services.feature_service import feature_service
|
||||
from models.schema.auth import UserContext
|
||||
|
||||
router = APIRouter(prefix="/features")
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Response Schemas
|
||||
# ============================================================================
|
||||
|
||||
|
||||
class FeatureResponse(BaseModel):
|
||||
"""Feature information for admin."""
|
||||
|
||||
id: int
|
||||
code: str
|
||||
name: str
|
||||
description: str | None = None
|
||||
category: str
|
||||
ui_location: str | None = None
|
||||
ui_icon: str | None = None
|
||||
ui_route: str | None = None
|
||||
ui_badge_text: str | None = None
|
||||
minimum_tier_id: int | None = None
|
||||
minimum_tier_code: str | None = None
|
||||
minimum_tier_name: str | None = None
|
||||
is_active: bool
|
||||
is_visible: bool
|
||||
display_order: int
|
||||
|
||||
|
||||
class FeatureListResponse(BaseModel):
|
||||
"""List of features."""
|
||||
|
||||
features: list[FeatureResponse]
|
||||
total: int
|
||||
|
||||
|
||||
class TierFeaturesResponse(BaseModel):
|
||||
"""Tier with its features."""
|
||||
|
||||
id: int
|
||||
code: str
|
||||
name: str
|
||||
description: str | None = None
|
||||
features: list[str]
|
||||
feature_count: int
|
||||
|
||||
|
||||
class TierListWithFeaturesResponse(BaseModel):
|
||||
"""All tiers with their features."""
|
||||
|
||||
tiers: list[TierFeaturesResponse]
|
||||
|
||||
|
||||
class UpdateTierFeaturesRequest(BaseModel):
|
||||
"""Request to update tier features."""
|
||||
|
||||
feature_codes: list[str]
|
||||
|
||||
|
||||
class UpdateFeatureRequest(BaseModel):
|
||||
"""Request to update feature metadata."""
|
||||
|
||||
name: str | None = None
|
||||
description: str | None = None
|
||||
category: str | None = None
|
||||
ui_location: str | None = None
|
||||
ui_icon: str | None = None
|
||||
ui_route: str | None = None
|
||||
ui_badge_text: str | None = None
|
||||
minimum_tier_code: str | None = None
|
||||
is_active: bool | None = None
|
||||
is_visible: bool | None = None
|
||||
display_order: int | None = None
|
||||
|
||||
|
||||
class CategoryListResponse(BaseModel):
|
||||
"""List of feature categories."""
|
||||
|
||||
categories: list[str]
|
||||
|
||||
|
||||
class TierFeatureDetailResponse(BaseModel):
|
||||
"""Tier features with full details."""
|
||||
|
||||
tier_code: str
|
||||
tier_name: str
|
||||
features: list[dict]
|
||||
feature_count: int
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Helper Functions
|
||||
# ============================================================================
|
||||
|
||||
|
||||
def _feature_to_response(feature) -> FeatureResponse:
|
||||
"""Convert Feature model to response."""
|
||||
return FeatureResponse(
|
||||
id=feature.id,
|
||||
code=feature.code,
|
||||
name=feature.name,
|
||||
description=feature.description,
|
||||
category=feature.category,
|
||||
ui_location=feature.ui_location,
|
||||
ui_icon=feature.ui_icon,
|
||||
ui_route=feature.ui_route,
|
||||
ui_badge_text=feature.ui_badge_text,
|
||||
minimum_tier_id=feature.minimum_tier_id,
|
||||
minimum_tier_code=feature.minimum_tier.code if feature.minimum_tier else None,
|
||||
minimum_tier_name=feature.minimum_tier.name if feature.minimum_tier else None,
|
||||
is_active=feature.is_active,
|
||||
is_visible=feature.is_visible,
|
||||
display_order=feature.display_order,
|
||||
)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Endpoints
|
||||
# ============================================================================
|
||||
|
||||
|
||||
@router.get("", response_model=FeatureListResponse)
|
||||
def list_features(
|
||||
category: str | None = Query(None, description="Filter by category"),
|
||||
active_only: bool = Query(False, description="Only active features"),
|
||||
current_user: UserContext = Depends(get_current_admin_api),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""List all features with their tier assignments."""
|
||||
features = feature_service.get_all_features(
|
||||
db, category=category, active_only=active_only
|
||||
)
|
||||
|
||||
return FeatureListResponse(
|
||||
features=[_feature_to_response(f) for f in features],
|
||||
total=len(features),
|
||||
)
|
||||
|
||||
|
||||
@router.get("/categories", response_model=CategoryListResponse)
|
||||
def list_categories(
|
||||
current_user: UserContext = Depends(get_current_admin_api),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""List all feature categories."""
|
||||
categories = feature_service.get_categories(db)
|
||||
return CategoryListResponse(categories=categories)
|
||||
|
||||
|
||||
@router.get("/tiers", response_model=TierListWithFeaturesResponse)
|
||||
def list_tiers_with_features(
|
||||
current_user: UserContext = Depends(get_current_admin_api),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""List all tiers with their feature assignments."""
|
||||
tiers = feature_service.get_all_tiers_with_features(db)
|
||||
|
||||
return TierListWithFeaturesResponse(
|
||||
tiers=[
|
||||
TierFeaturesResponse(
|
||||
id=t.id,
|
||||
code=t.code,
|
||||
name=t.name,
|
||||
description=t.description,
|
||||
features=t.features or [],
|
||||
feature_count=len(t.features or []),
|
||||
)
|
||||
for t in tiers
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
@router.get("/{feature_code}", response_model=FeatureResponse)
|
||||
def get_feature(
|
||||
feature_code: str,
|
||||
current_user: UserContext = Depends(get_current_admin_api),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""
|
||||
Get a single feature by code.
|
||||
|
||||
Raises 404 if feature not found.
|
||||
"""
|
||||
feature = feature_service.get_feature_by_code(db, feature_code)
|
||||
|
||||
if not feature:
|
||||
from app.exceptions import FeatureNotFoundError
|
||||
|
||||
raise FeatureNotFoundError(feature_code)
|
||||
|
||||
return _feature_to_response(feature)
|
||||
|
||||
|
||||
@router.put("/{feature_code}", response_model=FeatureResponse)
|
||||
def update_feature(
|
||||
feature_code: str,
|
||||
request: UpdateFeatureRequest,
|
||||
current_user: UserContext = Depends(get_current_admin_api),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""
|
||||
Update feature metadata.
|
||||
|
||||
Raises 404 if feature not found, 400 if tier code is invalid.
|
||||
"""
|
||||
feature = feature_service.update_feature(
|
||||
db,
|
||||
feature_code,
|
||||
name=request.name,
|
||||
description=request.description,
|
||||
category=request.category,
|
||||
ui_location=request.ui_location,
|
||||
ui_icon=request.ui_icon,
|
||||
ui_route=request.ui_route,
|
||||
ui_badge_text=request.ui_badge_text,
|
||||
minimum_tier_code=request.minimum_tier_code,
|
||||
is_active=request.is_active,
|
||||
is_visible=request.is_visible,
|
||||
display_order=request.display_order,
|
||||
)
|
||||
|
||||
db.commit()
|
||||
db.refresh(feature)
|
||||
|
||||
logger.info(f"Updated feature {feature_code} by admin {current_user.id}")
|
||||
|
||||
return _feature_to_response(feature)
|
||||
|
||||
|
||||
@router.put("/tiers/{tier_code}/features", response_model=TierFeaturesResponse)
|
||||
def update_tier_features(
|
||||
tier_code: str,
|
||||
request: UpdateTierFeaturesRequest,
|
||||
current_user: UserContext = Depends(get_current_admin_api),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""
|
||||
Update features assigned to a tier.
|
||||
|
||||
Raises 404 if tier not found, 422 if any feature codes are invalid.
|
||||
"""
|
||||
tier = feature_service.update_tier_features(db, tier_code, request.feature_codes)
|
||||
db.commit()
|
||||
|
||||
logger.info(
|
||||
f"Updated tier {tier_code} features to {len(request.feature_codes)} features "
|
||||
f"by admin {current_user.id}"
|
||||
)
|
||||
|
||||
return TierFeaturesResponse(
|
||||
id=tier.id,
|
||||
code=tier.code,
|
||||
name=tier.name,
|
||||
description=tier.description,
|
||||
features=tier.features or [],
|
||||
feature_count=len(tier.features or []),
|
||||
)
|
||||
|
||||
|
||||
@router.get("/tiers/{tier_code}/features", response_model=TierFeatureDetailResponse)
|
||||
def get_tier_features(
|
||||
tier_code: str,
|
||||
current_user: UserContext = Depends(get_current_admin_api),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""
|
||||
Get features assigned to a specific tier with full details.
|
||||
|
||||
Raises 404 if tier not found.
|
||||
"""
|
||||
tier, features = feature_service.get_tier_features_with_details(db, tier_code)
|
||||
|
||||
return TierFeatureDetailResponse(
|
||||
tier_code=tier.code,
|
||||
tier_name=tier.name,
|
||||
features=[
|
||||
{
|
||||
"code": f.code,
|
||||
"name": f.name,
|
||||
"category": f.category,
|
||||
"description": f.description,
|
||||
}
|
||||
for f in features
|
||||
],
|
||||
feature_count=len(features),
|
||||
)
|
||||
@@ -1,433 +0,0 @@
|
||||
# app/api/v1/admin/inventory.py
|
||||
"""
|
||||
Admin inventory management endpoints.
|
||||
|
||||
Provides inventory management capabilities for administrators:
|
||||
- View inventory across all vendors
|
||||
- View vendor-specific inventory
|
||||
- Set/adjust inventory on behalf of vendors
|
||||
- Low stock alerts and reporting
|
||||
|
||||
Admin Context: Uses admin JWT authentication.
|
||||
Vendor selection is passed as a request parameter.
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
from fastapi import APIRouter, Depends, File, Form, Query, UploadFile
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.api.deps import get_current_admin_api
|
||||
from app.core.database import get_db
|
||||
from app.services.inventory_import_service import inventory_import_service
|
||||
from app.services.inventory_service import inventory_service
|
||||
from app.services.inventory_transaction_service import inventory_transaction_service
|
||||
from models.schema.auth import UserContext
|
||||
from app.modules.inventory.schemas import (
|
||||
AdminInventoryAdjust,
|
||||
AdminInventoryCreate,
|
||||
AdminInventoryListResponse,
|
||||
AdminInventoryLocationsResponse,
|
||||
AdminInventoryStats,
|
||||
AdminInventoryTransactionItem,
|
||||
AdminInventoryTransactionListResponse,
|
||||
AdminLowStockItem,
|
||||
AdminTransactionStatsResponse,
|
||||
AdminVendorsWithInventoryResponse,
|
||||
InventoryAdjust,
|
||||
InventoryCreate,
|
||||
InventoryMessageResponse,
|
||||
InventoryResponse,
|
||||
InventoryUpdate,
|
||||
ProductInventorySummary,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/inventory")
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# List & Statistics Endpoints
|
||||
# ============================================================================
|
||||
|
||||
|
||||
@router.get("", response_model=AdminInventoryListResponse)
|
||||
def get_all_inventory(
|
||||
skip: int = Query(0, ge=0),
|
||||
limit: int = Query(50, ge=1, le=500),
|
||||
vendor_id: int | None = Query(None, description="Filter by vendor"),
|
||||
location: str | None = Query(None, description="Filter by location"),
|
||||
low_stock: int | None = Query(None, ge=0, description="Filter items below threshold"),
|
||||
search: str | None = Query(None, description="Search by product title or SKU"),
|
||||
db: Session = Depends(get_db),
|
||||
current_admin: UserContext = Depends(get_current_admin_api),
|
||||
):
|
||||
"""
|
||||
Get inventory across all vendors with filtering.
|
||||
|
||||
Allows admins to view and filter inventory across the platform.
|
||||
"""
|
||||
return inventory_service.get_all_inventory_admin(
|
||||
db=db,
|
||||
skip=skip,
|
||||
limit=limit,
|
||||
vendor_id=vendor_id,
|
||||
location=location,
|
||||
low_stock=low_stock,
|
||||
search=search,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/stats", response_model=AdminInventoryStats)
|
||||
def get_inventory_stats(
|
||||
db: Session = Depends(get_db),
|
||||
current_admin: UserContext = Depends(get_current_admin_api),
|
||||
):
|
||||
"""Get platform-wide inventory statistics."""
|
||||
return inventory_service.get_inventory_stats_admin(db)
|
||||
|
||||
|
||||
@router.get("/low-stock", response_model=list[AdminLowStockItem])
|
||||
def get_low_stock_items(
|
||||
threshold: int = Query(10, ge=0, description="Stock threshold"),
|
||||
vendor_id: int | None = Query(None, description="Filter by vendor"),
|
||||
limit: int = Query(50, ge=1, le=200),
|
||||
db: Session = Depends(get_db),
|
||||
current_admin: UserContext = Depends(get_current_admin_api),
|
||||
):
|
||||
"""Get items with low stock levels."""
|
||||
return inventory_service.get_low_stock_items_admin(
|
||||
db=db,
|
||||
threshold=threshold,
|
||||
vendor_id=vendor_id,
|
||||
limit=limit,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/vendors", response_model=AdminVendorsWithInventoryResponse)
|
||||
def get_vendors_with_inventory(
|
||||
db: Session = Depends(get_db),
|
||||
current_admin: UserContext = Depends(get_current_admin_api),
|
||||
):
|
||||
"""Get list of vendors that have inventory entries."""
|
||||
return inventory_service.get_vendors_with_inventory_admin(db)
|
||||
|
||||
|
||||
@router.get("/locations", response_model=AdminInventoryLocationsResponse)
|
||||
def get_inventory_locations(
|
||||
vendor_id: int | None = Query(None, description="Filter by vendor"),
|
||||
db: Session = Depends(get_db),
|
||||
current_admin: UserContext = Depends(get_current_admin_api),
|
||||
):
|
||||
"""Get list of unique inventory locations."""
|
||||
return inventory_service.get_inventory_locations_admin(db, vendor_id)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Vendor-Specific Endpoints
|
||||
# ============================================================================
|
||||
|
||||
|
||||
@router.get("/vendors/{vendor_id}", response_model=AdminInventoryListResponse)
|
||||
def get_vendor_inventory(
|
||||
vendor_id: int,
|
||||
skip: int = Query(0, ge=0),
|
||||
limit: int = Query(50, ge=1, le=500),
|
||||
location: str | None = Query(None, description="Filter by location"),
|
||||
low_stock: int | None = Query(None, ge=0, description="Filter items below threshold"),
|
||||
db: Session = Depends(get_db),
|
||||
current_admin: UserContext = Depends(get_current_admin_api),
|
||||
):
|
||||
"""Get inventory for a specific vendor."""
|
||||
return inventory_service.get_vendor_inventory_admin(
|
||||
db=db,
|
||||
vendor_id=vendor_id,
|
||||
skip=skip,
|
||||
limit=limit,
|
||||
location=location,
|
||||
low_stock=low_stock,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/products/{product_id}", response_model=ProductInventorySummary)
|
||||
def get_product_inventory(
|
||||
product_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_admin: UserContext = Depends(get_current_admin_api),
|
||||
):
|
||||
"""Get inventory summary for a specific product across all locations."""
|
||||
return inventory_service.get_product_inventory_admin(db, product_id)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Inventory Modification Endpoints
|
||||
# ============================================================================
|
||||
|
||||
|
||||
@router.post("/set", response_model=InventoryResponse)
|
||||
def set_inventory(
|
||||
inventory_data: AdminInventoryCreate,
|
||||
db: Session = Depends(get_db),
|
||||
current_admin: UserContext = Depends(get_current_admin_api),
|
||||
):
|
||||
"""
|
||||
Set exact inventory quantity for a product at a location.
|
||||
|
||||
Admin version - requires explicit vendor_id in request body.
|
||||
"""
|
||||
# Verify vendor exists
|
||||
inventory_service.verify_vendor_exists(db, inventory_data.vendor_id)
|
||||
|
||||
# Convert to standard schema for service
|
||||
service_data = InventoryCreate(
|
||||
product_id=inventory_data.product_id,
|
||||
location=inventory_data.location,
|
||||
quantity=inventory_data.quantity,
|
||||
)
|
||||
|
||||
result = inventory_service.set_inventory(
|
||||
db=db,
|
||||
vendor_id=inventory_data.vendor_id,
|
||||
inventory_data=service_data,
|
||||
)
|
||||
|
||||
logger.info(
|
||||
f"Admin {current_admin.email} set inventory for product {inventory_data.product_id} "
|
||||
f"at {inventory_data.location}: {inventory_data.quantity} units"
|
||||
)
|
||||
|
||||
db.commit()
|
||||
return result
|
||||
|
||||
|
||||
@router.post("/adjust", response_model=InventoryResponse)
|
||||
def adjust_inventory(
|
||||
adjustment: AdminInventoryAdjust,
|
||||
db: Session = Depends(get_db),
|
||||
current_admin: UserContext = Depends(get_current_admin_api),
|
||||
):
|
||||
"""
|
||||
Adjust inventory by adding or removing quantity.
|
||||
|
||||
Positive quantity = add stock, negative = remove stock.
|
||||
Admin version - requires explicit vendor_id in request body.
|
||||
"""
|
||||
# Verify vendor exists
|
||||
inventory_service.verify_vendor_exists(db, adjustment.vendor_id)
|
||||
|
||||
# Convert to standard schema for service
|
||||
service_data = InventoryAdjust(
|
||||
product_id=adjustment.product_id,
|
||||
location=adjustment.location,
|
||||
quantity=adjustment.quantity,
|
||||
)
|
||||
|
||||
result = inventory_service.adjust_inventory(
|
||||
db=db,
|
||||
vendor_id=adjustment.vendor_id,
|
||||
inventory_data=service_data,
|
||||
)
|
||||
|
||||
sign = "+" if adjustment.quantity >= 0 else ""
|
||||
logger.info(
|
||||
f"Admin {current_admin.email} adjusted inventory for product {adjustment.product_id} "
|
||||
f"at {adjustment.location}: {sign}{adjustment.quantity} units"
|
||||
f"{f' (reason: {adjustment.reason})' if adjustment.reason else ''}"
|
||||
)
|
||||
|
||||
db.commit()
|
||||
return result
|
||||
|
||||
|
||||
@router.put("/{inventory_id}", response_model=InventoryResponse)
|
||||
def update_inventory(
|
||||
inventory_id: int,
|
||||
inventory_update: InventoryUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
current_admin: UserContext = Depends(get_current_admin_api),
|
||||
):
|
||||
"""Update inventory entry fields."""
|
||||
# Get inventory to find vendor_id
|
||||
inventory = inventory_service.get_inventory_by_id_admin(db, inventory_id)
|
||||
|
||||
result = inventory_service.update_inventory(
|
||||
db=db,
|
||||
vendor_id=inventory.vendor_id,
|
||||
inventory_id=inventory_id,
|
||||
inventory_update=inventory_update,
|
||||
)
|
||||
|
||||
logger.info(f"Admin {current_admin.email} updated inventory {inventory_id}")
|
||||
|
||||
db.commit()
|
||||
return result
|
||||
|
||||
|
||||
@router.delete("/{inventory_id}", response_model=InventoryMessageResponse)
|
||||
def delete_inventory(
|
||||
inventory_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_admin: UserContext = Depends(get_current_admin_api),
|
||||
):
|
||||
"""Delete inventory entry."""
|
||||
# Get inventory to find vendor_id and log details
|
||||
inventory = inventory_service.get_inventory_by_id_admin(db, inventory_id)
|
||||
vendor_id = inventory.vendor_id
|
||||
product_id = inventory.product_id
|
||||
location = inventory.location
|
||||
|
||||
inventory_service.delete_inventory(
|
||||
db=db,
|
||||
vendor_id=vendor_id,
|
||||
inventory_id=inventory_id,
|
||||
)
|
||||
|
||||
logger.info(
|
||||
f"Admin {current_admin.email} deleted inventory {inventory_id} "
|
||||
f"(product {product_id} at {location})"
|
||||
)
|
||||
|
||||
db.commit()
|
||||
return InventoryMessageResponse(message="Inventory deleted successfully")
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Import Endpoints
|
||||
# ============================================================================
|
||||
|
||||
|
||||
class UnmatchedGtin(BaseModel):
|
||||
"""GTIN that couldn't be matched to a product."""
|
||||
|
||||
gtin: str
|
||||
quantity: int
|
||||
product_name: str
|
||||
|
||||
|
||||
class InventoryImportResponse(BaseModel):
|
||||
"""Response from inventory import."""
|
||||
|
||||
success: bool
|
||||
total_rows: int
|
||||
entries_created: int
|
||||
entries_updated: int
|
||||
quantity_imported: int
|
||||
unmatched_gtins: list[UnmatchedGtin]
|
||||
errors: list[str]
|
||||
|
||||
|
||||
@router.post("/import", response_model=InventoryImportResponse)
|
||||
async def import_inventory(
|
||||
file: UploadFile = File(..., description="TSV/CSV file with BIN, EAN, PRODUCT, QUANTITY columns"),
|
||||
vendor_id: int = Form(..., description="Vendor ID"),
|
||||
warehouse: str = Form("strassen", description="Warehouse name"),
|
||||
clear_existing: bool = Form(False, description="Clear existing inventory before import"),
|
||||
db: Session = Depends(get_db),
|
||||
current_admin: UserContext = Depends(get_current_admin_api),
|
||||
):
|
||||
"""
|
||||
Import inventory from a TSV/CSV file.
|
||||
|
||||
File format (TSV recommended):
|
||||
- Required columns: BIN, EAN
|
||||
- Optional columns: PRODUCT (for display), QUANTITY (defaults to 1 per row)
|
||||
|
||||
If QUANTITY column is present, each row represents the quantity specified.
|
||||
If QUANTITY is absent, each row counts as 1 unit (rows with same EAN+BIN are summed).
|
||||
|
||||
Products are matched by GTIN/EAN. Unmatched GTINs are reported in the response.
|
||||
"""
|
||||
# Verify vendor exists
|
||||
inventory_service.verify_vendor_exists(db, vendor_id)
|
||||
|
||||
# Read file content
|
||||
content = await file.read()
|
||||
try:
|
||||
content_str = content.decode("utf-8")
|
||||
except UnicodeDecodeError:
|
||||
content_str = content.decode("latin-1")
|
||||
|
||||
# Detect delimiter
|
||||
first_line = content_str.split("\n")[0] if content_str else ""
|
||||
delimiter = "\t" if "\t" in first_line else ","
|
||||
|
||||
# Run import
|
||||
result = inventory_import_service.import_from_text(
|
||||
db=db,
|
||||
content=content_str,
|
||||
vendor_id=vendor_id,
|
||||
warehouse=warehouse,
|
||||
delimiter=delimiter,
|
||||
clear_existing=clear_existing,
|
||||
)
|
||||
|
||||
if result.success:
|
||||
db.commit()
|
||||
logger.info(
|
||||
f"Admin {current_admin.email} imported inventory: "
|
||||
f"{result.entries_created} created, {result.entries_updated} updated, "
|
||||
f"{result.quantity_imported} total units"
|
||||
)
|
||||
else:
|
||||
db.rollback()
|
||||
logger.error(f"Inventory import failed: {result.errors}")
|
||||
|
||||
return InventoryImportResponse(
|
||||
success=result.success,
|
||||
total_rows=result.total_rows,
|
||||
entries_created=result.entries_created,
|
||||
entries_updated=result.entries_updated,
|
||||
quantity_imported=result.quantity_imported,
|
||||
unmatched_gtins=[UnmatchedGtin(**g) for g in result.unmatched_gtins],
|
||||
errors=result.errors,
|
||||
)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Transaction History Endpoints
|
||||
# ============================================================================
|
||||
|
||||
|
||||
@router.get("/transactions", response_model=AdminInventoryTransactionListResponse)
|
||||
def get_all_transactions(
|
||||
skip: int = Query(0, ge=0),
|
||||
limit: int = Query(50, ge=1, le=200),
|
||||
vendor_id: int | None = Query(None, description="Filter by vendor"),
|
||||
product_id: int | None = Query(None, description="Filter by product"),
|
||||
transaction_type: str | None = Query(None, description="Filter by type"),
|
||||
order_id: int | None = Query(None, description="Filter by order"),
|
||||
db: Session = Depends(get_db),
|
||||
current_admin: UserContext = Depends(get_current_admin_api),
|
||||
):
|
||||
"""
|
||||
Get inventory transaction history across all vendors.
|
||||
|
||||
Returns a paginated list of all stock movements with vendor and product details.
|
||||
"""
|
||||
transactions, total = inventory_transaction_service.get_all_transactions_admin(
|
||||
db=db,
|
||||
skip=skip,
|
||||
limit=limit,
|
||||
vendor_id=vendor_id,
|
||||
product_id=product_id,
|
||||
transaction_type=transaction_type,
|
||||
order_id=order_id,
|
||||
)
|
||||
|
||||
return AdminInventoryTransactionListResponse(
|
||||
transactions=[AdminInventoryTransactionItem(**tx) for tx in transactions],
|
||||
total=total,
|
||||
skip=skip,
|
||||
limit=limit,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/transactions/stats", response_model=AdminTransactionStatsResponse)
|
||||
def get_transaction_stats(
|
||||
db: Session = Depends(get_db),
|
||||
current_admin: UserContext = Depends(get_current_admin_api),
|
||||
):
|
||||
"""Get transaction statistics for the platform."""
|
||||
stats = inventory_transaction_service.get_transaction_stats_admin(db)
|
||||
return AdminTransactionStatsResponse(**stats)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,173 +0,0 @@
|
||||
# app/api/v1/admin/marketplace.py
|
||||
"""
|
||||
Marketplace import job monitoring endpoints for admin.
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
from fastapi import APIRouter, BackgroundTasks, Depends, Query
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.api.deps import get_current_admin_api
|
||||
from app.core.database import get_db
|
||||
from app.services.marketplace_import_job_service import marketplace_import_job_service
|
||||
from app.services.stats_service import stats_service
|
||||
from app.services.vendor_service import vendor_service
|
||||
from app.tasks.background_tasks import process_marketplace_import
|
||||
from models.schema.auth import UserContext
|
||||
from app.modules.marketplace.schemas import (
|
||||
AdminMarketplaceImportJobListResponse,
|
||||
AdminMarketplaceImportJobRequest,
|
||||
AdminMarketplaceImportJobResponse,
|
||||
MarketplaceImportErrorListResponse,
|
||||
MarketplaceImportErrorResponse,
|
||||
MarketplaceImportJobRequest,
|
||||
MarketplaceImportJobResponse,
|
||||
)
|
||||
from app.modules.analytics.schemas import ImportStatsResponse
|
||||
|
||||
router = APIRouter(prefix="/marketplace-import-jobs")
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@router.get("", response_model=AdminMarketplaceImportJobListResponse)
|
||||
def get_all_marketplace_import_jobs(
|
||||
marketplace: str | None = Query(None),
|
||||
status: str | None = Query(None),
|
||||
page: int = Query(1, ge=1),
|
||||
limit: int = Query(100, ge=1, le=100),
|
||||
db: Session = Depends(get_db),
|
||||
current_admin: UserContext = Depends(get_current_admin_api),
|
||||
):
|
||||
"""Get all marketplace import jobs with pagination (Admin only)."""
|
||||
jobs, total = marketplace_import_job_service.get_all_import_jobs_paginated(
|
||||
db=db,
|
||||
marketplace=marketplace,
|
||||
status=status,
|
||||
page=page,
|
||||
limit=limit,
|
||||
)
|
||||
|
||||
return AdminMarketplaceImportJobListResponse(
|
||||
items=[
|
||||
marketplace_import_job_service.convert_to_admin_response_model(job)
|
||||
for job in jobs
|
||||
],
|
||||
total=total,
|
||||
page=page,
|
||||
limit=limit,
|
||||
)
|
||||
|
||||
|
||||
@router.post("", response_model=MarketplaceImportJobResponse)
|
||||
async def create_marketplace_import_job(
|
||||
request: AdminMarketplaceImportJobRequest,
|
||||
background_tasks: BackgroundTasks,
|
||||
db: Session = Depends(get_db),
|
||||
current_admin: UserContext = Depends(get_current_admin_api),
|
||||
):
|
||||
"""
|
||||
Create a new marketplace import job (Admin only).
|
||||
|
||||
Admins can trigger imports for any vendor by specifying vendor_id.
|
||||
The import is processed asynchronously in the background.
|
||||
|
||||
The `language` parameter specifies the language code for product
|
||||
translations (e.g., 'en', 'fr', 'de'). Default is 'en'.
|
||||
"""
|
||||
vendor = vendor_service.get_vendor_by_id(db, request.vendor_id)
|
||||
|
||||
job_request = MarketplaceImportJobRequest(
|
||||
source_url=request.source_url,
|
||||
marketplace=request.marketplace,
|
||||
batch_size=request.batch_size,
|
||||
language=request.language,
|
||||
)
|
||||
|
||||
job = marketplace_import_job_service.create_import_job(
|
||||
db=db,
|
||||
request=job_request,
|
||||
vendor=vendor,
|
||||
user=current_admin,
|
||||
)
|
||||
db.commit()
|
||||
|
||||
logger.info(
|
||||
f"Admin {current_admin.username} created import job {job.id} "
|
||||
f"for vendor {vendor.vendor_code} (language={request.language})"
|
||||
)
|
||||
|
||||
# Dispatch via task dispatcher (supports Celery or BackgroundTasks)
|
||||
from app.tasks.dispatcher import task_dispatcher
|
||||
|
||||
celery_task_id = task_dispatcher.dispatch_marketplace_import(
|
||||
background_tasks=background_tasks,
|
||||
job_id=job.id,
|
||||
url=request.source_url,
|
||||
marketplace=request.marketplace,
|
||||
vendor_id=vendor.id,
|
||||
batch_size=request.batch_size or 1000,
|
||||
language=request.language,
|
||||
)
|
||||
|
||||
# Store Celery task ID if using Celery
|
||||
if celery_task_id:
|
||||
job.celery_task_id = celery_task_id
|
||||
db.commit()
|
||||
|
||||
return marketplace_import_job_service.convert_to_response_model(job)
|
||||
|
||||
|
||||
# NOTE: /stats must be defined BEFORE /{job_id} to avoid route conflicts
|
||||
@router.get("/stats", response_model=ImportStatsResponse)
|
||||
def get_import_statistics(
|
||||
db: Session = Depends(get_db),
|
||||
current_admin: UserContext = Depends(get_current_admin_api),
|
||||
):
|
||||
"""Get marketplace import statistics (Admin only)."""
|
||||
stats = stats_service.get_import_statistics(db)
|
||||
return ImportStatsResponse(**stats)
|
||||
|
||||
|
||||
@router.get("/{job_id}", response_model=AdminMarketplaceImportJobResponse)
|
||||
def get_marketplace_import_job(
|
||||
job_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_admin: UserContext = Depends(get_current_admin_api),
|
||||
):
|
||||
"""Get a single marketplace import job by ID (Admin only)."""
|
||||
job = marketplace_import_job_service.get_import_job_by_id_admin(db, job_id)
|
||||
return marketplace_import_job_service.convert_to_admin_response_model(job)
|
||||
|
||||
|
||||
@router.get("/{job_id}/errors", response_model=MarketplaceImportErrorListResponse)
|
||||
def get_import_job_errors(
|
||||
job_id: int,
|
||||
page: int = Query(1, ge=1),
|
||||
limit: int = Query(50, ge=1, le=100),
|
||||
error_type: str | None = Query(None, description="Filter by error type"),
|
||||
db: Session = Depends(get_db),
|
||||
current_admin: UserContext = Depends(get_current_admin_api),
|
||||
):
|
||||
"""Get import errors for a specific job (Admin only).
|
||||
|
||||
Returns detailed error information including row number, identifier,
|
||||
error type, error message, and raw row data for review.
|
||||
"""
|
||||
# Verify job exists
|
||||
marketplace_import_job_service.get_import_job_by_id_admin(db, job_id)
|
||||
|
||||
# Get errors from service
|
||||
errors, total = marketplace_import_job_service.get_import_job_errors(
|
||||
db=db,
|
||||
job_id=job_id,
|
||||
error_type=error_type,
|
||||
page=page,
|
||||
limit=limit,
|
||||
)
|
||||
|
||||
return MarketplaceImportErrorListResponse(
|
||||
errors=[MarketplaceImportErrorResponse.model_validate(e) for e in errors],
|
||||
total=total,
|
||||
import_job_id=job_id,
|
||||
)
|
||||
@@ -1,252 +0,0 @@
|
||||
# app/api/v1/admin/order_item_exceptions.py
|
||||
"""
|
||||
Admin API endpoints for order item exception management.
|
||||
|
||||
Provides admin-level management of:
|
||||
- Listing exceptions across all vendors
|
||||
- Resolving exceptions by assigning products
|
||||
- Bulk resolution by GTIN
|
||||
- Exception statistics
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
from fastapi import APIRouter, Depends, Path, Query
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.api.deps import get_current_admin_api
|
||||
from app.core.database import get_db
|
||||
from app.services.order_item_exception_service import order_item_exception_service
|
||||
from models.schema.auth import UserContext
|
||||
from app.modules.orders.schemas import (
|
||||
BulkResolveRequest,
|
||||
BulkResolveResponse,
|
||||
IgnoreExceptionRequest,
|
||||
OrderItemExceptionListResponse,
|
||||
OrderItemExceptionResponse,
|
||||
OrderItemExceptionStats,
|
||||
ResolveExceptionRequest,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/order-exceptions", tags=["Order Item Exceptions"])
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Exception Listing and Stats
|
||||
# ============================================================================
|
||||
|
||||
|
||||
@router.get("", response_model=OrderItemExceptionListResponse)
|
||||
def list_exceptions(
|
||||
vendor_id: int | None = Query(None, description="Filter by vendor"),
|
||||
status: str | None = Query(
|
||||
None,
|
||||
pattern="^(pending|resolved|ignored)$",
|
||||
description="Filter by status"
|
||||
),
|
||||
search: str | None = Query(
|
||||
None,
|
||||
description="Search in GTIN, product name, SKU, or order number"
|
||||
),
|
||||
skip: int = Query(0, ge=0),
|
||||
limit: int = Query(50, ge=1, le=200),
|
||||
db: Session = Depends(get_db),
|
||||
current_admin: UserContext = Depends(get_current_admin_api),
|
||||
):
|
||||
"""
|
||||
List order item exceptions with filtering and pagination.
|
||||
|
||||
Returns exceptions for unmatched products during marketplace order imports.
|
||||
"""
|
||||
exceptions, total = order_item_exception_service.get_pending_exceptions(
|
||||
db=db,
|
||||
vendor_id=vendor_id,
|
||||
status=status,
|
||||
search=search,
|
||||
skip=skip,
|
||||
limit=limit,
|
||||
)
|
||||
|
||||
# Enrich with order and vendor info
|
||||
response_items = []
|
||||
for exc in exceptions:
|
||||
item = OrderItemExceptionResponse.model_validate(exc)
|
||||
if exc.order_item and exc.order_item.order:
|
||||
order = exc.order_item.order
|
||||
item.order_number = order.order_number
|
||||
item.order_id = order.id
|
||||
item.order_date = order.order_date
|
||||
item.order_status = order.status
|
||||
# Add vendor name for cross-vendor view
|
||||
if order.vendor:
|
||||
item.vendor_name = order.vendor.name
|
||||
response_items.append(item)
|
||||
|
||||
return OrderItemExceptionListResponse(
|
||||
exceptions=response_items,
|
||||
total=total,
|
||||
skip=skip,
|
||||
limit=limit,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/stats", response_model=OrderItemExceptionStats)
|
||||
def get_exception_stats(
|
||||
vendor_id: int | None = Query(None, description="Filter by vendor"),
|
||||
db: Session = Depends(get_db),
|
||||
current_admin: UserContext = Depends(get_current_admin_api),
|
||||
):
|
||||
"""
|
||||
Get exception statistics.
|
||||
|
||||
Returns counts of pending, resolved, and ignored exceptions.
|
||||
"""
|
||||
stats = order_item_exception_service.get_exception_stats(db, vendor_id)
|
||||
return OrderItemExceptionStats(**stats)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Exception Details
|
||||
# ============================================================================
|
||||
|
||||
|
||||
@router.get("/{exception_id}", response_model=OrderItemExceptionResponse)
|
||||
def get_exception(
|
||||
exception_id: int = Path(..., description="Exception ID"),
|
||||
db: Session = Depends(get_db),
|
||||
current_admin: UserContext = Depends(get_current_admin_api),
|
||||
):
|
||||
"""
|
||||
Get details of a single exception.
|
||||
"""
|
||||
exception = order_item_exception_service.get_exception_by_id(db, exception_id)
|
||||
|
||||
response = OrderItemExceptionResponse.model_validate(exception)
|
||||
if exception.order_item and exception.order_item.order:
|
||||
order = exception.order_item.order
|
||||
response.order_number = order.order_number
|
||||
response.order_id = order.id
|
||||
response.order_date = order.order_date
|
||||
response.order_status = order.status
|
||||
|
||||
return response
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Exception Resolution
|
||||
# ============================================================================
|
||||
|
||||
|
||||
@router.post("/{exception_id}/resolve", response_model=OrderItemExceptionResponse)
|
||||
def resolve_exception(
|
||||
exception_id: int = Path(..., description="Exception ID"),
|
||||
request: ResolveExceptionRequest = ...,
|
||||
db: Session = Depends(get_db),
|
||||
current_admin: UserContext = Depends(get_current_admin_api),
|
||||
):
|
||||
"""
|
||||
Resolve an exception by assigning a product.
|
||||
|
||||
This updates the order item's product_id and marks the exception as resolved.
|
||||
"""
|
||||
exception = order_item_exception_service.resolve_exception(
|
||||
db=db,
|
||||
exception_id=exception_id,
|
||||
product_id=request.product_id,
|
||||
resolved_by=current_admin.id,
|
||||
notes=request.notes,
|
||||
)
|
||||
db.commit()
|
||||
|
||||
response = OrderItemExceptionResponse.model_validate(exception)
|
||||
if exception.order_item and exception.order_item.order:
|
||||
order = exception.order_item.order
|
||||
response.order_number = order.order_number
|
||||
response.order_id = order.id
|
||||
response.order_date = order.order_date
|
||||
response.order_status = order.status
|
||||
|
||||
logger.info(
|
||||
f"Admin {current_admin.id} resolved exception {exception_id} "
|
||||
f"with product {request.product_id}"
|
||||
)
|
||||
|
||||
return response
|
||||
|
||||
|
||||
@router.post("/{exception_id}/ignore", response_model=OrderItemExceptionResponse)
|
||||
def ignore_exception(
|
||||
exception_id: int = Path(..., description="Exception ID"),
|
||||
request: IgnoreExceptionRequest = ...,
|
||||
db: Session = Depends(get_db),
|
||||
current_admin: UserContext = Depends(get_current_admin_api),
|
||||
):
|
||||
"""
|
||||
Mark an exception as ignored.
|
||||
|
||||
Note: Ignored exceptions still block order confirmation.
|
||||
Use this when a product will never be matched (e.g., discontinued).
|
||||
"""
|
||||
exception = order_item_exception_service.ignore_exception(
|
||||
db=db,
|
||||
exception_id=exception_id,
|
||||
resolved_by=current_admin.id,
|
||||
notes=request.notes,
|
||||
)
|
||||
db.commit()
|
||||
|
||||
response = OrderItemExceptionResponse.model_validate(exception)
|
||||
if exception.order_item and exception.order_item.order:
|
||||
order = exception.order_item.order
|
||||
response.order_number = order.order_number
|
||||
response.order_id = order.id
|
||||
response.order_date = order.order_date
|
||||
response.order_status = order.status
|
||||
|
||||
logger.info(
|
||||
f"Admin {current_admin.id} ignored exception {exception_id}: {request.notes}"
|
||||
)
|
||||
|
||||
return response
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Bulk Operations
|
||||
# ============================================================================
|
||||
|
||||
|
||||
@router.post("/bulk-resolve", response_model=BulkResolveResponse)
|
||||
def bulk_resolve_by_gtin(
|
||||
request: BulkResolveRequest,
|
||||
vendor_id: int = Query(..., description="Vendor ID"),
|
||||
db: Session = Depends(get_db),
|
||||
current_admin: UserContext = Depends(get_current_admin_api),
|
||||
):
|
||||
"""
|
||||
Bulk resolve all pending exceptions for a GTIN.
|
||||
|
||||
Useful when a new product is imported and multiple orders have
|
||||
items with the same unmatched GTIN.
|
||||
"""
|
||||
resolved_count = order_item_exception_service.bulk_resolve_by_gtin(
|
||||
db=db,
|
||||
vendor_id=vendor_id,
|
||||
gtin=request.gtin,
|
||||
product_id=request.product_id,
|
||||
resolved_by=current_admin.id,
|
||||
notes=request.notes,
|
||||
)
|
||||
db.commit()
|
||||
|
||||
logger.info(
|
||||
f"Admin {current_admin.id} bulk resolved {resolved_count} exceptions "
|
||||
f"for GTIN {request.gtin} with product {request.product_id}"
|
||||
)
|
||||
|
||||
return BulkResolveResponse(
|
||||
resolved_count=resolved_count,
|
||||
gtin=request.gtin,
|
||||
product_id=request.product_id,
|
||||
)
|
||||
@@ -1,193 +0,0 @@
|
||||
# app/api/v1/admin/orders.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.
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.api.deps import get_current_admin_api
|
||||
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,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/orders")
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# List & Statistics Endpoints
|
||||
# ============================================================================
|
||||
|
||||
|
||||
@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,
|
||||
)
|
||||
|
||||
|
||||
@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)
|
||||
|
||||
|
||||
@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
|
||||
# ============================================================================
|
||||
|
||||
|
||||
@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
|
||||
|
||||
|
||||
@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
|
||||
|
||||
|
||||
@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
|
||||
|
||||
|
||||
@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)
|
||||
@@ -1,331 +0,0 @@
|
||||
# app/api/v1/admin/subscriptions.py
|
||||
"""
|
||||
Admin Subscription Management API.
|
||||
|
||||
Provides endpoints for platform administrators to manage:
|
||||
- Subscription tiers (CRUD)
|
||||
- Vendor subscriptions (view, update, override limits)
|
||||
- Billing history across all vendors
|
||||
- Subscription analytics
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
from fastapi import APIRouter, Depends, Path, Query
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.api.deps import get_current_admin_api
|
||||
from app.core.database import get_db
|
||||
from app.services.admin_subscription_service import admin_subscription_service
|
||||
from app.services.subscription_service import subscription_service
|
||||
from models.schema.auth import UserContext
|
||||
from app.modules.billing.schemas import (
|
||||
BillingHistoryListResponse,
|
||||
BillingHistoryWithVendor,
|
||||
SubscriptionStatsResponse,
|
||||
SubscriptionTierCreate,
|
||||
SubscriptionTierListResponse,
|
||||
SubscriptionTierResponse,
|
||||
SubscriptionTierUpdate,
|
||||
VendorSubscriptionCreate,
|
||||
VendorSubscriptionListResponse,
|
||||
VendorSubscriptionResponse,
|
||||
VendorSubscriptionUpdate,
|
||||
VendorSubscriptionWithVendor,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/subscriptions")
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Subscription Tier Endpoints
|
||||
# ============================================================================
|
||||
|
||||
|
||||
@router.get("/tiers", response_model=SubscriptionTierListResponse)
|
||||
def list_subscription_tiers(
|
||||
include_inactive: bool = Query(False, description="Include inactive tiers"),
|
||||
current_user: UserContext = Depends(get_current_admin_api),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""
|
||||
List all subscription tiers.
|
||||
|
||||
Returns all tiers with their limits, features, and Stripe configuration.
|
||||
"""
|
||||
tiers = admin_subscription_service.get_tiers(db, include_inactive=include_inactive)
|
||||
|
||||
return SubscriptionTierListResponse(
|
||||
tiers=[SubscriptionTierResponse.model_validate(t) for t in tiers],
|
||||
total=len(tiers),
|
||||
)
|
||||
|
||||
|
||||
@router.get("/tiers/{tier_code}", response_model=SubscriptionTierResponse)
|
||||
def get_subscription_tier(
|
||||
tier_code: str = Path(..., description="Tier code"),
|
||||
current_user: UserContext = Depends(get_current_admin_api),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""Get a specific subscription tier by code."""
|
||||
tier = admin_subscription_service.get_tier_by_code(db, tier_code)
|
||||
return SubscriptionTierResponse.model_validate(tier)
|
||||
|
||||
|
||||
@router.post("/tiers", response_model=SubscriptionTierResponse, status_code=201)
|
||||
def create_subscription_tier(
|
||||
tier_data: SubscriptionTierCreate,
|
||||
current_user: UserContext = Depends(get_current_admin_api),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""Create a new subscription tier."""
|
||||
tier = admin_subscription_service.create_tier(db, tier_data.model_dump())
|
||||
db.commit()
|
||||
db.refresh(tier)
|
||||
return SubscriptionTierResponse.model_validate(tier)
|
||||
|
||||
|
||||
@router.patch("/tiers/{tier_code}", response_model=SubscriptionTierResponse)
|
||||
def update_subscription_tier(
|
||||
tier_data: SubscriptionTierUpdate,
|
||||
tier_code: str = Path(..., description="Tier code"),
|
||||
current_user: UserContext = Depends(get_current_admin_api),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""Update a subscription tier."""
|
||||
update_data = tier_data.model_dump(exclude_unset=True)
|
||||
tier = admin_subscription_service.update_tier(db, tier_code, update_data)
|
||||
db.commit()
|
||||
db.refresh(tier)
|
||||
return SubscriptionTierResponse.model_validate(tier)
|
||||
|
||||
|
||||
@router.delete("/tiers/{tier_code}", status_code=204)
|
||||
def delete_subscription_tier(
|
||||
tier_code: str = Path(..., description="Tier code"),
|
||||
current_user: UserContext = Depends(get_current_admin_api),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""
|
||||
Soft-delete a subscription tier.
|
||||
|
||||
Sets is_active=False rather than deleting to preserve history.
|
||||
"""
|
||||
admin_subscription_service.deactivate_tier(db, tier_code)
|
||||
db.commit()
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Vendor Subscription Endpoints
|
||||
# ============================================================================
|
||||
|
||||
|
||||
@router.get("", response_model=VendorSubscriptionListResponse)
|
||||
def list_vendor_subscriptions(
|
||||
page: int = Query(1, ge=1),
|
||||
per_page: int = Query(20, ge=1, le=100),
|
||||
status: str | None = Query(None, description="Filter by status"),
|
||||
tier: str | None = Query(None, description="Filter by tier"),
|
||||
search: str | None = Query(None, description="Search vendor name"),
|
||||
current_user: UserContext = Depends(get_current_admin_api),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""
|
||||
List all vendor subscriptions with filtering.
|
||||
|
||||
Includes vendor information for each subscription.
|
||||
"""
|
||||
data = admin_subscription_service.list_subscriptions(
|
||||
db, page=page, per_page=per_page, status=status, tier=tier, search=search
|
||||
)
|
||||
|
||||
subscriptions = []
|
||||
for sub, vendor in data["results"]:
|
||||
sub_dict = {
|
||||
**VendorSubscriptionResponse.model_validate(sub).model_dump(),
|
||||
"vendor_name": vendor.name,
|
||||
"vendor_code": vendor.subdomain,
|
||||
}
|
||||
subscriptions.append(VendorSubscriptionWithVendor(**sub_dict))
|
||||
|
||||
return VendorSubscriptionListResponse(
|
||||
subscriptions=subscriptions,
|
||||
total=data["total"],
|
||||
page=data["page"],
|
||||
per_page=data["per_page"],
|
||||
pages=data["pages"],
|
||||
)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Statistics Endpoints
|
||||
# ============================================================================
|
||||
|
||||
|
||||
@router.get("/stats", response_model=SubscriptionStatsResponse)
|
||||
def get_subscription_stats(
|
||||
current_user: UserContext = Depends(get_current_admin_api),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""Get subscription statistics for admin dashboard."""
|
||||
stats = admin_subscription_service.get_stats(db)
|
||||
return SubscriptionStatsResponse(**stats)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Billing History Endpoints
|
||||
# ============================================================================
|
||||
|
||||
|
||||
@router.get("/billing/history", response_model=BillingHistoryListResponse)
|
||||
def list_billing_history(
|
||||
page: int = Query(1, ge=1),
|
||||
per_page: int = Query(20, ge=1, le=100),
|
||||
vendor_id: int | None = Query(None, description="Filter by vendor"),
|
||||
status: str | None = Query(None, description="Filter by status"),
|
||||
current_user: UserContext = Depends(get_current_admin_api),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""List billing history (invoices) across all vendors."""
|
||||
data = admin_subscription_service.list_billing_history(
|
||||
db, page=page, per_page=per_page, vendor_id=vendor_id, status=status
|
||||
)
|
||||
|
||||
invoices = []
|
||||
for invoice, vendor in data["results"]:
|
||||
invoice_dict = {
|
||||
"id": invoice.id,
|
||||
"vendor_id": invoice.vendor_id,
|
||||
"stripe_invoice_id": invoice.stripe_invoice_id,
|
||||
"invoice_number": invoice.invoice_number,
|
||||
"invoice_date": invoice.invoice_date,
|
||||
"due_date": invoice.due_date,
|
||||
"subtotal_cents": invoice.subtotal_cents,
|
||||
"tax_cents": invoice.tax_cents,
|
||||
"total_cents": invoice.total_cents,
|
||||
"amount_paid_cents": invoice.amount_paid_cents,
|
||||
"currency": invoice.currency,
|
||||
"status": invoice.status,
|
||||
"invoice_pdf_url": invoice.invoice_pdf_url,
|
||||
"hosted_invoice_url": invoice.hosted_invoice_url,
|
||||
"description": invoice.description,
|
||||
"created_at": invoice.created_at,
|
||||
"vendor_name": vendor.name,
|
||||
"vendor_code": vendor.subdomain,
|
||||
}
|
||||
invoices.append(BillingHistoryWithVendor(**invoice_dict))
|
||||
|
||||
return BillingHistoryListResponse(
|
||||
invoices=invoices,
|
||||
total=data["total"],
|
||||
page=data["page"],
|
||||
per_page=data["per_page"],
|
||||
pages=data["pages"],
|
||||
)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Vendor Subscription Detail Endpoints
|
||||
# ============================================================================
|
||||
|
||||
|
||||
@router.post("/{vendor_id}", response_model=VendorSubscriptionWithVendor, status_code=201)
|
||||
def create_vendor_subscription(
|
||||
create_data: VendorSubscriptionCreate,
|
||||
vendor_id: int = Path(..., description="Vendor ID"),
|
||||
current_user: UserContext = Depends(get_current_admin_api),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""
|
||||
Create a subscription for a vendor.
|
||||
|
||||
Creates a new subscription with the specified tier and status.
|
||||
Defaults to Essential tier with trial status.
|
||||
"""
|
||||
# Verify vendor exists
|
||||
vendor = admin_subscription_service.get_vendor(db, vendor_id)
|
||||
|
||||
# Create subscription using the subscription service
|
||||
sub = subscription_service.get_or_create_subscription(
|
||||
db,
|
||||
vendor_id=vendor_id,
|
||||
tier=create_data.tier,
|
||||
trial_days=create_data.trial_days,
|
||||
)
|
||||
|
||||
# Update status if not trial
|
||||
if create_data.status != "trial":
|
||||
sub.status = create_data.status
|
||||
|
||||
sub.is_annual = create_data.is_annual
|
||||
|
||||
db.commit()
|
||||
db.refresh(sub)
|
||||
|
||||
# Get usage counts
|
||||
usage = admin_subscription_service.get_vendor_usage_counts(db, vendor_id)
|
||||
|
||||
logger.info(f"Admin created subscription for vendor {vendor_id}: tier={create_data.tier}")
|
||||
|
||||
return VendorSubscriptionWithVendor(
|
||||
**VendorSubscriptionResponse.model_validate(sub).model_dump(),
|
||||
vendor_name=vendor.name,
|
||||
vendor_code=vendor.subdomain,
|
||||
products_count=usage["products_count"],
|
||||
team_count=usage["team_count"],
|
||||
)
|
||||
|
||||
|
||||
@router.get("/{vendor_id}", response_model=VendorSubscriptionWithVendor)
|
||||
def get_vendor_subscription(
|
||||
vendor_id: int = Path(..., description="Vendor ID"),
|
||||
current_user: UserContext = Depends(get_current_admin_api),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""Get subscription details for a specific vendor."""
|
||||
sub, vendor = admin_subscription_service.get_subscription(db, vendor_id)
|
||||
|
||||
# Get usage counts
|
||||
usage = admin_subscription_service.get_vendor_usage_counts(db, vendor_id)
|
||||
|
||||
return VendorSubscriptionWithVendor(
|
||||
**VendorSubscriptionResponse.model_validate(sub).model_dump(),
|
||||
vendor_name=vendor.name,
|
||||
vendor_code=vendor.subdomain,
|
||||
products_count=usage["products_count"],
|
||||
team_count=usage["team_count"],
|
||||
)
|
||||
|
||||
|
||||
@router.patch("/{vendor_id}", response_model=VendorSubscriptionWithVendor)
|
||||
def update_vendor_subscription(
|
||||
update_data: VendorSubscriptionUpdate,
|
||||
vendor_id: int = Path(..., description="Vendor ID"),
|
||||
current_user: UserContext = Depends(get_current_admin_api),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""
|
||||
Update a vendor's subscription.
|
||||
|
||||
Allows admins to:
|
||||
- Change tier
|
||||
- Update status
|
||||
- Set custom limit overrides
|
||||
- Extend trial period
|
||||
"""
|
||||
data = update_data.model_dump(exclude_unset=True)
|
||||
sub, vendor = admin_subscription_service.update_subscription(db, vendor_id, data)
|
||||
db.commit()
|
||||
db.refresh(sub)
|
||||
|
||||
# Get usage counts
|
||||
usage = admin_subscription_service.get_vendor_usage_counts(db, vendor_id)
|
||||
|
||||
return VendorSubscriptionWithVendor(
|
||||
**VendorSubscriptionResponse.model_validate(sub).model_dump(),
|
||||
vendor_name=vendor.name,
|
||||
vendor_code=vendor.subdomain,
|
||||
products_count=usage["products_count"],
|
||||
team_count=usage["team_count"],
|
||||
)
|
||||
@@ -345,7 +345,7 @@ def export_vendor_products_letzshop(
|
||||
"""
|
||||
from fastapi.responses import Response
|
||||
|
||||
from app.services.letzshop_export_service import letzshop_export_service
|
||||
from app.modules.marketplace.services.letzshop_export_service import letzshop_export_service
|
||||
|
||||
vendor = vendor_service.get_vendor_by_identifier(db, vendor_identifier)
|
||||
|
||||
@@ -396,7 +396,7 @@ def export_vendor_products_letzshop_to_folder(
|
||||
from pathlib import Path as FilePath
|
||||
|
||||
from app.core.config import settings
|
||||
from app.services.letzshop_export_service import letzshop_export_service
|
||||
from app.modules.marketplace.services.letzshop_export_service import letzshop_export_service
|
||||
|
||||
vendor = vendor_service.get_vendor_by_identifier(db, vendor_identifier)
|
||||
include_inactive = request.include_inactive if request else False
|
||||
|
||||
Reference in New Issue
Block a user