Skip to content

Commit

Permalink
Fixed bugs
Browse files Browse the repository at this point in the history
  • Loading branch information
Princekumarofficial committed Oct 6, 2024
1 parent 1151420 commit e3f3efd
Show file tree
Hide file tree
Showing 11 changed files with 178 additions and 95 deletions.
24 changes: 15 additions & 9 deletions api/utils/rebate_checker.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,26 @@
from django.utils import timezone
from home.models.students import Student, LongRebate, TodayRebate, Allocation
from home.models.students import Student, LongRebate, Rebate, Allocation


def is_student_on_rebate(student: Student, allocation: Allocation):
"""
This function checks if the student is on rebate or not
"""
long_rebate = LongRebate.objects.filter(email=student)
today = timezone.localtime().date()

rebate_exists = TodayRebate.objects.filter(allocation_id=allocation.id).exists()

if rebate_exists:
# Check if there is a TodayRebate for the given allocation
if Rebate.objects.filter(
allocation_id=allocation,
start_date__lte=today,
end_date__gte=today,
approved=True
).exists():
return True

for r in long_rebate:
if r.start_date <= today <= r.end_date and r.approved:
return True
return False
# Check if there is an approved LongRebate for the student within the date range
return LongRebate.objects.filter(
email=student,
start_date__lte=today,
end_date__gte=today,
approved=True
).exists()
26 changes: 13 additions & 13 deletions api/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,14 @@
from drf_yasg.utils import swagger_auto_schema

from home.models import Allocation, Period
from qrscan.models import MessCard, Meal
from qrscan.models import MessCard, Meal, MessTiming
from .permissions import IsStaff
from .serializers import (
AllocationSerializer, PeriodSerializer, AllocationDetailSerializer,
QRVerifySerializer, MealSerializer, UserSerializer, QRVerifyPostSerializer
)
from .utils.rebate_checker import is_student_on_rebate

# Constants
BREAKFAST_END_TIME = timezone.datetime.strptime('11:00:00', '%H:%M:%S').time()
LUNCH_END_TIME = timezone.datetime.strptime('15:00:00', '%H:%M:%S').time()

