hotspot / App /Payments /Model.py
Mbonea's picture
testing deployment
9e798a1
raw
history blame
2.51 kB
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()