feat(loyalty): implement complete loyalty module MVP

Add stamp-based and points-based loyalty programs for vendors with:

Database Models (5 tables):
- loyalty_programs: Vendor program configuration
- loyalty_cards: Customer cards with stamp/point balances
- loyalty_transactions: Immutable audit log
- staff_pins: Fraud prevention PINs (bcrypt hashed)
- apple_device_registrations: Apple Wallet push tokens

Services:
- program_service: Program CRUD and statistics
- card_service: Customer enrollment and card lookup
- stamp_service: Stamp operations with anti-fraud checks
- points_service: Points earning and redemption
- pin_service: Staff PIN management with lockout
- wallet_service: Unified wallet abstraction
- google_wallet_service: Google Wallet API integration
- apple_wallet_service: Apple Wallet .pkpass generation

API Routes:
- Admin: /api/v1/admin/loyalty/* (programs list, stats)
- Vendor: /api/v1/vendor/loyalty/* (stamp, points, cards, PINs)
- Public: /api/v1/loyalty/* (enrollment, Apple Web Service)

Anti-Fraud Features:
- Staff PIN verification (configurable per program)
- Cooldown period between stamps (default 15 min)
- Daily stamp limits (default 5/day)
- PIN lockout after failed attempts

Wallet Integration:
- Google Wallet: LoyaltyClass and LoyaltyObject management
- Apple Wallet: .pkpass generation with PKCS#7 signing
- Apple Web Service endpoints for device registration/updates

Also includes:
- Alembic migration for all tables with indexes
- Localization files (en, fr, de, lu)
- Module documentation
- Phase 2 interface and user journey plan

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
2026-01-28 23:04:00 +01:00
parent fbcf07914e
commit b5a803cde8
44 changed files with 8073 additions and 0 deletions

View File

@@ -0,0 +1,106 @@
# app/modules/loyalty/schemas/__init__.py
"""
Loyalty module Pydantic schemas.
Request and response models for the loyalty API endpoints.
Usage:
from app.modules.loyalty.schemas import (
# Program
ProgramCreate,
ProgramUpdate,
ProgramResponse,
# Card
CardEnrollRequest,
CardResponse,
# Stamp
StampRequest,
StampResponse,
# Points
PointsEarnRequest,
PointsRedeemRequest,
# PIN
PinCreate,
PinVerifyRequest,
)
"""
from app.modules.loyalty.schemas.program import (
# Program CRUD
ProgramCreate,
ProgramUpdate,
ProgramResponse,
ProgramListResponse,
# Points rewards
PointsRewardConfig,
# Stats
ProgramStatsResponse,
)
from app.modules.loyalty.schemas.card import (
# Card operations
CardEnrollRequest,
CardResponse,
CardDetailResponse,
CardListResponse,
CardLookupResponse,
)
from app.modules.loyalty.schemas.stamp import (
# Stamp operations
StampRequest,
StampResponse,
StampRedeemRequest,
StampRedeemResponse,
)
from app.modules.loyalty.schemas.points import (
# Points operations
PointsEarnRequest,
PointsEarnResponse,
PointsRedeemRequest,
PointsRedeemResponse,
)
from app.modules.loyalty.schemas.pin import (
# Staff PIN
PinCreate,
PinUpdate,
PinResponse,
PinListResponse,
PinVerifyRequest,
PinVerifyResponse,
)
__all__ = [
# Program
"ProgramCreate",
"ProgramUpdate",
"ProgramResponse",
"ProgramListResponse",
"PointsRewardConfig",
"ProgramStatsResponse",
# Card
"CardEnrollRequest",
"CardResponse",
"CardDetailResponse",
"CardListResponse",
"CardLookupResponse",
# Stamp
"StampRequest",
"StampResponse",
"StampRedeemRequest",
"StampRedeemResponse",
# Points
"PointsEarnRequest",
"PointsEarnResponse",
"PointsRedeemRequest",
"PointsRedeemResponse",
# PIN
"PinCreate",
"PinUpdate",
"PinResponse",
"PinListResponse",
"PinVerifyRequest",
"PinVerifyResponse",
]

View File

@@ -0,0 +1,118 @@
# app/modules/loyalty/schemas/card.py
"""
Pydantic schemas for loyalty card operations.
"""
from datetime import datetime
from pydantic import BaseModel, ConfigDict, Field
class CardEnrollRequest(BaseModel):
"""Schema for enrolling a customer in a loyalty program."""
customer_id: int | None = Field(
None,
description="Customer ID (required for vendor API, optional for public enrollment)",
)
email: str | None = Field(
None,
description="Customer email (for public enrollment without customer_id)",
)
class CardResponse(BaseModel):
"""Schema for loyalty card response (summary)."""
model_config = ConfigDict(from_attributes=True)
id: int
card_number: str
customer_id: int
vendor_id: int
program_id: int
# Stamps
stamp_count: int
stamps_target: int # From program
stamps_until_reward: int
total_stamps_earned: int
stamps_redeemed: int
# Points
points_balance: int
total_points_earned: int
points_redeemed: int
# Status
is_active: bool
created_at: datetime
# Wallet
has_google_wallet: bool = False
has_apple_wallet: bool = False
class CardDetailResponse(CardResponse):
"""Schema for detailed loyalty card response."""
# QR code
qr_code_data: str
qr_code_url: str | None = None # Generated QR code image URL
# Customer info
customer_name: str | None = None
customer_email: str | None = None
# Program info
program_name: str
program_type: str
reward_description: str | None = None
# Activity
last_stamp_at: datetime | None = None
last_points_at: datetime | None = None
last_redemption_at: datetime | None = None
# Wallet URLs
google_wallet_url: str | None = None
apple_wallet_url: str | None = None
class CardListResponse(BaseModel):
"""Schema for listing loyalty cards."""
cards: list[CardResponse]
total: int
class CardLookupResponse(BaseModel):
"""Schema for card lookup by QR code or card number."""
# Card info
card_id: int
card_number: str
# Customer
customer_id: int
customer_name: str | None = None
customer_email: str
# Current balances
stamp_count: int
stamps_target: int
stamps_until_reward: int
points_balance: int
# Can redeem?
can_redeem_stamps: bool = False
stamp_reward_description: str | None = None
# Cooldown status
can_stamp: bool = True
cooldown_ends_at: datetime | None = None
# Today's activity
stamps_today: int = 0
max_daily_stamps: int = 5
can_earn_more_stamps: bool = True

View File

@@ -0,0 +1,98 @@
# app/modules/loyalty/schemas/pin.py
"""
Pydantic schemas for staff PIN operations.
"""
from datetime import datetime
from pydantic import BaseModel, ConfigDict, Field
class PinCreate(BaseModel):
"""Schema for creating a staff PIN."""
name: str = Field(
...,
min_length=1,
max_length=100,
description="Staff member name",
)
staff_id: str | None = Field(
None,
max_length=50,
description="Optional employee ID",
)
pin: str = Field(
...,
min_length=4,
max_length=6,
pattern="^[0-9]+$",
description="4-6 digit PIN",
)
class PinUpdate(BaseModel):
"""Schema for updating a staff PIN."""
model_config = ConfigDict(from_attributes=True)
name: str | None = Field(
None,
min_length=1,
max_length=100,
)
staff_id: str | None = Field(
None,
max_length=50,
)
pin: str | None = Field(
None,
min_length=4,
max_length=6,
pattern="^[0-9]+$",
description="New PIN (if changing)",
)
is_active: bool | None = None
class PinResponse(BaseModel):
"""Schema for staff PIN response (never includes actual PIN)."""
model_config = ConfigDict(from_attributes=True)
id: int
name: str
staff_id: str | None = None
is_active: bool
is_locked: bool = False
locked_until: datetime | None = None
last_used_at: datetime | None = None
created_at: datetime
class PinListResponse(BaseModel):
"""Schema for listing staff PINs."""
pins: list[PinResponse]
total: int
class PinVerifyRequest(BaseModel):
"""Schema for verifying a staff PIN."""
pin: str = Field(
...,
min_length=4,
max_length=6,
pattern="^[0-9]+$",
description="PIN to verify",
)
class PinVerifyResponse(BaseModel):
"""Schema for PIN verification response."""
valid: bool
staff_name: str | None = None
remaining_attempts: int | None = None
locked_until: datetime | None = None

View File

@@ -0,0 +1,124 @@
# app/modules/loyalty/schemas/points.py
"""
Pydantic schemas for points operations.
"""
from pydantic import BaseModel, Field
class PointsEarnRequest(BaseModel):
"""Schema for earning points from a purchase."""
card_id: int | None = Field(
None,
description="Card ID (use this or qr_code)",
)
qr_code: str | None = Field(
None,
description="QR code data from card scan",
)
card_number: str | None = Field(
None,
description="Card number (manual entry)",
)
# Purchase info
purchase_amount_cents: int = Field(
...,
gt=0,
description="Purchase amount in cents",
)
order_reference: str | None = Field(
None,
max_length=100,
description="Order reference for tracking",
)
# Authentication
staff_pin: str | None = Field(
None,
min_length=4,
max_length=6,
description="Staff PIN for verification",
)
# Optional metadata
notes: str | None = Field(
None,
max_length=500,
description="Optional note",
)
class PointsEarnResponse(BaseModel):
"""Schema for points earning response."""
success: bool = True
message: str = "Points earned successfully"
# Points info
points_earned: int
points_per_euro: int
purchase_amount_cents: int
# Card state after earning
card_id: int
card_number: str
points_balance: int
total_points_earned: int
class PointsRedeemRequest(BaseModel):
"""Schema for redeeming points for a reward."""
card_id: int | None = Field(
None,
description="Card ID (use this or qr_code)",
)
qr_code: str | None = Field(
None,
description="QR code data from card scan",
)
card_number: str | None = Field(
None,
description="Card number (manual entry)",
)
# Reward selection
reward_id: str = Field(
...,
description="ID of the reward to redeem",
)
# Authentication
staff_pin: str | None = Field(
None,
min_length=4,
max_length=6,
description="Staff PIN for verification",
)
# Optional metadata
notes: str | None = Field(
None,
max_length=500,
description="Optional note",
)
class PointsRedeemResponse(BaseModel):
"""Schema for points redemption response."""
success: bool = True
message: str = "Reward redeemed successfully"
# Reward info
reward_id: str
reward_name: str
points_spent: int
# Card state after redemption
card_id: int
card_number: str
points_balance: int
total_points_redeemed: int

View File

@@ -0,0 +1,203 @@
# app/modules/loyalty/schemas/program.py
"""
Pydantic schemas for loyalty program operations.
"""
from datetime import datetime
from pydantic import BaseModel, ConfigDict, Field
class PointsRewardConfig(BaseModel):
"""Configuration for a points-based reward."""
id: str = Field(..., description="Unique reward identifier")
name: str = Field(..., max_length=100, description="Reward name")
points_required: int = Field(..., gt=0, description="Points needed to redeem")
description: str | None = Field(None, max_length=255, description="Reward description")
is_active: bool = Field(True, description="Whether reward is currently available")
class ProgramCreate(BaseModel):
"""Schema for creating a loyalty program."""
# Program type
loyalty_type: str = Field(
"stamps",
pattern="^(stamps|points|hybrid)$",
description="Program type: stamps, points, or hybrid",
)
# Stamps configuration
stamps_target: int = Field(10, ge=1, le=50, description="Stamps needed for reward")
stamps_reward_description: str = Field(
"Free item",
max_length=255,
description="Description of stamp reward",
)
stamps_reward_value_cents: int | None = Field(
None,
ge=0,
description="Value of reward in cents (for analytics)",
)
# Points configuration
points_per_euro: int = Field(10, ge=1, le=1000, description="Points per euro spent")
points_rewards: list[PointsRewardConfig] = Field(
default_factory=list,
description="Available point rewards",
)
# Anti-fraud
cooldown_minutes: int = Field(15, ge=0, le=1440, description="Minutes between stamps")
max_daily_stamps: int = Field(5, ge=1, le=50, description="Max stamps per card per day")
require_staff_pin: bool = Field(True, description="Require staff PIN for operations")
# Branding
card_name: str | None = Field(None, max_length=100, description="Display name for card")
card_color: str = Field(
"#4F46E5",
pattern="^#[0-9A-Fa-f]{6}$",
description="Primary color (hex)",
)
card_secondary_color: str | None = Field(
None,
pattern="^#[0-9A-Fa-f]{6}$",
description="Secondary color (hex)",
)
logo_url: str | None = Field(None, max_length=500, description="Logo URL")
hero_image_url: str | None = Field(None, max_length=500, description="Hero image URL")
# Terms
terms_text: str | None = Field(None, description="Terms and conditions")
privacy_url: str | None = Field(None, max_length=500, description="Privacy policy URL")
class ProgramUpdate(BaseModel):
"""Schema for updating a loyalty program."""
model_config = ConfigDict(from_attributes=True)
# Program type (cannot change from stamps to points after cards exist)
loyalty_type: str | None = Field(
None,
pattern="^(stamps|points|hybrid)$",
)
# Stamps configuration
stamps_target: int | None = Field(None, ge=1, le=50)
stamps_reward_description: str | None = Field(None, max_length=255)
stamps_reward_value_cents: int | None = Field(None, ge=0)
# Points configuration
points_per_euro: int | None = Field(None, ge=1, le=1000)
points_rewards: list[PointsRewardConfig] | None = None
# Anti-fraud
cooldown_minutes: int | None = Field(None, ge=0, le=1440)
max_daily_stamps: int | None = Field(None, ge=1, le=50)
require_staff_pin: bool | None = None
# Branding
card_name: str | None = Field(None, max_length=100)
card_color: str | None = Field(None, pattern="^#[0-9A-Fa-f]{6}$")
card_secondary_color: str | None = Field(None, pattern="^#[0-9A-Fa-f]{6}$")
logo_url: str | None = Field(None, max_length=500)
hero_image_url: str | None = Field(None, max_length=500)
# Terms
terms_text: str | None = None
privacy_url: str | None = Field(None, max_length=500)
# Wallet integration
google_issuer_id: str | None = Field(None, max_length=100)
apple_pass_type_id: str | None = Field(None, max_length=100)
# Status
is_active: bool | None = None
class ProgramResponse(BaseModel):
"""Schema for loyalty program response."""
model_config = ConfigDict(from_attributes=True)
id: int
vendor_id: int
loyalty_type: str
# Stamps
stamps_target: int
stamps_reward_description: str
stamps_reward_value_cents: int | None = None
# Points
points_per_euro: int
points_rewards: list[PointsRewardConfig] = []
# Anti-fraud
cooldown_minutes: int
max_daily_stamps: int
require_staff_pin: bool
# Branding
card_name: str | None = None
card_color: str
card_secondary_color: str | None = None
logo_url: str | None = None
hero_image_url: str | None = None
# Terms
terms_text: str | None = None
privacy_url: str | None = None
# Wallet
google_issuer_id: str | None = None
google_class_id: str | None = None
apple_pass_type_id: str | None = None
# Status
is_active: bool
activated_at: datetime | None = None
created_at: datetime
updated_at: datetime
# Computed
is_stamps_enabled: bool = False
is_points_enabled: bool = False
display_name: str = "Loyalty Card"
class ProgramListResponse(BaseModel):
"""Schema for listing loyalty programs (admin)."""
programs: list[ProgramResponse]
total: int
class ProgramStatsResponse(BaseModel):
"""Schema for program statistics."""
# Cards
total_cards: int = 0
active_cards: int = 0
# Stamps (if enabled)
total_stamps_issued: int = 0
total_stamps_redeemed: int = 0
stamps_this_month: int = 0
redemptions_this_month: int = 0
# Points (if enabled)
total_points_issued: int = 0
total_points_redeemed: int = 0
points_this_month: int = 0
points_redeemed_this_month: int = 0
# Engagement
cards_with_activity_30d: int = 0
average_stamps_per_card: float = 0.0
average_points_per_card: float = 0.0
# Value
estimated_liability_cents: int = 0 # Unredeemed stamps/points value

View File

@@ -0,0 +1,114 @@
# app/modules/loyalty/schemas/stamp.py
"""
Pydantic schemas for stamp operations.
"""
from datetime import datetime
from pydantic import BaseModel, Field
class StampRequest(BaseModel):
"""Schema for adding a stamp to a card."""
card_id: int | None = Field(
None,
description="Card ID (use this or qr_code)",
)
qr_code: str | None = Field(
None,
description="QR code data from card scan",
)
card_number: str | None = Field(
None,
description="Card number (manual entry)",
)
# Authentication
staff_pin: str | None = Field(
None,
min_length=4,
max_length=6,
description="Staff PIN for verification",
)
# Optional metadata
notes: str | None = Field(
None,
max_length=500,
description="Optional note about this stamp",
)
class StampResponse(BaseModel):
"""Schema for stamp operation response."""
success: bool = True
message: str = "Stamp added successfully"
# Card state after stamp
card_id: int
card_number: str
stamp_count: int
stamps_target: int
stamps_until_reward: int
# Did this trigger a reward?
reward_earned: bool = False
reward_description: str | None = None
# Cooldown info
next_stamp_available_at: datetime | None = None
# Today's activity
stamps_today: int
stamps_remaining_today: int
class StampRedeemRequest(BaseModel):
"""Schema for redeeming stamps for a reward."""
card_id: int | None = Field(
None,
description="Card ID (use this or qr_code)",
)
qr_code: str | None = Field(
None,
description="QR code data from card scan",
)
card_number: str | None = Field(
None,
description="Card number (manual entry)",
)
# Authentication
staff_pin: str | None = Field(
None,
min_length=4,
max_length=6,
description="Staff PIN for verification",
)
# Optional metadata
notes: str | None = Field(
None,
max_length=500,
description="Optional note about this redemption",
)
class StampRedeemResponse(BaseModel):
"""Schema for stamp redemption response."""
success: bool = True
message: str = "Reward redeemed successfully"
# Card state after redemption
card_id: int
card_number: str
stamp_count: int # Should be 0 after redemption
stamps_target: int
# Reward info
reward_description: str
total_redemptions: int # Lifetime redemptions for this card