Skip to content

Commit

Permalink
refactor urls
Browse files Browse the repository at this point in the history
  • Loading branch information
TareqMonwer committed Dec 31, 2024
1 parent 0666bc8 commit 81250a6
Show file tree
Hide file tree
Showing 10 changed files with 446 additions and 153 deletions.
25 changes: 12 additions & 13 deletions config/settings/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,20 +115,19 @@

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
str(BASE_DIR / 'templates')
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [str(BASE_DIR / "templates")],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.debug",
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
# ctx processeor to attach institute data in templates
'context_processors.dj_sms_context_processor.attach_institute_data_ctx_processor',
'context_processors.dj_sms_context_processor.attach_urls_for_common_templates',
"context_processors.attach_resources.attach_institute_data_ctx_processor",
"context_processors.attach_resources.attach_urls_for_common_templates",
"context_processors.attach_resources.attach_dashboard_menu_items",
],
},
},
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
from django_school_management.academics.constants import AcademicsURLConstants
from django_school_management.accounts.constants import AccountURLConstants
from django_school_management.institute.models import (InstituteProfile,
TextWidget, ListWidget
)
from django_school_management.accounts.services.menu import MenuService
from django_school_management.accounts.utils.menu_config import MENU_CONFIG
from django_school_management.institute.models import (
InstituteProfile,
TextWidget,
ListWidget,
)
from django_school_management.articles.models import Category


Expand All @@ -12,33 +16,33 @@ def attach_institute_data_ctx_processor(request):
except:
institute = None
ctx = {
'request_institute': institute,
"request_institute": institute,
}

if 'articles' in request.resolver_match._func_path.split('.'):
if "articles" in request.resolver_match._func_path.split("."):
# If request is coming for articles app's views,
# only then pass registered_navlinks in the context.
# Registered navlinks are Category objects from the articles app.
try:
registered_navlinks = Category.objects.filter(
display_on_menu=True,
).order_by('-created')
).order_by("-created")
except:
registered_navlinks = []
try:
# Setting up widgets for footer and other places of the
# Setting up widgets for footer and other places of the
# website. (TODO: Add location hints to the widget models).
# first text-widget for the footer (footer-col-number-1)
first_widget = TextWidget.objects.get(widget_number=0)
first_widget = TextWidget.objects.get(widget_number=0)
# get rest three widgets
list_widgets = ListWidget.objects.filter(widget_number__lte=4)
except (TextWidget.DoesNotExist, Exception):
first_widget = None
list_widgets = None

ctx['registered_navlinks'] = registered_navlinks
ctx['first_widget'] = first_widget
ctx['list_widgets'] = list_widgets
ctx["registered_navlinks"] = registered_navlinks
ctx["first_widget"] = first_widget
ctx["list_widgets"] = list_widgets
return ctx


Expand All @@ -47,3 +51,15 @@ def attach_urls_for_common_templates(request):
account_urls=AccountURLConstants,
academic_urls=AcademicsURLConstants,
)


def attach_dashboard_menu_items(request):
menu_service = MenuService(MENU_CONFIG)
return dict(
student_menu_items=menu_service.get_menu_items(
"student", request.user
),
teacher_menu_items=menu_service.get_menu_items(
"teacher", request.user
),
)
27 changes: 21 additions & 6 deletions django_school_management/accounts/services/auth.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
from django_school_management.accounts.constants import ProfileApprovalStatusEnum, AccountTypesEnum
from django_school_management.accounts.models import CommonUserProfile, CustomGroup
from django_school_management.accounts.request_context import RequestUserContext
from django_school_management.accounts.constants import (
ProfileApprovalStatusEnum,
AccountTypesEnum,
)
from django_school_management.accounts.models import (
CommonUserProfile,
CustomGroup,
)
from django_school_management.accounts.request_context import (
RequestUserContext,
)


def create_profile_for_approved_account(user):
Expand All @@ -18,8 +26,15 @@ def handle_superuser_creation(user):


def assign_role_based_groups(user):
already_assigned_to_group = user.groups.filter(name=user.requested_role).exists()
if user.approval_status == ProfileApprovalStatusEnum.approved.value and not already_assigned_to_group:
already_assigned_to_group = user.groups.filter(
name=user.requested_role
).exists()
if (
user.approval_status == ProfileApprovalStatusEnum.approved.value
and not already_assigned_to_group
):
group_creator = RequestUserContext.get_current_user()
group, created = CustomGroup.objects.get_or_create(name=user.requested_role, group_creator=group_creator)
group, created = CustomGroup.objects.get_or_create(
name=user.requested_role, group_creator=group_creator
)
user.groups.add(group)
44 changes: 44 additions & 0 deletions django_school_management/accounts/services/menu.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
from django.urls import reverse
from django_school_management.accounts.models import User
from typing import List, Dict, Any, Set


class MenuService:
def __init__(self, menu_config: Dict[str, Any]):
"""
Initialize the MenuService with the given configuration.
"""
self.menu_config = menu_config

def get_user_groups(self, user: User) -> Set[str]:
"""
Retrieve the groups of the user as a set.
"""
return set(user.groups.values_list("name", flat=True))

def add_urls_to_menu(
self, menu_items: List[Dict[str, str]], urls: List[Dict[str, str]]
) -> None:
"""
Add reversed URLs and titles to the menu_items list.
"""
for url in urls:
menu_items.append(
{"url": reverse(url["name"]), "title": url["title"]}
)

