File size: 5,155 Bytes
9e798a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
from fastapi import APIRouter, HTTPException, status, Depends
from typing import List
from datetime import datetime
from .Model import Subscription
from App.Users.Model import User
from App.Plans.Model import Plan
from .Schema import (
    CreateSubscriptionRequest,
    SubscriptionResponse,
    BaseResponse,
    UpdateUsageRequest,
    SubscriptionListResponse,
)

subscription_router = APIRouter(tags=["Subscriptions"])


@subscription_router.post("/subscription/create", response_model=BaseResponse)
async def create_subscription(request: CreateSubscriptionRequest):
    # Check if user exists
    user = await User.get_or_none(id=request.user_id)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND, detail="User not found"
        )

    # Check if plan exists
    plan = await Plan.get_or_none(id=request.plan_id)
    if not plan:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND, detail="Plan not found"
        )

    # Create new subscription based on plan details
    expiration_time = datetime.datetime.now() + datetime.timedelta(hours=plan.duration)
    subscription = await Subscription.create(
        user=user,
        plan=plan,
        duration=plan.duration,
        download_mb=plan.download_speed * 1024,  # Converting Mbps to MB
        upload_mb=plan.upload_speed * 1024,  # Converting Mbps to MB
        expiration_time=expiration_time,
        active=True,
    )
    await subscription.save()

    return BaseResponse(
        code=200,
        message="Subscription created successfully",
        payload={"subscription_id": str(subscription.id)},
    )


@subscription_router.get(
    "/subscription/{subscription_id}", response_model=SubscriptionResponse
)
async def get_subscription(subscription_id: str):
    subscription = await Subscription.get_or_none(id=subscription_id)
    if not subscription:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND, detail="Subscription not found"
        )

    remaining_hours = await subscription.time_remaining()

    return SubscriptionResponse(
        id=str(subscription.id),
        user_id=subscription.user_id,
        plan_id=subscription.plan_id,
        active=subscription.active,
        duration=subscription.duration,
        download_mb=subscription.download_mb,
        upload_mb=subscription.upload_mb,
        remaining_hours=remaining_hours,
        created_time=subscription.created_time,
        expiration_time=subscription.expiration_time,
    )


@subscription_router.get(
    "/subscription/user/{user_id}", response_model=List[SubscriptionResponse]
)
async def get_user_subscriptions(user_id: str):
    user = await User.get_or_none(id=user_id)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND, detail="User not found"
        )

    subscriptions = await Subscription.filter(user_id=user_id)
    result = []

    for subscription in subscriptions:
        remaining_hours = await subscription.time_remaining()
        result.append(
            SubscriptionResponse(
                id=str(subscription.id),
                user_id=subscription.user_id,
                plan_id=subscription.plan_id,
                active=subscription.active,
                duration=subscription.duration,
                download_mb=subscription.download_mb,
                upload_mb=subscription.upload_mb,
                remaining_hours=remaining_hours,
                created_time=subscription.created_time,
                expiration_time=subscription.expiration_time,
            )
        )

    return result


@subscription_router.put(
    "/subscription/{subscription_id}/update-usage", response_model=BaseResponse
)
async def update_usage(subscription_id: str, request: UpdateUsageRequest):
    subscription = await Subscription.get_or_none(id=subscription_id)
    if not subscription:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND, detail="Subscription not found"
        )

    if not await subscription.is_valid():
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Subscription is not active or has expired",
        )

    subscription.download_mb += request.download_mb
    subscription.upload_mb += request.upload_mb
    await subscription.save()

    return BaseResponse(
        code=200,
        message="Usage updated successfully",
        payload={
            "total_download_mb": subscription.download_mb,
            "total_upload_mb": subscription.upload_mb,
        },
    )


@subscription_router.post(
    "/subscription/{subscription_id}/deactivate", response_model=BaseResponse
)
async def deactivate_subscription(subscription_id: str):
    subscription = await Subscription.get_or_none(id=subscription_id)
    if not subscription:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND, detail="Subscription not found"
        )

    subscription.active = False
    await subscription.save()

    return BaseResponse(code=200, message="Subscription deactivated successfully")