Backend Draft

This commit is contained in:
__init__
2026-02-23 20:31:53 +05:30
commit eec700af51
127 changed files with 2356 additions and 0 deletions

View File

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,3 @@
from django.contrib import admin
# Register your models here.

View File

@@ -0,0 +1,6 @@
from django.apps import AppConfig
class DashboardConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "dashboard"

View File

@@ -0,0 +1,62 @@
# Generated by Django 4.2.28 on 2026-02-20 19:49
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
("tenants", "0001_initial"),
]
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=255)),
("message", models.TextField()),
("is_read", models.BooleanField(default=False)),
("link", models.URLField(blank=True, max_length=500, null=True)),
("created_at", models.DateTimeField(auto_now_add=True)),
(
"tenant",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="notifications",
to="tenants.tenant",
),
),
(
"user",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="notifications",
to=settings.AUTH_USER_MODEL,
),
),
],
options={
"ordering": ["-created_at"],
"indexes": [
models.Index(
fields=["tenant", "user", "is_read"],
name="dashboard_n_tenant__eff9b5_idx",
)
],
},
),
]

View File

View File

@@ -0,0 +1,24 @@
from django.db import models
from django.conf import settings
from tenants.managers import TenantScopedManager
from tenants.models import Tenant
class Notification(models.Model):
tenant = models.ForeignKey(Tenant, on_delete=models.CASCADE, related_name='notifications')
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='notifications')
title = models.CharField(max_length=255)
message = models.TextField()
is_read = models.BooleanField(default=False)
link = models.URLField(max_length=500, null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
objects = TenantScopedManager()
class Meta:
ordering = ['-created_at']
indexes = [
models.Index(fields=['tenant', 'user', 'is_read']),
]
def __str__(self):
return f"Notification for {self.user}: {self.title}"

View File

@@ -0,0 +1,8 @@
from rest_framework import serializers
from .models import Notification
class NotificationSerializer(serializers.ModelSerializer):
class Meta:
model = Notification
fields = ['id', 'title', 'message', 'is_read', 'link', 'created_at']
read_only_fields = ['id', 'title', 'message', 'link', 'created_at']

View File

@@ -0,0 +1,23 @@
from celery import shared_task
from django.contrib.auth import get_user_model
from dashboard.models import Notification
from tenants.models import Tenant
User = get_user_model()
@shared_task
def send_notification_email_async(notification_id):
"""
Example Celery task to asynchronously send an email
when a new notification is generated.
"""
try:
notification = Notification.objects.get(id=notification_id)
user = notification.user
# In a real scenario, this would use django.core.mail.send_mail
print(f"ASYNC TASK: Sending email to {user.email} regarding: {notification.title}")
return True
except Notification.DoesNotExist:
print(f"ASYNC TASK ERR: Notification {notification_id} not found.")
return False

View File

@@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

12
backend/dashboard/urls.py Normal file
View File

@@ -0,0 +1,12 @@
from django.urls import path
from .views import DashboardSummaryView, NotificationViewSet
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register(r'notifications', NotificationViewSet, basename='notification')
urlpatterns = [
path('summary/', DashboardSummaryView.as_view(), name='dashboard-summary'),
]
urlpatterns += router.urls

View File

@@ -0,0 +1,62 @@
from rest_framework import viewsets, generics, permissions, status
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.decorators import action
from django.db.models import Count
from django.contrib.auth import get_user_model
from projects.models import Project, Task
from analytics.models import ActivityLog
from analytics.serializers import ActivityLogSerializer
from .models import Notification
from .serializers import NotificationSerializer
from accounts.permissions import IsTenantUser
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page
User = get_user_model()
class DashboardSummaryView(APIView):
permission_classes = [permissions.IsAuthenticated, IsTenantUser]
def get(self, request):
tenant = request.tenant
# Basic Counts
total_projects = Project.objects.filter(tenant=tenant).count()
total_tasks = Task.objects.filter(tenant=tenant).count()
total_users = User.objects.filter(tenant=tenant).count()
# Task Status Breakdown
task_status_counts = Task.objects.filter(tenant=tenant).values('status').annotate(count=Count('status'))
status_breakdown = {item['status']: item['count'] for item in task_status_counts}
# Recent Activity (Last 10)
recent_activity = ActivityLog.objects.filter(tenant=tenant).order_by('-created_at')[:10]
activity_serializer = ActivityLogSerializer(recent_activity, many=True)
return Response({
'total_projects': total_projects,
'total_tasks': total_tasks,
'total_users': total_users,
'task_status_breakdown': status_breakdown,
'recent_activity': activity_serializer.data
})
class NotificationViewSet(viewsets.ModelViewSet):
serializer_class = NotificationSerializer
permission_classes = [permissions.IsAuthenticated, IsTenantUser]
def get_queryset(self):
return Notification.objects.filter(tenant=self.request.tenant, user=self.request.user)
@action(detail=True, methods=['post'])
def mark_read(self, request, pk=None):
notification = self.get_object()
notification.is_read = True
notification.save()
return Response({'status': 'notification marked as read'})
@action(detail=False, methods=['post'])
def mark_all_read(self, request):
self.get_queryset().filter(is_read=False).update(is_read=True)
return Response({'status': 'all notifications marked as read'})