Compare commits
46
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cd7555e35f | ||
|
|
3cc29cade6 | ||
|
|
7003e4bcba | ||
|
|
2da9dcf141 | ||
|
|
081366f87f | ||
|
|
6431d61d39 | ||
|
|
8871de8ce1 | ||
|
|
54056e9b7e | ||
|
|
09768ef2d3 | ||
|
|
48bde9d52b | ||
|
|
e85d605454 | ||
|
|
683cfe76f1 | ||
|
|
3b3e963568 | ||
|
|
c31acead70 | ||
|
|
6ec31023c7 | ||
|
|
6fb70e82a3 | ||
|
|
cf25863afe | ||
|
|
cd17ced67d | ||
|
|
f3e86d5873 | ||
|
|
b6517e79ab | ||
|
|
e88f4268cf | ||
|
|
e8e6a09b24 | ||
|
|
70f8efb19a | ||
|
|
ddb65ca985 | ||
|
|
740d16189b | ||
|
|
212ea2541f | ||
|
|
5db71edc2c | ||
|
|
6568504f5b | ||
|
|
d4b26074e6 | ||
|
|
638c32cb80 | ||
|
|
61e008d4fb | ||
|
|
25bad98900 | ||
|
|
cec2045e5f | ||
|
|
e4a01597aa | ||
|
|
4a944c176b | ||
|
|
f67a3762ad | ||
|
|
2122e8dfee | ||
|
|
978a4a27d0 | ||
|
|
367ccf0f88 | ||
|
|
c07d3c93d2 | ||
|
|
bae0882879 | ||
|
|
708d7c2bec | ||
|
|
dc8fe44004 | ||
|
|
c4f8989734 | ||
|
|
eb43b3108d
|
||
|
|
828da25046
|
+5
-4
@@ -7,7 +7,6 @@ from django.db.models.signals import post_save
|
||||
from api.models import User
|
||||
from django.contrib.auth.models import Permission
|
||||
from api.tasks import verify_user_with_person_api_task
|
||||
from asgiref.sync import sync_to_async
|
||||
|
||||
|
||||
@receiver(post_save, sender=User)
|
||||
@@ -18,7 +17,10 @@ def assign_device_permissions(sender, instance, created, **kwargs):
|
||||
atoll_read_permission = Permission.objects.get(codename="view_atoll")
|
||||
island_read_permission = Permission.objects.get(codename="view_island")
|
||||
payment_permissions = Permission.objects.filter(content_type__model="payment")
|
||||
topup_permissions = Permission.objects.filter(content_type__model="topup")
|
||||
|
||||
for permission in topup_permissions:
|
||||
instance.user_permissions.add(permission)
|
||||
for permission in device_permissions:
|
||||
instance.user_permissions.add(permission)
|
||||
instance.user_permissions.add(atoll_read_permission, island_read_permission)
|
||||
@@ -27,10 +29,9 @@ def assign_device_permissions(sender, instance, created, **kwargs):
|
||||
|
||||
|
||||
@receiver(post_save, sender=User)
|
||||
@sync_to_async
|
||||
def verify_user_with_person_api(sender, instance, created, **kwargs):
|
||||
async def verify_user_with_person_api(sender, instance, created, **kwargs):
|
||||
if created:
|
||||
verify_user_with_person_api_task(instance.id)
|
||||
await verify_user_with_person_api_task.defer_async(instance.id)
|
||||
|
||||
|
||||
@receiver(reset_password_token_created)
|
||||
|
||||
+18
-16
@@ -15,16 +15,16 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
env.read_env(os.path.join(BASE_DIR, ".env"))
|
||||
|
||||
omada_client = Omada()
|
||||
|
||||
|
||||
@app.task
|
||||
def add(x, y):
|
||||
print(f"Adding {x} and {y}")
|
||||
logger.info(f"Executing test background task with {x} and {y}")
|
||||
return x + y
|
||||
|
||||
|
||||
@app.periodic(cron="0 0 */28 * *") # type: ignore
|
||||
@app.periodic(
|
||||
cron="0 0 */28 * *", queue="heavy_tasks", periodic_id="deactivate_expired_devices"
|
||||
) # type: ignore
|
||||
@app.task
|
||||
def deactivate_expired_devices():
|
||||
expired_devices = Device.objects.filter(
|
||||
@@ -64,10 +64,12 @@ def add_new_devices_to_omada(new_devices: list[dict]):
|
||||
:param new_devices: List of new device names to add.
|
||||
"""
|
||||
logger.info("Running add new devices to Omada task...")
|
||||
omada_client = Omada()
|
||||
omada_client.add_new_devices_to_omada(new_devices)
|
||||
|
||||
|
||||
def verify_user_with_person_api_task(user_id: int):
|
||||
@app.task
|
||||
async def verify_user_with_person_api_task(user_id: int):
|
||||
"""
|
||||
Verify the user with the Person API.
|
||||
:param user_id: The ID of the user to verify.
|
||||
@@ -81,16 +83,16 @@ def verify_user_with_person_api_task(user_id: int):
|
||||
return None
|
||||
# Call the Person API to verify the user
|
||||
|
||||
verification_failed_message = f"""
|
||||
_The following user verification failed_:
|
||||
*ID Card:* {user.id_card}
|
||||
*Name:* {user.first_name} {user.last_name}
|
||||
*House Name:* {user.address}
|
||||
*Date of Birth:* {user.dob}
|
||||
*Island:* {(user.atoll.name if user.atoll else "N/A")} {(user.island.name if user.island else "N/A")}
|
||||
*Mobile:* {user.mobile}
|
||||
Visit [SAR Link Portal](https://portal.sarlink.net) to manually verify this user.
|
||||
"""
|
||||
# verification_failed_message = f"""
|
||||
# _The following user verification failed_:
|
||||
# *ID Card:* {user.id_card}
|
||||
# *Name:* {user.first_name} {user.last_name}
|
||||
# *House Name:* {user.address}
|
||||
# *Date of Birth:* {user.dob}
|
||||
# *Island:* {(user.atoll.name if user.atoll else "N/A")} {(user.island.name if user.island else "N/A")}
|
||||
# *Mobile:* {user.mobile}
|
||||
# Visit [SAR Link Portal](https://portal.sarlink.net) to manually verify this user.
|
||||
# """
|
||||
|
||||
# logger.info(verification_failed_message)
|
||||
PERSON_VERIFY_BASE_URL = env.str("PERSON_VERIFY_BASE_URL", default="") # type: ignore
|
||||
@@ -171,7 +173,7 @@ def verify_user_with_person_api_task(user_id: int):
|
||||
user.mobile,
|
||||
f"Dear {user.first_name} {user.last_name}, \n\nYour account registration is being processed. \n\nWe will notify you once verification is complete. \n\n - SAR Link",
|
||||
)
|
||||
send_clean_telegram_markdown(message=verification_failed_message)
|
||||
# send_clean_telegram_markdown(message=verification_failed_message)
|
||||
return False
|
||||
else:
|
||||
# Handle the error case
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
# projects/tasks_app.py
|
||||
from procrastinate import App
|
||||
from procrastinate.contrib.django import django_connector
|
||||
|
||||
app = App(
|
||||
connector=django_connector.DjangoConnector(),
|
||||
periodic_defaults={"max_delay": 86400}, # accept up to 24h delay
|
||||
)
|
||||
|
||||
|
||||
def on_app_ready(app):
|
||||
app.periodic_defaults = {"max_delay": 86400}
|
||||
app.import_paths.append("api.tasks")
|
||||
app.import_paths.append("billing.tasks")
|
||||
+14
-31
@@ -137,37 +137,23 @@ if not DEBUG:
|
||||
DATABASES = {
|
||||
"default": {
|
||||
"ENGINE": "django.db.backends.postgresql",
|
||||
"NAME": env("POSTGRES_DATABASE"),
|
||||
"USER": env("POSTGRES_USER"),
|
||||
"PASSWORD": env("POSTGRES_PASSWORD"),
|
||||
"HOST": env("POSTGRES_HOST"),
|
||||
"PORT": env("POSTGRES_PORT"),
|
||||
"NAME": env("POSTGRES_DATABASE", default="mydb"), # type: ignore
|
||||
"USER": env("POSTGRES_USER", default="postgres"), # type: ignore
|
||||
"PASSWORD": env("POSTGRES_PASSWORD", default="testpass123"), # type: ignore
|
||||
"HOST": env("POSTGRES_HOST", default="localhost"), # type: ignore
|
||||
"PORT": env("POSTGRES_PORT", default="6500"), # type: ignore
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
# More robust caching configuration
|
||||
CACHES = {
|
||||
"default": {
|
||||
"BACKEND": (
|
||||
"django_redis.cache.RedisCache"
|
||||
if not DEBUG
|
||||
else "django.core.cache.backends.locmem.LocMemCache"
|
||||
),
|
||||
"LOCATION": (
|
||||
env("REDIS_URL", default="redis://redis:6379/") if not DEBUG else "" # type: ignore
|
||||
),
|
||||
"OPTIONS": (
|
||||
{
|
||||
"CLIENT_CLASS": (
|
||||
"django_redis.client.DefaultClient" if not DEBUG else None
|
||||
),
|
||||
}
|
||||
if not DEBUG
|
||||
else {}
|
||||
),
|
||||
}
|
||||
}
|
||||
# More robust caching configuration
|
||||
# CACHES = {
|
||||
# "default": {
|
||||
# "BACKEND": "django.core.cache.backends.memcached.PyMemcacheCache",
|
||||
# "LOCATION": "unix:/tmp/memcached.sock",
|
||||
# }
|
||||
# }
|
||||
|
||||
|
||||
# Password validation
|
||||
@@ -371,8 +357,5 @@ PASSWORDLESS_AUTH = {
|
||||
}
|
||||
|
||||
|
||||
# CELERY CONFIGURATION
|
||||
CELERY_BROKER_URL = f"redis://{REDIS_HOST}:6379/0"
|
||||
CELERY_ACCEPT_CONTENT = ["json"]
|
||||
CELERY_TASK_SERIALIZER = "json"
|
||||
CELERY_RESULT_BACKEND = f"redis://{REDIS_HOST}:6379/0"
|
||||
PROCRASTINATE_ON_APP_READY = "api.tasks_app.on_app_ready"
|
||||
PROCRASTINATE_APP = "api.tasks_app.app"
|
||||
|
||||
+27
-1
@@ -18,6 +18,32 @@ class PaymentAdmin(admin.ModelAdmin):
|
||||
)
|
||||
|
||||
|
||||
class TopupAdmin(admin.ModelAdmin):
|
||||
list_display = (
|
||||
"id",
|
||||
"user",
|
||||
"amount",
|
||||
"paid",
|
||||
"paid_at",
|
||||
"status",
|
||||
"created_at",
|
||||
"is_expired",
|
||||
"expires_at",
|
||||
"updated_at",
|
||||
)
|
||||
|
||||
search_fields = (
|
||||
"user__first_name",
|
||||
"user__last_name",
|
||||
"user__id_card",
|
||||
"user__mobile",
|
||||
)
|
||||
|
||||
@admin.display(boolean=True, description="Expired")
|
||||
def is_expired(self, obj):
|
||||
return obj.is_expired
|
||||
|
||||
|
||||
admin.site.register(Payment, PaymentAdmin)
|
||||
admin.site.register(BillFormula)
|
||||
admin.site.register(Topup)
|
||||
admin.site.register(Topup, TopupAdmin)
|
||||
|
||||
+29
-1
@@ -1,5 +1,6 @@
|
||||
import django_filters
|
||||
from .models import Payment
|
||||
from .models import Payment, Topup
|
||||
from django.db.models import Q
|
||||
|
||||
|
||||
class PaymentFilter(django_filters.FilterSet):
|
||||
@@ -16,3 +17,30 @@ class PaymentFilter(django_filters.FilterSet):
|
||||
class Meta:
|
||||
model = Payment
|
||||
fields = "__all__"
|
||||
|
||||
|
||||
class TopupFilter(django_filters.FilterSet):
|
||||
amount = django_filters.RangeFilter(field_name="amount")
|
||||
paid = django_filters.BooleanFilter(field_name="paid")
|
||||
user = django_filters.CharFilter(method="filter_user_search")
|
||||
created_at = django_filters.DateFromToRangeFilter(field_name="created_at")
|
||||
|
||||
def filter_user_search(self, queryset, name, value):
|
||||
"""
|
||||
Search across multiple user fields: first_name, last_name, id_card, mobile
|
||||
"""
|
||||
return queryset.filter(
|
||||
Q(user__first_name__icontains=value)
|
||||
| Q(user__last_name__icontains=value)
|
||||
| Q(user__id_card__icontains=value)
|
||||
| Q(user__mobile__icontains=value)
|
||||
)
|
||||
|
||||
class Meta:
|
||||
model = Topup # Assuming Topup is a subclass of Payment
|
||||
fields = [
|
||||
"amount",
|
||||
"paid",
|
||||
"user",
|
||||
"created_at",
|
||||
]
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
# billing/management/commands/seed_billing.py
|
||||
|
||||
import random
|
||||
from django.core.management.base import BaseCommand
|
||||
from django.utils import timezone
|
||||
from faker import Faker
|
||||
from billing.models import Topup
|
||||
from api.models import User
|
||||
|
||||
|
||||
class Command(BaseCommand):
|
||||
help = "Seeds topup models with dummy data."
|
||||
|
||||
def add_arguments(self, parser):
|
||||
parser.add_argument(
|
||||
"--number",
|
||||
type=int,
|
||||
default=10,
|
||||
help="The number of topups to create.",
|
||||
)
|
||||
|
||||
def handle(self, *args, **options):
|
||||
number = options["number"]
|
||||
fake = Faker()
|
||||
|
||||
users = User.objects.all()
|
||||
if not users.exists():
|
||||
self.stdout.write(
|
||||
self.style.ERROR(
|
||||
"No users found. Please seed users first (e.g., python manage.py seed_users)."
|
||||
)
|
||||
)
|
||||
return
|
||||
|
||||
self.stdout.write(self.style.NOTICE(f"Seeding {number} topups..."))
|
||||
|
||||
for _ in range(number):
|
||||
random_user = random.choice(users)
|
||||
|
||||
expires_at_date = timezone.now() + timezone.timedelta(
|
||||
minutes=10,
|
||||
)
|
||||
print(
|
||||
f"Creating topup for user {getattr(random_user, 'id', None)} expires at: {expires_at_date}"
|
||||
)
|
||||
Topup.objects.create(
|
||||
amount=fake.pydecimal(
|
||||
left_digits=4,
|
||||
right_digits=2,
|
||||
positive=True,
|
||||
min_value=100.00,
|
||||
max_value=5000.00,
|
||||
),
|
||||
status=random.choice(["PENDING", "PAID", "CANCELLED"]),
|
||||
user=random_user,
|
||||
updated_at=timezone.now(),
|
||||
expires_at=expires_at_date,
|
||||
)
|
||||
|
||||
self.stdout.write(self.style.SUCCESS(f"Successfully seeded {number} topups."))
|
||||
@@ -0,0 +1,17 @@
|
||||
# Generated by Django 5.2 on 2025-07-03 11:30
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
dependencies = [
|
||||
("billing", "0005_alter_payment_options_payment_mib_reference"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name="topup",
|
||||
name="mib_reference",
|
||||
field=models.CharField(blank=True, default="", null=True),
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,17 @@
|
||||
# Generated by Django 5.2 on 2025-07-03 12:04
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
dependencies = [
|
||||
("billing", "0006_topup_mib_reference"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name="topup",
|
||||
name="paid_at",
|
||||
field=models.DateTimeField(blank=True, null=True),
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,26 @@
|
||||
# Generated by Django 5.2 on 2025-07-04 06:10
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
dependencies = [
|
||||
("billing", "0007_topup_paid_at"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterModelOptions(
|
||||
name="topup",
|
||||
options={"ordering": ["-created_at"]},
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name="topup",
|
||||
name="expired",
|
||||
field=models.BooleanField(default=False),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name="topup",
|
||||
name="expires_at",
|
||||
field=models.DateTimeField(blank=True, null=True),
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,16 @@
|
||||
# Generated by Django 5.2 on 2025-07-04 11:13
|
||||
|
||||
from django.db import migrations
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
dependencies = [
|
||||
("billing", "0008_alter_topup_options_topup_expired_topup_expires_at"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.RemoveField(
|
||||
model_name="topup",
|
||||
name="expired",
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,17 @@
|
||||
# Generated by Django 5.2 on 2025-07-05 09:26
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
dependencies = [
|
||||
("billing", "0009_remove_topup_expired"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name="topup",
|
||||
name="expiry_notification_sent",
|
||||
field=models.BooleanField(default=False),
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,25 @@
|
||||
# Generated by Django 5.2 on 2025-07-05 12:32
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
dependencies = [
|
||||
("billing", "0010_add_expiry_notification_sent_to_topup"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name="topup",
|
||||
name="status",
|
||||
field=models.CharField(
|
||||
choices=[
|
||||
("PENDING", "Pending"),
|
||||
("PAID", "Paid"),
|
||||
("CANCELLED", "Cancelled"),
|
||||
],
|
||||
default="PENDING",
|
||||
max_length=20,
|
||||
),
|
||||
),
|
||||
]
|
||||
@@ -51,8 +51,30 @@ class Topup(models.Model):
|
||||
amount = models.FloatField()
|
||||
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="topups")
|
||||
paid = models.BooleanField(default=False)
|
||||
paid_at = models.DateTimeField(null=True, blank=True)
|
||||
status = models.CharField(
|
||||
max_length=20,
|
||||
choices=[
|
||||
("PENDING", "Pending"),
|
||||
("PAID", "Paid"),
|
||||
("CANCELLED", "Cancelled"),
|
||||
],
|
||||
default="PENDING",
|
||||
)
|
||||
mib_reference = models.CharField(default="", null=True, blank=True)
|
||||
expires_at = models.DateTimeField(null=True, blank=True)
|
||||
expiry_notification_sent = models.BooleanField(default=False)
|
||||
created_at = models.DateTimeField(default=timezone.now)
|
||||
updated_at = models.DateTimeField(auto_now=True)
|
||||
|
||||
@property
|
||||
def is_expired(self):
|
||||
if self.expires_at is None:
|
||||
return False
|
||||
return timezone.now() > self.expires_at
|
||||
|
||||
def __str__(self):
|
||||
return f"Topup for {self.user}"
|
||||
|
||||
class Meta:
|
||||
ordering = ["-created_at"]
|
||||
|
||||
+38
-3
@@ -1,19 +1,54 @@
|
||||
from rest_framework import serializers
|
||||
from .models import Payment
|
||||
from .models import Payment, Topup
|
||||
from devices.serializers import DeviceSerializer
|
||||
|
||||
|
||||
class PaymentSerializer(serializers.ModelSerializer):
|
||||
devices = DeviceSerializer(many=True, read_only=True)
|
||||
|
||||
class Meta:
|
||||
class Meta: # type: ignore
|
||||
model = Payment
|
||||
fields = "__all__"
|
||||
|
||||
|
||||
class UpdatePaymentSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
class Meta: # type: ignore
|
||||
model = Payment
|
||||
fields = [
|
||||
"number_of_months",
|
||||
]
|
||||
|
||||
|
||||
class TopupSerializer(serializers.ModelSerializer):
|
||||
user = serializers.SerializerMethodField()
|
||||
is_expired = serializers.SerializerMethodField()
|
||||
|
||||
def get_user(self, obj):
|
||||
user = obj.user
|
||||
if user:
|
||||
return {
|
||||
"id": user.id,
|
||||
"name": user.first_name + " " + user.last_name,
|
||||
"id_card": user.id_card,
|
||||
"mobile": user.mobile,
|
||||
}
|
||||
return None
|
||||
|
||||
def get_is_expired(self, obj):
|
||||
return obj.is_expired
|
||||
|
||||
class Meta: # type: ignore
|
||||
model = Topup
|
||||
fields = [
|
||||
"id",
|
||||
"amount",
|
||||
"user",
|
||||
"paid",
|
||||
"status",
|
||||
"mib_reference",
|
||||
"is_expired",
|
||||
"expires_at",
|
||||
"created_at",
|
||||
"updated_at",
|
||||
]
|
||||
read_only_fields = ["id", "created_at", "updated_at"]
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import logging
|
||||
|
||||
from django.db import transaction
|
||||
from django.utils import timezone
|
||||
from procrastinate.contrib.django import app
|
||||
from api.notifications import send_sms
|
||||
from billing.models import Topup
|
||||
from django.utils.timezone import localtime
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@app.periodic(
|
||||
cron="*/30 * * * * *", periodic_id="notify_expired_topups", queue="heavy_tasks"
|
||||
) # every 30 seconds
|
||||
@app.task
|
||||
def update_expired_topups(timestamp: int):
|
||||
expired_topups_qs = Topup.objects.filter(
|
||||
expires_at__lte=timezone.now(), expiry_notification_sent=False
|
||||
).select_related("user")
|
||||
|
||||
with transaction.atomic():
|
||||
count = expired_topups_qs.count()
|
||||
logger.info(f"Found {count} topups to expire.")
|
||||
|
||||
for topup in expired_topups_qs:
|
||||
if topup.user and topup.user.mobile and not topup.expiry_notification_sent:
|
||||
send_sms_task.defer(
|
||||
mobile=topup.user.mobile,
|
||||
amount=topup.amount,
|
||||
topup_id=str(topup.id),
|
||||
created_at=localtime(topup.created_at).isoformat(),
|
||||
)
|
||||
else:
|
||||
# Mark as notified even if we can't send SMS (no mobile number)
|
||||
topup.expiry_notification_sent = True
|
||||
topup.save()
|
||||
|
||||
return {
|
||||
"total_expired_topups": count,
|
||||
}
|
||||
|
||||
|
||||
# Assuming you have a separate task for sending SMS if you go that route
|
||||
@app.task
|
||||
def send_sms_task(mobile: str, amount: float, topup_id: str, created_at: str):
|
||||
message = (
|
||||
f"Dear {mobile}, \n\nYour topup of {amount} MVR [created at {created_at}] has expired. "
|
||||
"Please make a new topup to update your wallet. \n\n- SAR Link"
|
||||
)
|
||||
send_sms(mobile, message)
|
||||
logger.info(f"SMS sent to {mobile} for expired topup of {amount} MVR.")
|
||||
|
||||
# Mark the topup as notified after successful SMS sending
|
||||
try:
|
||||
topup = Topup.objects.get(id=topup_id)
|
||||
topup.expiry_notification_sent = True
|
||||
topup.save()
|
||||
logger.info(f"Marked topup {topup_id} as notified.")
|
||||
except Topup.DoesNotExist:
|
||||
logger.error(f"Topup {topup_id} not found when trying to mark as notified.")
|
||||
+205
-1
@@ -1,3 +1,207 @@
|
||||
from django.test import TestCase
|
||||
from django.urls import reverse
|
||||
from rest_framework import status
|
||||
from rest_framework.test import APIClient
|
||||
from django.contrib.auth import get_user_model
|
||||
from .models import Topup
|
||||
from .serializers import TopupSerializer
|
||||
from django.utils import timezone
|
||||
from datetime import timedelta
|
||||
from decouple import config
|
||||
from unittest import mock
|
||||
|
||||
# Create your tests here.
|
||||
User = get_user_model()
|
||||
|
||||
REAL_USER_FIRST_NAME = config("REAL_USER_FIRST_NAME", default="josh")
|
||||
REAL_USER_LAST_NAME = config("REAL_USER_LAST_NAME", default="mosh")
|
||||
|
||||
|
||||
class TopupTests(TestCase):
|
||||
def setUp(self):
|
||||
self.client = APIClient()
|
||||
self.real_user = User.objects.create_user(
|
||||
username="testuser",
|
||||
password="testpassword",
|
||||
first_name=REAL_USER_FIRST_NAME,
|
||||
last_name=REAL_USER_LAST_NAME,
|
||||
acc_no="7770000010629",
|
||||
is_admin=True,
|
||||
)
|
||||
self.user = User.objects.create_user(
|
||||
username="plskillme",
|
||||
password="modewasgayithink",
|
||||
first_name="mode",
|
||||
last_name="hussain",
|
||||
acc_no="1122334455",
|
||||
)
|
||||
self.admin_user = User.objects.create_superuser(
|
||||
username="adminuser",
|
||||
password="adminpassword",
|
||||
email="admin@example.com",
|
||||
first_name="Admin",
|
||||
last_name="User",
|
||||
acc_no="987654321",
|
||||
)
|
||||
self.client.force_authenticate(user=self.real_user)
|
||||
|
||||
def test_create_topup(self):
|
||||
url = reverse("create-list-topups")
|
||||
data = {"amount": 100.00}
|
||||
response = self.client.post(url, data, format="json")
|
||||
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
|
||||
self.assertEqual(Topup.objects.count(), 1)
|
||||
topup = Topup.objects.first()
|
||||
self.assertEqual(getattr(topup, "amount"), 100.00)
|
||||
self.assertEqual(getattr(topup, "user"), self.real_user)
|
||||
|
||||
def test_create_topup_no_amount(self):
|
||||
url = reverse("create-list-topups")
|
||||
data = {}
|
||||
response = self.client.post(url, data, format="json")
|
||||
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
def test_list_topups(self):
|
||||
Topup.objects.create(amount=50.00, user=self.real_user)
|
||||
Topup.objects.create(amount=75.00, user=self.real_user)
|
||||
url = reverse("create-list-topups")
|
||||
response = self.client.get(url, format="json")
|
||||
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
||||
self.assertEqual(len(response.json()["data"]), 2)
|
||||
|
||||
def test_list_topups_admin(self):
|
||||
self.client = APIClient()
|
||||
self.client.force_authenticate(user=self.admin_user)
|
||||
Topup.objects.create(amount=50.00, user=self.real_user)
|
||||
admin_user = User.objects.create_user(
|
||||
username="anotheruser",
|
||||
password="testpassword",
|
||||
first_name="Another",
|
||||
last_name="User",
|
||||
acc_no="1122334455",
|
||||
is_admin=True,
|
||||
)
|
||||
Topup.objects.create(amount=75.00, user=admin_user)
|
||||
url = reverse("create-list-topups")
|
||||
response = self.client.get(url, format="json")
|
||||
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
||||
self.assertEqual(len(response.json()["data"]), 2) # Admin sees all
|
||||
|
||||
def test_list_topups_filtered_by_user(self):
|
||||
other_user = User.objects.create_user(
|
||||
username="otheruser",
|
||||
password="testpassword",
|
||||
first_name="Other",
|
||||
last_name="User",
|
||||
acc_no="5544332211",
|
||||
)
|
||||
Topup.objects.create(amount=50.00, user=self.user)
|
||||
Topup.objects.create(amount=75.00, user=other_user)
|
||||
url = reverse("create-list-topups")
|
||||
response = self.client.get(url, format="json")
|
||||
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
||||
self.assertEqual(len(response.json()["data"]), 2)
|
||||
|
||||
@mock.patch("billing.views.localtime")
|
||||
def test_verify_topup_payment(self, mock_localtime):
|
||||
fixed_time = timezone.datetime(
|
||||
2025, 7, 3, 19, 36, tzinfo=timezone.get_current_timezone()
|
||||
)
|
||||
mock_localtime.return_value = fixed_time
|
||||
|
||||
topup = Topup.objects.create(amount=1.5, user=self.real_user)
|
||||
url = reverse("verify-topup-payment", kwargs={"pk": topup.pk})
|
||||
self.client = APIClient()
|
||||
|
||||
self.client.force_authenticate(user=self.real_user)
|
||||
data = {
|
||||
"benefName": f"{REAL_USER_FIRST_NAME} {REAL_USER_LAST_NAME}",
|
||||
"accountNo": "7770000010629",
|
||||
"absAmount": 1.5,
|
||||
"time": fixed_time.strftime("%Y-%m-%d %H:%M"), # Use the same fixed time
|
||||
}
|
||||
response = self.client.patch(url, data, format="json")
|
||||
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
||||
topup.refresh_from_db()
|
||||
self.assertEqual(topup.paid, True)
|
||||
|
||||
def test_verify_topup_payment_already_verified(self):
|
||||
topup = Topup.objects.create(amount=100.00, user=self.real_user, paid=True)
|
||||
url = reverse("verify-topup-payment", kwargs={"pk": topup.pk})
|
||||
data = {}
|
||||
response = self.client.patch(url, data, format="json")
|
||||
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
def test_verify_topup_payment_unauthorized(self):
|
||||
other_user = User.objects.create_user(
|
||||
username="otheruser",
|
||||
password="testpassword",
|
||||
first_name="Other",
|
||||
last_name="User",
|
||||
acc_no="5544332211",
|
||||
)
|
||||
topup = Topup.objects.create(amount=100.00, user=other_user)
|
||||
url = reverse("verify-topup-payment", kwargs={"pk": topup.pk})
|
||||
data = {}
|
||||
response = self.client.patch(url, data, format="json")
|
||||
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
|
||||
|
||||
def test_topup_serializer(self):
|
||||
topup = Topup.objects.create(amount=120.00, user=self.real_user)
|
||||
serializer = TopupSerializer(topup)
|
||||
self.assertEqual(serializer.data["amount"], 120.00)
|
||||
self.assertEqual(serializer.data["user"]["id"], getattr(self.real_user, "id"))
|
||||
|
||||
def test_topup_filter_amount(self):
|
||||
Topup.objects.create(amount=50.00, user=self.real_user)
|
||||
Topup.objects.create(amount=100.00, user=self.real_user)
|
||||
url = reverse("create-list-topups") + "?amount_min=75"
|
||||
response = self.client.get(url, format="json")
|
||||
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
||||
self.assertEqual(len(response.json()["data"]), 1)
|
||||
self.assertEqual(response.json()["data"][0]["amount"], 100.00)
|
||||
|
||||
def test_topup_filter_user_search(self):
|
||||
Topup.objects.create(amount=50.00, user=self.real_user)
|
||||
other_user = User.objects.create_user(
|
||||
username="otheruser",
|
||||
password="testpassword",
|
||||
first_name="Other",
|
||||
last_name="User",
|
||||
id_card="12345",
|
||||
mobile="1234567890",
|
||||
acc_no="5544332211",
|
||||
)
|
||||
Topup.objects.create(amount=75.00, user=other_user)
|
||||
url = reverse("create-list-topups") + "?user=Other"
|
||||
response = self.client.get(url, format="json")
|
||||
print(response.json())
|
||||
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
||||
self.assertEqual(len(response.json()["data"]), 1)
|
||||
self.assertEqual(response.json()["data"][0]["amount"], 75.00)
|
||||
|
||||
def test_topup_filter_created_at(self):
|
||||
now = timezone.now()
|
||||
Topup.objects.create(
|
||||
amount=50.00, user=self.real_user, created_at=now - timedelta(days=2)
|
||||
)
|
||||
Topup.objects.create(amount=100.00, user=self.real_user, created_at=now)
|
||||
url = reverse("create-list-topups") + f"?created_at_after={now.date()}"
|
||||
response = self.client.get(url, format="json")
|
||||
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
||||
self.assertEqual(len(response.json()["data"]), 1)
|
||||
self.assertEqual(response.json()["data"][0]["amount"], 100.00)
|
||||
|
||||
def test_retrieve_single_topup(self):
|
||||
topup = Topup.objects.create(amount=50.00, user=self.real_user)
|
||||
url = reverse("retrieve-topup", kwargs={"pk": topup.pk})
|
||||
response = self.client.get(url, format="json")
|
||||
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
||||
self.assertEqual(response.json()["amount"], 50.00)
|
||||
self.assertEqual(response.json()["user"]["id"], getattr(self.real_user, "id"))
|
||||
|
||||
def test_delete_topup(self):
|
||||
topup = Topup.objects.create(amount=50.00, user=self.real_user)
|
||||
url = reverse("delete-topup", kwargs={"pk": topup.pk})
|
||||
response = self.client.delete(url, format="json")
|
||||
self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
|
||||
self.assertEqual(Topup.objects.count(), 0)
|
||||
|
||||
@@ -6,6 +6,10 @@ from .views import (
|
||||
PaymentDetailAPIView,
|
||||
UpdatePaymentAPIView,
|
||||
DeletePaymentView,
|
||||
ListCreateTopupView,
|
||||
VerifyTopupPaymentAPIView,
|
||||
TopupDetailAPIView,
|
||||
CancelTopupView,
|
||||
)
|
||||
|
||||
urlpatterns = [
|
||||
@@ -24,4 +28,17 @@ urlpatterns = [
|
||||
path(
|
||||
"payment/<str:pk>/verify/", VerifyPaymentView.as_view(), name="verify-payment"
|
||||
),
|
||||
# Topups
|
||||
path("topup/", ListCreateTopupView.as_view(), name="create-list-topups"),
|
||||
path("topup/<str:pk>/", TopupDetailAPIView.as_view(), name="retrieve-topup"),
|
||||
path(
|
||||
"topup/<str:pk>/verify/",
|
||||
VerifyTopupPaymentAPIView.as_view(),
|
||||
name="verify-topup-payment",
|
||||
),
|
||||
path(
|
||||
"topup/<str:pk>/cancel/",
|
||||
CancelTopupView.as_view(),
|
||||
name="cancel-topup",
|
||||
),
|
||||
]
|
||||
|
||||
+201
-6
@@ -15,9 +15,11 @@ from api.tasks import add_new_devices_to_omada
|
||||
from apibase.env import BASE_DIR, env
|
||||
import logging
|
||||
|
||||
from .models import Device, Payment
|
||||
from .serializers import PaymentSerializer, UpdatePaymentSerializer
|
||||
from .filters import PaymentFilter
|
||||
from .models import Device, Payment, Topup
|
||||
from .serializers import PaymentSerializer, UpdatePaymentSerializer, TopupSerializer
|
||||
from .filters import PaymentFilter, TopupFilter
|
||||
from dataclasses import dataclass, asdict
|
||||
from typing import Optional
|
||||
|
||||
env.read_env(os.path.join(BASE_DIR, ".env"))
|
||||
|
||||
@@ -218,15 +220,19 @@ class VerifyPaymentView(StaffEditorPermissionMixin, generics.UpdateAPIView):
|
||||
raise ValueError(
|
||||
"PAYMENT_BASE_URL is not set. Please set it in your environment variables."
|
||||
)
|
||||
logger.info(data)
|
||||
response = requests.post(
|
||||
f"{PAYMENT_BASE_URL}/verify-payment",
|
||||
json=data,
|
||||
headers={"Content-Type": "application/json"},
|
||||
)
|
||||
response.raise_for_status()
|
||||
logger.info("MIB Verification Response -> ", response)
|
||||
try:
|
||||
response.raise_for_status()
|
||||
except requests.exceptions.HTTPError as e:
|
||||
logger.error(f"HTTPError: {e}")
|
||||
return False
|
||||
mib_resp = response.json()
|
||||
print(mib_resp)
|
||||
logger.info("MIB Verification Response ->", mib_resp)
|
||||
if not response.json().get("success"):
|
||||
return mib_resp["success"]
|
||||
else:
|
||||
@@ -259,3 +265,192 @@ class DeletePaymentView(StaffEditorPermissionMixin, generics.DestroyAPIView):
|
||||
devices = instance.devices.all()
|
||||
devices.update(is_active=False, expiry_date=None, has_a_pending_payment=False)
|
||||
return super().delete(request, *args, **kwargs)
|
||||
|
||||
|
||||
class ListCreateTopupView(StaffEditorPermissionMixin, generics.ListCreateAPIView):
|
||||
queryset = Topup.objects.all()
|
||||
serializer_class = TopupSerializer
|
||||
filter_backends = [DjangoFilterBackend]
|
||||
filterset_fields = "__all__"
|
||||
filterset_class = TopupFilter
|
||||
|
||||
def create(self, request, *args, **kwargs):
|
||||
data = request.data
|
||||
user = request.user
|
||||
current_time = timezone.now()
|
||||
expires_at = current_time + timedelta(minutes=10) # Topup expires in 10 minutes
|
||||
amount = data.get("amount")
|
||||
if not amount:
|
||||
return Response(
|
||||
{"message": "amount is required."},
|
||||
status=status.HTTP_400_BAD_REQUEST,
|
||||
)
|
||||
topup = Topup.objects.create(amount=amount, user=user, expires_at=expires_at)
|
||||
serializer = TopupSerializer(topup)
|
||||
return Response(serializer.data, status=status.HTTP_201_CREATED)
|
||||
|
||||
def get_queryset(self):
|
||||
queryset = super().get_queryset()
|
||||
if getattr(self.request.user, "is_admin") or self.request.user.is_superuser:
|
||||
return queryset
|
||||
return queryset.filter(user=self.request.user)
|
||||
|
||||
|
||||
class TopupDetailAPIView(StaffEditorPermissionMixin, generics.RetrieveAPIView):
|
||||
queryset = Topup.objects.all()
|
||||
serializer_class = TopupSerializer
|
||||
lookup_field = "pk"
|
||||
|
||||
def get_queryset(self):
|
||||
queryset = super().get_queryset()
|
||||
if getattr(self.request.user, "is_admin") or self.request.user.is_superuser:
|
||||
return queryset
|
||||
return queryset.filter(user=self.request.user)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Transaction:
|
||||
ref: str
|
||||
sourceBank: str
|
||||
trxDate: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class PaymentVerificationResponse:
|
||||
message: str
|
||||
success: bool
|
||||
transaction: Optional[Transaction] = None
|
||||
|
||||
|
||||
class VerifyTopupPaymentAPIView(StaffEditorPermissionMixin, generics.UpdateAPIView):
|
||||
queryset = Topup.objects.all()
|
||||
serializer_class = TopupSerializer
|
||||
lookup_field = "pk"
|
||||
|
||||
def verify_transfer_topup(self, data, topup) -> PaymentVerificationResponse:
|
||||
if not PAYMENT_BASE_URL:
|
||||
raise ValueError(
|
||||
"PAYMENT_BASE_URL is not set. Please set it in your environment variables."
|
||||
)
|
||||
logger.info(data)
|
||||
response = requests.post(
|
||||
f"{PAYMENT_BASE_URL}/verify-payment",
|
||||
json=data,
|
||||
headers={"Content-Type": "application/json"},
|
||||
)
|
||||
try:
|
||||
response.raise_for_status()
|
||||
except requests.exceptions.HTTPError as e:
|
||||
logger.error(f"HTTPError: {e}")
|
||||
return PaymentVerificationResponse(
|
||||
message="Payment verification failed.", success=False, transaction=None
|
||||
)
|
||||
mib_resp = response.json()
|
||||
print(mib_resp)
|
||||
if not response.json().get("success"):
|
||||
return PaymentVerificationResponse(
|
||||
message=mib_resp["message"],
|
||||
success=mib_resp["success"],
|
||||
transaction=None,
|
||||
)
|
||||
else:
|
||||
topup.paid = True
|
||||
topup.mib_reference = mib_resp["transaction"]["ref"] or ""
|
||||
topup.paid_at = mib_resp["transaction"]["trxDate"]
|
||||
topup.save()
|
||||
return PaymentVerificationResponse(
|
||||
message=mib_resp["message"],
|
||||
success=mib_resp["success"],
|
||||
transaction=Transaction(
|
||||
ref=topup.mib_reference,
|
||||
sourceBank=mib_resp["transaction"]["sourceBank"],
|
||||
trxDate=mib_resp["transaction"]["trxDate"],
|
||||
),
|
||||
)
|
||||
|
||||
def update(self, request, *args, **kwargs):
|
||||
topup_instance = self.get_object()
|
||||
user = request.user
|
||||
|
||||
if topup_instance.paid:
|
||||
return Response(
|
||||
{"message": "Payment has already been verified."},
|
||||
status=status.HTTP_400_BAD_REQUEST,
|
||||
)
|
||||
if topup_instance.user != user and not user.is_superuser:
|
||||
return Response(
|
||||
{"message": "You are not allowed to pay for this topup."},
|
||||
status=status.HTTP_403_FORBIDDEN,
|
||||
)
|
||||
data = {
|
||||
"benefName": f"{user.first_name} {user.last_name}", # type: ignore
|
||||
"accountNo": user.acc_no, # type: ignore
|
||||
"absAmount": "{:.2f}".format(topup_instance.amount),
|
||||
"time": localtime(topup_instance.created_at).strftime("%Y-%m-%d %H:%M"),
|
||||
}
|
||||
logger.info(
|
||||
f"Verifying topup payment created at {localtime(topup_instance.created_at)} with data: {data}"
|
||||
)
|
||||
topup_verification_response = self.verify_transfer_topup(data, topup_instance)
|
||||
print("Topup verification response:", topup_verification_response)
|
||||
if topup_verification_response.success:
|
||||
user.wallet_balance += topup_instance.amount # type: ignore
|
||||
user.save()
|
||||
topup_instance.status = "PAID"
|
||||
topup_instance.save()
|
||||
return Response(
|
||||
{
|
||||
"status": topup_verification_response.success,
|
||||
"message": topup_verification_response.message,
|
||||
"transaction": asdict(topup_verification_response.transaction)
|
||||
if topup_verification_response.transaction
|
||||
else None,
|
||||
},
|
||||
status=status.HTTP_200_OK,
|
||||
)
|
||||
else:
|
||||
return Response(
|
||||
{
|
||||
"status": topup_verification_response.success,
|
||||
"message": topup_verification_response.message
|
||||
or "Topup payment verification failed.",
|
||||
},
|
||||
status=status.HTTP_400_BAD_REQUEST,
|
||||
)
|
||||
|
||||
|
||||
class CancelTopupView(StaffEditorPermissionMixin, generics.UpdateAPIView):
|
||||
queryset = Topup.objects.all().select_related("user")
|
||||
serializer_class = TopupSerializer
|
||||
lookup_field = "pk"
|
||||
|
||||
def update(self, request, *args, **kwargs):
|
||||
instance = self.get_object()
|
||||
user = request.user
|
||||
if instance.status == "CANCELLED":
|
||||
return Response(
|
||||
{"message": "Topup has already been cancelled."},
|
||||
status=status.HTTP_400_BAD_REQUEST,
|
||||
)
|
||||
if instance.is_expired:
|
||||
return Response(
|
||||
{"message": "Expired topups cannot be cancelled."},
|
||||
status=status.HTTP_400_BAD_REQUEST,
|
||||
)
|
||||
if (
|
||||
instance.user != user
|
||||
and getattr(user, "is_admin")
|
||||
and not user.is_superuser
|
||||
):
|
||||
return Response(
|
||||
{"message": "You are not authorized to delete this topup."},
|
||||
status=status.HTTP_403_FORBIDDEN,
|
||||
)
|
||||
if instance.paid:
|
||||
return Response(
|
||||
{"message": "Paid topups cannot be deleted."},
|
||||
status=status.HTTP_400_BAD_REQUEST,
|
||||
)
|
||||
instance.status = "CANCELLED"
|
||||
instance.save()
|
||||
return super().update(request, *args, **kwargs)
|
||||
|
||||
+13
-3
@@ -1,14 +1,24 @@
|
||||
import django_filters
|
||||
from .models import Device
|
||||
from django.db.models import Q
|
||||
|
||||
|
||||
class DeviceFilter(django_filters.FilterSet):
|
||||
name = django_filters.CharFilter(lookup_expr="icontains")
|
||||
mac = django_filters.CharFilter(lookup_expr="icontains")
|
||||
vendor = django_filters.CharFilter(lookup_expr="icontains")
|
||||
user = django_filters.CharFilter(
|
||||
field_name="user__last_name", lookup_expr="icontains"
|
||||
)
|
||||
user = django_filters.CharFilter(method="filter_user_search")
|
||||
|
||||
def filter_user_search(self, queryset, name, value):
|
||||
"""
|
||||
Search across multiple user fields: first_name, last_name, id_card, mobile
|
||||
"""
|
||||
return queryset.filter(
|
||||
Q(user__first_name__icontains=value)
|
||||
| Q(user__last_name__icontains=value)
|
||||
| Q(user__id_card__icontains=value)
|
||||
| Q(user__mobile__icontains=value)
|
||||
)
|
||||
|
||||
class Meta:
|
||||
model = Device
|
||||
|
||||
+7
-3
@@ -30,11 +30,15 @@ class DeviceListCreateAPIView(
|
||||
|
||||
def list(self, request, *args, **kwargs):
|
||||
queryset = self.filter_queryset(self.get_queryset())
|
||||
all_devices = request.query_params.get("all_devices", None)
|
||||
all_devices = request.query_params.get("all_devices", "false").lower() in [
|
||||
"true",
|
||||
"1",
|
||||
"yes",
|
||||
]
|
||||
if (
|
||||
request.user.is_authenticated
|
||||
and getattr(request.user, "is_admin", False)
|
||||
and all_devices
|
||||
and getattr(request.user, "is_admin")
|
||||
and bool(all_devices)
|
||||
):
|
||||
pass
|
||||
else:
|
||||
|
||||
@@ -4,3 +4,17 @@ default:
|
||||
dev:
|
||||
python manage.py runserver
|
||||
python manage.py procrastinate worker
|
||||
|
||||
migrate:
|
||||
python manage.py migrate
|
||||
make-migrations:
|
||||
python manage.py makemigrations
|
||||
|
||||
seed-topups:
|
||||
python manage.py seed_topups --number=50
|
||||
seed-payments:
|
||||
python manage.py seed_payments --number=50
|
||||
|
||||
# TESTS
|
||||
test-billing:
|
||||
python manage.py test billing
|
||||
Reference in New Issue
Block a user