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:
55
app/modules/loyalty/models/__init__.py
Normal file
55
app/modules/loyalty/models/__init__.py
Normal file
@@ -0,0 +1,55 @@
|
||||
# app/modules/loyalty/models/__init__.py
|
||||
"""
|
||||
Loyalty module database models.
|
||||
|
||||
This is the canonical location for loyalty models. Module models are automatically
|
||||
discovered and registered with SQLAlchemy's Base.metadata at startup.
|
||||
|
||||
Usage:
|
||||
from app.modules.loyalty.models import (
|
||||
LoyaltyProgram,
|
||||
LoyaltyCard,
|
||||
LoyaltyTransaction,
|
||||
StaffPin,
|
||||
AppleDeviceRegistration,
|
||||
LoyaltyType,
|
||||
TransactionType,
|
||||
)
|
||||
"""
|
||||
|
||||
from app.modules.loyalty.models.loyalty_program import (
|
||||
# Enums
|
||||
LoyaltyType,
|
||||
# Model
|
||||
LoyaltyProgram,
|
||||
)
|
||||
from app.modules.loyalty.models.loyalty_card import (
|
||||
# Model
|
||||
LoyaltyCard,
|
||||
)
|
||||
from app.modules.loyalty.models.loyalty_transaction import (
|
||||
# Enums
|
||||
TransactionType,
|
||||
# Model
|
||||
LoyaltyTransaction,
|
||||
)
|
||||
from app.modules.loyalty.models.staff_pin import (
|
||||
# Model
|
||||
StaffPin,
|
||||
)
|
||||
from app.modules.loyalty.models.apple_device import (
|
||||
# Model
|
||||
AppleDeviceRegistration,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
# Enums
|
||||
"LoyaltyType",
|
||||
"TransactionType",
|
||||
# Models
|
||||
"LoyaltyProgram",
|
||||
"LoyaltyCard",
|
||||
"LoyaltyTransaction",
|
||||
"StaffPin",
|
||||
"AppleDeviceRegistration",
|
||||
]
|
||||
79
app/modules/loyalty/models/apple_device.py
Normal file
79
app/modules/loyalty/models/apple_device.py
Normal file
@@ -0,0 +1,79 @@
|
||||
# app/modules/loyalty/models/apple_device.py
|
||||
"""
|
||||
Apple device registration database model.
|
||||
|
||||
Tracks devices that have added an Apple Wallet pass for push
|
||||
notification updates when the pass changes.
|
||||
"""
|
||||
|
||||
from sqlalchemy import (
|
||||
Column,
|
||||
ForeignKey,
|
||||
Index,
|
||||
Integer,
|
||||
String,
|
||||
)
|
||||
from sqlalchemy.orm import relationship
|
||||
|
||||
from app.core.database import Base
|
||||
from models.database.base import TimestampMixin
|
||||
|
||||
|
||||
class AppleDeviceRegistration(Base, TimestampMixin):
|
||||
"""
|
||||
Apple Wallet device registration.
|
||||
|
||||
When a user adds a pass to Apple Wallet, the device registers
|
||||
with us to receive push notifications when the pass updates.
|
||||
|
||||
This implements the Apple Wallet Web Service for passbook updates:
|
||||
https://developer.apple.com/documentation/walletpasses/
|
||||
"""
|
||||
|
||||
__tablename__ = "apple_device_registrations"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
|
||||
# Card relationship
|
||||
card_id = Column(
|
||||
Integer,
|
||||
ForeignKey("loyalty_cards.id", ondelete="CASCADE"),
|
||||
nullable=False,
|
||||
index=True,
|
||||
)
|
||||
|
||||
# Device identification
|
||||
device_library_identifier = Column(
|
||||
String(100),
|
||||
nullable=False,
|
||||
index=True,
|
||||
comment="Unique identifier for the device/library",
|
||||
)
|
||||
|
||||
# Push notification token
|
||||
push_token = Column(
|
||||
String(100),
|
||||
nullable=False,
|
||||
comment="APNs push token for this device",
|
||||
)
|
||||
|
||||
# =========================================================================
|
||||
# Relationships
|
||||
# =========================================================================
|
||||
card = relationship("LoyaltyCard", back_populates="apple_devices")
|
||||
|
||||
# Indexes - unique constraint on device + card combination
|
||||
__table_args__ = (
|
||||
Index(
|
||||
"idx_apple_device_card",
|
||||
"device_library_identifier",
|
||||
"card_id",
|
||||
unique=True,
|
||||
),
|
||||
)
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return (
|
||||
f"<AppleDeviceRegistration(id={self.id}, "
|
||||
f"device='{self.device_library_identifier[:8]}...', card_id={self.card_id})>"
|
||||
)
|
||||
317
app/modules/loyalty/models/loyalty_card.py
Normal file
317
app/modules/loyalty/models/loyalty_card.py
Normal file
@@ -0,0 +1,317 @@
|
||||
# app/modules/loyalty/models/loyalty_card.py
|
||||
"""
|
||||
Loyalty card database model.
|
||||
|
||||
Represents a customer's loyalty card (PassObject) that tracks:
|
||||
- Stamp count and history
|
||||
- Points balance and history
|
||||
- Wallet integration (Google/Apple pass IDs)
|
||||
- QR code for scanning
|
||||
"""
|
||||
|
||||
import secrets
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from sqlalchemy import (
|
||||
Boolean,
|
||||
Column,
|
||||
DateTime,
|
||||
ForeignKey,
|
||||
Index,
|
||||
Integer,
|
||||
String,
|
||||
)
|
||||
from sqlalchemy.orm import relationship
|
||||
|
||||
from app.core.database import Base
|
||||
from models.database.base import TimestampMixin
|
||||
|
||||
|
||||
def generate_card_number() -> str:
|
||||
"""Generate a unique 12-digit card number."""
|
||||
return "".join([str(secrets.randbelow(10)) for _ in range(12)])
|
||||
|
||||
|
||||
def generate_qr_code_data() -> str:
|
||||
"""Generate unique QR code data (URL-safe token)."""
|
||||
return secrets.token_urlsafe(24)
|
||||
|
||||
|
||||
def generate_apple_auth_token() -> str:
|
||||
"""Generate Apple Wallet authentication token."""
|
||||
return secrets.token_urlsafe(32)
|
||||
|
||||
|
||||
class LoyaltyCard(Base, TimestampMixin):
|
||||
"""
|
||||
Customer's loyalty card (PassObject).
|
||||
|
||||
Links a customer to a vendor's loyalty program and tracks:
|
||||
- Stamps and points balances
|
||||
- Wallet pass integration
|
||||
- Activity timestamps
|
||||
"""
|
||||
|
||||
__tablename__ = "loyalty_cards"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
|
||||
# Relationships
|
||||
customer_id = Column(
|
||||
Integer,
|
||||
ForeignKey("customers.id", ondelete="CASCADE"),
|
||||
nullable=False,
|
||||
index=True,
|
||||
)
|
||||
program_id = Column(
|
||||
Integer,
|
||||
ForeignKey("loyalty_programs.id", ondelete="CASCADE"),
|
||||
nullable=False,
|
||||
index=True,
|
||||
)
|
||||
vendor_id = Column(
|
||||
Integer,
|
||||
ForeignKey("vendors.id", ondelete="CASCADE"),
|
||||
nullable=False,
|
||||
index=True,
|
||||
comment="Denormalized for query performance",
|
||||
)
|
||||
|
||||
# =========================================================================
|
||||
# Card Identification
|
||||
# =========================================================================
|
||||
card_number = Column(
|
||||
String(20),
|
||||
unique=True,
|
||||
nullable=False,
|
||||
default=generate_card_number,
|
||||
index=True,
|
||||
comment="Human-readable card number",
|
||||
)
|
||||
qr_code_data = Column(
|
||||
String(50),
|
||||
unique=True,
|
||||
nullable=False,
|
||||
default=generate_qr_code_data,
|
||||
index=True,
|
||||
comment="Data encoded in QR code for scanning",
|
||||
)
|
||||
|
||||
# =========================================================================
|
||||
# Stamps Tracking
|
||||
# =========================================================================
|
||||
stamp_count = Column(
|
||||
Integer,
|
||||
default=0,
|
||||
nullable=False,
|
||||
comment="Current stamps toward next reward",
|
||||
)
|
||||
total_stamps_earned = Column(
|
||||
Integer,
|
||||
default=0,
|
||||
nullable=False,
|
||||
comment="Lifetime stamps earned",
|
||||
)
|
||||
stamps_redeemed = Column(
|
||||
Integer,
|
||||
default=0,
|
||||
nullable=False,
|
||||
comment="Total rewards redeemed (stamps reset on redemption)",
|
||||
)
|
||||
|
||||
# =========================================================================
|
||||
# Points Tracking
|
||||
# =========================================================================
|
||||
points_balance = Column(
|
||||
Integer,
|
||||
default=0,
|
||||
nullable=False,
|
||||
comment="Current available points",
|
||||
)
|
||||
total_points_earned = Column(
|
||||
Integer,
|
||||
default=0,
|
||||
nullable=False,
|
||||
comment="Lifetime points earned",
|
||||
)
|
||||
points_redeemed = Column(
|
||||
Integer,
|
||||
default=0,
|
||||
nullable=False,
|
||||
comment="Lifetime points redeemed",
|
||||
)
|
||||
|
||||
# =========================================================================
|
||||
# Wallet Integration
|
||||
# =========================================================================
|
||||
# Google Wallet
|
||||
google_object_id = Column(
|
||||
String(200),
|
||||
nullable=True,
|
||||
index=True,
|
||||
comment="Google Wallet Loyalty Object ID",
|
||||
)
|
||||
google_object_jwt = Column(
|
||||
String(2000),
|
||||
nullable=True,
|
||||
comment="JWT for Google Wallet 'Add to Wallet' button",
|
||||
)
|
||||
|
||||
# Apple Wallet
|
||||
apple_serial_number = Column(
|
||||
String(100),
|
||||
nullable=True,
|
||||
unique=True,
|
||||
index=True,
|
||||
comment="Apple Wallet pass serial number",
|
||||
)
|
||||
apple_auth_token = Column(
|
||||
String(100),
|
||||
nullable=True,
|
||||
default=generate_apple_auth_token,
|
||||
comment="Apple Wallet authentication token for updates",
|
||||
)
|
||||
|
||||
# =========================================================================
|
||||
# Activity Timestamps
|
||||
# =========================================================================
|
||||
last_stamp_at = Column(
|
||||
DateTime(timezone=True),
|
||||
nullable=True,
|
||||
comment="Last stamp added (for cooldown)",
|
||||
)
|
||||
last_points_at = Column(
|
||||
DateTime(timezone=True),
|
||||
nullable=True,
|
||||
comment="Last points earned",
|
||||
)
|
||||
last_redemption_at = Column(
|
||||
DateTime(timezone=True),
|
||||
nullable=True,
|
||||
comment="Last reward redemption",
|
||||
)
|
||||
|
||||
# =========================================================================
|
||||
# Status
|
||||
# =========================================================================
|
||||
is_active = Column(
|
||||
Boolean,
|
||||
default=True,
|
||||
nullable=False,
|
||||
index=True,
|
||||
)
|
||||
|
||||
# =========================================================================
|
||||
# Relationships
|
||||
# =========================================================================
|
||||
customer = relationship("Customer", backref="loyalty_cards")
|
||||
program = relationship("LoyaltyProgram", back_populates="cards")
|
||||
vendor = relationship("Vendor", backref="loyalty_cards")
|
||||
transactions = relationship(
|
||||
"LoyaltyTransaction",
|
||||
back_populates="card",
|
||||
cascade="all, delete-orphan",
|
||||
order_by="desc(LoyaltyTransaction.created_at)",
|
||||
)
|
||||
apple_devices = relationship(
|
||||
"AppleDeviceRegistration",
|
||||
back_populates="card",
|
||||
cascade="all, delete-orphan",
|
||||
)
|
||||
|
||||
# Indexes
|
||||
__table_args__ = (
|
||||
Index("idx_loyalty_card_customer_program", "customer_id", "program_id", unique=True),
|
||||
Index("idx_loyalty_card_vendor_active", "vendor_id", "is_active"),
|
||||
)
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"<LoyaltyCard(id={self.id}, card_number='{self.card_number}', stamps={self.stamp_count})>"
|
||||
|
||||
# =========================================================================
|
||||
# Stamp Operations
|
||||
# =========================================================================
|
||||
|
||||
def add_stamp(self) -> bool:
|
||||
"""
|
||||
Add a stamp to the card.
|
||||
|
||||
Returns True if this stamp completed a reward cycle.
|
||||
"""
|
||||
self.stamp_count += 1
|
||||
self.total_stamps_earned += 1
|
||||
self.last_stamp_at = datetime.now(UTC)
|
||||
|
||||
# Check if reward cycle is complete (handled by caller with program.stamps_target)
|
||||
return False # Caller checks against program.stamps_target
|
||||
|
||||
def redeem_stamps(self, stamps_target: int) -> bool:
|
||||
"""
|
||||
Redeem stamps for a reward.
|
||||
|
||||
Args:
|
||||
stamps_target: Number of stamps required for reward
|
||||
|
||||
Returns True if redemption was successful.
|
||||
"""
|
||||
if self.stamp_count >= stamps_target:
|
||||
self.stamp_count -= stamps_target
|
||||
self.stamps_redeemed += 1
|
||||
self.last_redemption_at = datetime.now(UTC)
|
||||
return True
|
||||
return False
|
||||
|
||||
# =========================================================================
|
||||
# Points Operations
|
||||
# =========================================================================
|
||||
|
||||
def add_points(self, points: int) -> None:
|
||||
"""Add points to the card."""
|
||||
self.points_balance += points
|
||||
self.total_points_earned += points
|
||||
self.last_points_at = datetime.now(UTC)
|
||||
|
||||
def redeem_points(self, points: int) -> bool:
|
||||
"""
|
||||
Redeem points for a reward.
|
||||
|
||||
Returns True if redemption was successful.
|
||||
"""
|
||||
if self.points_balance >= points:
|
||||
self.points_balance -= points
|
||||
self.points_redeemed += points
|
||||
self.last_redemption_at = datetime.now(UTC)
|
||||
return True
|
||||
return False
|
||||
|
||||
# =========================================================================
|
||||
# Properties
|
||||
# =========================================================================
|
||||
|
||||
@property
|
||||
def stamps_until_reward(self) -> int | None:
|
||||
"""Get stamps remaining until next reward (needs program context)."""
|
||||
# This should be calculated with program.stamps_target
|
||||
return None
|
||||
|
||||
def can_stamp(self, cooldown_minutes: int) -> tuple[bool, str | None]:
|
||||
"""
|
||||
Check if card can receive a stamp (cooldown check).
|
||||
|
||||
Args:
|
||||
cooldown_minutes: Minutes required between stamps
|
||||
|
||||
Returns:
|
||||
(can_stamp, error_message)
|
||||
"""
|
||||
if not self.last_stamp_at:
|
||||
return True, None
|
||||
|
||||
now = datetime.now(UTC)
|
||||
elapsed = (now - self.last_stamp_at).total_seconds() / 60
|
||||
|
||||
if elapsed < cooldown_minutes:
|
||||
remaining = int(cooldown_minutes - elapsed)
|
||||
return False, f"Please wait {remaining} minutes before next stamp"
|
||||
|
||||
return True, None
|
||||
268
app/modules/loyalty/models/loyalty_program.py
Normal file
268
app/modules/loyalty/models/loyalty_program.py
Normal file
@@ -0,0 +1,268 @@
|
||||
# app/modules/loyalty/models/loyalty_program.py
|
||||
"""
|
||||
Loyalty program database model.
|
||||
|
||||
Defines the vendor's loyalty program configuration including:
|
||||
- Program type (stamps, points, hybrid)
|
||||
- Stamp configuration (target, reward description)
|
||||
- Points configuration (per euro rate, rewards catalog)
|
||||
- Anti-fraud settings (cooldown, daily limits, PIN requirement)
|
||||
- Branding (card name, color, logo)
|
||||
- Wallet integration IDs (Google, Apple)
|
||||
"""
|
||||
|
||||
import enum
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from sqlalchemy import (
|
||||
Boolean,
|
||||
Column,
|
||||
DateTime,
|
||||
ForeignKey,
|
||||
Index,
|
||||
Integer,
|
||||
String,
|
||||
Text,
|
||||
)
|
||||
from sqlalchemy.dialects.sqlite import JSON
|
||||
from sqlalchemy.orm import relationship
|
||||
|
||||
from app.core.database import Base
|
||||
from models.database.base import TimestampMixin
|
||||
|
||||
|
||||
class LoyaltyType(str, enum.Enum):
|
||||
"""Type of loyalty program."""
|
||||
|
||||
STAMPS = "stamps" # Collect N stamps, get reward
|
||||
POINTS = "points" # Earn points per euro, redeem for rewards
|
||||
HYBRID = "hybrid" # Both stamps and points
|
||||
|
||||
|
||||
class LoyaltyProgram(Base, TimestampMixin):
|
||||
"""
|
||||
Vendor's loyalty program configuration.
|
||||
|
||||
Each vendor can have one loyalty program that defines:
|
||||
- Program type and mechanics
|
||||
- Stamp or points configuration
|
||||
- Anti-fraud rules
|
||||
- Branding and wallet integration
|
||||
"""
|
||||
|
||||
__tablename__ = "loyalty_programs"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
|
||||
# Vendor association (one program per vendor)
|
||||
vendor_id = Column(
|
||||
Integer,
|
||||
ForeignKey("vendors.id", ondelete="CASCADE"),
|
||||
unique=True,
|
||||
nullable=False,
|
||||
index=True,
|
||||
)
|
||||
|
||||
# Program type
|
||||
loyalty_type = Column(
|
||||
String(20),
|
||||
default=LoyaltyType.STAMPS.value,
|
||||
nullable=False,
|
||||
)
|
||||
|
||||
# =========================================================================
|
||||
# Stamps Configuration
|
||||
# =========================================================================
|
||||
stamps_target = Column(
|
||||
Integer,
|
||||
default=10,
|
||||
nullable=False,
|
||||
comment="Number of stamps needed for reward",
|
||||
)
|
||||
stamps_reward_description = Column(
|
||||
String(255),
|
||||
default="Free item",
|
||||
nullable=False,
|
||||
comment="Description of stamp reward",
|
||||
)
|
||||
stamps_reward_value_cents = Column(
|
||||
Integer,
|
||||
nullable=True,
|
||||
comment="Value of stamp reward in cents (for analytics)",
|
||||
)
|
||||
|
||||
# =========================================================================
|
||||
# Points Configuration
|
||||
# =========================================================================
|
||||
points_per_euro = Column(
|
||||
Integer,
|
||||
default=10,
|
||||
nullable=False,
|
||||
comment="Points earned per euro spent",
|
||||
)
|
||||
points_rewards = Column(
|
||||
JSON,
|
||||
default=list,
|
||||
nullable=False,
|
||||
comment="List of point rewards: [{id, name, points_required, description}]",
|
||||
)
|
||||
|
||||
# =========================================================================
|
||||
# Anti-Fraud Settings
|
||||
# =========================================================================
|
||||
cooldown_minutes = Column(
|
||||
Integer,
|
||||
default=15,
|
||||
nullable=False,
|
||||
comment="Minutes between stamps for same card",
|
||||
)
|
||||
max_daily_stamps = Column(
|
||||
Integer,
|
||||
default=5,
|
||||
nullable=False,
|
||||
comment="Maximum stamps per card per day",
|
||||
)
|
||||
require_staff_pin = Column(
|
||||
Boolean,
|
||||
default=True,
|
||||
nullable=False,
|
||||
comment="Require staff PIN for stamp/points operations",
|
||||
)
|
||||
|
||||
# =========================================================================
|
||||
# Branding
|
||||
# =========================================================================
|
||||
card_name = Column(
|
||||
String(100),
|
||||
nullable=True,
|
||||
comment="Display name for loyalty card",
|
||||
)
|
||||
card_color = Column(
|
||||
String(7),
|
||||
default="#4F46E5",
|
||||
nullable=False,
|
||||
comment="Primary color for card (hex)",
|
||||
)
|
||||
card_secondary_color = Column(
|
||||
String(7),
|
||||
nullable=True,
|
||||
comment="Secondary color for card (hex)",
|
||||
)
|
||||
logo_url = Column(
|
||||
String(500),
|
||||
nullable=True,
|
||||
comment="URL to vendor logo for card",
|
||||
)
|
||||
hero_image_url = Column(
|
||||
String(500),
|
||||
nullable=True,
|
||||
comment="URL to hero image for card",
|
||||
)
|
||||
|
||||
# =========================================================================
|
||||
# Wallet Integration
|
||||
# =========================================================================
|
||||
google_issuer_id = Column(
|
||||
String(100),
|
||||
nullable=True,
|
||||
comment="Google Wallet Issuer ID",
|
||||
)
|
||||
google_class_id = Column(
|
||||
String(200),
|
||||
nullable=True,
|
||||
comment="Google Wallet Loyalty Class ID",
|
||||
)
|
||||
apple_pass_type_id = Column(
|
||||
String(100),
|
||||
nullable=True,
|
||||
comment="Apple Wallet Pass Type ID",
|
||||
)
|
||||
|
||||
# =========================================================================
|
||||
# Terms and Conditions
|
||||
# =========================================================================
|
||||
terms_text = Column(
|
||||
Text,
|
||||
nullable=True,
|
||||
comment="Loyalty program terms and conditions",
|
||||
)
|
||||
privacy_url = Column(
|
||||
String(500),
|
||||
nullable=True,
|
||||
comment="URL to privacy policy",
|
||||
)
|
||||
|
||||
# =========================================================================
|
||||
# Status
|
||||
# =========================================================================
|
||||
is_active = Column(
|
||||
Boolean,
|
||||
default=True,
|
||||
nullable=False,
|
||||
index=True,
|
||||
)
|
||||
activated_at = Column(
|
||||
DateTime(timezone=True),
|
||||
nullable=True,
|
||||
comment="When program was first activated",
|
||||
)
|
||||
|
||||
# =========================================================================
|
||||
# Relationships
|
||||
# =========================================================================
|
||||
vendor = relationship("Vendor", back_populates="loyalty_program")
|
||||
cards = relationship(
|
||||
"LoyaltyCard",
|
||||
back_populates="program",
|
||||
cascade="all, delete-orphan",
|
||||
)
|
||||
staff_pins = relationship(
|
||||
"StaffPin",
|
||||
back_populates="program",
|
||||
cascade="all, delete-orphan",
|
||||
)
|
||||
|
||||
# Indexes
|
||||
__table_args__ = (
|
||||
Index("idx_loyalty_program_vendor_active", "vendor_id", "is_active"),
|
||||
)
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"<LoyaltyProgram(id={self.id}, vendor_id={self.vendor_id}, type='{self.loyalty_type}')>"
|
||||
|
||||
# =========================================================================
|
||||
# Properties
|
||||
# =========================================================================
|
||||
|
||||
@property
|
||||
def is_stamps_enabled(self) -> bool:
|
||||
"""Check if stamps are enabled for this program."""
|
||||
return self.loyalty_type in (LoyaltyType.STAMPS.value, LoyaltyType.HYBRID.value)
|
||||
|
||||
@property
|
||||
def is_points_enabled(self) -> bool:
|
||||
"""Check if points are enabled for this program."""
|
||||
return self.loyalty_type in (LoyaltyType.POINTS.value, LoyaltyType.HYBRID.value)
|
||||
|
||||
@property
|
||||
def display_name(self) -> str:
|
||||
"""Get display name for the program."""
|
||||
return self.card_name or "Loyalty Card"
|
||||
|
||||
def get_points_reward(self, reward_id: str) -> dict | None:
|
||||
"""Get a specific points reward by ID."""
|
||||
rewards = self.points_rewards or []
|
||||
for reward in rewards:
|
||||
if reward.get("id") == reward_id:
|
||||
return reward
|
||||
return None
|
||||
|
||||
def activate(self) -> None:
|
||||
"""Activate the loyalty program."""
|
||||
self.is_active = True
|
||||
if not self.activated_at:
|
||||
self.activated_at = datetime.now(UTC)
|
||||
|
||||
def deactivate(self) -> None:
|
||||
"""Deactivate the loyalty program."""
|
||||
self.is_active = False
|
||||
238
app/modules/loyalty/models/loyalty_transaction.py
Normal file
238
app/modules/loyalty/models/loyalty_transaction.py
Normal file
@@ -0,0 +1,238 @@
|
||||
# app/modules/loyalty/models/loyalty_transaction.py
|
||||
"""
|
||||
Loyalty transaction database model.
|
||||
|
||||
Records all loyalty events including:
|
||||
- Stamps earned and redeemed
|
||||
- Points earned and redeemed
|
||||
- Associated metadata (staff PIN, purchase amount, IP, etc.)
|
||||
"""
|
||||
|
||||
import enum
|
||||
|
||||
from sqlalchemy import (
|
||||
Column,
|
||||
DateTime,
|
||||
ForeignKey,
|
||||
Index,
|
||||
Integer,
|
||||
String,
|
||||
Text,
|
||||
)
|
||||
from sqlalchemy.orm import relationship
|
||||
|
||||
from app.core.database import Base
|
||||
from models.database.base import TimestampMixin
|
||||
|
||||
|
||||
class TransactionType(str, enum.Enum):
|
||||
"""Type of loyalty transaction."""
|
||||
|
||||
# Stamps
|
||||
STAMP_EARNED = "stamp_earned"
|
||||
STAMP_REDEEMED = "stamp_redeemed"
|
||||
|
||||
# Points
|
||||
POINTS_EARNED = "points_earned"
|
||||
POINTS_REDEEMED = "points_redeemed"
|
||||
|
||||
# Adjustments (manual corrections by staff)
|
||||
STAMP_ADJUSTMENT = "stamp_adjustment"
|
||||
POINTS_ADJUSTMENT = "points_adjustment"
|
||||
|
||||
# Card lifecycle
|
||||
CARD_CREATED = "card_created"
|
||||
CARD_DEACTIVATED = "card_deactivated"
|
||||
|
||||
|
||||
class LoyaltyTransaction(Base, TimestampMixin):
|
||||
"""
|
||||
Loyalty transaction record.
|
||||
|
||||
Immutable audit log of all loyalty operations for fraud
|
||||
detection, analytics, and customer support.
|
||||
"""
|
||||
|
||||
__tablename__ = "loyalty_transactions"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
|
||||
# Core relationships
|
||||
card_id = Column(
|
||||
Integer,
|
||||
ForeignKey("loyalty_cards.id", ondelete="CASCADE"),
|
||||
nullable=False,
|
||||
index=True,
|
||||
)
|
||||
vendor_id = Column(
|
||||
Integer,
|
||||
ForeignKey("vendors.id", ondelete="CASCADE"),
|
||||
nullable=False,
|
||||
index=True,
|
||||
comment="Denormalized for query performance",
|
||||
)
|
||||
staff_pin_id = Column(
|
||||
Integer,
|
||||
ForeignKey("staff_pins.id", ondelete="SET NULL"),
|
||||
nullable=True,
|
||||
index=True,
|
||||
comment="Staff PIN used for this operation",
|
||||
)
|
||||
|
||||
# =========================================================================
|
||||
# Transaction Details
|
||||
# =========================================================================
|
||||
transaction_type = Column(
|
||||
String(30),
|
||||
nullable=False,
|
||||
index=True,
|
||||
)
|
||||
|
||||
# Delta values (positive for earn, negative for redeem/adjustment)
|
||||
stamps_delta = Column(
|
||||
Integer,
|
||||
default=0,
|
||||
nullable=False,
|
||||
comment="Change in stamps (+1 for earn, -N for redeem)",
|
||||
)
|
||||
points_delta = Column(
|
||||
Integer,
|
||||
default=0,
|
||||
nullable=False,
|
||||
comment="Change in points (+N for earn, -N for redeem)",
|
||||
)
|
||||
|
||||
# Balance after transaction (for historical reference)
|
||||
stamps_balance_after = Column(
|
||||
Integer,
|
||||
nullable=True,
|
||||
comment="Stamp count after this transaction",
|
||||
)
|
||||
points_balance_after = Column(
|
||||
Integer,
|
||||
nullable=True,
|
||||
comment="Points balance after this transaction",
|
||||
)
|
||||
|
||||
# =========================================================================
|
||||
# Purchase Context (for points earned)
|
||||
# =========================================================================
|
||||
purchase_amount_cents = Column(
|
||||
Integer,
|
||||
nullable=True,
|
||||
comment="Purchase amount in cents (for points calculation)",
|
||||
)
|
||||
order_reference = Column(
|
||||
String(100),
|
||||
nullable=True,
|
||||
index=True,
|
||||
comment="Reference to order that triggered points",
|
||||
)
|
||||
|
||||
# =========================================================================
|
||||
# Reward Context (for redemptions)
|
||||
# =========================================================================
|
||||
reward_id = Column(
|
||||
String(50),
|
||||
nullable=True,
|
||||
comment="ID of redeemed reward (from program.points_rewards)",
|
||||
)
|
||||
reward_description = Column(
|
||||
String(255),
|
||||
nullable=True,
|
||||
comment="Description of redeemed reward",
|
||||
)
|
||||
|
||||
# =========================================================================
|
||||
# Audit Fields
|
||||
# =========================================================================
|
||||
ip_address = Column(
|
||||
String(45),
|
||||
nullable=True,
|
||||
comment="IP address of requester (IPv4 or IPv6)",
|
||||
)
|
||||
user_agent = Column(
|
||||
String(500),
|
||||
nullable=True,
|
||||
comment="User agent string",
|
||||
)
|
||||
notes = Column(
|
||||
Text,
|
||||
nullable=True,
|
||||
comment="Additional notes (e.g., reason for adjustment)",
|
||||
)
|
||||
|
||||
# =========================================================================
|
||||
# Timestamps
|
||||
# =========================================================================
|
||||
transaction_at = Column(
|
||||
DateTime(timezone=True),
|
||||
nullable=False,
|
||||
index=True,
|
||||
comment="When the transaction occurred (may differ from created_at)",
|
||||
)
|
||||
|
||||
# =========================================================================
|
||||
# Relationships
|
||||
# =========================================================================
|
||||
card = relationship("LoyaltyCard", back_populates="transactions")
|
||||
vendor = relationship("Vendor", backref="loyalty_transactions")
|
||||
staff_pin = relationship("StaffPin", backref="transactions")
|
||||
|
||||
# Indexes
|
||||
__table_args__ = (
|
||||
Index("idx_loyalty_tx_card_type", "card_id", "transaction_type"),
|
||||
Index("idx_loyalty_tx_vendor_date", "vendor_id", "transaction_at"),
|
||||
Index("idx_loyalty_tx_type_date", "transaction_type", "transaction_at"),
|
||||
)
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return (
|
||||
f"<LoyaltyTransaction(id={self.id}, type='{self.transaction_type}', "
|
||||
f"stamps={self.stamps_delta:+d}, points={self.points_delta:+d})>"
|
||||
)
|
||||
|
||||
# =========================================================================
|
||||
# Properties
|
||||
# =========================================================================
|
||||
|
||||
@property
|
||||
def is_stamp_transaction(self) -> bool:
|
||||
"""Check if this is a stamp-related transaction."""
|
||||
return self.transaction_type in (
|
||||
TransactionType.STAMP_EARNED.value,
|
||||
TransactionType.STAMP_REDEEMED.value,
|
||||
TransactionType.STAMP_ADJUSTMENT.value,
|
||||
)
|
||||
|
||||
@property
|
||||
def is_points_transaction(self) -> bool:
|
||||
"""Check if this is a points-related transaction."""
|
||||
return self.transaction_type in (
|
||||
TransactionType.POINTS_EARNED.value,
|
||||
TransactionType.POINTS_REDEEMED.value,
|
||||
TransactionType.POINTS_ADJUSTMENT.value,
|
||||
)
|
||||
|
||||
@property
|
||||
def is_earn_transaction(self) -> bool:
|
||||
"""Check if this is an earning transaction (stamp or points)."""
|
||||
return self.transaction_type in (
|
||||
TransactionType.STAMP_EARNED.value,
|
||||
TransactionType.POINTS_EARNED.value,
|
||||
)
|
||||
|
||||
@property
|
||||
def is_redemption_transaction(self) -> bool:
|
||||
"""Check if this is a redemption transaction."""
|
||||
return self.transaction_type in (
|
||||
TransactionType.STAMP_REDEEMED.value,
|
||||
TransactionType.POINTS_REDEEMED.value,
|
||||
)
|
||||
|
||||
@property
|
||||
def staff_name(self) -> str | None:
|
||||
"""Get the name of the staff member who performed this transaction."""
|
||||
if self.staff_pin:
|
||||
return self.staff_pin.name
|
||||
return None
|
||||
205
app/modules/loyalty/models/staff_pin.py
Normal file
205
app/modules/loyalty/models/staff_pin.py
Normal file
@@ -0,0 +1,205 @@
|
||||
# app/modules/loyalty/models/staff_pin.py
|
||||
"""
|
||||
Staff PIN database model.
|
||||
|
||||
Provides fraud prevention by requiring staff to authenticate
|
||||
before performing stamp/points operations. Includes:
|
||||
- Secure PIN hashing with bcrypt
|
||||
- Failed attempt tracking
|
||||
- Automatic lockout after too many failures
|
||||
"""
|
||||
|
||||
from datetime import UTC, datetime
|
||||
|
||||
import bcrypt
|
||||
from sqlalchemy import (
|
||||
Boolean,
|
||||
Column,
|
||||
DateTime,
|
||||
ForeignKey,
|
||||
Index,
|
||||
Integer,
|
||||
String,
|
||||
)
|
||||
from sqlalchemy.orm import relationship
|
||||
|
||||
from app.core.database import Base
|
||||
from models.database.base import TimestampMixin
|
||||
|
||||
|
||||
class StaffPin(Base, TimestampMixin):
|
||||
"""
|
||||
Staff PIN for loyalty operations.
|
||||
|
||||
Each staff member can have their own PIN to authenticate
|
||||
stamp/points operations. PINs are hashed with bcrypt and
|
||||
include lockout protection.
|
||||
"""
|
||||
|
||||
__tablename__ = "staff_pins"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
|
||||
# Relationships
|
||||
program_id = Column(
|
||||
Integer,
|
||||
ForeignKey("loyalty_programs.id", ondelete="CASCADE"),
|
||||
nullable=False,
|
||||
index=True,
|
||||
)
|
||||
vendor_id = Column(
|
||||
Integer,
|
||||
ForeignKey("vendors.id", ondelete="CASCADE"),
|
||||
nullable=False,
|
||||
index=True,
|
||||
comment="Denormalized for query performance",
|
||||
)
|
||||
|
||||
# Staff identity
|
||||
name = Column(
|
||||
String(100),
|
||||
nullable=False,
|
||||
comment="Staff member name",
|
||||
)
|
||||
staff_id = Column(
|
||||
String(50),
|
||||
nullable=True,
|
||||
index=True,
|
||||
comment="Optional staff ID/employee number",
|
||||
)
|
||||
|
||||
# PIN authentication
|
||||
pin_hash = Column(
|
||||
String(255),
|
||||
nullable=False,
|
||||
comment="bcrypt hash of PIN",
|
||||
)
|
||||
|
||||
# Security tracking
|
||||
failed_attempts = Column(
|
||||
Integer,
|
||||
default=0,
|
||||
nullable=False,
|
||||
comment="Consecutive failed PIN attempts",
|
||||
)
|
||||
locked_until = Column(
|
||||
DateTime(timezone=True),
|
||||
nullable=True,
|
||||
comment="Lockout expires at this time",
|
||||
)
|
||||
last_used_at = Column(
|
||||
DateTime(timezone=True),
|
||||
nullable=True,
|
||||
comment="Last successful use of PIN",
|
||||
)
|
||||
|
||||
# Status
|
||||
is_active = Column(
|
||||
Boolean,
|
||||
default=True,
|
||||
nullable=False,
|
||||
index=True,
|
||||
)
|
||||
|
||||
# =========================================================================
|
||||
# Relationships
|
||||
# =========================================================================
|
||||
program = relationship("LoyaltyProgram", back_populates="staff_pins")
|
||||
vendor = relationship("Vendor", backref="staff_pins")
|
||||
|
||||
# Indexes
|
||||
__table_args__ = (
|
||||
Index("idx_staff_pin_vendor_active", "vendor_id", "is_active"),
|
||||
Index("idx_staff_pin_program_active", "program_id", "is_active"),
|
||||
)
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"<StaffPin(id={self.id}, name='{self.name}', active={self.is_active})>"
|
||||
|
||||
# =========================================================================
|
||||
# PIN Operations
|
||||
# =========================================================================
|
||||
|
||||
def set_pin(self, plain_pin: str) -> None:
|
||||
"""
|
||||
Hash and store a PIN.
|
||||
|
||||
Args:
|
||||
plain_pin: The plain text PIN (typically 4-6 digits)
|
||||
"""
|
||||
salt = bcrypt.gensalt()
|
||||
self.pin_hash = bcrypt.hashpw(plain_pin.encode("utf-8"), salt).decode("utf-8")
|
||||
|
||||
def verify_pin(self, plain_pin: str) -> bool:
|
||||
"""
|
||||
Verify a PIN against the stored hash.
|
||||
|
||||
Args:
|
||||
plain_pin: The plain text PIN to verify
|
||||
|
||||
Returns:
|
||||
True if PIN matches, False otherwise
|
||||
"""
|
||||
if not self.pin_hash:
|
||||
return False
|
||||
return bcrypt.checkpw(plain_pin.encode("utf-8"), self.pin_hash.encode("utf-8"))
|
||||
|
||||
# =========================================================================
|
||||
# Lockout Management
|
||||
# =========================================================================
|
||||
|
||||
@property
|
||||
def is_locked(self) -> bool:
|
||||
"""Check if PIN is currently locked out."""
|
||||
if not self.locked_until:
|
||||
return False
|
||||
return datetime.now(UTC) < self.locked_until
|
||||
|
||||
def record_failed_attempt(self, max_attempts: int = 5, lockout_minutes: int = 30) -> bool:
|
||||
"""
|
||||
Record a failed PIN attempt.
|
||||
|
||||
Args:
|
||||
max_attempts: Maximum failed attempts before lockout
|
||||
lockout_minutes: Duration of lockout in minutes
|
||||
|
||||
Returns:
|
||||
True if account is now locked
|
||||
"""
|
||||
self.failed_attempts += 1
|
||||
|
||||
if self.failed_attempts >= max_attempts:
|
||||
from datetime import timedelta
|
||||
|
||||
self.locked_until = datetime.now(UTC) + timedelta(minutes=lockout_minutes)
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
def record_success(self) -> None:
|
||||
"""Record a successful PIN verification."""
|
||||
self.failed_attempts = 0
|
||||
self.locked_until = None
|
||||
self.last_used_at = datetime.now(UTC)
|
||||
|
||||
def unlock(self) -> None:
|
||||
"""Manually unlock a PIN (admin action)."""
|
||||
self.failed_attempts = 0
|
||||
self.locked_until = None
|
||||
|
||||
# =========================================================================
|
||||
# Properties
|
||||
# =========================================================================
|
||||
|
||||
@property
|
||||
def remaining_attempts(self) -> int:
|
||||
"""Get remaining attempts before lockout (assuming max 5)."""
|
||||
return max(0, 5 - self.failed_attempts)
|
||||
|
||||
@property
|
||||
def lockout_remaining_seconds(self) -> int | None:
|
||||
"""Get seconds remaining in lockout, or None if not locked."""
|
||||
if not self.locked_until:
|
||||
return None
|
||||
remaining = (self.locked_until - datetime.now(UTC)).total_seconds()
|
||||
return max(0, int(remaining))
|
||||
Reference in New Issue
Block a user