Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allocation logic fix #97

Merged
merged 7 commits into from
Nov 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion api/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ def _get_meal_type(self, time):
if meal_timing.start_time <= time <= meal_timing.end_time:
return meal_type
except MessTiming.DoesNotExist:
raise ValueError(f"{meal_type.capitalize()} timings not found.")
return None
return None

def _filter_valid_cards(self, cards, meal_type):
Expand Down Expand Up @@ -187,6 +187,9 @@ def post(self, request):

meal_type = self._get_meal_type(time)

if(meal_type == None):
return Response({"success": False, "detail": "Meal time over.", "mess_card": card_return_data}, status=status.HTTP_403_FORBIDDEN)

if getattr(meal, meal_type):
return Response({"success": False, "detail": "Meal Already Recorded", "mess_card": card_return_data}, status=status.HTTP_409_CONFLICT)

Expand Down
125 changes: 47 additions & 78 deletions home/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from django.shortcuts import redirect, render
from django.utils.http import url_has_allowed_host_and_scheme
from django.utils.dateparse import parse_date
from django.utils.timezone import now

Expand Down Expand Up @@ -363,94 +364,62 @@
:template:`home/allocationForm.html`
Gets the data from the allocation form , and adds it to the coresponding allocation model
Gets the data from the allocation form, and adds it to the corresponding allocation model
"""
caterer_list = Caterer.objects.filter(visible=True).all()
alloc_form = AllocationForm.objects.filter(active=True).last()
try:
if not alloc_form:
raise Exception("Form is closed for now")
text = ""
message = ""

if not alloc_form:
message = "Form is closed for now"
else:
student = Student.objects.filter(email__iexact=str(request.user.email)).last()
if not student:
raise Exception(
"Signed in account can not fill the allocation form. Please inform the dining Office to add your email ID to the database"
)
text = ""
message = ""
if (alloc_form.start_time and alloc_form.start_time > now()) or (
message = "Signed in account cannot fill the allocation form. Please inform the dining Office to add your email ID to the database"
elif (alloc_form.start_time and alloc_form.start_time > now()) or (
alloc_form.end_time and alloc_form.end_time < now()
):
raise Exception("The Form is closed for now")
elif Allocation.objects.filter(
email=student, period=alloc_form.period
).exists():
raise Exception(
"You have filled the form for this period. Please visit the profile page after the allocation process is completed to check your allocated caterer"
)
message = "The Form is closed for now"
elif Allocation.objects.filter(email=student, period=alloc_form.period).exists():
message = "You have filled the form for this period. Please visit the profile page after the allocation process is completed to check your allocated caterer"
elif request.method == "POST" and request.user.is_authenticated:
period_obj = alloc_form.period
high_tea = False
jain = request.POST["jain"]
# if jain == "True":
# high_tea = False
if caterer_list.count() < 1:
first_pref = None
else:
first_pref = request.POST["first_pref"]
caterer1 = Caterer.objects.get(name=first_pref)
if caterer_list.count() < 2:
second_pref = None
else:
second_pref = request.POST["second_pref"]
caterer2 = Caterer.objects.get(name=second_pref)
if caterer_list.count() < 3:
third_pref = None
jain = request.POST["jain"] == "True"
caterer_prefs = [
request.POST.get(pref) for pref in ["first_pref", "second_pref", "third_pref"]
]
caterer_prefs = [Caterer.objects.get(name=pref) for pref in caterer_prefs if pref]

caterer = next((c for c in caterer_prefs if c.student_limit > Allocation.objects.filter(caterer=c, period=period_obj).count()), None)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we rewrite this to make it clear what we intend to do. Right now unreadable.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

tr breaking it into 2-3 lines

if caterer:
student_id = f"{caterer.name[0]}{'J' if jain else ''}{caterer.student_limit}"
allocation = Allocation(
email=student,
student_id=student_id,
period=period_obj,
caterer=caterer,
high_tea=False,
jain=jain,
first_pref=caterer_prefs[0].name if caterer_prefs else None,
second_pref=caterer_prefs[1].name if len(caterer_prefs) > 1 else None,
third_pref=caterer_prefs[2].name if len(caterer_prefs) > 2 else None,
)
allocation.save()
UnregisteredStudent.objects.filter(email__iexact=student.email).delete()
text = "Allocation Form filled Successfully"
request.session["text"] = text
if url_has_allowed_host_and_scheme(request.path, allowed_hosts=None):
return redirect(request.path)
Dismissed Show dismissed Hide dismissed
else:
return redirect('/')
else:
third_pref = request.POST["third_pref"]
caterer3 = Caterer.objects.get(name=third_pref)
if caterer1.student_limit > 0:
caterer1.student_limit -= 1
caterer1.save(update_fields=["student_limit"])
caterer = caterer1
elif caterer2 and caterer2.student_limit > 0:
caterer2.student_limit -= 1
caterer2.save(update_fields=["student_limit"])
caterer = caterer2
elif caterer3 and caterer3.student_limit > 0:
caterer3.student_limit -= 1
caterer3.save(update_fields=["student_limit"])
caterer = caterer3
student_id = str(caterer.name[0])
# if high_tea == "True":
# student_id += "H"
# else:
# student_id+="NH"
if jain == "True":
student_id += "J"
student_id += str(caterer.student_limit)
allocation = Allocation(
email=student,
student_id=student_id,
period=period_obj,
caterer=caterer,
high_tea=high_tea,
jain=jain,
first_pref=first_pref,
second_pref=second_pref,
third_pref=third_pref,
)
allocation.save()
UnregisteredStudent.objects.filter(email__iexact=student.email).delete()
text = "Allocation Form filled Successfully"
request.session["text"] = text
return redirect(request.path)
text = request.session.get("text", "")
if text != "":
del request.session["text"]
except Exception as e:
logger.error(e)
message = e
text = ""
message = "No caterer available with sufficient student limit"

text = request.session.get("text", "")
if text:
del request.session["text"]

context = {
"text": text,
"caterer_list": caterer_list,
Expand Down
20 changes: 20 additions & 0 deletions qrscan/migrations/0005_alter_messcard_student.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Generated by Django 5.0.8 on 2024-10-22 13:30

import django.db.models.deletion
from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('home', '0001_initial'),
('qrscan', '0004_messtiming_delete_messtimings'),
]

operations = [
migrations.AlterField(
model_name='messcard',
name='student',
field=models.ForeignKey(help_text='This contains the student details', on_delete=django.db.models.deletion.CASCADE, to='home.student'),
),
]
2 changes: 1 addition & 1 deletion qrscan/templates/mess_card.html
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
<main>
<div class="wrapper">
<div class="id-card" id="id-card">
<div class="header"></div>
<div class="card-header"></div>
<div class="photo">
<img
class="img-fluid rounded-4"
Expand Down
9 changes: 5 additions & 4 deletions qrscan/views.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from django.utils import timezone
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from home.models import Student
Expand All @@ -19,22 +20,22 @@ def mess_card(request):
provider="google", user_id=request.user.id
)
allocation = student.allocation_set.last()

if(not allocation):
raise ValueError("Allocation not found!")
mess_card, _ = MessCard.objects.get_or_create(student=student)

if(not mess_card.allocation):
setattr(mess_card, allocation)
mess_card.save()
elif(mess_card.allocation != allocation):
setattr(mess_card, allocation)
elif((mess_card.allocation != allocation) and allocation.period.end_date < timezone.localtime().date()):
setattr(mess_card, "allocation", allocation)
mess_card.save()

picture = "not available"
try:
if socialaccount_obj:
picture = socialaccount_obj[0].extra_data["picture"]
else:
picture = "not available"
except (IndexError, KeyError):
picture = "not available"

Expand Down
38 changes: 24 additions & 14 deletions static/css/mess-card.css
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
main {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100vh;
height: max-content;
margin: 0;
background-color: #f0f0f0;
font-family: "Arial", sans-serif;
overflow-x: hidden;
}

.id-card {
width: 400px;
height: 500px;
min-height: max-content;
width: 100%;
max-width: 400px;
height: auto;
background-color: white;
border-radius: 15px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
Expand All @@ -19,43 +22,42 @@ main {
position: relative;
overflow: hidden;
}
.id-card .header {

.id-card .card-header {
background-color: #2579a6;
border-top-left-radius: 15px;
border-top-right-radius: 15px;
height: 100px;
position: relative;
clip-path: ellipse(70% 100% at 50% 0%);
}
.id-card {
margin-top: -50px;
}

.id-card .photo {
margin-top: 10px;
}

.id-card .name {
font-size: 22px;
font-weight: bold;
margin-top: 10px;
}

.id-card .divider {
width: 50px;
height: 3px;
background-color: #2579a6;
margin: 10px auto;
}

.id-card .id-number {
font-size: 14px;
margin-top: 10px;
}

.id-card .qr-code {
margin-top: 20px;
}
.id-card .website {
font-size: 12px;
color: #2579a6;
margin-top: 10px;
}

.id-card .footer {
background-color: #2579a6;
border-bottom-left-radius: 15px;
Expand All @@ -70,11 +72,19 @@ main {

.wrapper {
display: flex;
justify-content: center;
flex-direction: column;
align-items: center;
margin-bottom: 1rem;
margin-top: 1rem;
}

.card-subtitle {
font-size: 28px;
margin-top: 10px;
}

@media (max-width: 768px) {
.id-card {
width: 90%;
}
}
Loading