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

Add PUT, PATCH and DELETE methods for the pizzas. #161

Merged
merged 2 commits into from
Aug 27, 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
7 changes: 7 additions & 0 deletions insalan/pizza/admin.py
Original file line number Diff line number Diff line change
@@ -1,27 +1,33 @@
"""This module contains the admin configuration for the Pizza app."""

from django.contrib import admin
from django.http import HttpResponse

from .models import Pizza, TimeSlot, Order, PizzaOrder, PizzaExport, PaymentMethod

class PizzaAdmin(admin.ModelAdmin):
"""Admin class for the Pizza model"""
list_display = ("id", "name", "ingredients")
search_fields = ["name", "ingredients", "allergens"]

admin.site.register(Pizza, PizzaAdmin)


class TimeSlotAdmin(admin.ModelAdmin):
"""Admin class for the TimeSlot model"""
list_display = ("id", "delivery_time", "end", "pizza_max")
search_fields = ["delivery_time", "end"]

admin.site.register(TimeSlot, TimeSlotAdmin)


class PizzaOrderInline(admin.TabularInline):
"""Admin class for the PizzaOrder model"""
model = PizzaOrder
extra = 1

class OrderAdmin(admin.ModelAdmin):
"""Admin class for the Order model"""
list_display = ("id", "get_username", "time_slot", "created_at")
search_fields = ["user", "time_slot__delivery_time"]
inlines = [PizzaOrderInline]
Expand Down Expand Up @@ -56,6 +62,7 @@ def export(self, request, queryset):
admin.site.register(Order, OrderAdmin)

class ExportAdmin(admin.ModelAdmin):
"""Admin class for the Export model"""
list_display = ("id", "time_slot", "created_at")
search_fields = ["time_slot"]

Expand Down
1 change: 1 addition & 0 deletions insalan/pizza/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from django.utils.translation import gettext_lazy as _

class PizzaConfig(AppConfig):
"""Configuration of the Pizza App"""
default_auto_field = "django.db.models.BigAutoField"
name = "insalan.pizza"
verbose_name = _("Pizza")
8 changes: 5 additions & 3 deletions insalan/pizza/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,15 @@

It includes the following models:
- Pizza: Represents a pizza with its name, price, ingredients, image, and availability.
- TimeSlot: Represents a time slot for ordering pizzas, including delivery time, end time, and maximum number of pizzas.
- Order: Represents a pizza order, including the user, time slot, pizzas, payment method, price, and delivery status.
- TimeSlot: Represents a time slot for ordering pizzas, including delivery time, end time, and
maximum number of pizzas.
- Order: Represents a pizza order, including the user, time slot, pizzas, payment method, price,
and delivery status.
"""
from typing import List

from django.core.validators import FileExtensionValidator
from django.db import models
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from django.contrib.postgres.fields import ArrayField

Expand Down Expand Up @@ -216,6 +217,7 @@ def get_orders_id(self) -> List[int]:
return Order.objects.filter(time_slot=self).values_list("id", flat=True).order_by("-id")

class PizzaOrder(models.Model):
"""Pizza order model"""
order = models.ForeignKey('Order', on_delete=models.CASCADE)
pizza = models.ForeignKey('pizza.Pizza', on_delete=models.CASCADE)

Expand Down
27 changes: 20 additions & 7 deletions insalan/pizza/serializers.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
""" Serializers for pizza models"""

from typing import List

from rest_framework import serializers

from .models import Pizza, Order, TimeSlot, PizzaOrder, PizzaExport, PaymentMethod
from typing import List

class PizzaSerializer(serializers.ModelSerializer):
"""Serializer for a pizza model"""
Expand All @@ -27,7 +29,8 @@ class OrderSerializer(serializers.ModelSerializer):
class Meta:
model = Order
read_only_fields = ("id", )
fields = ("id", "user", "time_slot", "pizza", "payment_method", "price", "paid", "created_at", "delivered", "delivery_date")
fields = ("id", "user", "time_slot", "pizza", "payment_method", "price", "paid",
"created_at", "delivered", "delivery_date")

class CreateOrderSerializer(serializers.ModelSerializer):
""" Serializer for an order"""
Expand All @@ -53,9 +56,13 @@ def create(self, validated_data):
elif price_type == "staff":
price = TimeSlot.objects.get(id=validated_data["time_slot"].id).staff_price * len(pizza)
elif price_type == "player":
price = TimeSlot.objects.get(id=validated_data["time_slot"].id).player_price * len(pizza)
price = TimeSlot.objects.get(
id=validated_data["time_slot"].id
).player_price * len(pizza)
else:
price = TimeSlot.objects.get(id=validated_data["time_slot"].id).external_price * len(pizza)
price = TimeSlot.objects.get(
id=validated_data["time_slot"].id
).external_price * len(pizza)
validated_data["price"] = price
order = Order.objects.create(**validated_data)
for p in pizza:
Expand All @@ -75,7 +82,7 @@ class Meta:
"""
model = Order
fields = ("id", )

