Files
orion/app/modules/loyalty/routes/api/platform.py
Samir Boulahtit 967f08e4ba feat: add module definition completeness validation and permissions
Add new validation rules MOD-020 to MOD-023 for module definition
completeness and standardize permissions across all modules.

Changes:
- Add MOD-020: Module definitions must have required attributes
- Add MOD-021: Modules with menus should have features
- Add MOD-022: Feature modules should have permissions
- Add MOD-023: Modules with routers should use get_*_with_routers pattern

Module permissions added:
- analytics: view, export, manage_dashboards
- billing: view_tiers, manage_tiers, view_subscriptions, manage_subscriptions, view_invoices
- cart: view, manage
- checkout: view_settings, manage_settings
- cms: view_pages, manage_pages, view_media, manage_media, manage_themes
- loyalty: view_programs, manage_programs, view_rewards, manage_rewards
- marketplace: view_integration, manage_integration, sync_products
- messaging: view_messages, send_messages, manage_templates
- payments: view_gateways, manage_gateways, view_transactions

Module improvements:
- Complete cart module with features and permissions
- Complete checkout module with features and permissions
- Add features to catalog module
- Add version to cms module
- Fix loyalty platform_router attachment
- Add path definitions to payments module
- Remove empty scheduled_tasks from dev_tools module

Documentation:
- Update module-system.md with new validation rules
- Update architecture-rules.md with MOD-020 to MOD-023

Tests:
- Add unit tests for module definition completeness
- Add tests for permission structure validation

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-02 18:23:04 +01:00

314 lines
9.4 KiB
Python

