hotspot / App /Plans /PlanRoutes.py
Mbonea's picture
user powers not tested
f9fbe3f
raw
history blame
3.48 kB
from fastapi import APIRouter, HTTPException, status, Depends
from typing import List
from .Model import Plan
from .Schema import (
CreatePlanRequest,
UpdatePlanRequest,
PlanResponse,
PlanListResponse,
BaseResponse,
)
plan_router = APIRouter(tags=["Plans"])
@plan_router.post("/plan/create", response_model=BaseResponse)
async def create_plan(request: CreatePlanRequest):
# Check if a plan with the same name already exists
existing_plan = await Plan.get_or_none(name=request.name)
if existing_plan:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="A plan with this name already exists",
)
if request.is_promo:
plan = await Plan.create(
name=request.name,
amount=request.amount,
duration=request.duration,
download_speed=request.download_speed,
upload_speed=request.upload_speed,
is_promo=request.is_promo,
)
await plan.set_expiration()
await plan.save()
return BaseResponse(
code=200,
message="Plan created successfully",
payload={"plan_id": str(plan.id)},
)
# Create a new plan not promo
plan = await Plan.create(
name=request.name,
amount=request.amount,
duration=request.duration,
download_speed=request.download_speed,
upload_speed=request.upload_speed,
)
await plan.save()
return BaseResponse(
code=200, message="Plan created successfully", payload={"plan_id": str(plan.id)}
)
@plan_router.put("/plan/{plan_id}/update", response_model=BaseResponse)
async def update_plan(plan_id: str, request: UpdatePlanRequest):
# Find the plan by ID
plan = await Plan.get_or_none(id=plan_id)
if not plan:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail="Plan not found"
)
# Update the plan fields if provided
if request.name is not None:
plan.name = request.name
if request.amount is not None:
plan.amount = request.amount
if request.duration is not None:
plan.duration = request.duration
if request.download_speed is not None:
plan.download_speed = request.download_speed
if request.upload_speed is not None:
plan.upload_speed = request.upload_speed
await plan.save()
return BaseResponse(
code=200, message="Plan updated successfully", payload={"plan_id": str(plan.id)}
)
@plan_router.delete("/plan/{plan_id}/delete", response_model=BaseResponse)
async def delete_plan(plan_id: str):
# Find the plan by ID
plan = await Plan.get_or_none(id=plan_id)
if not plan:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail="Plan not found"
)
await plan.delete()
return BaseResponse(code=200, message="Plan deleted successfully")
@plan_router.get("/plans", response_model=PlanListResponse)
async def list_plans():
plans = await Plan.all()
total_count = await Plan.all().count()
result = [
PlanResponse(
id=str(plan.id),
name=plan.name,
amount=plan.amount,
duration=plan.duration,
download_speed=plan.download_speed,
upload_speed=plan.upload_speed,
)
for plan in plans
]
return PlanListResponse(plans=result, total_count=total_count)