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,
|
||||
}
|
||||
|
||||
216
app/modules/loyalty/routes/api/storefront.py
Normal file
216
app/modules/loyalty/routes/api/storefront.py
Normal file
@@ -0,0 +1,216 @@
|
||||
# app/modules/loyalty/routes/api/storefront.py
|
||||
"""
|
||||
Loyalty Module - Storefront API Routes
|
||||
|
||||
Customer-facing endpoints for:
|
||||
- View loyalty card and balance
|
||||
- View transaction history
|
||||
- Self-service enrollment
|
||||
- Get program information
|
||||
|
||||
Uses vendor from middleware context (VendorContextMiddleware).
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
from fastapi import APIRouter, Depends, Query, Request
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.api.deps import get_current_customer_api
|
||||
from app.core.database import get_db
|
||||
from app.modules.customers.schemas import CustomerContext
|
||||
from app.modules.loyalty.services import card_service, program_service
|
||||
from app.modules.loyalty.schemas import (
|
||||
CardResponse,
|
||||
CardEnrollRequest,
|
||||
TransactionListResponse,
|
||||
TransactionResponse,
|
||||
ProgramResponse,
|
||||
)
|
||||
from app.modules.tenancy.exceptions import VendorNotFoundException
|
||||
|
||||
router = APIRouter()
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Public Endpoints (No Authentication Required)
|
||||
# =============================================================================
|
||||
|
||||
|
||||
@router.get("/loyalty/program")
|
||||
def get_program_info(
|
||||
request: Request,
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""
|
||||
Get loyalty program information for current vendor.
|
||||
Public endpoint - no authentication required.
|
||||
"""
|
||||
vendor = getattr(request.state, "vendor", None)
|
||||
if not vendor:
|
||||
raise VendorNotFoundException("context", identifier_type="subdomain")
|
||||
|
||||
program = program_service.get_program_by_vendor(db, vendor.id)
|
||||
if not program:
|
||||
return None
|
||||
|
||||
response = ProgramResponse.model_validate(program)
|
||||
response.is_stamps_enabled = program.is_stamps_enabled
|
||||
response.is_points_enabled = program.is_points_enabled
|
||||
response.display_name = program.display_name
|
||||
|
||||
return response
|
||||
|
||||
|
||||
@router.post("/loyalty/enroll")
|
||||
def self_enroll(
|
||||
request: Request,
|
||||
data: CardEnrollRequest,
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""
|
||||
Self-service enrollment.
|
||||
Public endpoint - customers can enroll via QR code without authentication.
|
||||
"""
|
||||
vendor = getattr(request.state, "vendor", None)
|
||||
if not vendor:
|
||||
raise VendorNotFoundException("context", identifier_type="subdomain")
|
||||
|
||||
logger.info(f"Self-enrollment for {data.customer_email} at vendor {vendor.subdomain}")
|
||||
|
||||
card = card_service.enroll_customer(
|
||||
db,
|
||||
vendor_id=vendor.id,
|
||||
customer_email=data.customer_email,
|
||||
customer_phone=data.customer_phone,
|
||||
customer_name=data.customer_name,
|
||||
)
|
||||
|
||||
return CardResponse.model_validate(card)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Authenticated Endpoints
|
||||
# =============================================================================
|
||||
|
||||
|
||||
@router.get("/loyalty/card")
|
||||
def get_my_card(
|
||||
request: Request,
|
||||
customer: CustomerContext = Depends(get_current_customer_api),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""
|
||||
Get customer's loyalty card and program info.
|
||||
Returns card details, program info, and available rewards.
|
||||
"""
|
||||
vendor = getattr(request.state, "vendor", None)
|
||||
if not vendor:
|
||||
raise VendorNotFoundException("context", identifier_type="subdomain")
|
||||
|
||||
logger.debug(f"Getting loyalty card for customer {customer.id}")
|
||||
|
||||
# Get program
|
||||
program = program_service.get_program_by_vendor(db, vendor.id)
|
||||
if not program:
|
||||
return {"card": None, "program": None, "locations": []}
|
||||
|
||||
# Look up card by customer email
|
||||
card = card_service.get_card_by_customer_email(
|
||||
db,
|
||||
company_id=program.company_id,
|
||||
customer_email=customer.email,
|
||||
)
|
||||
|
||||
if not card:
|
||||
return {"card": None, "program": None, "locations": []}
|
||||
|
||||
# Get company locations
|
||||
from app.modules.tenancy.models import Vendor as VendorModel
|
||||
locations = (
|
||||
db.query(VendorModel)
|
||||
.filter(VendorModel.company_id == program.company_id, VendorModel.is_active == True)
|
||||
.all()
|
||||
)
|
||||
|
||||
program_response = ProgramResponse.model_validate(program)
|
||||
program_response.is_stamps_enabled = program.is_stamps_enabled
|
||||
program_response.is_points_enabled = program.is_points_enabled
|
||||
program_response.display_name = program.display_name
|
||||
|
||||
return {
|
||||
"card": CardResponse.model_validate(card),
|
||||
"program": program_response,
|
||||
"locations": [{"id": v.id, "name": v.name} for v in locations],
|
||||
}
|
||||
|
||||
|
||||
@router.get("/loyalty/transactions")
|
||||
def get_my_transactions(
|
||||
request: Request,
|
||||
skip: int = Query(0, ge=0),
|
||||
limit: int = Query(20, ge=1, le=100),
|
||||
customer: CustomerContext = Depends(get_current_customer_api),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""
|
||||
Get customer's loyalty transaction history.
|
||||
"""
|
||||
vendor = getattr(request.state, "vendor", None)
|
||||
if not vendor:
|
||||
raise VendorNotFoundException("context", identifier_type="subdomain")
|
||||
|
||||
logger.debug(f"Getting transactions for customer {customer.id}")
|
||||
|
||||
# Get program
|
||||
program = program_service.get_program_by_vendor(db, vendor.id)
|
||||
if not program:
|
||||
return {"transactions": [], "total": 0}
|
||||
|
||||
# Get card
|
||||
card = card_service.get_card_by_customer_email(
|
||||
db,
|
||||
company_id=program.company_id,
|
||||
customer_email=customer.email,
|
||||
)
|
||||
|
||||
if not card:
|
||||
return {"transactions": [], "total": 0}
|
||||
|
||||
# Get transactions
|
||||
from sqlalchemy import func
|
||||
from app.modules.loyalty.models import LoyaltyTransaction
|
||||
from app.modules.tenancy.models import Vendor as VendorModel
|
||||
|
||||
query = (
|
||||
db.query(LoyaltyTransaction)
|
||||
.filter(LoyaltyTransaction.card_id == card.id)
|
||||
.order_by(LoyaltyTransaction.transaction_at.desc())
|
||||
)
|
||||
|
||||
total = query.count()
|
||||
transactions = query.offset(skip).limit(limit).all()
|
||||
|
||||
# Build response with vendor names
|
||||
tx_responses = []
|
||||
for tx in transactions:
|
||||
tx_data = {
|
||||
"id": tx.id,
|
||||
"transaction_type": tx.transaction_type.value if hasattr(tx.transaction_type, 'value') else str(tx.transaction_type),
|
||||
"points_delta": tx.points_delta,
|
||||
"stamps_delta": tx.stamps_delta,
|
||||
"balance_after": tx.balance_after,
|
||||
"transaction_at": tx.transaction_at.isoformat() if tx.transaction_at else None,
|
||||
"notes": tx.notes,
|
||||
"vendor_name": None,
|
||||
}
|
||||
|
||||
if tx.vendor_id:
|
||||
vendor_obj = db.query(VendorModel).filter(VendorModel.id == tx.vendor_id).first()
|
||||
if vendor_obj:
|
||||
tx_data["vendor_name"] = vendor_obj.name
|
||||
|
||||
tx_responses.append(tx_data)
|
||||
|
||||
return {"transactions": tx_responses, "total": total}
|
||||
@@ -2,12 +2,15 @@
|
||||
"""
|
||||
Loyalty module vendor routes.
|
||||
|
||||
Store/vendor endpoints for:
|
||||
- Program management
|
||||
- Staff PINs
|
||||
- Card operations (stamps, points, redemptions)
|
||||
Company-based vendor endpoints for:
|
||||
- Program management (company-wide, managed by vendor)
|
||||
- Staff PINs (per-vendor)
|
||||
- Card operations (stamps, points, redemptions, voids)
|
||||
- Customer cards lookup
|
||||
- Dashboard stats
|
||||
|
||||
All operations are scoped to the vendor's company.
|
||||
Cards can be used at any vendor within the same company.
|
||||
"""
|
||||
|
||||
import logging
|
||||
@@ -36,14 +39,23 @@ from app.modules.loyalty.schemas import (
|
||||
PointsEarnResponse,
|
||||
PointsRedeemRequest,
|
||||
PointsRedeemResponse,
|
||||
PointsVoidRequest,
|
||||
PointsVoidResponse,
|
||||
PointsAdjustRequest,
|
||||
PointsAdjustResponse,
|
||||
ProgramCreate,
|
||||
ProgramResponse,
|
||||
ProgramStatsResponse,
|
||||
ProgramUpdate,
|
||||
CompanyStatsResponse,
|
||||
StampRedeemRequest,
|
||||
StampRedeemResponse,
|
||||
StampRequest,
|
||||
StampResponse,
|
||||
StampVoidRequest,
|
||||
StampVoidResponse,
|
||||
TransactionListResponse,
|
||||
TransactionResponse,
|
||||
)
|
||||
from app.modules.loyalty.services import (
|
||||
card_service,
|
||||
@@ -54,7 +66,7 @@ from app.modules.loyalty.services import (
|
||||
wallet_service,
|
||||
)
|
||||
from app.modules.enums import FrontendType
|
||||
from app.modules.tenancy.models import User
|
||||
from app.modules.tenancy.models import User, Vendor
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -72,6 +84,14 @@ def get_client_info(request: Request) -> tuple[str | None, str | None]:
|
||||
return ip, user_agent
|
||||
|
||||
|
||||
def get_vendor_company_id(db: Session, vendor_id: int) -> int:
|
||||
"""Get the company ID for a vendor."""
|
||||
vendor = db.query(Vendor).filter(Vendor.id == vendor_id).first()
|
||||
if not vendor:
|
||||
raise HTTPException(status_code=404, detail="Vendor not found")
|
||||
return vendor.company_id
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Program Management
|
||||
# =============================================================================
|
||||
@@ -82,7 +102,7 @@ def get_program(
|
||||
current_user: User = Depends(get_current_vendor_api),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""Get the vendor's loyalty program."""
|
||||
"""Get the company's loyalty program."""
|
||||
vendor_id = current_user.token_vendor_id
|
||||
|
||||
program = program_service.get_program_by_vendor(db, vendor_id)
|
||||
@@ -103,11 +123,12 @@ def create_program(
|
||||
current_user: User = Depends(get_current_vendor_api),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""Create a loyalty program for the vendor."""
|
||||
"""Create a loyalty program for the company."""
|
||||
vendor_id = current_user.token_vendor_id
|
||||
company_id = get_vendor_company_id(db, vendor_id)
|
||||
|
||||
try:
|
||||
program = program_service.create_program(db, vendor_id, data)
|
||||
program = program_service.create_program(db, company_id, data)
|
||||
except LoyaltyException as e:
|
||||
raise HTTPException(status_code=e.status_code, detail=e.message)
|
||||
|
||||
@@ -125,7 +146,7 @@ def update_program(
|
||||
current_user: User = Depends(get_current_vendor_api),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""Update the vendor's loyalty program."""
|
||||
"""Update the company's loyalty program."""
|
||||
vendor_id = current_user.token_vendor_id
|
||||
|
||||
program = program_service.get_program_by_vendor(db, vendor_id)
|
||||
@@ -158,6 +179,22 @@ def get_stats(
|
||||
return ProgramStatsResponse(**stats)
|
||||
|
||||
|
||||
@vendor_router.get("/stats/company", response_model=CompanyStatsResponse)
|
||||
def get_company_stats(
|
||||
current_user: User = Depends(get_current_vendor_api),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""Get company-wide loyalty statistics across all locations."""
|
||||
vendor_id = current_user.token_vendor_id
|
||||
company_id = get_vendor_company_id(db, vendor_id)
|
||||
|
||||
stats = program_service.get_company_stats(db, company_id)
|
||||
if "error" in stats:
|
||||
raise HTTPException(status_code=404, detail=stats["error"])
|
||||
|
||||
return CompanyStatsResponse(**stats)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Staff PINs
|
||||
# =============================================================================
|
||||
@@ -168,14 +205,15 @@ def list_pins(
|
||||
current_user: User = Depends(get_current_vendor_api),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""List all staff PINs for the loyalty program."""
|
||||
"""List staff PINs for this vendor location."""
|
||||
vendor_id = current_user.token_vendor_id
|
||||
|
||||
program = program_service.get_program_by_vendor(db, vendor_id)
|
||||
if not program:
|
||||
raise HTTPException(status_code=404, detail="No loyalty program configured")
|
||||
|
||||
pins = pin_service.list_pins(db, program.id)
|
||||
# List PINs for this vendor only
|
||||
pins = pin_service.list_pins(db, program.id, vendor_id=vendor_id)
|
||||
|
||||
return PinListResponse(
|
||||
pins=[PinResponse.model_validate(pin) for pin in pins],
|
||||
@@ -189,7 +227,7 @@ def create_pin(
|
||||
current_user: User = Depends(get_current_vendor_api),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""Create a new staff PIN."""
|
||||
"""Create a new staff PIN for this vendor location."""
|
||||
vendor_id = current_user.token_vendor_id
|
||||
|
||||
program = program_service.get_program_by_vendor(db, vendor_id)
|
||||
@@ -244,19 +282,30 @@ def list_cards(
|
||||
limit: int = Query(50, ge=1, le=100),
|
||||
is_active: bool | None = Query(None),
|
||||
search: str | None = Query(None, max_length=100),
|
||||
enrolled_here: bool = Query(False, description="Only show cards enrolled at this location"),
|
||||
current_user: User = Depends(get_current_vendor_api),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""List loyalty cards for the vendor."""
|
||||
"""
|
||||
List loyalty cards for the company.
|
||||
|
||||
By default lists all cards in the company's loyalty program.
|
||||
Use enrolled_here=true to filter to cards enrolled at this location.
|
||||
"""
|
||||
vendor_id = current_user.token_vendor_id
|
||||
company_id = get_vendor_company_id(db, vendor_id)
|
||||
|
||||
program = program_service.get_program_by_vendor(db, vendor_id)
|
||||
if not program:
|
||||
raise HTTPException(status_code=404, detail="No loyalty program configured")
|
||||
|
||||
# Filter by enrolled_at_vendor_id if requested
|
||||
filter_vendor_id = vendor_id if enrolled_here else None
|
||||
|
||||
cards, total = card_service.list_cards(
|
||||
db,
|
||||
vendor_id,
|
||||
company_id,
|
||||
vendor_id=filter_vendor_id,
|
||||
skip=skip,
|
||||
limit=limit,
|
||||
is_active=is_active,
|
||||
@@ -269,8 +318,9 @@ def list_cards(
|
||||
id=card.id,
|
||||
card_number=card.card_number,
|
||||
customer_id=card.customer_id,
|
||||
vendor_id=card.vendor_id,
|
||||
company_id=card.company_id,
|
||||
program_id=card.program_id,
|
||||
enrolled_at_vendor_id=card.enrolled_at_vendor_id,
|
||||
stamp_count=card.stamp_count,
|
||||
stamps_target=program.stamps_target,
|
||||
stamps_until_reward=max(0, program.stamps_target - card.stamp_count),
|
||||
@@ -298,12 +348,18 @@ def lookup_card(
|
||||
current_user: User = Depends(get_current_vendor_api),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""Look up a card by ID, QR code, or card number."""
|
||||
"""
|
||||
Look up a card by ID, QR code, or card number.
|
||||
|
||||
Card must belong to the same company as the vendor.
|
||||
"""
|
||||
vendor_id = current_user.token_vendor_id
|
||||
|
||||
try:
|
||||
card = card_service.lookup_card(
|
||||
# Uses lookup_card_for_vendor which validates company membership
|
||||
card = card_service.lookup_card_for_vendor(
|
||||
db,
|
||||
vendor_id,
|
||||
card_id=card_id,
|
||||
qr_code=qr_code,
|
||||
card_number=card_number,
|
||||
@@ -311,10 +367,6 @@ def lookup_card(
|
||||
except LoyaltyCardNotFoundException:
|
||||
raise HTTPException(status_code=404, detail="Card not found")
|
||||
|
||||
# Verify card belongs to this vendor
|
||||
if card.vendor_id != vendor_id:
|
||||
raise HTTPException(status_code=404, detail="Card not found")
|
||||
|
||||
program = card.program
|
||||
|
||||
# Check cooldown
|
||||
@@ -328,18 +380,27 @@ def lookup_card(
|
||||
# Get stamps today
|
||||
stamps_today = card_service.get_stamps_today(db, card.id)
|
||||
|
||||
# Get available points rewards
|
||||
available_rewards = []
|
||||
for reward in program.points_rewards or []:
|
||||
if reward.get("is_active", True) and card.points_balance >= reward.get("points_required", 0):
|
||||
available_rewards.append(reward)
|
||||
|
||||
return CardLookupResponse(
|
||||
card_id=card.id,
|
||||
card_number=card.card_number,
|
||||
customer_id=card.customer_id,
|
||||
customer_name=card.customer.full_name if card.customer else None,
|
||||
customer_email=card.customer.email if card.customer else "",
|
||||
company_id=card.company_id,
|
||||
company_name=card.company.name if card.company else None,
|
||||
stamp_count=card.stamp_count,
|
||||
stamps_target=program.stamps_target,
|
||||
stamps_until_reward=max(0, program.stamps_target - card.stamp_count),
|
||||
points_balance=card.points_balance,
|
||||
can_redeem_stamps=card.stamp_count >= program.stamps_target,
|
||||
stamp_reward_description=program.stamps_reward_description,
|
||||
available_rewards=available_rewards,
|
||||
can_stamp=can_stamp,
|
||||
cooldown_ends_at=cooldown_ends,
|
||||
stamps_today=stamps_today,
|
||||
@@ -354,14 +415,19 @@ def enroll_customer(
|
||||
current_user: User = Depends(get_current_vendor_api),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""Enroll a customer in the loyalty program."""
|
||||
"""
|
||||
Enroll a customer in the company's loyalty program.
|
||||
|
||||
The card will be associated with the company and track which
|
||||
vendor enrolled them.
|
||||
"""
|
||||
vendor_id = current_user.token_vendor_id
|
||||
|
||||
if not data.customer_id:
|
||||
raise HTTPException(status_code=400, detail="customer_id is required")
|
||||
|
||||
try:
|
||||
card = card_service.enroll_customer(db, data.customer_id, vendor_id)
|
||||
card = card_service.enroll_customer_for_vendor(db, data.customer_id, vendor_id)
|
||||
except LoyaltyException as e:
|
||||
raise HTTPException(status_code=e.status_code, detail=e.message)
|
||||
|
||||
@@ -371,11 +437,12 @@ def enroll_customer(
|
||||
id=card.id,
|
||||
card_number=card.card_number,
|
||||
customer_id=card.customer_id,
|
||||
vendor_id=card.vendor_id,
|
||||
company_id=card.company_id,
|
||||
program_id=card.program_id,
|
||||
enrolled_at_vendor_id=card.enrolled_at_vendor_id,
|
||||
stamp_count=card.stamp_count,
|
||||
stamps_target=program.stamps_target,
|
||||
stamps_until_reward=program.stamps_target,
|
||||
stamps_until_reward=max(0, program.stamps_target - card.stamp_count),
|
||||
total_stamps_earned=card.total_stamps_earned,
|
||||
stamps_redeemed=card.stamps_redeemed,
|
||||
points_balance=card.points_balance,
|
||||
@@ -386,6 +453,33 @@ def enroll_customer(
|
||||
)
|
||||
|
||||
|
||||
@vendor_router.get("/cards/{card_id}/transactions", response_model=TransactionListResponse)
|
||||
def get_card_transactions(
|
||||
card_id: int = Path(..., gt=0),
|
||||
skip: int = Query(0, ge=0),
|
||||
limit: int = Query(50, ge=1, le=100),
|
||||
current_user: User = Depends(get_current_vendor_api),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""Get transaction history for a card."""
|
||||
vendor_id = current_user.token_vendor_id
|
||||
|
||||
# Verify card belongs to this company
|
||||
try:
|
||||
card = card_service.lookup_card_for_vendor(db, vendor_id, card_id=card_id)
|
||||
except LoyaltyCardNotFoundException:
|
||||
raise HTTPException(status_code=404, detail="Card not found")
|
||||
|
||||
transactions, total = card_service.get_card_transactions(
|
||||
db, card_id, skip=skip, limit=limit
|
||||
)
|
||||
|
||||
return TransactionListResponse(
|
||||
transactions=[TransactionResponse.model_validate(t) for t in transactions],
|
||||
total=total,
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Stamp Operations
|
||||
# =============================================================================
|
||||
@@ -399,11 +493,13 @@ def add_stamp(
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""Add a stamp to a loyalty card."""
|
||||
vendor_id = current_user.token_vendor_id
|
||||
ip, user_agent = get_client_info(request)
|
||||
|
||||
try:
|
||||
result = stamp_service.add_stamp(
|
||||
db,
|
||||
vendor_id=vendor_id,
|
||||
card_id=data.card_id,
|
||||
qr_code=data.qr_code,
|
||||
card_number=data.card_number,
|
||||
@@ -426,11 +522,13 @@ def redeem_stamps(
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""Redeem stamps for a reward."""
|
||||
vendor_id = current_user.token_vendor_id
|
||||
ip, user_agent = get_client_info(request)
|
||||
|
||||
try:
|
||||
result = stamp_service.redeem_stamps(
|
||||
db,
|
||||
vendor_id=vendor_id,
|
||||
card_id=data.card_id,
|
||||
qr_code=data.qr_code,
|
||||
card_number=data.card_number,
|
||||
@@ -445,6 +543,37 @@ def redeem_stamps(
|
||||
return StampRedeemResponse(**result)
|
||||
|
||||
|
||||
@vendor_router.post("/stamp/void", response_model=StampVoidResponse)
|
||||
def void_stamps(
|
||||
request: Request,
|
||||
data: StampVoidRequest,
|
||||
current_user: User = Depends(get_current_vendor_api),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""Void stamps for a return."""
|
||||
vendor_id = current_user.token_vendor_id
|
||||
ip, user_agent = get_client_info(request)
|
||||
|
||||
try:
|
||||
result = stamp_service.void_stamps(
|
||||
db,
|
||||
vendor_id=vendor_id,
|
||||
card_id=data.card_id,
|
||||
qr_code=data.qr_code,
|
||||
card_number=data.card_number,
|
||||
stamps_to_void=data.stamps_to_void,
|
||||
original_transaction_id=data.original_transaction_id,
|
||||
staff_pin=data.staff_pin,
|
||||
ip_address=ip,
|
||||
user_agent=user_agent,
|
||||
notes=data.notes,
|
||||
)
|
||||
except LoyaltyException as e:
|
||||
raise HTTPException(status_code=e.status_code, detail=e.message)
|
||||
|
||||
return StampVoidResponse(**result)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Points Operations
|
||||
# =============================================================================
|
||||
@@ -458,11 +587,13 @@ def earn_points(
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""Earn points from a purchase."""
|
||||
vendor_id = current_user.token_vendor_id
|
||||
ip, user_agent = get_client_info(request)
|
||||
|
||||
try:
|
||||
result = points_service.earn_points(
|
||||
db,
|
||||
vendor_id=vendor_id,
|
||||
card_id=data.card_id,
|
||||
qr_code=data.qr_code,
|
||||
card_number=data.card_number,
|
||||
@@ -487,11 +618,13 @@ def redeem_points(
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""Redeem points for a reward."""
|
||||
vendor_id = current_user.token_vendor_id
|
||||
ip, user_agent = get_client_info(request)
|
||||
|
||||
try:
|
||||
result = points_service.redeem_points(
|
||||
db,
|
||||
vendor_id=vendor_id,
|
||||
card_id=data.card_id,
|
||||
qr_code=data.qr_code,
|
||||
card_number=data.card_number,
|
||||
@@ -505,3 +638,64 @@ def redeem_points(
|
||||
raise HTTPException(status_code=e.status_code, detail=e.message)
|
||||
|
||||
return PointsRedeemResponse(**result)
|
||||
|
||||
|
||||
@vendor_router.post("/points/void", response_model=PointsVoidResponse)
|
||||
def void_points(
|
||||
request: Request,
|
||||
data: PointsVoidRequest,
|
||||
current_user: User = Depends(get_current_vendor_api),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""Void points for a return."""
|
||||
vendor_id = current_user.token_vendor_id
|
||||
ip, user_agent = get_client_info(request)
|
||||
|
||||
try:
|
||||
result = points_service.void_points(
|
||||
db,
|
||||
vendor_id=vendor_id,
|
||||
card_id=data.card_id,
|
||||
qr_code=data.qr_code,
|
||||
card_number=data.card_number,
|
||||
points_to_void=data.points_to_void,
|
||||
original_transaction_id=data.original_transaction_id,
|
||||
order_reference=data.order_reference,
|
||||
staff_pin=data.staff_pin,
|
||||
ip_address=ip,
|
||||
user_agent=user_agent,
|
||||
notes=data.notes,
|
||||
)
|
||||
except LoyaltyException as e:
|
||||
raise HTTPException(status_code=e.status_code, detail=e.message)
|
||||
|
||||
return PointsVoidResponse(**result)
|
||||
|
||||
|
||||
@vendor_router.post("/cards/{card_id}/points/adjust", response_model=PointsAdjustResponse)
|
||||
def adjust_points(
|
||||
request: Request,
|
||||
data: PointsAdjustRequest,
|
||||
card_id: int = Path(..., gt=0),
|
||||
current_user: User = Depends(get_current_vendor_api),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""Manually adjust points (vendor operation)."""
|
||||
vendor_id = current_user.token_vendor_id
|
||||
ip, user_agent = get_client_info(request)
|
||||
|
||||
try:
|
||||
result = points_service.adjust_points(
|
||||
db,
|
||||
card_id=card_id,
|
||||
points_delta=data.points_delta,
|
||||
vendor_id=vendor_id,
|
||||
reason=data.reason,
|
||||
staff_pin=data.staff_pin,
|
||||
ip_address=ip,
|
||||
user_agent=user_agent,
|
||||
)
|
||||
except LoyaltyException as e:
|
||||
raise HTTPException(status_code=e.status_code, detail=e.message)
|
||||
|
||||
return PointsAdjustResponse(**result)
|
||||
|
||||
Reference in New Issue
Block a user