File size: 4,838 Bytes
9e798a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73fedea
9e798a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73fedea
 
 
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
from fastapi import APIRouter, HTTPException, status
from typing import List
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

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


@payment_router.post("/payment/create", response_model=BaseResponse)
async def create_payment(request: CreatePaymentRequest, internal=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"
        )

    # 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},
    )