File size: 7,457 Bytes
41eef54
9e798a1
41eef54
9e798a1
 
 
 
 
 
 
 
 
 
 
 
41eef54
 
 
 
 
9e798a1
 
 
 
 
41eef54
9e798a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41eef54
 
 
 
 
 
 
 
9e798a1
 
 
 
 
 
 
 
 
 
73fedea
 
 
9e798a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41eef54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
from fastapi import APIRouter, HTTPException, status, Query, Depends
from typing import List
from datetime import datetime
from .Model import Payment
from App.Users.Model import User
from App.Plans.Model import Plan
from .Schema import (
    CreatePaymentRequest,
    UpdatePaymentStatusRequest,
    PaymentResponse,
    UpdatePaymentUserRequest,
    BaseResponse,
    PaymentListResponse,
)
from .Schema import PaymentMethod
from App.Users.dependencies import (
    get_current_active_user,
    UserType,
)  # Assuming you have a dependency to get the current user


payment_router = APIRouter(tags=["Payments"])


@payment_router.post("/payment/create", response_model=BaseResponse)
async def create_payment(request: CreatePaymentRequest, internal: bool = False):
    # If payment method is "Lipa Number", transaction_id is required
    if (
        request.payment_method == PaymentMethod.LIPA_NUMBER
        and not request.transaction_id
    ):
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Transaction ID is required for Lipa Number payments",
        )

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

    payment = await Payment.get_or_none(transaction_id=request.transaction_id)

    if payment:
        return BaseResponse(
            code=404,
            message="Payment already exists",
            payload={"payment_id": str(payment.id)},
        )
    # Create new payment without linking a user initially
    payment = await Payment.create(
        user_id=request.user_id,
        plan=plan,
        amount=request.amount,
        payment_method=request.payment_method,
        transaction_id=request.transaction_id,
        status="pending",  # Default status
    )

    if internal:
        return payment

    # If payment method is "cash", attempt to create a subscription
    if payment.payment_method == PaymentMethod.CASH:
        await payment.create_subscription_if_cash()

    await payment.save()

    return BaseResponse(
        code=200,
        message="Payment created successfully",
        payload={"payment_id": str(payment.id)},
    )


@payment_router.get("/payment/{payment_id}", response_model=PaymentResponse)
async def get_payment(payment_id: str):
    payment = await Payment.get_or_none(id=payment_id)
    if not payment:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND, detail="Payment not found"
        )

    return PaymentResponse(
        id=str(payment.id),
        user_id=payment.user_id,
        plan_id=payment.plan_id,
        amount=payment.amount,
        payment_method=payment.payment_method,
        status=payment.status,
        transaction_id=payment.transaction_id,
        created_time=payment.created_time,
        updated_time=payment.updated_time,
    )


@payment_router.get("/payments/unlinked", response_model=PaymentListResponse)
async def get_unlinked_payments():
    unlinked_payments = await Payment.filter(user_id=None)
    result = [
        PaymentResponse(
            id=str(payment.id),
            user_id=payment.user_id,
            plan_id=payment.plan_id,
            amount=payment.amount,
            payment_method=payment.payment_method,
            status=payment.status,
            transaction_id=payment.transaction_id,
            created_time=payment.created_time,
            updated_time=payment.updated_time,
        )
        for payment in unlinked_payments
    ]

    return PaymentListResponse(payments=result, total_count=len(result))


@payment_router.put("/payment/{payment_id}/link-user", response_model=BaseResponse)
async def link_user_to_payment(payment_id: str, request: UpdatePaymentUserRequest):
    payment = await Payment.get_or_none(id=payment_id)
    if not payment:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND, detail="Payment not found"
        )

    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"
        )

    # Link payment to the user
    payment.user_id = request.user_id
    await payment.save()

    # If the payment method is "Lipa Number" or "M-Pesa", add to user's balance directly
    if (
        payment.payment_method in [PaymentMethod.LIPA_NUMBER, PaymentMethod.MPESA]
        and not payment.plan
    ):
        user.balance += payment.amount
        await user.save()

        # Update payment status to indicate it was assigned to balance
        payment.status = "balance-assigned"
        await payment.save()

        return BaseResponse(
            code=200,
            message="Payment linked to user and amount added to balance successfully",
            payload={
                "payment_id": str(payment.id),
                "user_id": request.user_id,
                "new_balance": user.balance,
            },
        )

    return BaseResponse(
        code=200,
        message="Payment linked to user successfully",
        payload={"payment_id": str(payment.id), "user_id": request.user_id},
    )


@payment_router.get("/payments/date-range", response_model=PaymentListResponse)
async def get_payments_by_date_range(
    start_date: datetime = Query(..., description="Start date in ISO format"),
    end_date: datetime = Query(..., description="End date in ISO format"),
):
    if start_date > end_date:
        raise HTTPException(
            status_code=400, detail="Start date must be less than or equal to end date"
        )

    payments = await Payment.filter(created_time__range=(start_date, end_date))

    result = [
        PaymentResponse(
            id=str(payment.id),
            user_id=payment.user_id,
            plan_id=payment.plan_id,
            amount=payment.amount,
            payment_method=payment.payment_method,
            status=payment.status,
            transaction_id=payment.transaction_id,
            created_time=payment.created_time,
            updated_time=payment.updated_time,
        )
        for payment in payments
    ]

    return PaymentListResponse(payments=result, total_count=len(result))


@payment_router.get("/payments/user/{user_id}", response_model=PaymentListResponse)
async def get_user_payment_history(
    user_id: str, current_user: User = Depends(get_current_active_user)
):
    # Optionally, you can check if the current user has permission to view this user's payment history
    if current_user.user_type != UserType.ADMIN and current_user.id != user_id:
        raise HTTPException(
            status_code=403,
            detail="User does not have permission to view this payment history",
        )

    payments = await Payment.filter(user_id=user_id)

    result = [
        PaymentResponse(
            id=str(payment.id),
            user_id=payment.user_id,
            plan_id=payment.plan_id,
            amount=payment.amount,
            payment_method=payment.payment_method,
            status=payment.status,
            transaction_id=payment.transaction_id,
            created_time=payment.created_time,
            updated_time=payment.updated_time,
        )
        for payment in payments
    ]

    return PaymentListResponse(payments=result, total_count=len(result))