def to_representation(self, instance):
"""Turn a Django object into a serialized representation"""
return instance.id
Expand Down Expand Up @@ -112,8 +119,14 @@ class Meta:
def get_pizza(self, obj):
result = {}
# for each pizza type in the timeslot, count the number of pizza ordered
for pizza in PizzaOrder.objects.filter(order__time_slot__id=obj.id).values("pizza__id").distinct():
result[pizza["pizza__id"]] = PizzaOrder.objects.filter(order__time_slot__id=obj.id, pizza__id=pizza["pizza__id"]).count()
pizzas = PizzaOrder.objects.filter(
order__time_slot__id=obj.id
).values("pizza__id").distinct()
for pizza in pizzas:
result[pizza["pizza__id"]] = PizzaOrder.objects.filter(
order__time_slot__id=obj.id,
pizza__id=pizza["pizza__id"]
).count()
return result

class PizzaExportSerializer(serializers.ModelSerializer):
Expand Down
131 changes: 125 additions & 6 deletions insalan/pizza/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,16 @@

"""

from datetime import timedelta

from django.test import TestCase
from django.urls import reverse
from django.utils import timezone
from rest_framework import status
from rest_framework.test import APIClient

from insalan.pizza.models import Pizza, TimeSlot, Order, PizzaOrder, PizzaExport
from insalan.pizza.serializers import PizzaSerializer, PizzaIdSerializer
from insalan.user.models import User
from datetime import timedelta


class PizzaEndpointsTestCase(TestCase):
Expand All @@ -25,7 +25,7 @@ def setUp(self):
self.admin_user = User.objects.create(
username="admin", email="admin@example.com", is_staff=True
)

self.pizza1 = Pizza.objects.create(name="Test Pizza")
self.pizza2 = Pizza.objects.create(name="Test Pizza 2")

Expand Down Expand Up @@ -57,7 +57,7 @@ def test_pizza_list(self):
self.assertEqual(len(response.data), 2)
self.assertEqual(response.data[0], self.pizza1.id)
self.assertEqual(response.data[1], self.pizza2.id)

def test_pizza_post(self):
"""Test the pizza post endpoint"""
client = APIClient()
Expand Down Expand Up @@ -138,6 +138,125 @@ def test_pizza_by_timeslot_id_not_found(self):
)
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

def test_pizza_put(self) -> None:
"""Test the pizza put endpoint"""
client = APIClient()
client.force_login(user=self.admin_user)
pizza_id: int = self.pizza1.id
response = client.put(reverse(
"pizza/detail",
kwargs={"pk": pizza_id}
), {"name": "New Pizza Name"})
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data, {
"id": pizza_id,
"name": "New Pizza Name",
"ingredients": None,
"allergens": None,
"image": None
})

def test_pizza_put_unauthorized(self) -> None:
"""Test the pizza put endpoint with unauthorized user"""
client = APIClient()
pizza_id: int = self.pizza1.id
response = client.put(reverse(
"pizza/detail",
kwargs={"pk": pizza_id}
), {"name": "New Pizza Name"})
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
self.assertEqual(response.data, {
"detail": "Informations d'authentification non fournies."
})
self.assertEqual(Pizza.objects.get(id=pizza_id).name, "Test Pizza")

def test_pizza_put_not_found(self) -> None:
"Test the pizza put endpoint with wrong id"""
client = APIClient()
client.force_login(user=self.admin_user)
response = client.put(reverse(
"pizza/detail",
kwargs={"pk": 999}
), {"name": "New Pizza Name"})
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
self.assertEqual(response.data, {
"detail": "Pas trouvé."
})

