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:
2026-02-05 22:10:27 +01:00
parent 3bdf1695fd
commit d8f3338bc8
54 changed files with 7252 additions and 186 deletions

View File

@@ -12,8 +12,10 @@ Usage:
LoyaltyTransaction,
StaffPin,
AppleDeviceRegistration,
CompanyLoyaltySettings,
LoyaltyType,
TransactionType,
StaffPinPolicy,
)
"""
@@ -41,15 +43,23 @@ from app.modules.loyalty.models.apple_device import (
# Model
AppleDeviceRegistration,
)
from app.modules.loyalty.models.company_settings import (
# Enums
StaffPinPolicy,
# Model
CompanyLoyaltySettings,
)
__all__ = [
# Enums
"LoyaltyType",
"TransactionType",
"StaffPinPolicy",
# Models
"LoyaltyProgram",
"LoyaltyCard",
"LoyaltyTransaction",
"StaffPin",
"AppleDeviceRegistration",
"CompanyLoyaltySettings",
]

View File

@@ -0,0 +1,135 @@
# app/modules/loyalty/models/company_settings.py
"""
Company loyalty settings database model.
Admin-controlled settings that apply to a company's loyalty program.
These settings are managed by platform administrators, not vendors.
"""
from sqlalchemy import (
Boolean,
Column,
ForeignKey,
Index,
Integer,
String,
)
from sqlalchemy.orm import relationship
from app.core.database import Base
from models.database.base import TimestampMixin
class StaffPinPolicy(str):
"""Staff PIN policy options."""
REQUIRED = "required" # Staff PIN always required
OPTIONAL = "optional" # Vendor can choose
DISABLED = "disabled" # Staff PIN not used
class CompanyLoyaltySettings(Base, TimestampMixin):
"""
Admin-controlled settings for company loyalty programs.
These settings are managed by platform administrators and
cannot be changed by vendors. They apply to all vendors
within the company.
"""
__tablename__ = "company_loyalty_settings"
id = Column(Integer, primary_key=True, index=True)
# Company association (one settings per company)
company_id = Column(
Integer,
ForeignKey("companies.id", ondelete="CASCADE"),
unique=True,
nullable=False,
index=True,
comment="Company these settings apply to",
)
# =========================================================================
# Staff PIN Policy (Admin-controlled)
# =========================================================================
staff_pin_policy = Column(
String(20),
default=StaffPinPolicy.REQUIRED,
nullable=False,
comment="Staff PIN policy: required, optional, disabled",
)
staff_pin_lockout_attempts = Column(
Integer,
default=5,
nullable=False,
comment="Max failed PIN attempts before lockout",
)
staff_pin_lockout_minutes = Column(
Integer,
default=30,
nullable=False,
comment="Lockout duration in minutes",
)
# =========================================================================
# Feature Toggles (Admin-controlled)
# =========================================================================
allow_self_enrollment = Column(
Boolean,
default=True,
nullable=False,
comment="Allow customers to self-enroll via QR code",
)
allow_void_transactions = Column(
Boolean,
default=True,
nullable=False,
comment="Allow voiding points for returns",
)
allow_cross_location_redemption = Column(
Boolean,
default=True,
nullable=False,
comment="Allow redemption at any company location",
)
# =========================================================================
# Audit Settings
# =========================================================================
require_order_reference = Column(
Boolean,
default=False,
nullable=False,
comment="Require order reference when earning points",
)
log_ip_addresses = Column(
Boolean,
default=True,
nullable=False,
comment="Log IP addresses for transactions",
)
# =========================================================================
# Relationships
# =========================================================================
company = relationship("Company", backref="loyalty_settings")
# Indexes
__table_args__ = (
Index("idx_company_loyalty_settings_company", "company_id"),
)
def __repr__(self) -> str:
return f"<CompanyLoyaltySettings(id={self.id}, company_id={self.company_id}, pin_policy='{self.staff_pin_policy}')>"
@property
def is_staff_pin_required(self) -> bool:
"""Check if staff PIN is required."""
return self.staff_pin_policy == StaffPinPolicy.REQUIRED
@property
def is_staff_pin_disabled(self) -> bool:
"""Check if staff PIN is disabled."""
return self.staff_pin_policy == StaffPinPolicy.DISABLED

View File

@@ -2,11 +2,16 @@
"""
Loyalty card database model.
Company-based loyalty cards:
- Cards belong to a Company's loyalty program
- Customers can earn and redeem at any vendor within the company
- Tracks where customer enrolled for analytics
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
- QR code/barcode for scanning
"""
import secrets
@@ -28,8 +33,9 @@ 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)])
"""Generate a unique 12-digit card number formatted as XXXX-XXXX-XXXX."""
digits = "".join([str(secrets.randbelow(10)) for _ in range(12)])
return f"{digits[:4]}-{digits[4:8]}-{digits[8:]}"
def generate_qr_code_data() -> str:
@@ -46,7 +52,10 @@ class LoyaltyCard(Base, TimestampMixin):
"""
Customer's loyalty card (PassObject).
Links a customer to a vendor's loyalty program and tracks:
Card belongs to a Company's loyalty program.
The customer can earn and redeem at any vendor within the company.
Links a customer to a company's loyalty program and tracks:
- Stamps and points balances
- Wallet pass integration
- Activity timestamps
@@ -56,7 +65,16 @@ class LoyaltyCard(Base, TimestampMixin):
id = Column(Integer, primary_key=True, index=True)
# Relationships
# Company association (card belongs to company's program)
company_id = Column(
Integer,
ForeignKey("companies.id", ondelete="CASCADE"),
nullable=False,
index=True,
comment="Company whose program this card belongs to",
)
# Customer and program relationships
customer_id = Column(
Integer,
ForeignKey("customers.id", ondelete="CASCADE"),
@@ -69,12 +87,14 @@ class LoyaltyCard(Base, TimestampMixin):
nullable=False,
index=True,
)
vendor_id = Column(
# Track where customer enrolled (for analytics)
enrolled_at_vendor_id = Column(
Integer,
ForeignKey("vendors.id", ondelete="CASCADE"),
nullable=False,
ForeignKey("vendors.id", ondelete="SET NULL"),
nullable=True,
index=True,
comment="Denormalized for query performance",
comment="Vendor where customer enrolled (for analytics)",
)
# =========================================================================
@@ -86,7 +106,7 @@ class LoyaltyCard(Base, TimestampMixin):
nullable=False,
default=generate_card_number,
index=True,
comment="Human-readable card number",
comment="Human-readable card number (XXXX-XXXX-XXXX)",
)
qr_code_data = Column(
String(50),
@@ -183,13 +203,18 @@ class LoyaltyCard(Base, TimestampMixin):
last_points_at = Column(
DateTime(timezone=True),
nullable=True,
comment="Last points earned",
comment="Last points earned (for expiration tracking)",
)
last_redemption_at = Column(
DateTime(timezone=True),
nullable=True,
comment="Last reward redemption",
)
last_activity_at = Column(
DateTime(timezone=True),
nullable=True,
comment="Any activity (for expiration calculation)",
)
# =========================================================================
# Status
@@ -204,9 +229,13 @@ class LoyaltyCard(Base, TimestampMixin):
# =========================================================================
# Relationships
# =========================================================================
company = relationship("Company", backref="loyalty_cards")
customer = relationship("Customer", backref="loyalty_cards")
program = relationship("LoyaltyProgram", back_populates="cards")
vendor = relationship("Vendor", backref="loyalty_cards")
enrolled_at_vendor = relationship(
"Vendor",
backref="enrolled_loyalty_cards",
)
transactions = relationship(
"LoyaltyTransaction",
back_populates="card",
@@ -219,14 +248,15 @@ class LoyaltyCard(Base, TimestampMixin):
cascade="all, delete-orphan",
)
# Indexes
# Indexes - one card per customer per company
__table_args__ = (
Index("idx_loyalty_card_company_customer", "company_id", "customer_id", unique=True),
Index("idx_loyalty_card_company_active", "company_id", "is_active"),
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})>"
return f"<LoyaltyCard(id={self.id}, card_number='{self.card_number}', stamps={self.stamp_count}, points={self.points_balance})>"
# =========================================================================
# Stamp Operations
@@ -241,6 +271,7 @@ class LoyaltyCard(Base, TimestampMixin):
self.stamp_count += 1
self.total_stamps_earned += 1
self.last_stamp_at = datetime.now(UTC)
self.last_activity_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
@@ -258,6 +289,7 @@ class LoyaltyCard(Base, TimestampMixin):
self.stamp_count -= stamps_target
self.stamps_redeemed += 1
self.last_redemption_at = datetime.now(UTC)
self.last_activity_at = datetime.now(UTC)
return True
return False
@@ -270,6 +302,7 @@ class LoyaltyCard(Base, TimestampMixin):
self.points_balance += points
self.total_points_earned += points
self.last_points_at = datetime.now(UTC)
self.last_activity_at = datetime.now(UTC)
def redeem_points(self, points: int) -> bool:
"""
@@ -281,9 +314,29 @@ class LoyaltyCard(Base, TimestampMixin):
self.points_balance -= points
self.points_redeemed += points
self.last_redemption_at = datetime.now(UTC)
self.last_activity_at = datetime.now(UTC)
return True
return False
def void_points(self, points: int) -> None:
"""
Void points (for returns).
Args:
points: Number of points to void
"""
self.points_balance = max(0, self.points_balance - points)
self.last_activity_at = datetime.now(UTC)
def expire_points(self, points: int) -> None:
"""
Expire points due to inactivity.
Args:
points: Number of points to expire
"""
self.points_balance = max(0, self.points_balance - points)
# =========================================================================
# Properties
# =========================================================================

View File

@@ -2,7 +2,12 @@
"""
Loyalty program database model.
Defines the vendor's loyalty program configuration including:
Company-based loyalty program configuration:
- Program belongs to Company (one program per company)
- All vendors under a company share the same loyalty program
- Customers earn and redeem points at any location (vendor) within the company
Defines:
- Program type (stamps, points, hybrid)
- Stamp configuration (target, reward description)
- Points configuration (per euro rate, rewards catalog)
@@ -41,9 +46,13 @@ class LoyaltyType(str, enum.Enum):
class LoyaltyProgram(Base, TimestampMixin):
"""
Vendor's loyalty program configuration.
Company's loyalty program configuration.
Each vendor can have one loyalty program that defines:
Program belongs to Company (chain-wide shared points).
All vendors under a company share the same loyalty program.
Customers can earn and redeem at any vendor within the company.
Each company can have one loyalty program that defines:
- Program type and mechanics
- Stamp or points configuration
- Anti-fraud rules
@@ -54,19 +63,20 @@ class LoyaltyProgram(Base, TimestampMixin):
id = Column(Integer, primary_key=True, index=True)
# Vendor association (one program per vendor)
vendor_id = Column(
# Company association (one program per company)
company_id = Column(
Integer,
ForeignKey("vendors.id", ondelete="CASCADE"),
ForeignKey("companies.id", ondelete="CASCADE"),
unique=True,
nullable=False,
index=True,
comment="Company that owns this program (chain-wide)",
)
# Program type
loyalty_type = Column(
String(20),
default=LoyaltyType.STAMPS.value,
default=LoyaltyType.POINTS.value,
nullable=False,
)
@@ -96,9 +106,9 @@ class LoyaltyProgram(Base, TimestampMixin):
# =========================================================================
points_per_euro = Column(
Integer,
default=10,
default=1,
nullable=False,
comment="Points earned per euro spent",
comment="Points earned per euro spent (1 euro = X points)",
)
points_rewards = Column(
JSON,
@@ -107,6 +117,38 @@ class LoyaltyProgram(Base, TimestampMixin):
comment="List of point rewards: [{id, name, points_required, description}]",
)
# Points expiration and bonus settings
points_expiration_days = Column(
Integer,
nullable=True,
comment="Days of inactivity before points expire (None = never expire)",
)
welcome_bonus_points = Column(
Integer,
default=0,
nullable=False,
comment="Bonus points awarded on enrollment",
)
minimum_redemption_points = Column(
Integer,
default=100,
nullable=False,
comment="Minimum points required for any redemption",
)
minimum_purchase_cents = Column(
Integer,
default=0,
nullable=False,
comment="Minimum purchase amount (cents) to earn points (0 = no minimum)",
)
# Future tier configuration (Bronze/Silver/Gold)
tier_config = Column(
JSON,
nullable=True,
comment='Future: Tier thresholds {"bronze": 0, "silver": 1000, "gold": 5000}',
)
# =========================================================================
# Anti-Fraud Settings
# =========================================================================
@@ -151,7 +193,7 @@ class LoyaltyProgram(Base, TimestampMixin):
logo_url = Column(
String(500),
nullable=True,
comment="URL to vendor logo for card",
comment="URL to company logo for card",
)
hero_image_url = Column(
String(500),
@@ -210,7 +252,7 @@ class LoyaltyProgram(Base, TimestampMixin):
# =========================================================================
# Relationships
# =========================================================================
vendor = relationship("Vendor", back_populates="loyalty_program")
company = relationship("Company", backref="loyalty_program")
cards = relationship(
"LoyaltyCard",
back_populates="program",
@@ -224,11 +266,11 @@ class LoyaltyProgram(Base, TimestampMixin):
# Indexes
__table_args__ = (
Index("idx_loyalty_program_vendor_active", "vendor_id", "is_active"),
Index("idx_loyalty_program_company_active", "company_id", "is_active"),
)
def __repr__(self) -> str:
return f"<LoyaltyProgram(id={self.id}, vendor_id={self.vendor_id}, type='{self.loyalty_type}')>"
return f"<LoyaltyProgram(id={self.id}, company_id={self.company_id}, type='{self.loyalty_type}')>"
# =========================================================================
# Properties

View File

@@ -2,9 +2,15 @@
"""
Loyalty transaction database model.
Company-based transaction tracking:
- Tracks which company and vendor processed each transaction
- Enables chain-wide reporting while maintaining per-location audit trails
- Supports voiding transactions for returns
Records all loyalty events including:
- Stamps earned and redeemed
- Points earned and redeemed
- Welcome bonuses and expirations
- Associated metadata (staff PIN, purchase amount, IP, etc.)
"""
@@ -31,10 +37,12 @@ class TransactionType(str, enum.Enum):
# Stamps
STAMP_EARNED = "stamp_earned"
STAMP_REDEEMED = "stamp_redeemed"
STAMP_VOIDED = "stamp_voided" # Stamps voided due to return
# Points
POINTS_EARNED = "points_earned"
POINTS_REDEEMED = "points_redeemed"
POINTS_VOIDED = "points_voided" # Points voided due to return
# Adjustments (manual corrections by staff)
STAMP_ADJUSTMENT = "stamp_adjustment"
@@ -44,6 +52,10 @@ class TransactionType(str, enum.Enum):
CARD_CREATED = "card_created"
CARD_DEACTIVATED = "card_deactivated"
# Bonuses and expiration
WELCOME_BONUS = "welcome_bonus" # Welcome bonus points on enrollment
POINTS_EXPIRED = "points_expired" # Points expired due to inactivity
class LoyaltyTransaction(Base, TimestampMixin):
"""
@@ -51,12 +63,25 @@ class LoyaltyTransaction(Base, TimestampMixin):
Immutable audit log of all loyalty operations for fraud
detection, analytics, and customer support.
Tracks which vendor (location) processed the transaction,
enabling chain-wide reporting while maintaining per-location
audit trails.
"""
__tablename__ = "loyalty_transactions"
id = Column(Integer, primary_key=True, index=True)
# Company association
company_id = Column(
Integer,
ForeignKey("companies.id", ondelete="CASCADE"),
nullable=False,
index=True,
comment="Company that owns the loyalty program",
)
# Core relationships
card_id = Column(
Integer,
@@ -66,10 +91,10 @@ class LoyaltyTransaction(Base, TimestampMixin):
)
vendor_id = Column(
Integer,
ForeignKey("vendors.id", ondelete="CASCADE"),
nullable=False,
ForeignKey("vendors.id", ondelete="SET NULL"),
nullable=True,
index=True,
comment="Denormalized for query performance",
comment="Vendor (location) that processed this transaction",
)
staff_pin_id = Column(
Integer,
@@ -79,6 +104,15 @@ class LoyaltyTransaction(Base, TimestampMixin):
comment="Staff PIN used for this operation",
)
# Related transaction (for voids/returns)
related_transaction_id = Column(
Integer,
ForeignKey("loyalty_transactions.id", ondelete="SET NULL"),
nullable=True,
index=True,
comment="Original transaction (for voids/returns)",
)
# =========================================================================
# Transaction Details
# =========================================================================
@@ -175,15 +209,23 @@ class LoyaltyTransaction(Base, TimestampMixin):
# =========================================================================
# Relationships
# =========================================================================
company = relationship("Company", backref="loyalty_transactions")
card = relationship("LoyaltyCard", back_populates="transactions")
vendor = relationship("Vendor", backref="loyalty_transactions")
staff_pin = relationship("StaffPin", backref="transactions")
related_transaction = relationship(
"LoyaltyTransaction",
remote_side=[id],
backref="voiding_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"),
Index("idx_loyalty_tx_company_date", "company_id", "transaction_at"),
Index("idx_loyalty_tx_company_vendor", "company_id", "vendor_id"),
)
def __repr__(self) -> str:
@@ -202,6 +244,7 @@ class LoyaltyTransaction(Base, TimestampMixin):
return self.transaction_type in (
TransactionType.STAMP_EARNED.value,
TransactionType.STAMP_REDEEMED.value,
TransactionType.STAMP_VOIDED.value,
TransactionType.STAMP_ADJUSTMENT.value,
)
@@ -212,6 +255,9 @@ class LoyaltyTransaction(Base, TimestampMixin):
TransactionType.POINTS_EARNED.value,
TransactionType.POINTS_REDEEMED.value,
TransactionType.POINTS_ADJUSTMENT.value,
TransactionType.POINTS_VOIDED.value,
TransactionType.WELCOME_BONUS.value,
TransactionType.POINTS_EXPIRED.value,
)
@property
@@ -220,6 +266,7 @@ class LoyaltyTransaction(Base, TimestampMixin):
return self.transaction_type in (
TransactionType.STAMP_EARNED.value,
TransactionType.POINTS_EARNED.value,
TransactionType.WELCOME_BONUS.value,
)
@property
@@ -230,9 +277,24 @@ class LoyaltyTransaction(Base, TimestampMixin):
TransactionType.POINTS_REDEEMED.value,
)
@property
def is_void_transaction(self) -> bool:
"""Check if this is a void transaction (for returns)."""
return self.transaction_type in (
TransactionType.POINTS_VOIDED.value,
TransactionType.STAMP_VOIDED.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
@property
def vendor_name(self) -> str | None:
"""Get the name of the vendor where this transaction occurred."""
if self.vendor:
return self.vendor.name
return None

View File

@@ -2,6 +2,11 @@
"""
Staff PIN database model.
Company-based staff PINs:
- PINs belong to a company's loyalty program
- Each vendor (location) has its own set of staff PINs
- Staff can only use PINs at their assigned location
Provides fraud prevention by requiring staff to authenticate
before performing stamp/points operations. Includes:
- Secure PIN hashing with bcrypt
@@ -34,13 +39,25 @@ class StaffPin(Base, TimestampMixin):
Each staff member can have their own PIN to authenticate
stamp/points operations. PINs are hashed with bcrypt and
include lockout protection.
PINs are scoped to a specific vendor (location) within the
company's loyalty program.
"""
__tablename__ = "staff_pins"
id = Column(Integer, primary_key=True, index=True)
# Relationships
# Company association
company_id = Column(
Integer,
ForeignKey("companies.id", ondelete="CASCADE"),
nullable=False,
index=True,
comment="Company that owns the loyalty program",
)
# Program and vendor relationships
program_id = Column(
Integer,
ForeignKey("loyalty_programs.id", ondelete="CASCADE"),
@@ -52,7 +69,7 @@ class StaffPin(Base, TimestampMixin):
ForeignKey("vendors.id", ondelete="CASCADE"),
nullable=False,
index=True,
comment="Denormalized for query performance",
comment="Vendor (location) where this staff member works",
)
# Staff identity
@@ -104,17 +121,19 @@ class StaffPin(Base, TimestampMixin):
# =========================================================================
# Relationships
# =========================================================================
company = relationship("Company", backref="staff_pins")
program = relationship("LoyaltyProgram", back_populates="staff_pins")
vendor = relationship("Vendor", backref="staff_pins")
# Indexes
__table_args__ = (
Index("idx_staff_pin_company_active", "company_id", "is_active"),
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})>"
return f"<StaffPin(id={self.id}, name='{self.name}', vendor_id={self.vendor_id}, active={self.is_active})>"
# =========================================================================
# PIN Operations