File size: 2,510 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
from tortoise import fields
from tortoise.models import Model
import datetime
from decimal import Decimal
from App.Users.Model import User
from App.Plans.Model import Plan
from App.Subscriptions.Model import Subscription
from .Schema import PaymentMethod


class Payment(Model):
    id = fields.UUIDField(pk=True)
    user = fields.ForeignKeyField("models.User", related_name="payments", null=True)
    plan = fields.ForeignKeyField(
        "models.Plan",
        related_name="payments",
        null=True,
        description="Plan associated with the payment",
    )
    amount = fields.DecimalField(
        max_digits=10, decimal_places=2, description="Payment amount"
    )
    status = fields.CharField(
        max_length=50,
        default="pending",
        description="Payment status (e.g., pending, completed, failed, balance-assigned)",
    )
    payment_method = fields.CharField(
        max_length=50, choices=PaymentMethod.CHOICES, description="Payment method"
    )
    transaction_id = fields.CharField(
        max_length=100,
        unique=True,
        null=True,
        description="Unique transaction ID for payment (for methods like Lipa Number)",
    )
    created_time = fields.DatetimeField(auto_now_add=True)
    updated_time = fields.DatetimeField(auto_now=True)

    class Meta:
        table = "payments"

    async def create_subscription_if_cash(self):
        """
        Creates a subscription for the user if the payment method is 'cash'
        and the user has enough balance for the specified plan.
        """
        if self.payment_method == PaymentMethod.CASH and self.user and self.plan:
            if self.amount >= self.plan.amount:
                expiration_time = datetime.datetime.now() + datetime.timedelta(
                    hours=self.plan.duration
                )

                # Create the subscription
                await Subscription.create(
                    user=self.user,
                    duration=self.plan.duration,
                    download_mb=self.plan.download_speed
                    * 1024,  # Converting Mbps to MB
                    upload_mb=self.plan.upload_speed * 1024,  # Converting Mbps to MB
                    created_time=datetime.datetime.now(),
                    expiration_time=expiration_time,
                    active=True,
                )
                self.status = "subscription-created"
            else:
                self.status = "insufficient-funds"
            await self.save()