feat(loyalty): implement Phase 2 - company-wide points system
Complete implementation of loyalty module Phase 2 features: Database & Models: - Add company_id to LoyaltyProgram for chain-wide loyalty - Add company_id to LoyaltyCard for multi-location support - Add CompanyLoyaltySettings model for admin-controlled settings - Add points expiration, welcome bonus, and minimum redemption fields - Add POINTS_EXPIRED, WELCOME_BONUS transaction types Services: - Update program_service for company-based queries - Update card_service with enrollment and welcome bonus - Update points_service with void_points for returns - Update stamp_service for company context - Update pin_service for company-wide operations API Endpoints: - Admin: Program listing with stats, company detail views - Vendor: Terminal operations, card management, settings - Storefront: Customer card/transactions, self-enrollment UI Templates: - Admin: Programs dashboard, company detail, settings - Vendor: Terminal, cards list, card detail, settings, stats, enrollment - Storefront: Dashboard, history, enrollment, success pages Background Tasks: - Point expiration task (daily, based on inactivity) - Wallet sync task (hourly) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
@@ -3,13 +3,14 @@
|
||||
Loyalty module admin routes.
|
||||
|
||||
Platform admin endpoints for:
|
||||
- Viewing all loyalty programs
|
||||
- Viewing all loyalty programs (company-based)
|
||||
- Company loyalty settings management
|
||||
- Platform-wide analytics
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from fastapi import APIRouter, Depends, HTTPException, Path, Query
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.api.deps import get_current_admin_api, require_module_access
|
||||
@@ -19,6 +20,9 @@ from app.modules.loyalty.schemas import (
|
||||
ProgramListResponse,
|
||||
ProgramResponse,
|
||||
ProgramStatsResponse,
|
||||
CompanyStatsResponse,
|
||||
CompanySettingsResponse,
|
||||
CompanySettingsUpdate,
|
||||
)
|
||||
from app.modules.loyalty.services import program_service
|
||||
from app.modules.tenancy.models import User
|
||||
@@ -42,15 +46,22 @@ def list_programs(
|
||||
skip: int = Query(0, ge=0),
|
||||
limit: int = Query(50, ge=1, le=100),
|
||||
is_active: bool | None = Query(None),
|
||||
search: str | None = Query(None, description="Search by company name"),
|
||||
current_user: User = Depends(get_current_admin_api),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""List all loyalty programs (platform admin)."""
|
||||
from sqlalchemy import func
|
||||
|
||||
from app.modules.loyalty.models import LoyaltyCard, LoyaltyTransaction
|
||||
from app.modules.tenancy.models import Company
|
||||
|
||||
programs, total = program_service.list_programs(
|
||||
db,
|
||||
skip=skip,
|
||||
limit=limit,
|
||||
is_active=is_active,
|
||||
search=search,
|
||||
)
|
||||
|
||||
program_responses = []
|
||||
@@ -59,6 +70,47 @@ def list_programs(
|
||||
response.is_stamps_enabled = program.is_stamps_enabled
|
||||
response.is_points_enabled = program.is_points_enabled
|
||||
response.display_name = program.display_name
|
||||
|
||||
# Get company name
|
||||
company = db.query(Company).filter(Company.id == program.company_id).first()
|
||||
if company:
|
||||
response.company_name = company.name
|
||||
|
||||
# Get basic stats for this program
|
||||
response.total_cards = (
|
||||
db.query(func.count(LoyaltyCard.id))
|
||||
.filter(LoyaltyCard.company_id == program.company_id)
|
||||
.scalar()
|
||||
or 0
|
||||
)
|
||||
response.active_cards = (
|
||||
db.query(func.count(LoyaltyCard.id))
|
||||
.filter(
|
||||
LoyaltyCard.company_id == program.company_id,
|
||||
LoyaltyCard.is_active == True,
|
||||
)
|
||||
.scalar()
|
||||
or 0
|
||||
)
|
||||
response.total_points_issued = (
|
||||
db.query(func.sum(LoyaltyTransaction.points_delta))
|
||||
.filter(
|
||||
LoyaltyTransaction.company_id == program.company_id,
|
||||
LoyaltyTransaction.points_delta > 0,
|
||||
)
|
||||
.scalar()
|
||||
or 0
|
||||
)
|
||||
response.total_points_redeemed = (
|
||||
db.query(func.sum(func.abs(LoyaltyTransaction.points_delta)))
|
||||
.filter(
|
||||
LoyaltyTransaction.company_id == program.company_id,
|
||||
LoyaltyTransaction.points_delta < 0,
|
||||
)
|
||||
.scalar()
|
||||
or 0
|
||||
)
|
||||
|
||||
program_responses.append(response)
|
||||
|
||||
return ProgramListResponse(programs=program_responses, total=total)
|
||||
@@ -92,6 +144,60 @@ def get_program_stats(
|
||||
return ProgramStatsResponse(**stats)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Company Management
|
||||
# =============================================================================
|
||||
|
||||
|
||||
@admin_router.get("/companies/{company_id}/stats", response_model=CompanyStatsResponse)
|
||||
def get_company_stats(
|
||||
company_id: int = Path(..., gt=0),
|
||||
current_user: User = Depends(get_current_admin_api),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""Get company-wide loyalty statistics across all locations."""
|
||||
stats = program_service.get_company_stats(db, company_id)
|
||||
if "error" in stats:
|
||||
raise HTTPException(status_code=404, detail=stats["error"])
|
||||
|
||||
return CompanyStatsResponse(**stats)
|
||||
|
||||
|
||||
@admin_router.get("/companies/{company_id}/settings", response_model=CompanySettingsResponse)
|
||||
def get_company_settings(
|
||||
company_id: int = Path(..., gt=0),
|
||||
current_user: User = Depends(get_current_admin_api),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""Get company loyalty settings."""
|
||||
settings = program_service.get_or_create_company_settings(db, company_id)
|
||||
return CompanySettingsResponse.model_validate(settings)
|
||||
|
||||
|
||||
@admin_router.patch("/companies/{company_id}/settings", response_model=CompanySettingsResponse)
|
||||
def update_company_settings(
|
||||
data: CompanySettingsUpdate,
|
||||
company_id: int = Path(..., gt=0),
|
||||
current_user: User = Depends(get_current_admin_api),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""Update company loyalty settings (admin only)."""
|
||||
from app.modules.loyalty.models import CompanyLoyaltySettings
|
||||
|
||||
settings = program_service.get_or_create_company_settings(db, company_id)
|
||||
|
||||
update_data = data.model_dump(exclude_unset=True)
|
||||
for field, value in update_data.items():
|
||||
setattr(settings, field, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(settings)
|
||||
|
||||
logger.info(f"Updated company {company_id} loyalty settings: {list(update_data.keys())}")
|
||||
|
||||
return CompanySettingsResponse.model_validate(settings)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Platform Stats
|
||||
# =============================================================================
|
||||
@@ -136,10 +242,39 @@ def get_platform_stats(
|
||||
or 0
|
||||
)
|
||||
|
||||
# Points issued/redeemed (last 30 days)
|
||||
points_issued_30d = (
|
||||
db.query(func.sum(LoyaltyTransaction.points_delta))
|
||||
.filter(
|
||||
LoyaltyTransaction.transaction_at >= thirty_days_ago,
|
||||
LoyaltyTransaction.points_delta > 0,
|
||||
)
|
||||
.scalar()
|
||||
or 0
|
||||
)
|
||||
|
||||
points_redeemed_30d = (
|
||||
db.query(func.sum(func.abs(LoyaltyTransaction.points_delta)))
|
||||
.filter(
|
||||
LoyaltyTransaction.transaction_at >= thirty_days_ago,
|
||||
LoyaltyTransaction.points_delta < 0,
|
||||
)
|
||||
.scalar()
|
||||
or 0
|
||||
)
|
||||
|
||||
# Company count with programs
|
||||
companies_with_programs = (
|
||||
db.query(func.count(func.distinct(LoyaltyProgram.company_id))).scalar() or 0
|
||||
)
|
||||
|
||||
return {
|
||||
"total_programs": total_programs,
|
||||
"active_programs": active_programs,
|
||||
"companies_with_programs": companies_with_programs,
|
||||
"total_cards": total_cards,
|
||||
"active_cards": active_cards,
|
||||
"transactions_30d": transactions_30d,
|
||||
"points_issued_30d": points_issued_30d,
|
||||
"points_redeemed_30d": points_redeemed_30d,
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user