feat: add comprehensive tier-based feature management system
Implement database-driven feature gating with contextual upgrade prompts: - Add Feature model with 30 features across 8 categories - Create FeatureService with caching for tier-based feature checking - Add @require_feature decorator and RequireFeature dependency for backend enforcement - Create vendor features API (6 endpoints) and admin features API - Add Alpine.js feature store and upgrade prompts store for frontend - Create Jinja macros: feature_gate, feature_locked, limit_warning, usage_bar - Add usage API for tracking orders/products/team limits with upgrade info - Fix Stripe webhook to create VendorAddOn records on addon purchase - Integrate upgrade prompts into vendor dashboard with tier badge and usage bars 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
@@ -33,6 +33,7 @@ from . import (
|
||||
content_pages,
|
||||
customers,
|
||||
dashboard,
|
||||
features,
|
||||
images,
|
||||
inventory,
|
||||
letzshop,
|
||||
@@ -181,6 +182,9 @@ router.include_router(
|
||||
# Include subscription management endpoints
|
||||
router.include_router(subscriptions.router, tags=["admin-subscriptions"])
|
||||
|
||||
# Include feature management endpoints
|
||||
router.include_router(features.router, tags=["admin-features"])
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Code Quality & Architecture
|
||||
|
||||
357
app/api/v1/admin/features.py
Normal file
357
app/api/v1/admin/features.py
Normal file
@@ -0,0 +1,357 @@
|
||||
# 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, HTTPException, 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.database.feature import Feature
|
||||
from models.database.subscription import SubscriptionTier
|
||||
from models.database.user import User
|
||||
|
||||
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]
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# 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: User = 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=[
|
||||
FeatureResponse(
|
||||
id=f.id,
|
||||
code=f.code,
|
||||
name=f.name,
|
||||
description=f.description,
|
||||
category=f.category,
|
||||
ui_location=f.ui_location,
|
||||
ui_icon=f.ui_icon,
|
||||
ui_route=f.ui_route,
|
||||
ui_badge_text=f.ui_badge_text,
|
||||
minimum_tier_id=f.minimum_tier_id,
|
||||
minimum_tier_code=f.minimum_tier.code if f.minimum_tier else None,
|
||||
minimum_tier_name=f.minimum_tier.name if f.minimum_tier else None,
|
||||
is_active=f.is_active,
|
||||
is_visible=f.is_visible,
|
||||
display_order=f.display_order,
|
||||
)
|
||||
for f in features
|
||||
],
|
||||
total=len(features),
|
||||
)
|
||||
|
||||
|
||||
@router.get("/categories", response_model=CategoryListResponse)
|
||||
def list_categories(
|
||||
current_user: User = 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: User = Depends(get_current_admin_api),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""List all tiers with their feature assignments."""
|
||||
tiers = (
|
||||
db.query(SubscriptionTier)
|
||||
.filter(SubscriptionTier.is_active == True) # noqa: E712
|
||||
.order_by(SubscriptionTier.display_order)
|
||||
.all()
|
||||
)
|
||||
|
||||
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: User = Depends(get_current_admin_api),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""Get a single feature by code."""
|
||||
feature = feature_service.get_feature_by_code(db, feature_code)
|
||||
|
||||
if not feature:
|
||||
raise HTTPException(status_code=404, detail=f"Feature '{feature_code}' not found")
|
||||
|
||||
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,
|
||||
)
|
||||
|
||||
|
||||
@router.put("/{feature_code}", response_model=FeatureResponse)
|
||||
def update_feature(
|
||||
feature_code: str,
|
||||
request: UpdateFeatureRequest,
|
||||
current_user: User = Depends(get_current_admin_api),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""Update feature metadata."""
|
||||
feature = db.query(Feature).filter(Feature.code == feature_code).first()
|
||||
|
||||
if not feature:
|
||||
raise HTTPException(status_code=404, detail=f"Feature '{feature_code}' not found")
|
||||
|
||||
# Update fields if provided
|
||||
if request.name is not None:
|
||||
feature.name = request.name
|
||||
if request.description is not None:
|
||||
feature.description = request.description
|
||||
if request.category is not None:
|
||||
feature.category = request.category
|
||||
if request.ui_location is not None:
|
||||
feature.ui_location = request.ui_location
|
||||
if request.ui_icon is not None:
|
||||
feature.ui_icon = request.ui_icon
|
||||
if request.ui_route is not None:
|
||||
feature.ui_route = request.ui_route
|
||||
if request.ui_badge_text is not None:
|
||||
feature.ui_badge_text = request.ui_badge_text
|
||||
if request.is_active is not None:
|
||||
feature.is_active = request.is_active
|
||||
if request.is_visible is not None:
|
||||
feature.is_visible = request.is_visible
|
||||
if request.display_order is not None:
|
||||
feature.display_order = request.display_order
|
||||
|
||||
# Update minimum tier if provided
|
||||
if request.minimum_tier_code is not None:
|
||||
if request.minimum_tier_code == "":
|
||||
feature.minimum_tier_id = None
|
||||
else:
|
||||
tier = (
|
||||
db.query(SubscriptionTier)
|
||||
.filter(SubscriptionTier.code == request.minimum_tier_code)
|
||||
.first()
|
||||
)
|
||||
if not tier:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Tier '{request.minimum_tier_code}' not found",
|
||||
)
|
||||
feature.minimum_tier_id = tier.id
|
||||
|
||||
db.commit()
|
||||
db.refresh(feature)
|
||||
|
||||
logger.info(f"Updated feature {feature_code} by admin {current_user.id}")
|
||||
|
||||
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,
|
||||
)
|
||||
|
||||
|
||||
@router.put("/tiers/{tier_code}/features", response_model=TierFeaturesResponse)
|
||||
def update_tier_features(
|
||||
tier_code: str,
|
||||
request: UpdateTierFeaturesRequest,
|
||||
current_user: User = Depends(get_current_admin_api),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""Update features assigned to a tier."""
|
||||
try:
|
||||
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 []),
|
||||
)
|
||||
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
|
||||
@router.get("/tiers/{tier_code}/features")
|
||||
def get_tier_features(
|
||||
tier_code: str,
|
||||
current_user: User = Depends(get_current_admin_api),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""Get features assigned to a specific tier."""
|
||||
tier = db.query(SubscriptionTier).filter(SubscriptionTier.code == tier_code).first()
|
||||
|
||||
if not tier:
|
||||
raise HTTPException(status_code=404, detail=f"Tier '{tier_code}' not found")
|
||||
|
||||
# Get full feature details for the tier's features
|
||||
feature_codes = tier.features or []
|
||||
features = (
|
||||
db.query(Feature)
|
||||
.filter(Feature.code.in_(feature_codes))
|
||||
.order_by(Feature.category, Feature.display_order)
|
||||
.all()
|
||||
)
|
||||
|
||||
return {
|
||||
"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),
|
||||
}
|
||||
4
app/api/v1/vendor/__init__.py
vendored
4
app/api/v1/vendor/__init__.py
vendored
@@ -20,6 +20,7 @@ from . import (
|
||||
content_pages,
|
||||
customers,
|
||||
dashboard,
|
||||
features,
|
||||
info,
|
||||
inventory,
|
||||
invoices,
|
||||
@@ -36,6 +37,7 @@ from . import (
|
||||
profile,
|
||||
settings,
|
||||
team,
|
||||
usage,
|
||||
)
|
||||
|
||||
# Create vendor router
|
||||
@@ -77,6 +79,8 @@ router.include_router(notifications.router, tags=["vendor-notifications"])
|
||||
router.include_router(messages.router, tags=["vendor-messages"])
|
||||
router.include_router(analytics.router, tags=["vendor-analytics"])
|
||||
router.include_router(billing.router, tags=["vendor-billing"])
|
||||
router.include_router(features.router, tags=["vendor-features"])
|
||||
router.include_router(usage.router, tags=["vendor-usage"])
|
||||
|
||||
# Content pages management
|
||||
router.include_router(
|
||||
|
||||
7
app/api/v1/vendor/analytics.py
vendored
7
app/api/v1/vendor/analytics.py
vendored
@@ -4,6 +4,10 @@ Vendor analytics and reporting endpoints.
|
||||
|
||||
Vendor Context: Uses token_vendor_id from JWT token (authenticated vendor API pattern).
|
||||
The get_current_vendor_api dependency guarantees token_vendor_id is present.
|
||||
|
||||
Feature Requirements:
|
||||
- basic_reports: Basic analytics (Essential tier)
|
||||
- analytics_dashboard: Advanced analytics (Business tier)
|
||||
"""
|
||||
|
||||
import logging
|
||||
@@ -13,7 +17,9 @@ from sqlalchemy.orm import Session
|
||||
|
||||
from app.api.deps import get_current_vendor_api
|
||||
from app.core.database import get_db
|
||||
from app.core.feature_gate import RequireFeature
|
||||
from app.services.stats_service import stats_service
|
||||
from models.database.feature import FeatureCode
|
||||
from models.database.user import User
|
||||
from models.schema.stats import (
|
||||
VendorAnalyticsCatalog,
|
||||
@@ -31,6 +37,7 @@ def get_vendor_analytics(
|
||||
period: str = Query("30d", description="Time period: 7d, 30d, 90d, 1y"),
|
||||
current_user: User = Depends(get_current_vendor_api),
|
||||
db: Session = Depends(get_db),
|
||||
_: None = Depends(RequireFeature(FeatureCode.BASIC_REPORTS, FeatureCode.ANALYTICS_DASHBOARD)),
|
||||
):
|
||||
"""Get vendor analytics data for specified time period."""
|
||||
data = stats_service.get_vendor_analytics(db, current_user.token_vendor_id, period)
|
||||
|
||||
340
app/api/v1/vendor/features.py
vendored
Normal file
340
app/api/v1/vendor/features.py
vendored
Normal file
@@ -0,0 +1,340 @@
|
||||
# app/api/v1/vendor/features.py
|
||||
"""
|
||||
Vendor features API endpoints.
|
||||
|
||||
Provides feature availability information for the frontend to:
|
||||
- Show/hide UI elements based on tier
|
||||
- Display upgrade prompts for unavailable features
|
||||
- Load feature metadata for dynamic rendering
|
||||
|
||||
Endpoints:
|
||||
- GET /features/available - List of feature codes (for quick checks)
|
||||
- GET /features - Full feature list with availability and metadata
|
||||
- GET /features/{code} - Single feature details with upgrade info
|
||||
- GET /features/categories - List feature categories
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.api.deps import get_current_vendor_api
|
||||
from app.core.database import get_db
|
||||
from app.services.feature_service import feature_service
|
||||
from models.database.user import User
|
||||
|
||||
router = APIRouter(prefix="/features")
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Response Schemas
|
||||
# ============================================================================
|
||||
|
||||
|
||||
class FeatureCodeListResponse(BaseModel):
|
||||
"""Simple list of available feature codes for quick checks."""
|
||||
|
||||
features: list[str]
|
||||
tier_code: str
|
||||
tier_name: str
|
||||
|
||||
|
||||
class FeatureResponse(BaseModel):
|
||||
"""Full feature information."""
|
||||
|
||||
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
|
||||
is_available: bool
|
||||
minimum_tier_code: str | None = None
|
||||
minimum_tier_name: str | None = None
|
||||
|
||||
|
||||
class FeatureListResponse(BaseModel):
|
||||
"""List of features with metadata."""
|
||||
|
||||
features: list[FeatureResponse]
|
||||
available_count: int
|
||||
total_count: int
|
||||
tier_code: str
|
||||
tier_name: str
|
||||
|
||||
|
||||
class FeatureDetailResponse(BaseModel):
|
||||
"""Single feature detail with upgrade info."""
|
||||
|
||||
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
|
||||
is_available: bool
|
||||
# Upgrade info (only if not available)
|
||||
upgrade_tier_code: str | None = None
|
||||
upgrade_tier_name: str | None = None
|
||||
upgrade_tier_price_monthly_cents: int | None = None
|
||||
|
||||
|
||||
class CategoryListResponse(BaseModel):
|
||||
"""List of feature categories."""
|
||||
|
||||
categories: list[str]
|
||||
|
||||
|
||||
class FeatureGroupedResponse(BaseModel):
|
||||
"""Features grouped by category."""
|
||||
|
||||
categories: dict[str, list[FeatureResponse]]
|
||||
available_count: int
|
||||
total_count: int
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Endpoints
|
||||
# ============================================================================
|
||||
|
||||
|
||||
@router.get("/available", response_model=FeatureCodeListResponse)
|
||||
def get_available_features(
|
||||
current_user: User = Depends(get_current_vendor_api),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""
|
||||
Get list of feature codes available to vendor.
|
||||
|
||||
This is a lightweight endpoint for quick feature checks.
|
||||
Use this to populate a frontend feature store on app init.
|
||||
|
||||
Returns:
|
||||
List of feature codes the vendor has access to
|
||||
"""
|
||||
vendor_id = current_user.token_vendor_id
|
||||
|
||||
# Get subscription for tier info
|
||||
from app.services.subscription_service import subscription_service
|
||||
|
||||
subscription = subscription_service.get_or_create_subscription(db, vendor_id)
|
||||
tier = subscription.tier_obj
|
||||
|
||||
# Get available features
|
||||
feature_codes = feature_service.get_available_feature_codes(db, vendor_id)
|
||||
|
||||
return FeatureCodeListResponse(
|
||||
features=feature_codes,
|
||||
tier_code=subscription.tier,
|
||||
tier_name=tier.name if tier else subscription.tier.title(),
|
||||
)
|
||||
|
||||
|
||||
@router.get("", response_model=FeatureListResponse)
|
||||
def get_features(
|
||||
category: str | None = Query(None, description="Filter by category"),
|
||||
include_unavailable: bool = Query(True, description="Include features not available to vendor"),
|
||||
current_user: User = Depends(get_current_vendor_api),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""
|
||||
Get all features with availability status and metadata.
|
||||
|
||||
This is a comprehensive endpoint for building feature-gated UIs.
|
||||
Each feature includes:
|
||||
- Availability status
|
||||
- UI metadata (icon, route, location)
|
||||
- Minimum tier required
|
||||
|
||||
Args:
|
||||
category: Filter to specific category (orders, inventory, etc.)
|
||||
include_unavailable: Whether to include locked features
|
||||
|
||||
Returns:
|
||||
List of features with metadata and availability
|
||||
"""
|
||||
vendor_id = current_user.token_vendor_id
|
||||
|
||||
# Get subscription for tier info
|
||||
from app.services.subscription_service import subscription_service
|
||||
|
||||
subscription = subscription_service.get_or_create_subscription(db, vendor_id)
|
||||
tier = subscription.tier_obj
|
||||
|
||||
# Get features
|
||||
features = feature_service.get_vendor_features(
|
||||
db,
|
||||
vendor_id,
|
||||
category=category,
|
||||
include_unavailable=include_unavailable,
|
||||
)
|
||||
|
||||
available_count = sum(1 for f in features if f.is_available)
|
||||
|
||||
return FeatureListResponse(
|
||||
features=[
|
||||
FeatureResponse(
|
||||
code=f.code,
|
||||
name=f.name,
|
||||
description=f.description,
|
||||
category=f.category,
|
||||
ui_location=f.ui_location,
|
||||
ui_icon=f.ui_icon,
|
||||
ui_route=f.ui_route,
|
||||
ui_badge_text=f.ui_badge_text,
|
||||
is_available=f.is_available,
|
||||
minimum_tier_code=f.minimum_tier_code,
|
||||
minimum_tier_name=f.minimum_tier_name,
|
||||
)
|
||||
for f in features
|
||||
],
|
||||
available_count=available_count,
|
||||
total_count=len(features),
|
||||
tier_code=subscription.tier,
|
||||
tier_name=tier.name if tier else subscription.tier.title(),
|
||||
)
|
||||
|
||||
|
||||
@router.get("/categories", response_model=CategoryListResponse)
|
||||
def get_feature_categories(
|
||||
current_user: User = Depends(get_current_vendor_api),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""
|
||||
Get list of feature categories.
|
||||
|
||||
Returns:
|
||||
List of category names
|
||||
"""
|
||||
categories = feature_service.get_categories(db)
|
||||
return CategoryListResponse(categories=categories)
|
||||
|
||||
|
||||
@router.get("/grouped", response_model=FeatureGroupedResponse)
|
||||
def get_features_grouped(
|
||||
current_user: User = Depends(get_current_vendor_api),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""
|
||||
Get features grouped by category.
|
||||
|
||||
Useful for rendering feature comparison tables or settings pages.
|
||||
"""
|
||||
vendor_id = current_user.token_vendor_id
|
||||
|
||||
grouped = feature_service.get_features_grouped_by_category(db, vendor_id)
|
||||
|
||||
# Convert to response format
|
||||
categories_response = {}
|
||||
total = 0
|
||||
available = 0
|
||||
|
||||
for category, features in grouped.items():
|
||||
categories_response[category] = [
|
||||
FeatureResponse(
|
||||
code=f.code,
|
||||
name=f.name,
|
||||
description=f.description,
|
||||
category=f.category,
|
||||
ui_location=f.ui_location,
|
||||
ui_icon=f.ui_icon,
|
||||
ui_route=f.ui_route,
|
||||
ui_badge_text=f.ui_badge_text,
|
||||
is_available=f.is_available,
|
||||
minimum_tier_code=f.minimum_tier_code,
|
||||
minimum_tier_name=f.minimum_tier_name,
|
||||
)
|
||||
for f in features
|
||||
]
|
||||
total += len(features)
|
||||
available += sum(1 for f in features if f.is_available)
|
||||
|
||||
return FeatureGroupedResponse(
|
||||
categories=categories_response,
|
||||
available_count=available,
|
||||
total_count=total,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/{feature_code}", response_model=FeatureDetailResponse)
|
||||
def get_feature_detail(
|
||||
feature_code: str,
|
||||
current_user: User = Depends(get_current_vendor_api),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""
|
||||
Get detailed information about a specific feature.
|
||||
|
||||
Includes upgrade information if the feature is not available.
|
||||
Use this for upgrade prompts and feature explanation modals.
|
||||
|
||||
Args:
|
||||
feature_code: The feature code
|
||||
|
||||
Returns:
|
||||
Feature details with upgrade info if locked
|
||||
"""
|
||||
vendor_id = current_user.token_vendor_id
|
||||
|
||||
# Get feature
|
||||
feature = feature_service.get_feature_by_code(db, feature_code)
|
||||
if not feature:
|
||||
raise HTTPException(status_code=404, detail=f"Feature '{feature_code}' not found")
|
||||
|
||||
# Check availability
|
||||
is_available = feature_service.has_feature(db, vendor_id, feature_code)
|
||||
|
||||
# Get upgrade info if not available
|
||||
upgrade_tier_code = None
|
||||
upgrade_tier_name = None
|
||||
upgrade_tier_price = None
|
||||
|
||||
if not is_available:
|
||||
upgrade_info = feature_service.get_feature_upgrade_info(db, feature_code)
|
||||
if upgrade_info:
|
||||
upgrade_tier_code = upgrade_info.required_tier_code
|
||||
upgrade_tier_name = upgrade_info.required_tier_name
|
||||
upgrade_tier_price = upgrade_info.required_tier_price_monthly_cents
|
||||
|
||||
return FeatureDetailResponse(
|
||||
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,
|
||||
is_available=is_available,
|
||||
upgrade_tier_code=upgrade_tier_code,
|
||||
upgrade_tier_name=upgrade_tier_name,
|
||||
upgrade_tier_price_monthly_cents=upgrade_tier_price,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/check/{feature_code}")
|
||||
def check_feature(
|
||||
feature_code: str,
|
||||
current_user: User = Depends(get_current_vendor_api),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""
|
||||
Quick check if vendor has access to a feature.
|
||||
|
||||
Returns simple boolean response for inline checks.
|
||||
|
||||
Args:
|
||||
feature_code: The feature code
|
||||
|
||||
Returns:
|
||||
{"has_feature": true/false}
|
||||
"""
|
||||
vendor_id = current_user.token_vendor_id
|
||||
has_feature = feature_service.has_feature(db, vendor_id, feature_code)
|
||||
|
||||
return {"has_feature": has_feature, "feature_code": feature_code}
|
||||
10
app/api/v1/vendor/invoices.py
vendored
10
app/api/v1/vendor/invoices.py
vendored
@@ -16,6 +16,12 @@ Endpoints:
|
||||
- POST /invoices/settings - Create invoice settings
|
||||
- PUT /invoices/settings - Update invoice settings
|
||||
- GET /invoices/stats - Get invoice statistics
|
||||
|
||||
Feature Requirements:
|
||||
- invoice_lu: Basic Luxembourg invoicing (Essential tier)
|
||||
- invoice_eu_vat: EU VAT support (Professional tier)
|
||||
- invoice_bulk: Bulk invoicing (Business tier)
|
||||
- accounting_export: Export to accounting software (Business tier)
|
||||
"""
|
||||
|
||||
import logging
|
||||
@@ -27,6 +33,7 @@ from sqlalchemy.orm import Session
|
||||
|
||||
from app.api.deps import get_current_vendor_api
|
||||
from app.core.database import get_db
|
||||
from app.core.feature_gate import RequireFeature
|
||||
from app.exceptions.invoice import (
|
||||
InvoiceNotFoundException,
|
||||
InvoicePDFGenerationException,
|
||||
@@ -34,6 +41,7 @@ from app.exceptions.invoice import (
|
||||
InvoiceSettingsNotFoundException,
|
||||
)
|
||||
from app.services.invoice_service import invoice_service
|
||||
from models.database.feature import FeatureCode
|
||||
from models.database.user import User
|
||||
from models.schema.invoice import (
|
||||
InvoiceCreate,
|
||||
@@ -61,11 +69,13 @@ logger = logging.getLogger(__name__)
|
||||
def get_invoice_settings(
|
||||
current_user: User = Depends(get_current_vendor_api),
|
||||
db: Session = Depends(get_db),
|
||||
_: None = Depends(RequireFeature(FeatureCode.INVOICE_LU)),
|
||||
):
|
||||
"""
|
||||
Get vendor invoice settings.
|
||||
|
||||
Returns null if settings not yet configured.
|
||||
Requires: invoice_lu feature (Essential tier)
|
||||
"""
|
||||
settings = invoice_service.get_settings(db, current_user.token_vendor_id)
|
||||
if settings:
|
||||
|
||||
380
app/api/v1/vendor/usage.py
vendored
Normal file
380
app/api/v1/vendor/usage.py
vendored
Normal file
@@ -0,0 +1,380 @@
|
||||
# app/api/v1/vendor/usage.py
|
||||
"""
|
||||
Vendor usage and limits API endpoints.
|
||||
|
||||
Provides endpoints for:
|
||||
- Current usage vs limits
|
||||
- Upgrade recommendations
|
||||
- Approaching limit warnings
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy import func
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.api.deps import get_current_vendor_api
|
||||
from app.core.database import get_db
|
||||
from app.services.subscription_service import subscription_service
|
||||
from models.database.product import Product
|
||||
from models.database.subscription import SubscriptionTier
|
||||
from models.database.user import User
|
||||
from models.database.vendor import VendorUser
|
||||
|
||||
router = APIRouter(prefix="/usage")
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Response Schemas
|
||||
# ============================================================================
|
||||
|
||||
|
||||
class UsageMetric(BaseModel):
|
||||
"""Single usage metric."""
|
||||
|
||||
name: str
|
||||
current: int
|
||||
limit: int | None # None = unlimited
|
||||
percentage: float # 0-100, or 0 if unlimited
|
||||
is_unlimited: bool
|
||||
is_at_limit: bool
|
||||
is_approaching_limit: bool # >= 80%
|
||||
|
||||
|
||||
class TierInfo(BaseModel):
|
||||
"""Current tier information."""
|
||||
|
||||
code: str
|
||||
name: str
|
||||
price_monthly_cents: int
|
||||
is_highest_tier: bool
|
||||
|
||||
|
||||
class UpgradeTierInfo(BaseModel):
|
||||
"""Next tier upgrade information."""
|
||||
|
||||
code: str
|
||||
name: str
|
||||
price_monthly_cents: int
|
||||
price_increase_cents: int
|
||||
benefits: list[str]
|
||||
|
||||
|
||||
class UsageResponse(BaseModel):
|
||||
"""Full usage response with limits and upgrade info."""
|
||||
|
||||
tier: TierInfo
|
||||
usage: list[UsageMetric]
|
||||
has_limits_approaching: bool
|
||||
has_limits_reached: bool
|
||||
upgrade_available: bool
|
||||
upgrade_tier: UpgradeTierInfo | None = None
|
||||
upgrade_reasons: list[str]
|
||||
|
||||
|
||||
class LimitCheckResponse(BaseModel):
|
||||
"""Response for checking a specific limit."""
|
||||
|
||||
limit_type: str
|
||||
can_proceed: bool
|
||||
current: int
|
||||
limit: int | None
|
||||
percentage: float
|
||||
message: str | None = None
|
||||
upgrade_tier_code: str | None = None
|
||||
upgrade_tier_name: str | None = None
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Endpoints
|
||||
# ============================================================================
|
||||
|
||||
|
||||
@router.get("", response_model=UsageResponse)
|
||||
def get_usage(
|
||||
current_user: User = Depends(get_current_vendor_api),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""
|
||||
Get current usage, limits, and upgrade recommendations.
|
||||
|
||||
Returns comprehensive usage info for displaying in dashboard
|
||||
and determining when to show upgrade prompts.
|
||||
"""
|
||||
vendor_id = current_user.token_vendor_id
|
||||
|
||||
# Get subscription
|
||||
subscription = subscription_service.get_or_create_subscription(db, vendor_id)
|
||||
|
||||
# Get current tier
|
||||
tier = subscription.tier_obj
|
||||
if not tier:
|
||||
tier = (
|
||||
db.query(SubscriptionTier)
|
||||
.filter(SubscriptionTier.code == subscription.tier)
|
||||
.first()
|
||||
)
|
||||
|
||||
# Calculate usage metrics
|
||||
usage_metrics = []
|
||||
|
||||
# Orders this period
|
||||
orders_current = subscription.orders_this_period or 0
|
||||
orders_limit = subscription.orders_limit
|
||||
orders_unlimited = orders_limit is None or orders_limit < 0
|
||||
orders_percentage = 0 if orders_unlimited else (orders_current / orders_limit * 100 if orders_limit > 0 else 100)
|
||||
|
||||
usage_metrics.append(
|
||||
UsageMetric(
|
||||
name="orders",
|
||||
current=orders_current,
|
||||
limit=None if orders_unlimited else orders_limit,
|
||||
percentage=orders_percentage,
|
||||
is_unlimited=orders_unlimited,
|
||||
is_at_limit=not orders_unlimited and orders_current >= orders_limit,
|
||||
is_approaching_limit=not orders_unlimited and orders_percentage >= 80,
|
||||
)
|
||||
)
|
||||
|
||||
# Products
|
||||
products_count = (
|
||||
db.query(func.count(Product.id))
|
||||
.filter(Product.vendor_id == vendor_id)
|
||||
.scalar()
|
||||
or 0
|
||||
)
|
||||
products_limit = subscription.products_limit
|
||||
products_unlimited = products_limit is None or products_limit < 0
|
||||
products_percentage = 0 if products_unlimited else (products_count / products_limit * 100 if products_limit > 0 else 100)
|
||||
|
||||
usage_metrics.append(
|
||||
UsageMetric(
|
||||
name="products",
|
||||
current=products_count,
|
||||
limit=None if products_unlimited else products_limit,
|
||||
percentage=products_percentage,
|
||||
is_unlimited=products_unlimited,
|
||||
is_at_limit=not products_unlimited and products_count >= products_limit,
|
||||
is_approaching_limit=not products_unlimited and products_percentage >= 80,
|
||||
)
|
||||
)
|
||||
|
||||
# Team members
|
||||
team_count = (
|
||||
db.query(func.count(VendorUser.id))
|
||||
.filter(VendorUser.vendor_id == vendor_id, VendorUser.is_active == True) # noqa: E712
|
||||
.scalar()
|
||||
or 0
|
||||
)
|
||||
team_limit = subscription.team_members_limit
|
||||
team_unlimited = team_limit is None or team_limit < 0
|
||||
team_percentage = 0 if team_unlimited else (team_count / team_limit * 100 if team_limit > 0 else 100)
|
||||
|
||||
usage_metrics.append(
|
||||
UsageMetric(
|
||||
name="team_members",
|
||||
current=team_count,
|
||||
limit=None if team_unlimited else team_limit,
|
||||
percentage=team_percentage,
|
||||
is_unlimited=team_unlimited,
|
||||
is_at_limit=not team_unlimited and team_count >= team_limit,
|
||||
is_approaching_limit=not team_unlimited and team_percentage >= 80,
|
||||
)
|
||||
)
|
||||
|
||||
# Check for approaching/reached limits
|
||||
has_limits_approaching = any(m.is_approaching_limit for m in usage_metrics)
|
||||
has_limits_reached = any(m.is_at_limit for m in usage_metrics)
|
||||
|
||||
# Get next tier for upgrade
|
||||
all_tiers = (
|
||||
db.query(SubscriptionTier)
|
||||
.filter(SubscriptionTier.is_active == True) # noqa: E712
|
||||
.order_by(SubscriptionTier.display_order)
|
||||
.all()
|
||||
)
|
||||
|
||||
current_tier_order = tier.display_order if tier else 0
|
||||
next_tier = None
|
||||
for t in all_tiers:
|
||||
if t.display_order > current_tier_order:
|
||||
next_tier = t
|
||||
break
|
||||
|
||||
is_highest_tier = next_tier is None
|
||||
|
||||
# Build upgrade info
|
||||
upgrade_tier_info = None
|
||||
upgrade_reasons = []
|
||||
|
||||
if next_tier:
|
||||
# Calculate benefits
|
||||
benefits = []
|
||||
if next_tier.orders_per_month and (not tier or (tier.orders_per_month and next_tier.orders_per_month > tier.orders_per_month)):
|
||||
if next_tier.orders_per_month < 0:
|
||||
benefits.append("Unlimited orders per month")
|
||||
else:
|
||||
benefits.append(f"{next_tier.orders_per_month:,} orders/month")
|
||||
|
||||
if next_tier.products_limit and (not tier or (tier.products_limit and next_tier.products_limit > tier.products_limit)):
|
||||
if next_tier.products_limit < 0:
|
||||
benefits.append("Unlimited products")
|
||||
else:
|
||||
benefits.append(f"{next_tier.products_limit:,} products")
|
||||
|
||||
if next_tier.team_members and (not tier or (tier.team_members and next_tier.team_members > tier.team_members)):
|
||||
if next_tier.team_members < 0:
|
||||
benefits.append("Unlimited team members")
|
||||
else:
|
||||
benefits.append(f"{next_tier.team_members} team members")
|
||||
|
||||
# Add feature benefits
|
||||
current_features = set(tier.features) if tier and tier.features else set()
|
||||
next_features = set(next_tier.features) if next_tier.features else set()
|
||||
new_features = next_features - current_features
|
||||
|
||||
feature_names = {
|
||||
"analytics_dashboard": "Advanced Analytics",
|
||||
"api_access": "API Access",
|
||||
"automation_rules": "Automation Rules",
|
||||
"team_roles": "Team Roles & Permissions",
|
||||
"custom_domain": "Custom Domain",
|
||||
"webhooks": "Webhooks",
|
||||
"accounting_export": "Accounting Export",
|
||||
}
|
||||
for feature in list(new_features)[:3]: # Show top 3
|
||||
if feature in feature_names:
|
||||
benefits.append(feature_names[feature])
|
||||
|
||||
current_price = tier.price_monthly_cents if tier else 0
|
||||
upgrade_tier_info = UpgradeTierInfo(
|
||||
code=next_tier.code,
|
||||
name=next_tier.name,
|
||||
price_monthly_cents=next_tier.price_monthly_cents,
|
||||
price_increase_cents=next_tier.price_monthly_cents - current_price,
|
||||
benefits=benefits,
|
||||
)
|
||||
|
||||
# Build upgrade reasons
|
||||
if has_limits_reached:
|
||||
for m in usage_metrics:
|
||||
if m.is_at_limit:
|
||||
upgrade_reasons.append(f"You've reached your {m.name.replace('_', ' ')} limit")
|
||||
elif has_limits_approaching:
|
||||
for m in usage_metrics:
|
||||
if m.is_approaching_limit:
|
||||
upgrade_reasons.append(f"You're approaching your {m.name.replace('_', ' ')} limit ({int(m.percentage)}%)")
|
||||
|
||||
return UsageResponse(
|
||||
tier=TierInfo(
|
||||
code=tier.code if tier else subscription.tier,
|
||||
name=tier.name if tier else subscription.tier.title(),
|
||||
price_monthly_cents=tier.price_monthly_cents if tier else 0,
|
||||
is_highest_tier=is_highest_tier,
|
||||
),
|
||||
usage=usage_metrics,
|
||||
has_limits_approaching=has_limits_approaching,
|
||||
has_limits_reached=has_limits_reached,
|
||||
upgrade_available=not is_highest_tier,
|
||||
upgrade_tier=upgrade_tier_info,
|
||||
upgrade_reasons=upgrade_reasons,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/check/{limit_type}", response_model=LimitCheckResponse)
|
||||
def check_limit(
|
||||
limit_type: str,
|
||||
current_user: User = Depends(get_current_vendor_api),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""
|
||||
Check a specific limit before performing an action.
|
||||
|
||||
Use this before creating orders, products, or inviting team members.
|
||||
|
||||
Args:
|
||||
limit_type: One of "orders", "products", "team_members"
|
||||
|
||||
Returns:
|
||||
Whether the action can proceed and upgrade info if not
|
||||
"""
|
||||
vendor_id = current_user.token_vendor_id
|
||||
|
||||
if limit_type == "orders":
|
||||
can_proceed, message = subscription_service.can_create_order(db, vendor_id)
|
||||
subscription = subscription_service.get_subscription(db, vendor_id)
|
||||
current = subscription.orders_this_period if subscription else 0
|
||||
limit = subscription.orders_limit if subscription else 0
|
||||
|
||||
elif limit_type == "products":
|
||||
can_proceed, message = subscription_service.can_add_product(db, vendor_id)
|
||||
subscription = subscription_service.get_subscription(db, vendor_id)
|
||||
current = (
|
||||
db.query(func.count(Product.id))
|
||||
.filter(Product.vendor_id == vendor_id)
|
||||
.scalar()
|
||||
or 0
|
||||
)
|
||||
limit = subscription.products_limit if subscription else 0
|
||||
|
||||
elif limit_type == "team_members":
|
||||
can_proceed, message = subscription_service.can_add_team_member(db, vendor_id)
|
||||
subscription = subscription_service.get_subscription(db, vendor_id)
|
||||
current = (
|
||||
db.query(func.count(VendorUser.id))
|
||||
.filter(VendorUser.vendor_id == vendor_id, VendorUser.is_active == True) # noqa: E712
|
||||
.scalar()
|
||||
or 0
|
||||
)
|
||||
limit = subscription.team_members_limit if subscription else 0
|
||||
|
||||
else:
|
||||
return LimitCheckResponse(
|
||||
limit_type=limit_type,
|
||||
can_proceed=True,
|
||||
current=0,
|
||||
limit=None,
|
||||
percentage=0,
|
||||
message=f"Unknown limit type: {limit_type}",
|
||||
)
|
||||
|
||||
# Calculate percentage
|
||||
is_unlimited = limit is None or limit < 0
|
||||
percentage = 0 if is_unlimited else (current / limit * 100 if limit > 0 else 100)
|
||||
|
||||
# Get upgrade info if at limit
|
||||
upgrade_tier_code = None
|
||||
upgrade_tier_name = None
|
||||
|
||||
if not can_proceed:
|
||||
subscription = subscription_service.get_subscription(db, vendor_id)
|
||||
current_tier = subscription.tier_obj if subscription else None
|
||||
|
||||
if current_tier:
|
||||
next_tier = (
|
||||
db.query(SubscriptionTier)
|
||||
.filter(
|
||||
SubscriptionTier.is_active == True, # noqa: E712
|
||||
SubscriptionTier.display_order > current_tier.display_order,
|
||||
)
|
||||
.order_by(SubscriptionTier.display_order)
|
||||
.first()
|
||||
)
|
||||
|
||||
if next_tier:
|
||||
upgrade_tier_code = next_tier.code
|
||||
upgrade_tier_name = next_tier.name
|
||||
|
||||
return LimitCheckResponse(
|
||||
limit_type=limit_type,
|
||||
can_proceed=can_proceed,
|
||||
current=current,
|
||||
limit=None if is_unlimited else limit,
|
||||
percentage=percentage,
|
||||
message=message,
|
||||
upgrade_tier_code=upgrade_tier_code,
|
||||
upgrade_tier_name=upgrade_tier_name,
|
||||
)
|
||||
Reference in New Issue
Block a user