diff --git a/apps/push_notifications/admin.py b/apps/push_notifications/admin.py index 39e55c2..145b537 100644 --- a/apps/push_notifications/admin.py +++ b/apps/push_notifications/admin.py @@ -1,6 +1,107 @@ +from functools import update_wrapper + from django.contrib import admin -from .models import PushUser, PushMessage +from django.contrib.admin.exceptions import DisallowedModelAdminToField +from django.contrib.admin.options import TO_FIELD_VAR +from django.core.exceptions import PermissionDenied +from django.template.response import TemplateResponse + +from .models import PushUser, PushMessage, BulkPushMessage admin.site.register(PushUser) + + +from django import forms +from django.shortcuts import render, redirect + + + +class PushMessageForm(forms.Form): + user_uuid = forms.UUIDField(required=False) + user_phone_number = forms.CharField(required=False) + title = forms.CharField(required=False) + message = forms.CharField(required=False) + priority = forms.IntegerField(required=False) + extras = forms.JSONField(required=False) + + + +class PushMessageAdmin(admin.ModelAdmin): + # change_list_template = 'admin/custom_form.html' + + def get_urls(self): + from django.urls import path + + def wrap(view): + def wrapper(*args, **kwargs): + return self.admin_site.admin_view(view)(*args, **kwargs) + + wrapper.model_admin = self + return update_wrapper(wrapper, view) + + info = self.opts.app_label, self.opts.model_name + + urls = super().get_urls() + custom_urls = [ + path("custom-action2/", wrap(self.add_view), name="%s_%s_custom-action2" % info), + # path("custom-action/", wrap(self.custom_action), name="%s_%s_custom-action" % info), + + # path('custom-action/', self.admin_site.admin_view(self.custom_action), name='custom-action'), + ] + return custom_urls + urls + + # def custom_action(self, request, form_url="", extra_context=None): + # + # + # + # return self.render_change_form( + # request, context, add=add, change=not add, obj=obj, form_url=form_url + # ) + + # def custom_action(self, request): + # if request.method == 'POST': + # form = PushMessageForm(request.POST) + # if form.is_valid(): + # # ایجاد آبجکت‌ها بر اساس داده‌های فرم + # data = form.cleaned_data + # + # # ایجاد آبجکت در Model1 + # obj1 = PushMessage.objects.create( + # field1=data['field1'], + # field2=data['field2'] + # ) + # + # # ایجاد آبجکت در Model2 + # obj2 = PushMessage.objects.create( + # related_field=obj1, + # other_field=data['field2'] * 2 + # ) + # + # self.message_user(request, "آبجکت‌ها با موفقیت ایجاد شدند") + # # ریدایرکت به صفحه‌ای مناسب + # return redirect('..') + # else: + # form = PushMessageForm() + # + # context = self.admin_site.each_context(request) + # context['opts'] = self.model._meta + # context['form'] = form + # return TemplateResponse(request, 'admin/custom_form.html', context) + + + +@admin.action(description="bulk_push") +def bulk_push(modeladmin, request, queryset): + + for s in queryset: + s.bulk_push_task() + +class BulkPushMessageAdmin(admin.ModelAdmin): + list_display = ['uuid', 'state', 'success_count', 'failure_count', 'created_at'] + actions = [bulk_push] + + admin.site.register(PushMessage) +admin.site.register(BulkPushMessage, BulkPushMessageAdmin) + diff --git a/apps/push_notifications/migrations/0003_bulkpushmessage_pushmessage_bulk.py b/apps/push_notifications/migrations/0003_bulkpushmessage_pushmessage_bulk.py new file mode 100644 index 0000000..0f637d8 --- /dev/null +++ b/apps/push_notifications/migrations/0003_bulkpushmessage_pushmessage_bulk.py @@ -0,0 +1,35 @@ +# Generated by Django 5.2.3 on 2025-07-19 11:57 + +import django.db.models.deletion +import uuid +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('push_notifications', '0002_pushmessage_stats'), + ] + + operations = [ + migrations.CreateModel( + name='BulkPushMessage', + fields=[ + ('uuid', models.UUIDField(db_index=True, default=uuid.uuid4, editable=False, primary_key=True, serialize=False, unique=True)), + ('created_at', models.DateTimeField(auto_now_add=True, db_index=True)), + ('updated_at', models.DateTimeField(auto_now=True, db_index=True)), + ('file', models.FileField(blank=True, null=True, upload_to='bulk_push')), + ('success_count', models.PositiveIntegerField(default=0)), + ('failure_count', models.PositiveIntegerField(default=0)), + ('state', models.IntegerField(choices=[(0, 'init'), (1, 'Start'), (2, 'done'), (3, 'timeout'), (4, 'failed')], default=0)), + ], + options={ + 'abstract': False, + }, + ), + migrations.AddField( + model_name='pushmessage', + name='bulk', + field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='push_notifications.bulkpushmessage'), + ), + ] diff --git a/apps/push_notifications/models.py b/apps/push_notifications/models.py index fae3d2f..a5ac60e 100644 --- a/apps/push_notifications/models.py +++ b/apps/push_notifications/models.py @@ -9,20 +9,20 @@ from django.utils.translation import gettext_lazy as _ class PushUserQuerySet(models.QuerySet): def submit(self, user): - push_user, created = self.get_or_create(user=user) + push_user, created = self.get_or_create(user=user) push_user: PushUser = push_user push_user.submit_user() push_user.submit_client() push_user.submit_application() return push_user + class PushUser(BaseModel): user = models.ForeignKey(User, on_delete=models.PROTECT) client_token = models.CharField(max_length=32, null=True, blank=True) application_token = models.CharField(max_length=32, null=True, blank=True) app_id = None - objects = PushUserQuerySet.as_manager() def submit_user(self): @@ -61,6 +61,78 @@ class PushMessage(BaseModel): extras = models.JSONField(default=dict) stats = models.IntegerField(default=StateChoices.INIT, choices=StateChoices.choices) + bulk = models.ForeignKey("BulkPushMessage", null=True, blank=True, on_delete=models.PROTECT) + def send_push(self): from apps.push_notifications.tasks import send_push_notification send_push_notification.delay(str(self.uuid)) + + +class BulkPushMessage(BaseModel): + class StateChoices(models.IntegerChoices): + INIT = 0, _('init') + START = 1, _('Start') + DONE = 2, _('done') + TIMEOUT = 3, _('timeout') + FAILED = 4, _('failed') + + file = models.FileField(null=True, blank=True, upload_to="bulk_push") + success_count = models.PositiveIntegerField(default=0) + failure_count = models.PositiveIntegerField(default=0) + state = models.IntegerField(choices=StateChoices.choices, default=StateChoices.INIT) + + def bulk_push_task(self): + from .tasks import bulk_push + bulk_push(str(self.pk)) + + def push_to_all(self, data: dict): + to_start = BulkPushMessage.objects.filter(pk=self.pk, state=self.StateChoices.INIT).update(state=self.StateChoices.START) + + if not to_start: + raise Exception('not in ini state') + + for user_uuid in data: + push_user = PushUser.objects.filter(user_id=user_uuid).first() + if push_user: + push_message = PushMessage.objects.create(push_user=push_user, + title=data[user_uuid].get('title'), + message=data[user_uuid].get('message'), + priority=data[user_uuid].get('priority', 5), + extras=data[user_uuid].get("extras", {})) + push_message.send_push() + + self.success_count += 1 + + else: + self.failure_count += 1 + + self.save() + + to_done = BulkPushMessage.objects.filter(pk=self.pk, state=self.StateChoices.START).update( + state=self.StateChoices.DONE) + + def extract_data(self): + push_dict = {} + import xlrd + import json + book = xlrd.open_workbook(self.file.path) + sh = book.sheet_by_index(0) + + for row in range(1, sh.nrows): + user_uuid = sh.cell(rowx=row, colx=0).value.strip() + title = sh.cell(rowx=row, colx=1).value.strip() + message = sh.cell(rowx=row, colx=2).value.strip() + priority = int(float(str(sh.cell(rowx=row, colx=3).value).strip())) + extras_str = sh.cell(rowx=row, colx=4).value.strip() + if extras_str: + extras = json.loads(extras) + else: + extras = {} + + push_dict[user_uuid] = { + "title" : title, + "message" : message, + "priority" : priority, + "extras" : extras, + } + return push_dict diff --git a/apps/push_notifications/tasks.py b/apps/push_notifications/tasks.py index fa34663..05b13e3 100644 --- a/apps/push_notifications/tasks.py +++ b/apps/push_notifications/tasks.py @@ -12,4 +12,11 @@ def send_push_notification(push_message_uuid): priority=push_message.priority, extras=push_message.extras) push_message.state = push_message.StateChoices.DONE - push_message.save() \ No newline at end of file + push_message.save() + + +@celery_app.task +def bulk_push(bulk_push_uuid): + from .models import BulkPushMessage + bulk_push = BulkPushMessage.objects.get(uuid=bulk_push_uuid) + bulk_push.push_to_all(bulk_push.extract_data())