Files
orion/app/modules/loyalty/routes/api/platform.py
Samir Boulahtit 7c43d6f4a2 refactor: fix all architecture validator findings (202 → 0)
Eliminate all 103 errors and 96 warnings from the architecture validator:

Phase 1 - Validator rules & YAML:
- Add NAM-001/NAM-002 exceptions for module-scoped router/service files
- Fix API-004 to detect # public comments on decorator lines
- Add module-specific exception bases to EXC-004 valid_bases
- Exclude storefront files from AUTH-004 store context check
- Add SVC-006 exceptions for loyalty service atomic commits
- Fix _get_rule() to search naming_rules and auth_rules categories
- Use plain # CODE comments instead of # noqa: CODE for custom rules

Phase 2 - Billing module (5 route files):
- Move _resolve_store_to_merchant to subscription_service
- Move tier/feature queries to feature_service, admin_subscription_service
- Extract 22 inline Pydantic schemas to billing/schemas/billing.py
- Replace all HTTPException with domain exceptions

Phase 3 - Loyalty module (4 routes + points_service):
- Add 7 domain exceptions (Apple auth, enrollment, device registration)
- Add service methods to card_service, program_service, apple_wallet_service
- Move all db.query() from routes to service layer
- Fix SVC-001: replace HTTPException in points_service with domain exception

Phase 4 - Remaining modules:
- tenancy: move store stats queries to admin_service
- cms: move platform resolution to content_page_service, add NoPlatformSubscriptionException
- messaging: move user/customer lookups to messaging_service
- Add ConfigDict(from_attributes=True) to ContentPageResponse

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 18:49:24 +01:00

212 lines
6.9 KiB
Python

# app/modules/loyalty/routes/api/platform.py
"""
Loyalty module platform routes.
Platform endpoints for:
- Customer enrollment (by store code)
- Apple Wallet pass download
- Apple Web Service endpoints for device registration/updates
"""
import logging
from fastapi import APIRouter, Depends, Header, Path, Response
from sqlalchemy.orm import Session
from app.core.database import get_db
from app.modules.loyalty.services import (
apple_wallet_service,
card_service,
program_service,
)
logger = logging.getLogger(__name__)
# Platform router (no auth required for some endpoints)
platform_router = APIRouter(prefix="/loyalty")
# =============================================================================
# Enrollment
# =============================================================================
@platform_router.get("/programs/{store_code}")
def get_program_by_store_code(
store_code: str = Path(..., min_length=1, max_length=50),
db: Session = Depends(get_db),
):
"""Get loyalty program info by store code (for enrollment page)."""
# Find store by code (store_code or subdomain)
store = program_service.get_store_by_code(db, store_code)
# Get program (raises LoyaltyProgramNotFoundException if not found)
program = program_service.require_active_program_by_store(db, store.id)
return {
"store_name": store.name,
"store_code": store.store_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
# =============================================================================
@platform_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 (raises LoyaltyCardNotFoundException if not found)
card = card_service.require_card_by_serial_number(db, serial_number)
pass_data = apple_wallet_service.generate_pass_safe(db, card)
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)
# =============================================================================
@platform_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.
"""
# Find card (raises LoyaltyCardNotFoundException if not found)
card = card_service.require_card_by_serial_number(db, serial_number)
# Verify auth token (raises InvalidAppleAuthTokenException if invalid)
apple_wallet_service.verify_auth_token(card, authorization)
# Get push token from request body
# Note: In real implementation, parse the JSON body for pushToken
# For now, use device_id as a placeholder
apple_wallet_service.register_device_safe(db, card, device_id, device_id)
return Response(status_code=201)
@platform_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.
"""
# Find card (raises LoyaltyCardNotFoundException if not found)
card = card_service.require_card_by_serial_number(db, serial_number)
# Verify auth token (raises InvalidAppleAuthTokenException if invalid)
apple_wallet_service.verify_auth_token(card, authorization)
apple_wallet_service.unregister_device_safe(db, card, device_id)
return Response(status_code=200)
@platform_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.
"""
# Get cards registered to this device, optionally filtered by update time
cards = apple_wallet_service.get_updated_cards_for_device(
db, device_id, updated_since=passesUpdatedSince
)
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(),
}
@platform_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.
"""
# Find card (raises LoyaltyCardNotFoundException if not found)
card = card_service.require_card_by_serial_number(db, serial_number)
# Verify auth token (raises InvalidAppleAuthTokenException if invalid)
apple_wallet_service.verify_auth_token(card, authorization)
pass_data = apple_wallet_service.generate_pass_safe(db, card)
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"),
},
)
@platform_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)