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>
This commit is contained in:
@@ -19,7 +19,10 @@ from sqlalchemy.orm import Session
|
||||
|
||||
from app.modules.loyalty.config import config
|
||||
from app.modules.loyalty.exceptions import (
|
||||
ApplePassGenerationException,
|
||||
AppleWalletNotConfiguredException,
|
||||
DeviceRegistrationException,
|
||||
InvalidAppleAuthTokenException,
|
||||
WalletIntegrationException,
|
||||
)
|
||||
from app.modules.loyalty.models import (
|
||||
@@ -45,6 +48,152 @@ class AppleWalletService:
|
||||
and config.apple_signer_key_path
|
||||
)
|
||||
|
||||
# =========================================================================
|
||||
# Auth Verification
|
||||
# =========================================================================
|
||||
|
||||
def verify_auth_token(self, card: LoyaltyCard, authorization: str | None) -> None:
|
||||
"""
|
||||
Verify the Apple Wallet authorization token for a card.
|
||||
|
||||
Args:
|
||||
card: Loyalty card
|
||||
authorization: Authorization header value (e.g. "ApplePass <token>")
|
||||
|
||||
Raises:
|
||||
InvalidAppleAuthTokenException: If token is missing or invalid
|
||||
"""
|
||||
auth_token = None
|
||||
if authorization and authorization.startswith("ApplePass "):
|
||||
auth_token = authorization.split(" ", 1)[1]
|
||||
|
||||
if not auth_token or auth_token != card.apple_auth_token:
|
||||
raise InvalidAppleAuthTokenException()
|
||||
|
||||
def generate_pass_safe(self, db: Session, card: LoyaltyCard) -> bytes:
|
||||
"""
|
||||
Generate an Apple Wallet pass, wrapping LoyaltyException into
|
||||
ApplePassGenerationException.
|
||||
|
||||
Args:
|
||||
db: Database session
|
||||
card: Loyalty card
|
||||
|
||||
Returns:
|
||||
Bytes of the .pkpass file
|
||||
|
||||
Raises:
|
||||
ApplePassGenerationException: If pass generation fails
|
||||
"""
|
||||
from app.modules.loyalty.exceptions import LoyaltyException
|
||||
|
||||
try:
|
||||
return self.generate_pass(db, card)
|
||||
except LoyaltyException as e:
|
||||
logger.error(f"Failed to generate Apple pass for card {card.id}: {e}")
|
||||
raise ApplePassGenerationException(card.id)
|
||||
|
||||
def get_device_registrations(self, db: Session, device_id: str) -> list:
|
||||
"""
|
||||
Get all device registrations for a device library identifier.
|
||||
|
||||
Args:
|
||||
db: Database session
|
||||
device_id: Device library identifier
|
||||
|
||||
Returns:
|
||||
List of AppleDeviceRegistration objects
|
||||
"""
|
||||
return (
|
||||
db.query(AppleDeviceRegistration)
|
||||
.filter(AppleDeviceRegistration.device_library_identifier == device_id)
|
||||
.all()
|
||||
)
|
||||
|
||||
def get_updated_cards_for_device(
|
||||
self,
|
||||
db: Session,
|
||||
device_id: str,
|
||||
updated_since: str | None = None,
|
||||
) -> list[LoyaltyCard] | None:
|
||||
"""
|
||||
Get cards registered to a device, optionally filtered by update time.
|
||||
|
||||
Args:
|
||||
db: Database session
|
||||
device_id: Device library identifier
|
||||
updated_since: ISO timestamp to filter by
|
||||
|
||||
Returns:
|
||||
List of LoyaltyCard objects, or None if no registrations found
|
||||
"""
|
||||
from datetime import datetime
|
||||
|
||||
registrations = self.get_device_registrations(db, device_id)
|
||||
if not registrations:
|
||||
return None
|
||||
|
||||
card_ids = [r.card_id for r in registrations]
|
||||
query = db.query(LoyaltyCard).filter(LoyaltyCard.id.in_(card_ids))
|
||||
|
||||
if updated_since:
|
||||
try:
|
||||
since = datetime.fromisoformat(updated_since.replace("Z", "+00:00"))
|
||||
query = query.filter(LoyaltyCard.updated_at > since)
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
cards = query.all()
|
||||
return cards if cards else None
|
||||
|
||||
def register_device_safe(
|
||||
self,
|
||||
db: Session,
|
||||
card: LoyaltyCard,
|
||||
device_id: str,
|
||||
push_token: str,
|
||||
) -> None:
|
||||
"""
|
||||
Register a device, wrapping exceptions into DeviceRegistrationException.
|
||||
|
||||
Args:
|
||||
db: Database session
|
||||
card: Loyalty card
|
||||
device_id: Device library identifier
|
||||
push_token: Push token
|
||||
|
||||
Raises:
|
||||
DeviceRegistrationException: If registration fails
|
||||
"""
|
||||
try:
|
||||
self.register_device(db, card, device_id, push_token)
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to register device: {e}")
|
||||
raise DeviceRegistrationException(device_id, "register")
|
||||
|
||||
def unregister_device_safe(
|
||||
self,
|
||||
db: Session,
|
||||
card: LoyaltyCard,
|
||||
device_id: str,
|
||||
) -> None:
|
||||
"""
|
||||
Unregister a device, wrapping exceptions into DeviceRegistrationException.
|
||||
|
||||
Args:
|
||||
db: Database session
|
||||
card: Loyalty card
|
||||
device_id: Device library identifier
|
||||
|
||||
Raises:
|
||||
DeviceRegistrationException: If unregistration fails
|
||||
"""
|
||||
try:
|
||||
self.unregister_device(db, card, device_id)
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to unregister device: {e}")
|
||||
raise DeviceRegistrationException(device_id, "unregister")
|
||||
|
||||
# =========================================================================
|
||||
# Pass Generation
|
||||
# =========================================================================
|
||||
|
||||
@@ -19,6 +19,8 @@ from datetime import UTC, datetime
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
|
||||
from app.modules.loyalty.exceptions import (
|
||||
CustomerIdentifierRequiredException,
|
||||
CustomerNotFoundByEmailException,
|
||||
LoyaltyCardAlreadyExistsException,
|
||||
LoyaltyCardNotFoundException,
|
||||
LoyaltyProgramInactiveException,
|
||||
@@ -106,6 +108,15 @@ class CardService:
|
||||
.first()
|
||||
)
|
||||
|
||||
def get_card_by_serial_number(self, db: Session, serial_number: str) -> LoyaltyCard | None:
|
||||
"""Get a loyalty card by Apple serial number."""
|
||||
return (
|
||||
db.query(LoyaltyCard)
|
||||
.options(joinedload(LoyaltyCard.program))
|
||||
.filter(LoyaltyCard.apple_serial_number == serial_number)
|
||||
.first()
|
||||
)
|
||||
|
||||
def require_card(self, db: Session, card_id: int) -> LoyaltyCard:
|
||||
"""Get a card or raise exception if not found."""
|
||||
card = self.get_card(db, card_id)
|
||||
@@ -113,6 +124,54 @@ class CardService:
|
||||
raise LoyaltyCardNotFoundException(str(card_id))
|
||||
return card
|
||||
|
||||
def require_card_by_serial_number(self, db: Session, serial_number: str) -> LoyaltyCard:
|
||||
"""Get a card by Apple serial number or raise exception if not found."""
|
||||
card = self.get_card_by_serial_number(db, serial_number)
|
||||
if not card:
|
||||
raise LoyaltyCardNotFoundException(serial_number)
|
||||
return card
|
||||
|
||||
def resolve_customer_id(
|
||||
self,
|
||||
db: Session,
|
||||
*,
|
||||
customer_id: int | None,
|
||||
email: str | None,
|
||||
store_id: int,
|
||||
) -> int:
|
||||
"""
|
||||
Resolve a customer ID from either a direct ID or email lookup.
|
||||
|
||||
Args:
|
||||
db: Database session
|
||||
customer_id: Direct customer ID (used if provided)
|
||||
email: Customer email to look up
|
||||
store_id: Store ID for scoping the email lookup
|
||||
|
||||
Returns:
|
||||
Resolved customer ID
|
||||
|
||||
Raises:
|
||||
CustomerIdentifierRequiredException: If neither customer_id nor email provided
|
||||
CustomerNotFoundByEmailException: If email lookup fails
|
||||
"""
|
||||
if customer_id:
|
||||
return customer_id
|
||||
|
||||
if email:
|
||||
from app.modules.customers.models.customer import Customer
|
||||
|
||||
customer = (
|
||||
db.query(Customer)
|
||||
.filter(Customer.email == email, Customer.store_id == store_id)
|
||||
.first()
|
||||
)
|
||||
if not customer:
|
||||
raise CustomerNotFoundByEmailException(email)
|
||||
return customer.id
|
||||
|
||||
raise CustomerIdentifierRequiredException()
|
||||
|
||||
def lookup_card(
|
||||
self,
|
||||
db: Session,
|
||||
@@ -478,6 +537,53 @@ class CardService:
|
||||
|
||||
return transactions, total
|
||||
|
||||
def get_customer_transactions_with_store_names(
|
||||
self,
|
||||
db: Session,
|
||||
card_id: int,
|
||||
*,
|
||||
skip: int = 0,
|
||||
limit: int = 20,
|
||||
) -> tuple[list[dict], int]:
|
||||
"""
|
||||
Get transaction history for a card with store names resolved.
|
||||
|
||||
Returns a list of dicts with transaction data including store_name.
|
||||
"""
|
||||
from app.modules.tenancy.models import Store as StoreModel
|
||||
|
||||
query = (
|
||||
db.query(LoyaltyTransaction)
|
||||
.filter(LoyaltyTransaction.card_id == card_id)
|
||||
.order_by(LoyaltyTransaction.transaction_at.desc())
|
||||
)
|
||||
|
||||
total = query.count()
|
||||
transactions = query.offset(skip).limit(limit).all()
|
||||
|
||||
tx_responses = []
|
||||
for tx in transactions:
|
||||
tx_data = {
|
||||
"id": tx.id,
|
||||
"transaction_type": tx.transaction_type.value if hasattr(tx.transaction_type, "value") else str(tx.transaction_type),
|
||||
"points_delta": tx.points_delta,
|
||||
"stamps_delta": tx.stamps_delta,
|
||||
"points_balance_after": tx.points_balance_after,
|
||||
"stamps_balance_after": tx.stamps_balance_after,
|
||||
"transaction_at": tx.transaction_at.isoformat() if tx.transaction_at else None,
|
||||
"notes": tx.notes,
|
||||
"store_name": None,
|
||||
}
|
||||
|
||||
if tx.store_id:
|
||||
store_obj = db.query(StoreModel).filter(StoreModel.id == tx.store_id).first()
|
||||
if store_obj:
|
||||
tx_data["store_name"] = store_obj.name
|
||||
|
||||
tx_responses.append(tx_data)
|
||||
|
||||
return tx_responses, total
|
||||
|
||||
|
||||
# Singleton instance
|
||||
card_service = CardService()
|
||||
|
||||
@@ -17,7 +17,6 @@ Handles points operations including:
|
||||
import logging
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from fastapi import HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.modules.loyalty.exceptions import (
|
||||
@@ -25,6 +24,7 @@ from app.modules.loyalty.exceptions import (
|
||||
InvalidRewardException,
|
||||
LoyaltyCardInactiveException,
|
||||
LoyaltyProgramInactiveException,
|
||||
OrderReferenceRequiredException,
|
||||
StaffPinRequiredException,
|
||||
)
|
||||
from app.modules.loyalty.models import LoyaltyTransaction, TransactionType
|
||||
@@ -99,7 +99,7 @@ class PointsService:
|
||||
from app.modules.loyalty.services.program_service import program_service
|
||||
settings = program_service.get_merchant_settings(db, card.merchant_id)
|
||||
if settings and settings.require_order_reference and not order_reference:
|
||||
raise HTTPException(400, "Order reference required")
|
||||
raise OrderReferenceRequiredException()
|
||||
|
||||
# Check minimum purchase amount
|
||||
if program.minimum_purchase_cents > 0 and purchase_amount_cents < program.minimum_purchase_cents:
|
||||
|
||||
@@ -111,6 +111,13 @@ class ProgramService:
|
||||
raise LoyaltyProgramNotFoundException(f"merchant:{merchant_id}")
|
||||
return program
|
||||
|
||||
def require_active_program_by_store(self, db: Session, store_id: int) -> LoyaltyProgram:
|
||||
"""Get a store's active program or raise exception if not found."""
|
||||
program = self.get_active_program_by_store(db, store_id)
|
||||
if not program:
|
||||
raise LoyaltyProgramNotFoundException(f"store:{store_id}")
|
||||
return program
|
||||
|
||||
def require_program_by_store(self, db: Session, store_id: int) -> LoyaltyProgram:
|
||||
"""Get a store's program or raise exception if not found."""
|
||||
program = self.get_program_by_store(db, store_id)
|
||||
@@ -118,6 +125,235 @@ class ProgramService:
|
||||
raise LoyaltyProgramNotFoundException(f"store:{store_id}")
|
||||
return program
|
||||
|
||||
def get_store_by_code(self, db: Session, store_code: str):
|
||||
"""
|
||||
Find a store by its store_code or subdomain.
|
||||
|
||||
Args:
|
||||
db: Database session
|
||||
store_code: Store code or subdomain
|
||||
|
||||
Returns:
|
||||
Store object
|
||||
|
||||
Raises:
|
||||
StoreNotFoundException: If store not found
|
||||
"""
|
||||
from app.modules.tenancy.exceptions import StoreNotFoundException
|
||||
from app.modules.tenancy.models import Store
|
||||
|
||||
store = (
|
||||
db.query(Store)
|
||||
.filter(
|
||||
(Store.store_code == store_code) | (Store.subdomain == store_code)
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if not store:
|
||||
raise StoreNotFoundException(store_code)
|
||||
return store
|
||||
|
||||
def get_store_merchant_id(self, db: Session, store_id: int) -> int:
|
||||
"""
|
||||
Get the merchant ID for a store.
|
||||
|
||||
Args:
|
||||
db: Database session
|
||||
store_id: Store ID
|
||||
|
||||
Returns:
|
||||
Merchant ID
|
||||
|
||||
Raises:
|
||||
StoreNotFoundException: If store not found
|
||||
"""
|
||||
from app.modules.tenancy.exceptions import StoreNotFoundException
|
||||
from app.modules.tenancy.models import Store
|
||||
|
||||
store = db.query(Store).filter(Store.id == store_id).first()
|
||||
if not store:
|
||||
raise StoreNotFoundException(str(store_id), identifier_type="id")
|
||||
return store.merchant_id
|
||||
|
||||
def get_merchant_locations(self, db: Session, merchant_id: int) -> list:
|
||||
"""
|
||||
Get all active store locations for a merchant.
|
||||
|
||||
Args:
|
||||
db: Database session
|
||||
merchant_id: Merchant ID
|
||||
|
||||
Returns:
|
||||
List of active Store objects
|
||||
"""
|
||||
from app.modules.tenancy.models import Store
|
||||
|
||||
return (
|
||||
db.query(Store)
|
||||
.filter(Store.merchant_id == merchant_id, Store.is_active == True)
|
||||
.all()
|
||||
)
|
||||
|
||||
def get_program_list_stats(self, db: Session, program) -> dict:
|
||||
"""
|
||||
Get aggregation stats for a program used in list views.
|
||||
|
||||
Args:
|
||||
db: Database session
|
||||
program: LoyaltyProgram instance
|
||||
|
||||
Returns:
|
||||
Dict with merchant_name, total_cards, active_cards,
|
||||
total_points_issued, total_points_redeemed
|
||||
"""
|
||||
from sqlalchemy import func
|
||||
|
||||
from app.modules.loyalty.models import LoyaltyCard, LoyaltyTransaction
|
||||
from app.modules.tenancy.models import Merchant
|
||||
|
||||
merchant = db.query(Merchant).filter(Merchant.id == program.merchant_id).first()
|
||||
merchant_name = merchant.name if merchant else None
|
||||
|
||||
total_cards = (
|
||||
db.query(func.count(LoyaltyCard.id))
|
||||
.filter(LoyaltyCard.merchant_id == program.merchant_id)
|
||||
.scalar()
|
||||
or 0
|
||||
)
|
||||
active_cards = (
|
||||
db.query(func.count(LoyaltyCard.id))
|
||||
.filter(
|
||||
LoyaltyCard.merchant_id == program.merchant_id,
|
||||
LoyaltyCard.is_active == True,
|
||||
)
|
||||
.scalar()
|
||||
or 0
|
||||
)
|
||||
total_points_issued = (
|
||||
db.query(func.sum(LoyaltyTransaction.points_delta))
|
||||
.filter(
|
||||
LoyaltyTransaction.merchant_id == program.merchant_id,
|
||||
LoyaltyTransaction.points_delta > 0,
|
||||
)
|
||||
.scalar()
|
||||
or 0
|
||||
)
|
||||
total_points_redeemed = (
|
||||
db.query(func.sum(func.abs(LoyaltyTransaction.points_delta)))
|
||||
.filter(
|
||||
LoyaltyTransaction.merchant_id == program.merchant_id,
|
||||
LoyaltyTransaction.points_delta < 0,
|
||||
)
|
||||
.scalar()
|
||||
or 0
|
||||
)
|
||||
|
||||
return {
|
||||
"merchant_name": merchant_name,
|
||||
"total_cards": total_cards,
|
||||
"active_cards": active_cards,
|
||||
"total_points_issued": total_points_issued,
|
||||
"total_points_redeemed": total_points_redeemed,
|
||||
}
|
||||
|
||||
def get_platform_stats(self, db: Session) -> dict:
|
||||
"""
|
||||
Get platform-wide loyalty statistics.
|
||||
|
||||
Returns dict with:
|
||||
- total_programs, active_programs
|
||||
- merchants_with_programs
|
||||
- total_cards, active_cards
|
||||
- transactions_30d
|
||||
- points_issued_30d, points_redeemed_30d
|
||||
"""
|
||||
from datetime import UTC, datetime, timedelta
|
||||
|
||||
from sqlalchemy import func
|
||||
|
||||
from app.modules.loyalty.models import (
|
||||
LoyaltyCard,
|
||||
LoyaltyProgram,
|
||||
LoyaltyTransaction,
|
||||
)
|
||||
|
||||
# Program counts
|
||||
total_programs = db.query(func.count(LoyaltyProgram.id)).scalar() or 0
|
||||
active_programs = (
|
||||
db.query(func.count(LoyaltyProgram.id))
|
||||
.filter(LoyaltyProgram.is_active == True)
|
||||
.scalar()
|
||||
or 0
|
||||
)
|
||||
|
||||
# Card counts
|
||||
total_cards = db.query(func.count(LoyaltyCard.id)).scalar() or 0
|
||||
active_cards = (
|
||||
db.query(func.count(LoyaltyCard.id))
|
||||
.filter(LoyaltyCard.is_active == True)
|
||||
.scalar()
|
||||
or 0
|
||||
)
|
||||
|
||||
# Transaction counts (last 30 days)
|
||||
thirty_days_ago = datetime.now(UTC) - timedelta(days=30)
|
||||
transactions_30d = (
|
||||
db.query(func.count(LoyaltyTransaction.id))
|
||||
.filter(LoyaltyTransaction.transaction_at >= thirty_days_ago)
|
||||
.scalar()
|
||||
or 0
|
||||
)
|
||||
|
||||
# Points issued/redeemed (last 30 days)
|
||||
points_issued_30d = (
|
||||
db.query(func.sum(LoyaltyTransaction.points_delta))
|
||||
.filter(
|
||||
LoyaltyTransaction.transaction_at >= thirty_days_ago,
|
||||
LoyaltyTransaction.points_delta > 0,
|
||||
)
|
||||
.scalar()
|
||||
or 0
|
||||
)
|
||||
|
||||
points_redeemed_30d = (
|
||||
db.query(func.sum(func.abs(LoyaltyTransaction.points_delta)))
|
||||
.filter(
|
||||
LoyaltyTransaction.transaction_at >= thirty_days_ago,
|
||||
LoyaltyTransaction.points_delta < 0,
|
||||
)
|
||||
.scalar()
|
||||
or 0
|
||||
)
|
||||
|
||||
# Merchant count with programs
|
||||
merchants_with_programs = (
|
||||
db.query(func.count(func.distinct(LoyaltyProgram.merchant_id))).scalar() or 0
|
||||
)
|
||||
|
||||
return {
|
||||
"total_programs": total_programs,
|
||||
"active_programs": active_programs,
|
||||
"merchants_with_programs": merchants_with_programs,
|
||||
"total_cards": total_cards,
|
||||
"active_cards": active_cards,
|
||||
"transactions_30d": transactions_30d,
|
||||
"points_issued_30d": points_issued_30d,
|
||||
"points_redeemed_30d": points_redeemed_30d,
|
||||
}
|
||||
|
||||
def check_self_enrollment_allowed(self, db: Session, merchant_id: int) -> None:
|
||||
"""
|
||||
Check if self-enrollment is allowed for a merchant.
|
||||
|
||||
Raises:
|
||||
SelfEnrollmentDisabledException: If self-enrollment is disabled
|
||||
"""
|
||||
from app.modules.loyalty.exceptions import SelfEnrollmentDisabledException
|
||||
|
||||
settings = self.get_merchant_settings(db, merchant_id)
|
||||
if settings and not settings.allow_self_enrollment:
|
||||
raise SelfEnrollmentDisabledException()
|
||||
|
||||
def list_programs(
|
||||
self,
|
||||
db: Session,
|
||||
|
||||
Reference in New Issue
Block a user