def get_menu_items(self, section: str, user: User) -> List[Dict[str, str]]:
"""
Retrieve menu items for a given section based on the user's groups.
"""
user_groups = self.get_user_groups(user)
menu_items = []

if section not in self.menu_config:
return menu_items

for entry in self.menu_config[section]:
if user_groups & entry["groups"]:
self.add_urls_to_menu(menu_items, entry["urls"])

return menu_items
76 changes: 76 additions & 0 deletions django_school_management/accounts/utils/menu_config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
from django_school_management.students.constants import StudentsURLConstants
from django_school_management.teachers.constants import TeachersURLConstants


all_teachers = dict(name=TeachersURLConstants.all_teacher, title="Teachers")
articles_manage = dict(name="articles:dashboard_manage", title="Articles")
teacher_designations = dict(name=TeachersURLConstants.designations, title="Designations")
write_article = dict(
name="articles:publish_article_from_dashboard",
title="Write Article",
)

add_student = {
"name": StudentsURLConstants.add_student,
"title": "New Application",
}
all_students = {"name": StudentsURLConstants.all_student, "title": "Students List"}
add_result = {"name": "result:result_entry", "title": "Add Result"}
results_index = {"name": "result:result_home", "title": "Results"}
alumnus = {"name": StudentsURLConstants.alumnus, "title": "Alumnus"}

MENU_CONFIG = {
"student": [
{
"groups": {"teacher", "admin"},
"urls": [
all_students,
add_result,
],
},
{
"groups": {"student", "teacher", "admin"},
"urls": [
results_index,
alumnus,
],
},
{
"groups": {"academic_officer"},
"urls": [
add_student,
all_students,
alumnus,
],
},
],
"teacher": [
{
"groups": {"teacher", "admin"},
"urls": [
write_article,
all_teachers,
],
},
{
"groups": {"student"},
"urls": [all_teachers],
},
{
"groups": {"editor"},
"urls": [
all_teachers,
articles_manage,
write_article,
],
},
{
"groups": {"academic_officer"},
"urls": [all_teachers],
},
{
"groups": {"admin"},
"urls": [teacher_designations],
},
],
}
55 changes: 55 additions & 0 deletions django_school_management/students/constants.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
from enum import Enum


class StudentsURLEnums(Enum):
students_dashboard_index = ""
test_pdf = "pdf/"
add_student = "add/"
all_student = "all/"
alumnus = "alumnus/"
all_applicants = "applicants/"
unpaid_registrants = "applicants/unpaid/"
mark_as_paid_or_unpaid = "applicants/mark-paid/"
add_counseling_data = "add-counsel-data/<int:student_id>/"
admitted_student_list = "admitted-students/"
admission_confirmation = "admission-confirm/"
get_json_batch_data = "api/batches/<int:department_code>/"
yearly_graph_api = "api/yearly-graph/"
admit_student = "online-applicants/<int:pk>/admit/"
paid_registrants = "paid-registrants/"
rejected_registrants = "rejected-registrants/"
update_online_registrant = "update-registrant/<int:pk>/"
update_student = "update/<int:pk>/"
student_details = "<int:pk>/detail/"
delete_student = "<int:pk>/delete/"
students_by_dept = "<int:pk>/students/"
counsel_monthly_report = "counsel-report/"
counsel_monthly_report_typed = "counsel-report/<str:response_type>/"
counsel_report_monthly_with_date = "counsel-report/<str:response_type>/<date:date_param>/"


class StudentsURLConstants:
students_dashboard_index = f"students:{StudentsURLEnums.students_dashboard_index.name}"
test_pdf = f"students:{StudentsURLEnums.test_pdf.name}"
add_student = f"students:{StudentsURLEnums.add_student.name}"
all_student = f"students:{StudentsURLEnums.all_student.name}"
alumnus = f"students:{StudentsURLEnums.alumnus.name}"
all_applicants = f"students:{StudentsURLEnums.all_applicants.name}"
unpaid_registrants = f"students:{StudentsURLEnums.unpaid_registrants.name}"
mark_as_paid_or_unpaid = f"students:{StudentsURLEnums.mark_as_paid_or_unpaid.name}"
add_counseling_data = f"students:{StudentsURLEnums.add_counseling_data.name}"
admitted_student_list = f"students:{StudentsURLEnums.admitted_student_list.name}"
admission_confirmation = f"students:{StudentsURLEnums.admission_confirmation.name}"
get_json_batch_data = f"students:{StudentsURLEnums.get_json_batch_data.name}"
yearly_graph_api = f"students:{StudentsURLEnums.yearly_graph_api.name}"
admit_student = f"students:{StudentsURLEnums.admit_student.name}"
paid_registrants = f"students:{StudentsURLEnums.paid_registrants.name}"
rejected_registrants = f"students:{StudentsURLEnums.rejected_registrants.name}"
update_online_registrant = f"students:{StudentsURLEnums.update_online_registrant.name}"
update_student = f"students:{StudentsURLEnums.update_student.name}"
student_details = f"students:{StudentsURLEnums.student_details.name}"
delete_student = f"students:{StudentsURLEnums.delete_student.name}"
students_by_dept = f"students:{StudentsURLEnums.students_by_dept.name}"
counsel_monthly_report = f"students:{StudentsURLEnums.counsel_monthly_report.name}"
counsel_monthly_report_typed = f"students:{StudentsURLEnums.counsel_monthly_report_typed.name}"
counsel_report_monthly_with_date = f"students:{StudentsURLEnums.counsel_report_monthly_with_date.name}"
Loading

0 comments on commit 81250a6

Please sign in to comment.