def test_pizza_patch(self) -> None:
"""Test the pizza patch endpoint"""
client = APIClient()
client.force_login(user=self.admin_user)
pizza_id: int = self.pizza1.id
response = client.patch(reverse(
"pizza/detail",
kwargs={"pk": pizza_id}
), {"name": "New Pizza Name"})
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data, {
"id": pizza_id,
"name": "New Pizza Name",
"ingredients": None,
"allergens": None,
"image": None
})

def test_pizza_patch_unauthorized(self) -> None:
"""Test the pizza patch endpoint with unauthorized user"""
client = APIClient()
pizza_id: int = self.pizza1.id
response = client.patch(reverse(
"pizza/detail",
kwargs={"pk": pizza_id}
), {"name": "New Pizza Name"})
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
self.assertEqual(response.data, {
"detail": "Informations d'authentification non fournies."
})
self.assertEqual(Pizza.objects.get(id=pizza_id).name, "Test Pizza")

def test_pizza_patch_not_found(self) -> None:
"Test the pizza patch endpoint with wrong id"""
client = APIClient()
client.force_login(user=self.admin_user)
response = client.patch(reverse(
"pizza/detail",
kwargs={"pk": 999}
), {"name": "New Pizza Name"})
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
self.assertEqual(response.data, {
"detail": "Pas trouvé."
})

def test_pizza_delete(self) -> None:
"""Test the pizza delete endpoint"""
client = APIClient()
client.force_login(user=self.admin_user)
response = client.delete(
reverse("pizza/detail", kwargs={"pk": self.pizza1.id})
)
self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
self.assertEqual(Pizza.objects.count(), 1)

def test_pizza_delete_unauthorized(self) -> None:
"""Test the pizza delete endpoint with unauthorized user"""
client = APIClient()
response = client.delete(
reverse("pizza/detail", kwargs={"pk": self.pizza1.id})
)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
self.assertEqual(Pizza.objects.count(), 2)

def test_pizza_delete_not_found(self) -> None:
"""Test the pizza delete endpoint with wrong id"""
client = APIClient()
client.force_login(user=self.admin_user)
response = client.delete(
reverse("pizza/detail", kwargs={"pk": 999})
)
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
self.assertEqual(Pizza.objects.count(), 2)

def test_timeslot_list(self):
"""Test the timeslot list endpoint"""
client = APIClient()
Expand Down Expand Up @@ -307,7 +426,7 @@ def test_order_post_unauthorized(self):
)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
self.assertEqual(Order.objects.count(), 1)

def test_order_post_not_found(self):
"""Test the order post endpoint with wrong id"""
client = APIClient()
Expand Down Expand Up @@ -481,4 +600,4 @@ def test_export_order_post_full(self):
)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(len(response.data), 1)
self.assertEqual(response.data[0]["orders"][self.order.pizza.all()[0].name], 1)
self.assertEqual(response.data[0]["orders"][self.order.pizza.all()[0].name], 1)
5 changes: 3 additions & 2 deletions insalan/pizza/urls.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
""" URLs for pizza
- /pizza/pizza:
- /pizza/pizza:
- GET: return pizza list id
- POST: create a pizza (admin only)
- /pizza/pizza/full: list pizza available with their infos
Expand Down Expand Up @@ -34,7 +34,8 @@
path("pizza/<int:pk>/", views.PizzaDetail.as_view(), name="pizza/detail"),
path("pizza/search/",views.PizzaSearch.as_view(), name="pizza/fuzzy-find"),
path("pizza/by-timeslot/", views.PizzaListByTimeSlot.as_view(), name="pizza/list/by-timeslot"),
path("pizza/by-timeslot/<int:pk>", views.PizzaListByGivenTimeSlot.as_view(), name="pizza/list/by-timeslot-id"),
path("pizza/by-timeslot/<int:pk>", views.PizzaListByGivenTimeSlot.as_view(),
name="pizza/list/by-timeslot-id"),
path("timeslot/", views.TimeSlotList.as_view(), name="timeslot/list"),
path("timeslot/full/", views.TimeSlotListFull.as_view(), name="timeslot/list/full"),
path("timeslot/<int:pk>/", views.TimeSlotDetail.as_view(), name="timeslot/detail"),
Expand Down
Loading
Loading