class LogoutView(APIView):
"""
View to handle user logout.
Expand Down Expand Up @@ -106,12 +102,15 @@ class QRVerifyUpdateView(APIView):
permission_classes = [IsStaff]

def _get_meal_type(self, time):
if time < BREAKFAST_END_TIME:
return 'breakfast'
elif time < LUNCH_END_TIME:
return 'lunch'
else:
return 'dinner'
meal_types = ['breakfast', 'lunch', 'high_tea', 'dinner']
for meal_type in meal_types:
try:
meal_timing = MessTiming.objects.get(meal_type=meal_type)
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

def _filter_valid_cards(self, cards, meal_type):
valid_cards = []
Expand All @@ -131,6 +130,8 @@ def _is_meal_recorded(self, card, meal_type):
return True
elif meal_type == 'lunch' and card.meal_set.filter(date=today, lunch=True).exists():
return True
elif meal_type == 'high_tea' and card.meal_set.filter(date=today, high_tea=True).exists():
return True
elif meal_type == 'dinner' and card.meal_set.filter(date=today, dinner=True).exists():
return True
return False
Expand Down Expand Up @@ -174,15 +175,14 @@ def post(self, request):
date = timezone.localtime().date()
time = timezone.localtime().time()
meal, _ = Meal.objects.get_or_create(mess_card=card, date=date)
is_rebate = is_student_on_rebate(card.student, card.allocation)

if card.allocation.period.end_date <= date:
return Response({"success": False, "detail": "Not registered for current Period.", "mess_card": card_return_data}, status=status.HTTP_403_FORBIDDEN)

if card.allocation.caterer.name != request.user.username:
return Response({"success": False, "detail": "Wrong caterer.", "mess_card": card_return_data}, status=status.HTTP_403_FORBIDDEN)

if is_rebate:
if is_student_on_rebate(card.student, card.allocation):
return Response({"success": False, "detail": "Student is on rebate.", "mess_card": card_return_data}, status=status.HTTP_403_FORBIDDEN)

meal_type = self._get_meal_type(time)
Expand Down
4 changes: 2 additions & 2 deletions messWebsite/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@
SECRET_KEY = env("SECRET_KEY")

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
DEBUG = env.bool("DEBUG", default=False)

ALLOWED_HOSTS = ["diningfee.iiti.ac.in", "127.0.0.1", "103.159.214.171", "*"]
ALLOWED_HOSTS = ["diningfee.iiti.ac.in", "127.0.0.1", "103.159.214.171"]
CSRF_TRUSTED_ORIGINS = ["http://diningfee.iiti.ac.in", "https://diningfee.iiti.ac.in"]
# Application definition

Expand Down
23 changes: 19 additions & 4 deletions qrscan/admin.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
from django.contrib import admin
from .models import MessCard, Meal
from .models import MessCard, Meal, MessTiming

# Admin configuration for MessCard model
@admin.register(MessCard)
class MessCardAdmin(admin.ModelAdmin):
list_display = ['id', 'allocation', 'student']
list_display_links = ['id', 'allocation', 'student']
Expand All @@ -11,7 +12,9 @@ class MessCardAdmin(admin.ModelAdmin):
ordering = ['id']
list_per_page = 25


# Admin configuration for Meal model
@admin.register(Meal)
class MealAdmin(admin.ModelAdmin):
list_display = ['id', 'mess_card', 'date', 'breakfast', 'lunch', 'dinner']
list_display_links = ['id', 'mess_card']
Expand All @@ -21,6 +24,18 @@ class MealAdmin(admin.ModelAdmin):
ordering = ['date', 'id']
list_per_page = 25

# Registering models with the admin site
admin.site.register(MessCard, MessCardAdmin)
admin.site.register(Meal, MealAdmin)

# Admin configuration for MessTimings model
@admin.register(MessTiming)
class MessTimingsAdmin(admin.ModelAdmin):
list_display = ['meal_type', 'start_time', 'end_time']
list_display_links = ['meal_type']
search_fields = ('meal_type',)
list_filter = ('meal_type',)
ordering = ['meal_type']

def start_time(self, obj):
return obj.start_time.strftime('%H:%M')

def end_time(self, obj):
return obj.end_time.strftime('%H:%M')
18 changes: 18 additions & 0 deletions qrscan/migrations/0002_meal_high_tea.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Generated by Django 5.0.8 on 2024-10-06 12:23

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('qrscan', '0001_initial'),
]

operations = [
migrations.AddField(
model_name='meal',
name='high_tea',
field=models.BooleanField(default=False, help_text='This contains the high tea status'),
),
]
22 changes: 22 additions & 0 deletions qrscan/migrations/0003_messtimings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Generated by Django 5.0.8 on 2024-10-06 13:00

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('qrscan', '0002_meal_high_tea'),
]

operations = [
migrations.CreateModel(
name='MessTimings',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('meal_type', models.CharField(choices=[('breakfast', 'Breakfast'), ('lunch', 'Lunch'), ('high_tea', 'High Tea'), ('dinner', 'Dinner')], help_text='This contains the meal type', max_length=10)),
('start_time', models.TimeField(blank=True, help_text='This contains the start time', null=True)),
('end_time', models.TimeField(blank=True, help_text='This contains the end time', null=True)),
],
),
]
25 changes: 25 additions & 0 deletions qrscan/migrations/0004_messtiming_delete_messtimings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Generated by Django 5.0.8 on 2024-10-06 13:14

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('qrscan', '0003_messtimings'),
]

operations = [
migrations.CreateModel(
name='MessTiming',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('meal_type', models.CharField(choices=[('breakfast', 'Breakfast'), ('lunch', 'Lunch'), ('high_tea', 'High Tea'), ('dinner', 'Dinner')], help_text='This contains the meal type', max_length=10, unique=True)),
('start_time', models.TimeField(blank=True, help_text='This contains the start time', null=True)),
('end_time', models.TimeField(blank=True, help_text='This contains the end time', null=True)),
],
),
migrations.DeleteModel(
name='MessTimings',
),
]
41 changes: 32 additions & 9 deletions qrscan/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,13 @@
from io import BytesIO
from PIL import Image
import qrcode
import secrets

from django.core.files import File
from django.db import models

from home.models import Allocation, Student


def generate_secret_key():
return secrets.token_hex(32)


class MessCard(models.Model):
id = models.UUIDField(
primary_key=True,
Expand Down Expand Up @@ -106,6 +101,10 @@ class Meal(models.Model):
help_text="This contains the lunch status",
default=False
)
high_tea = models.BooleanField(
help_text="This contains the high tea status",
default=False
)
dinner = models.BooleanField(
help_text="This contains the dinner status",
default=False
Expand All @@ -117,7 +116,31 @@ class Meta:
def __str__(self):
return f"{self.mess_card.allocation.student_id} - {self.date}"

def save(self, *args, **kwargs):
if not self.mess_card:
self.mess_card = MessCard.objects.get(allocation=self.mess_card.allocation)
super().save(*args, **kwargs)

class MessTiming(models.Model):
MEAL_TYPES = [
('breakfast', 'Breakfast'),
('lunch', 'Lunch'),
('high_tea', 'High Tea'),
('dinner', 'Dinner')
]

meal_type = models.CharField(
max_length=10,
choices=MEAL_TYPES,
help_text="This contains the meal type",
unique=True,
)
start_time = models.TimeField(
help_text="This contains the start time",
null=True,
blank=True
)
end_time = models.TimeField(
help_text="This contains the end time",
null=True,
blank=True
)

def __str__(self):
return f"{self.meal_type} Timings"
40 changes: 24 additions & 16 deletions qrscan/templates/mess_card.html
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
rel="stylesheet"
/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.9.3/html2pdf.bundle.min.js"></script>


{% endblock %} {%block body%}
<main>
Expand All @@ -26,7 +25,9 @@ <h6 class="card-subtitle mt-2">{{ student.name }}</h6>
<span class="card-text">Roll Number: {{ student.roll_no }}</span><br />
<span class="card-text">Email: {{ user.email }}</span><br />
<span class="card-text">Department: {{ student.department }}</span><br />
<span class="card-text">Hostel and Room: {{ student.hostel }} {{ student.room_no }}</span><br />
<span class="card-text"
>Hostel and Room: {{ student.hostel }} {{ student.room_no }}</span
><br />
<div class="qr-code">
<img
alt="QR Code"
Expand All @@ -35,27 +36,34 @@ <h6 class="card-subtitle mt-2">{{ student.name }}</h6>
width="100%"
/>
</div>
<div class="website">www.reallygreatsite.com</div>
<div class="footer"></div>
<!-- <div class="footer"></div> -->
</div>
<div>
<button id="download-btn" class="btn btn-primary w-100 mt-4">Download</button>
<button id="download-btn" class="btn btn-primary w-100 mt-4">
Download
</button>
</div>
</div>
<script>
document.getElementById("download-btn").addEventListener("click", function () {
var element = document.getElementById("id-card");
document
.getElementById("download-btn")
.addEventListener("click", function () {
var element = document.getElementById("id-card");

var opt = {
margin: 0,
filename: "mess-card.pdf",
image: { type: "jpeg", quality: 0.98 },
html2canvas: { scale: 2 },
jsPDF: { unit: "px", format: [element.clientHeight, element.clientWidth], orientation: "portrait" },
};
var opt = {
margin: 0,
filename: "mess-card.pdf",
image: { type: "jpeg", quality: 0.98 },
html2canvas: { scale: 2 },
jsPDF: {
unit: "px",
format: [element.clientHeight, element.clientWidth],
orientation: "portrait",
},
};

html2pdf().from(element).set(opt).save();
});
html2pdf().from(element).set(opt).save();
});
</script>
</main>

Expand Down
3 changes: 0 additions & 3 deletions qrscan/tests.py
Original file line number Diff line number Diff line change
@@ -1,3 +0,0 @@
from django.test import TestCase

# Create your tests here.
Loading

0 comments on commit e3f3efd

Please sign in to comment.