adding
This commit is contained in:
@@ -0,0 +1,24 @@
|
||||
from django.contrib import admin
|
||||
|
||||
from .models import Notification, NotificationRead
|
||||
|
||||
|
||||
@admin.register(Notification)
|
||||
class NotificationAdmin(admin.ModelAdmin):
|
||||
list_display = ("title", "user", "created_at")
|
||||
list_filter = ("created_at",)
|
||||
search_fields = ("title", "body", "user__phone")
|
||||
|
||||
def get_form(self, request, obj=None, **kwargs):
|
||||
form = super().get_form(request, obj, **kwargs)
|
||||
form.base_fields["user"].help_text = "خالی بگذار تا برای همهی کاربران نمایش داده شود."
|
||||
return form
|
||||
|
||||
|
||||
@admin.register(NotificationRead)
|
||||
class NotificationReadAdmin(admin.ModelAdmin):
|
||||
list_display = ("user", "notification", "read_at")
|
||||
search_fields = ("user__phone", "notification__title")
|
||||
|
||||
def has_add_permission(self, request):
|
||||
return False
|
||||
@@ -0,0 +1,21 @@
|
||||
from rest_framework import serializers
|
||||
|
||||
|
||||
class NotificationItemSerializer(serializers.Serializer):
|
||||
id = serializers.IntegerField()
|
||||
title = serializers.CharField()
|
||||
body = serializers.CharField()
|
||||
created_at = serializers.DateTimeField()
|
||||
is_read = serializers.BooleanField()
|
||||
|
||||
|
||||
class TrialWarningSerializer(serializers.Serializer):
|
||||
days_left = serializers.IntegerField()
|
||||
title = serializers.CharField()
|
||||
body = serializers.CharField()
|
||||
|
||||
|
||||
class NotificationListSerializer(serializers.Serializer):
|
||||
unread_count = serializers.IntegerField()
|
||||
trial_warning = TrialWarningSerializer(allow_null=True)
|
||||
items = NotificationItemSerializer(many=True)
|
||||
@@ -0,0 +1,31 @@
|
||||
from rest_framework.permissions import IsAuthenticated
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.views import APIView
|
||||
|
||||
from apps.notifications.services import NotificationService
|
||||
|
||||
from .serializers import NotificationListSerializer
|
||||
|
||||
|
||||
class NotificationListView(APIView):
|
||||
permission_classes = [IsAuthenticated]
|
||||
|
||||
def get(self, request):
|
||||
data = NotificationService.list_for_user(request.user)
|
||||
return Response(NotificationListSerializer(data).data)
|
||||
|
||||
|
||||
class NotificationMarkReadView(APIView):
|
||||
permission_classes = [IsAuthenticated]
|
||||
|
||||
def post(self, request, notification_id):
|
||||
NotificationService.mark_read(request.user, notification_id)
|
||||
return Response({"success": True})
|
||||
|
||||
|
||||
class NotificationMarkAllReadView(APIView):
|
||||
permission_classes = [IsAuthenticated]
|
||||
|
||||
def post(self, request):
|
||||
NotificationService.mark_all_read(request.user)
|
||||
return Response({"success": True})
|
||||
@@ -0,0 +1,7 @@
|
||||
from django.apps import AppConfig
|
||||
|
||||
|
||||
class NotificationsConfig(AppConfig):
|
||||
default_auto_field = "django.db.models.BigAutoField"
|
||||
name = "apps.notifications"
|
||||
verbose_name = "اطلاعرسانی"
|
||||
@@ -0,0 +1,46 @@
|
||||
# Generated by Django 5.1.15 on 2026-08-23 20:54
|
||||
|
||||
import django.db.models.deletion
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
initial = True
|
||||
|
||||
dependencies = [
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='Notification',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('title', models.CharField(max_length=150, verbose_name='عنوان')),
|
||||
('body', models.TextField(blank=True, verbose_name='متن')),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='notifications', to=settings.AUTH_USER_MODEL, verbose_name='کاربر (خالی = عمومی برای همه)')),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'اعلان',
|
||||
'verbose_name_plural': 'اعلان\u200cها',
|
||||
'ordering': ['-created_at'],
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='NotificationRead',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('read_at', models.DateTimeField(auto_now_add=True)),
|
||||
('notification', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='reads', to='notifications.notification')),
|
||||
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='notification_reads', to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'خوانده\u200cشدنِ اعلان',
|
||||
'verbose_name_plural': 'خوانده\u200cشدنِ اعلان\u200cها',
|
||||
'constraints': [models.UniqueConstraint(fields=('user', 'notification'), name='unique_user_notification_read')],
|
||||
},
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,50 @@
|
||||
from django.conf import settings
|
||||
from django.db import models
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
|
||||
# اعلانها دو جورند: عمومی (user=None، برای همهی کاربران — مثلا خبر جدید)
|
||||
# یا شخصی (user مشخص — مثلا «با کد معرفت جم گرفتی»). چون یک اعلانِ عمومی
|
||||
# بین همه مشترک است، وضعیت «خواندهشد» را نمیشود مستقیم روی خودِ رکورد
|
||||
# نگه داشت؛ به همین خاطر NotificationRead یک جدول واسط جداست.
|
||||
# هشدار «دورهی آزمایشی رو به پایان» ذخیره نمیشود — همیشه زنده از
|
||||
# User.trial_expires_at محاسبه میشود، چون دقیقتر و بدون نیاز به cron است.
|
||||
|
||||
|
||||
class Notification(models.Model):
|
||||
user = models.ForeignKey(
|
||||
settings.AUTH_USER_MODEL,
|
||||
null=True,
|
||||
blank=True,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="notifications",
|
||||
verbose_name=_("کاربر (خالی = عمومی برای همه)"),
|
||||
)
|
||||
title = models.CharField(max_length=150, verbose_name=_("عنوان"))
|
||||
body = models.TextField(blank=True, verbose_name=_("متن"))
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
|
||||
class Meta:
|
||||
verbose_name = _("اعلان")
|
||||
verbose_name_plural = _("اعلانها")
|
||||
ordering = ["-created_at"]
|
||||
|
||||
def __str__(self):
|
||||
return self.title
|
||||
|
||||
|
||||
class NotificationRead(models.Model):
|
||||
user = models.ForeignKey(
|
||||
settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="notification_reads"
|
||||
)
|
||||
notification = models.ForeignKey(Notification, on_delete=models.CASCADE, related_name="reads")
|
||||
read_at = models.DateTimeField(auto_now_add=True)
|
||||
|
||||
class Meta:
|
||||
verbose_name = _("خواندهشدنِ اعلان")
|
||||
verbose_name_plural = _("خواندهشدنِ اعلانها")
|
||||
constraints = [
|
||||
models.UniqueConstraint(fields=["user", "notification"], name="unique_user_notification_read")
|
||||
]
|
||||
|
||||
def __str__(self):
|
||||
return f"{self.user.phone} — {self.notification.title}"
|
||||
@@ -0,0 +1,71 @@
|
||||
from django.utils import timezone
|
||||
|
||||
from apps.account.models import User
|
||||
|
||||
from .models import Notification, NotificationRead
|
||||
|
||||
# آستانهی هشدار پایان دورهی آزمایشی — هر روزی که ≤ این عدد مانده باشد نشان داده میشود.
|
||||
TRIAL_WARNING_DAYS = 3
|
||||
|
||||
|
||||
class NotificationService:
|
||||
@staticmethod
|
||||
def notify(user: User, title: str, body: str = "") -> Notification:
|
||||
"""اعلان شخصی برای یک کاربر مشخص میسازد."""
|
||||
return Notification.objects.create(user=user, title=title, body=body)
|
||||
|
||||
@staticmethod
|
||||
def trial_warning(user: User) -> dict | None:
|
||||
if not user.is_in_trial or not user.trial_expires_at:
|
||||
return None
|
||||
days_left = (user.trial_expires_at - timezone.now()).days
|
||||
if days_left > TRIAL_WARNING_DAYS:
|
||||
return None
|
||||
return {
|
||||
"days_left": max(days_left, 0),
|
||||
"title": "دورهی رایگانت داره تموم میشه!",
|
||||
"body": (
|
||||
f"فقط {max(days_left, 0)} روز از دورهی آزمایشیات مونده — برای اینکه کارت زمین نمونه، "
|
||||
"از فروشگاه یکی از ابزارها رو با جم فعال کن."
|
||||
),
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def list_for_user(user: User) -> dict:
|
||||
notifications = Notification.objects.filter(user=user) | Notification.objects.filter(user__isnull=True)
|
||||
notifications = notifications.order_by("-created_at")
|
||||
read_ids = set(NotificationRead.objects.filter(user=user).values_list("notification_id", flat=True))
|
||||
|
||||
items = [
|
||||
{
|
||||
"id": n.id,
|
||||
"title": n.title,
|
||||
"body": n.body,
|
||||
"created_at": n.created_at,
|
||||
"is_read": n.id in read_ids,
|
||||
}
|
||||
for n in notifications
|
||||
]
|
||||
unread_count = sum(1 for i in items if not i["is_read"])
|
||||
return {
|
||||
"unread_count": unread_count,
|
||||
"trial_warning": NotificationService.trial_warning(user),
|
||||
"items": items,
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def mark_read(user: User, notification_id: int) -> None:
|
||||
NotificationRead.objects.get_or_create(user=user, notification_id=notification_id)
|
||||
|
||||
@staticmethod
|
||||
def mark_all_read(user: User) -> None:
|
||||
notifications = Notification.objects.filter(user=user) | Notification.objects.filter(user__isnull=True)
|
||||
already_read = set(NotificationRead.objects.filter(user=user).values_list("notification_id", flat=True))
|
||||
NotificationRead.objects.bulk_create(
|
||||
[
|
||||
NotificationRead(user=user, notification_id=n.id)
|
||||
for n in notifications
|
||||
if n.id not in already_read
|
||||
],
|
||||
ignore_conflicts=True,
|
||||
)
|
||||
@@ -0,0 +1,14 @@
|
||||
from django.urls import path
|
||||
|
||||
from .api.views import (
|
||||
NotificationListView,
|
||||
NotificationMarkAllReadView,
|
||||
NotificationMarkReadView,
|
||||
)
|
||||
|
||||
app_name = "notifications"
|
||||
urlpatterns = [
|
||||
path("", NotificationListView.as_view(), name="list"),
|
||||
path("read-all/", NotificationMarkAllReadView.as_view(), name="read-all"),
|
||||
path("<int:notification_id>/read/", NotificationMarkReadView.as_view(), name="read"),
|
||||
]
|
||||
Reference in New Issue
Block a user