Files
sasa-membership/backend/app/api/v1/memberships.py
James Pattinson 43b13ef52d Adding more shit
2025-11-10 15:42:09 +00:00

196 lines
6.2 KiB
Python

from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List
from datetime import date, timedelta
from ...core.database import get_db
from ...models.models import Membership, MembershipStatus, User, MembershipTier, Payment, PaymentStatus
from ...schemas import (
MembershipCreate, MembershipUpdate, MembershipResponse, MessageResponse
)
from ...api.dependencies import get_current_active_user, get_admin_user
from ...services.email_service import email_service
router = APIRouter()
@router.get("/my-memberships", response_model=List[MembershipResponse])
async def get_my_memberships(
current_user: User = Depends(get_current_active_user),
db: Session = Depends(get_db)
):
"""Get current user's memberships"""
memberships = db.query(Membership).filter(
Membership.user_id == current_user.id
).all()
return memberships
@router.post("/", response_model=MembershipResponse, status_code=status.HTTP_201_CREATED)
async def create_membership(
membership_data: MembershipCreate,
current_user: User = Depends(get_current_active_user),
db: Session = Depends(get_db)
):
"""Create a new membership for current user"""
# Verify tier exists
tier = db.query(MembershipTier).filter(
MembershipTier.id == membership_data.tier_id
).first()
if not tier:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Membership tier not found"
)
if not tier.is_active:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Membership tier is not active"
)
# Create membership
membership = Membership(
user_id=current_user.id,
tier_id=membership_data.tier_id,
start_date=membership_data.start_date,
end_date=membership_data.end_date,
auto_renew=membership_data.auto_renew,
status=MembershipStatus.PENDING
)
db.add(membership)
db.commit()
db.refresh(membership)
return membership
@router.get("/{membership_id}", response_model=MembershipResponse)
async def get_membership(
membership_id: int,
current_user: User = Depends(get_current_active_user),
db: Session = Depends(get_db)
):
"""Get membership by ID"""
membership = db.query(Membership).filter(
Membership.id == membership_id
).first()
if not membership:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Membership not found"
)
# Check if user has permission to view this membership
if membership.user_id != current_user.id and current_user.role.value not in ["admin", "super_admin"]:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Not authorized to view this membership"
)
return membership
@router.put("/{membership_id}", response_model=MembershipResponse)
async def update_membership(
membership_id: int,
membership_update: MembershipUpdate,
current_user = Depends(get_admin_user),
db: Session = Depends(get_db)
):
"""Update membership (admin only)"""
membership = db.query(Membership).filter(
Membership.id == membership_id
).first()
if not membership:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Membership not found"
)
update_data = membership_update.model_dump(exclude_unset=True)
was_activated = False
# Check if status is being changed to ACTIVE
if update_data.get("status") == MembershipStatus.ACTIVE and membership.status != MembershipStatus.ACTIVE:
was_activated = True
for field, value in update_data.items():
setattr(membership, field, value)
db.commit()
db.refresh(membership)
# Send activation email if membership was just activated
if was_activated:
try:
# Get the most recent payment for this membership
recent_payment = db.query(Payment).filter(
Payment.membership_id == membership.id,
Payment.status == PaymentStatus.COMPLETED
).order_by(Payment.payment_date.desc()).first()
payment_amount = recent_payment.amount if recent_payment else membership.tier.annual_fee
payment_method = recent_payment.payment_method.value if recent_payment else "N/A"
# Send activation email (non-blocking)
await email_service.send_membership_activation_email(
to_email=membership.user.email,
first_name=membership.user.first_name,
membership_tier=membership.tier.name,
annual_fee=membership.tier.annual_fee,
payment_amount=payment_amount,
payment_method=payment_method,
renewal_date=membership.end_date.strftime("%d %B %Y")
)
except Exception as e:
# Log error but don't fail the membership update
print(f"Failed to send membership activation email: {e}")
return membership
@router.get("/", response_model=List[MembershipResponse])
async def list_memberships(
skip: int = 0,
limit: int = 100,
status: MembershipStatus | None = None,
current_user = Depends(get_admin_user),
db: Session = Depends(get_db)
):
"""List all memberships (admin only)"""
query = db.query(Membership)
if status:
query = query.filter(Membership.status == status)
memberships = query.offset(skip).limit(limit).all()
return memberships
@router.delete("/{membership_id}", response_model=MessageResponse)
async def delete_membership(
membership_id: int,
current_user = Depends(get_admin_user),
db: Session = Depends(get_db)
):
"""Delete membership (admin only)"""
membership = db.query(Membership).filter(
Membership.id == membership_id
).first()
if not membership:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Membership not found"
)
db.delete(membership)
db.commit()
return {"message": "Membership deleted successfully"}