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:
@@ -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
|
||||
# =========================================================================
|
||||
|
||||
Reference in New Issue
Block a user