# app/modules/loyalty/routes/api/public.py
"""
Loyalty module public routes.
Public endpoints for:
- Customer enrollment (by vendor code)
- Apple Wallet pass download
- Apple Web Service endpoints for device registration/updates
"""
import logging
from datetime import UTC, datetime
from fastapi import APIRouter, Depends, Header, HTTPException, Path, Response
from sqlalchemy.orm import Session
from app.core.database import get_db
from app.modules.loyalty.exceptions import (
LoyaltyCardNotFoundException,
LoyaltyException,
LoyaltyProgramNotFoundException,
)
from app.modules.loyalty.models import LoyaltyCard, LoyaltyProgram
from app.modules.loyalty.services import (
apple_wallet_service,
card_service,
program_service,
)
logger = logging.getLogger(__name__)
# Public router (no auth required for some endpoints)
public_router = APIRouter(prefix="/loyalty")
# =============================================================================
# Enrollment
# =============================================================================
@public_router.get("/programs/{vendor_code}")
def get_program_by_vendor_code(
vendor_code: str = Path(..., min_length=1, max_length=50),
db: Session = Depends(get_db),
):
"""Get loyalty program info by vendor code (for enrollment page)."""
from app.modules.tenancy.models import Vendor
# Find vendor by code (vendor_code or subdomain)
vendor = (
db.query(Vendor)
.filter(
(Vendor.vendor_code == vendor_code) | (Vendor.subdomain == vendor_code)
)
.first()
)
if not vendor:
raise HTTPException(status_code=404, detail="Vendor not found")
# Get program
program = program_service.get_active_program_by_vendor(db, vendor.id)
if not program:
raise HTTPException(status_code=404, detail="No active loyalty program")
return {
"vendor_name": vendor.name,
"vendor_code": vendor.vendor_code,
"program": {
"id": program.id,
"type": program.loyalty_type,
"name": program.display_name,
"card_color": program.card_color,
"logo_url": program.logo_url,
"stamps_target": program.stamps_target if program.is_stamps_enabled else None,
"stamps_reward": program.stamps_reward_description if program.is_stamps_enabled else None,
"points_per_euro": program.points_per_euro if program.is_points_enabled else None,
"terms_text": program.terms_text,
"privacy_url": program.privacy_url,
},
}
# =============================================================================
# Apple Wallet Pass Download
# =============================================================================
@public_router.get("/passes/apple/{serial_number}.pkpass")
def download_apple_pass(
serial_number: str = Path(...),
db: Session = Depends(get_db),
):
"""Download Apple Wallet pass for a card."""
# Find card by serial number
card = (
db.query(LoyaltyCard)
.filter(LoyaltyCard.apple_serial_number == serial_number)
.first()
)
if not card:
raise HTTPException(status_code=404, detail="Pass not found")
try:
pass_data = apple_wallet_service.generate_pass(db, card)
except LoyaltyException as e:
logger.error(f"Failed to generate Apple pass for card {card.id}: {e}")
raise HTTPException(status_code=500, detail="Failed to generate pass")
return Response(
content=pass_data,
media_type="application/vnd.apple.pkpass",
headers={
"Content-Disposition": f'attachment; filename="{serial_number}.pkpass"',
},
)
# =============================================================================
# Apple Web Service Endpoints
# (Required for Apple Wallet to register devices and get updates)
# =============================================================================
@public_router.post("/apple/v1/devices/{device_id}/registrations/{pass_type_id}/{serial_number}")
def register_device(
device_id: str = Path(...),
pass_type_id: str = Path(...),
serial_number: str = Path(...),
authorization: str | None = Header(None),
db: Session = Depends(get_db),
):
"""
Register a device for push notifications.
Called by Apple when user adds pass to wallet.
"""
# Validate authorization token
auth_token = None
if authorization and authorization.startswith("ApplePass "):
auth_token = authorization.split(" ", 1)[1]
# Find card
card = (
db.query(LoyaltyCard)
.filter(LoyaltyCard.apple_serial_number == serial_number)
.first()
)
if not card:
raise HTTPException(status_code=404)
# Verify auth token
if not auth_token or auth_token != card.apple_auth_token:
raise HTTPException(status_code=401)
# Get push token from request body
# Note: In real implementation, parse the JSON body for pushToken
# For now, use device_id as a placeholder
try:
apple_wallet_service.register_device(db, card, device_id, device_id)
return Response(status_code=201)
except Exception as e:
logger.error(f"Failed to register device: {e}")
raise HTTPException(status_code=500)
@public_router.delete("/apple/v1/devices/{device_id}/registrations/{pass_type_id}/{serial_number}")
def unregister_device(
device_id: str = Path(...),
pass_type_id: str = Path(...),
serial_number: str = Path(...),
authorization: str | None = Header(None),
db: Session = Depends(get_db),
):
"""
Unregister a device.
Called by Apple when user removes pass from wallet.
"""
# Validate authorization token
auth_token = None
if authorization and authorization.startswith("ApplePass "):
auth_token = authorization.split(" ", 1)[1]
# Find card
card = (
db.query(LoyaltyCard)
.filter(LoyaltyCard.apple_serial_number == serial_number)
.first()
)
if not card:
raise HTTPException(status_code=404)
# Verify auth token
if not auth_token or auth_token != card.apple_auth_token:
raise HTTPException(status_code=401)
try:
apple_wallet_service.unregister_device(db, card, device_id)
return Response(status_code=200)
except Exception as e:
logger.error(f"Failed to unregister device: {e}")
raise HTTPException(status_code=500)
@public_router.get("/apple/v1/devices/{device_id}/registrations/{pass_type_id}")
def get_serial_numbers(
device_id: str = Path(...),
pass_type_id: str = Path(...),
passesUpdatedSince: str | None = None,
db: Session = Depends(get_db),
):
"""
Get list of pass serial numbers to update.
Called by Apple to check for updated passes.
"""
from app.modules.loyalty.models import AppleDeviceRegistration
# Find all cards registered to this device
registrations = (
db.query(AppleDeviceRegistration)
.filter(AppleDeviceRegistration.device_library_identifier == device_id)
.all()
)
if not registrations:
return Response(status_code=204)
# Get cards that have been updated since the given timestamp
card_ids = [r.card_id for r in registrations]
query = db.query(LoyaltyCard).filter(LoyaltyCard.id.in_(card_ids))
if passesUpdatedSince:
try:
since = datetime.fromisoformat(passesUpdatedSince.replace("Z", "+00:00"))
query = query.filter(LoyaltyCard.updated_at > since)
except ValueError:
pass
cards = query.all()
if not cards:
return Response(status_code=204)
# Return serial numbers
serial_numbers = [card.apple_serial_number for card in cards if card.apple_serial_number]
last_updated = max(card.updated_at for card in cards)
return {
"serialNumbers": serial_numbers,
"lastUpdated": last_updated.isoformat(),
}
@public_router.get("/apple/v1/passes/{pass_type_id}/{serial_number}")
def get_latest_pass(
pass_type_id: str = Path(...),
serial_number: str = Path(...),
authorization: str | None = Header(None),
db: Session = Depends(get_db),
):
"""
Get the latest version of a pass.
Called by Apple to fetch updated pass data.
"""
# Validate authorization token
auth_token = None
if authorization and authorization.startswith("ApplePass "):
auth_token = authorization.split(" ", 1)[1]
# Find card
card = (
db.query(LoyaltyCard)
.filter(LoyaltyCard.apple_serial_number == serial_number)
.first()
)
if not card:
raise HTTPException(status_code=404)
# Verify auth token
if not auth_token or auth_token != card.apple_auth_token:
raise HTTPException(status_code=401)
try:
pass_data = apple_wallet_service.generate_pass(db, card)
except LoyaltyException as e:
logger.error(f"Failed to generate Apple pass for card {card.id}: {e}")
raise HTTPException(status_code=500, detail="Failed to generate pass")
return Response(
content=pass_data,
media_type="application/vnd.apple.pkpass",
headers={
"Last-Modified": card.updated_at.strftime("%a, %d %b %Y %H:%M:%S GMT"),
},
)
@public_router.post("/apple/v1/log")
def log_errors():
"""
Receive error logs from Apple.
Apple sends error logs here when there are issues with passes.
"""
# Just acknowledge - in production you'd log these
return Response(status_code=200)