Verified Commit 966d1f93 authored by VAN ZUIJLEN Nils's avatar VAN ZUIJLEN Nils
Browse files

Black

parent 21206bbe
...@@ -120,7 +120,9 @@ class SellForm(forms.Form): ...@@ -120,7 +120,9 @@ class SellForm(forms.Form):
with transaction.atomic(): with transaction.atomic():
order = Order.objects.create(user=user, ordered=True) order = Order.objects.create(user=user, ordered=True)
Payment.objects.create(mean=mean, paid=True, order=order) Payment.objects.create(mean=mean, paid=True, order=order)
order_item = item.add_to_order(order, quantity, customization, option, second_option) order_item = item.add_to_order(
order, quantity, customization, option, second_option
)
order.compute_price() order.compute_price()
order.save() order.save()
order.post_payment() order.post_payment()
......
...@@ -159,12 +159,12 @@ class Item(models.Model): ...@@ -159,12 +159,12 @@ class Item(models.Model):
return static("images/default_product.png") return static("images/default_product.png")
def add_to_order( def add_to_order(
self, self,
order: "Order", order: "Order",
quantity: int = 1, quantity: int = 1,
customization: str = "", customization: str = "",
option: str = "", option: str = "",
second_option: str = "", second_option: str = "",
) -> "OrderItem": ) -> "OrderItem":
oi, created = None, False oi, created = None, False
if self.customizable: if self.customizable:
...@@ -196,7 +196,7 @@ class Item(models.Model): ...@@ -196,7 +196,7 @@ class Item(models.Model):
if not oi.is_pack_item: if not oi.is_pack_item:
break break
if ( if (
oi is None or oi.is_pack_item oi is None or oi.is_pack_item
): # The preceding queries in the try-except block were empty or they ): # The preceding queries in the try-except block were empty or they
# ended on a pack_item # ended on a pack_item
oi = OrderItem.objects.create( oi = OrderItem.objects.create(
...@@ -218,12 +218,12 @@ class Item(models.Model): ...@@ -218,12 +218,12 @@ class Item(models.Model):
return oi return oi
def add_to_user( def add_to_user(
self, self,
user, user,
quantity: int = 1, quantity: int = 1,
customization: str = "", customization: str = "",
option: str = "", option: str = "",
second_option: str = "", second_option: str = "",
) -> "OrderItem": ) -> "OrderItem":
if self.hidden or self.end_date < timezone.now(): if self.hidden or self.end_date < timezone.now():
raise ValidationError( raise ValidationError(
...@@ -267,7 +267,7 @@ class Order(models.Model): ...@@ -267,7 +267,7 @@ class Order(models.Model):
try: try:
return self.payment.mean return self.payment.mean
except Payment.DoesNotExist: except Payment.DoesNotExist:
return 'None' return "None"
@property @property
def contains_cotiz(self) -> bool: def contains_cotiz(self) -> bool:
...@@ -453,7 +453,7 @@ class OrderItem(models.Model): ...@@ -453,7 +453,7 @@ class OrderItem(models.Model):
) )
def delete( def delete(
self, *args, override_pack=False, **kwargs self, *args, override_pack=False, **kwargs
) -> Tuple[int, Dict[str, int]]: ) -> Tuple[int, Dict[str, int]]:
deleted = 0 deleted = 0
which: typing.Counter[str] = Counter() which: typing.Counter[str] = Counter()
...@@ -483,7 +483,7 @@ class OrderItem(models.Model): ...@@ -483,7 +483,7 @@ class OrderItem(models.Model):
@receiver(pre_save, sender=OrderItem) @receiver(pre_save, sender=OrderItem)
@receiver(pre_delete, sender=OrderItem) @receiver(pre_delete, sender=OrderItem)
def orderitem_price_computing( def orderitem_price_computing(
sender: Type[OrderItem], instance: OrderItem, **kwargs sender: Type[OrderItem], instance: OrderItem, **kwargs
) -> None: ) -> None:
if kwargs.get("raw", False): if kwargs.get("raw", False):
return return
...@@ -495,9 +495,9 @@ def orderitem_price_computing( ...@@ -495,9 +495,9 @@ def orderitem_price_computing(
@receiver(pre_delete, sender=OrderItem) @receiver(pre_delete, sender=OrderItem)
@receiver(pre_delete, sender=Order) @receiver(pre_delete, sender=Order)
def no_delete_for_ordered( def no_delete_for_ordered(
sender: Union[Type[Order], Type[OrderItem]], sender: Union[Type[Order], Type[OrderItem]],
instance: Union[Order, OrderItem], instance: Union[Order, OrderItem],
**kwargs, **kwargs,
) -> None: ) -> None:
if instance.ordered: if instance.ordered:
raise ValueError("Deletion of ordered instances is not allowed") raise ValueError("Deletion of ordered instances is not allowed")
...@@ -505,7 +505,7 @@ def no_delete_for_ordered( ...@@ -505,7 +505,7 @@ def no_delete_for_ordered(
@receiver(pre_save, sender=lydiaRequest) @receiver(pre_save, sender=lydiaRequest)
def mark_payment_as_paid( def mark_payment_as_paid(
sender: Type[lydiaRequest], instance: lydiaRequest, **kwargs sender: Type[lydiaRequest], instance: lydiaRequest, **kwargs
) -> None: ) -> None:
if kwargs.get("raw", False): if kwargs.get("raw", False):
return return
......
...@@ -510,7 +510,11 @@ class OrderEditViewTest(OrderItemTestCase): ...@@ -510,7 +510,11 @@ class OrderEditViewTest(OrderItemTestCase):
resp = self.client.get(url) resp = self.client.get(url)
self.assertRedirects(resp, "/accounts/login?next=/boutique/order/edit", fetch_redirect_response=False) self.assertRedirects(
resp,
"/accounts/login?next=/boutique/order/edit",
fetch_redirect_response=False,
)
class DeliveryViewTest(PaymentTestCase, OrderItemTestCase): class DeliveryViewTest(PaymentTestCase, OrderItemTestCase):
......
...@@ -49,5 +49,4 @@ urlpatterns = [ ...@@ -49,5 +49,4 @@ urlpatterns = [
), ),
), ),
path("delivery", views.DeliveryView.as_view(), name="delivery"), path("delivery", views.DeliveryView.as_view(), name="delivery"),
] ]
...@@ -224,12 +224,21 @@ class ItemManageView(PermissionRequiredMixin, ListView): ...@@ -224,12 +224,21 @@ class ItemManageView(PermissionRequiredMixin, ListView):
message = req.get("message") message = req.get("message")
if message == "begin-delivery": if message == "begin-delivery":
item_qs.get().order_items.filter(order__payment__paid=True).update(beeing_delivered=True) item_qs.get().order_items.filter(order__payment__paid=True).update(
return JsonResponse({"status": "success", "data": "Début des livraisons des articles déjà commandé"}) beeing_delivered=True
)
return JsonResponse(
{
"status": "success",
"data": "Début des livraisons des articles déjà commandé",
}
)
if message == "stop-delivery": if message == "stop-delivery":
item_qs.get().order_items.update(beeing_delivered=False) item_qs.get().order_items.update(beeing_delivered=False)
return JsonResponse({"status": "success", "data": "Arrêt des livraisons des articles"}) return JsonResponse(
{"status": "success", "data": "Arrêt des livraisons des articles"}
)
elif message == "see-orders": elif message == "see-orders":
item = item_qs.prefetch_related( item = item_qs.prefetch_related(
...@@ -240,7 +249,6 @@ class ItemManageView(PermissionRequiredMixin, ListView): ...@@ -240,7 +249,6 @@ class ItemManageView(PermissionRequiredMixin, ListView):
"status": "success", "status": "success",
"data": [ "data": [
{ {
"display_name": str(oi.order.user.profile), "display_name": str(oi.order.user.profile),
"email": str(oi.order.user.email), "email": str(oi.order.user.email),
"quantity": oi.quantity, "quantity": oi.quantity,
...@@ -253,9 +261,10 @@ class ItemManageView(PermissionRequiredMixin, ListView): ...@@ -253,9 +261,10 @@ class ItemManageView(PermissionRequiredMixin, ListView):
"paid": oi.order.paid, "paid": oi.order.paid,
"ordered_date": oi.order.ordered_date, "ordered_date": oi.order.ordered_date,
"mean": oi.order.mean, "mean": oi.order.mean,
} }
for oi in item.order_items.all().order_by("-order__ordered_date") for oi in item.order_items.all().order_by(
"-order__ordered_date"
)
], ],
} }
) )
...@@ -263,13 +272,29 @@ class ItemManageView(PermissionRequiredMixin, ListView): ...@@ -263,13 +272,29 @@ class ItemManageView(PermissionRequiredMixin, ListView):
raise SuspiciousOperation() raise SuspiciousOperation()
def get_queryset(self) -> "QuerySet[Item]": def get_queryset(self) -> "QuerySet[Item]":
return Item.objects.annotate( return (
total_quantity=Coalesce(Sum('order_items__quantity', filter=Q(order_items__order__payment__paid=True)), Item.objects.annotate(
Value(0)), total_quantity=Coalesce(
quantity_delivered=Coalesce(Sum('order_items__quantity_delivered'), Value(0)), Sum(
quantity_to_deliver=Coalesce(Sum('order_items__quantity', filter=Q(order_items__beeing_delivered=True)), "order_items__quantity",
Value(0))) \ filter=Q(order_items__order__payment__paid=True),
.order_by("hidden").prefetch_related("order_items") ),
Value(0),
),
quantity_delivered=Coalesce(
Sum("order_items__quantity_delivered"), Value(0)
),
quantity_to_deliver=Coalesce(
Sum(
"order_items__quantity",
filter=Q(order_items__beeing_delivered=True),
),
Value(0),
),
)
.order_by("hidden")
.prefetch_related("order_items")
)
class ItemSellView(PermissionRequiredMixin, CreateView): class ItemSellView(PermissionRequiredMixin, CreateView):
...@@ -546,9 +571,9 @@ class DeliveryView(PermissionRequiredMixin, ListView): ...@@ -546,9 +571,9 @@ class DeliveryView(PermissionRequiredMixin, ListView):
).select_related("order__user__profile", "order__user", "item") ).select_related("order__user__profile", "order__user", "item")
def boolQueryParam(self, param: str) -> Optional[bool]: def boolQueryParam(self, param: str) -> Optional[bool]:
if param == 'true': if param == "true":
return True return True
if param == 'false': if param == "false":
return False return False
else: else:
return None return None
...@@ -575,34 +600,44 @@ class DeliveryView(PermissionRequiredMixin, ListView): ...@@ -575,34 +600,44 @@ class DeliveryView(PermissionRequiredMixin, ListView):
if paid is True: if paid is True:
itemList = itemList.filter(order__payment__paid=True) itemList = itemList.filter(order__payment__paid=True)
elif paid is False: elif paid is False:
itemList = itemList.filter(Q(order__payment__isnull=True) | Q(order__payment__paid=False)) itemList = itemList.filter(
Q(order__payment__isnull=True) | Q(order__payment__paid=False)
)
itemList = itemList.filter(Q(item__name__icontains=request.GET["productContains"]) itemList = itemList.filter(
& Q(customization__icontains=request.GET["customizationContains"]) Q(item__name__icontains=request.GET["productContains"])
& Q(order__user__email__icontains=request.GET["emailContains"])) & Q(customization__icontains=request.GET["customizationContains"])
& Q(order__user__email__icontains=request.GET["emailContains"])
)
optionContains = request.GET["optionContains"] optionContains = request.GET["optionContains"]
if optionContains != "": if optionContains != "":
itemList = itemList.filter(Q(option__iexact=optionContains) | Q(second_option__iexact=optionContains)) itemList = itemList.filter(
Q(option__iexact=optionContains)
| Q(second_option__iexact=optionContains)
)
orderedItems = [ orderedItems = [
{"id": orderItem.id, {
"item": str(orderItem.item), "id": orderItem.id,
"image": orderItem.item.get_image_url(), "item": str(orderItem.item),
"display_name": str(orderItem.order.user.profile), "image": orderItem.item.get_image_url(),
"email": str(orderItem.order.user.email), "display_name": str(orderItem.order.user.profile),
"quantity": orderItem.quantity, "email": str(orderItem.order.user.email),
"quantity_delivered": orderItem.quantity_delivered, "quantity": orderItem.quantity,
"option_label": orderItem.item.option_label, "quantity_delivered": orderItem.quantity_delivered,
"option": orderItem.option, "option_label": orderItem.item.option_label,
"second_option_label": orderItem.item.second_option_label, "option": orderItem.option,
"second_option": orderItem.second_option, "second_option_label": orderItem.item.second_option_label,
"customization": orderItem.customization, "second_option": orderItem.second_option,
"paid": orderItem.order.paid, "customization": orderItem.customization,
"ordered_date": orderItem.order.ordered_date, "paid": orderItem.order.paid,
"mean": orderItem.order.mean, "ordered_date": orderItem.order.ordered_date,
} "mean": orderItem.order.mean,
for orderItem in itemList.select_related("order__user__profile", "order__user", "item").all() }
for orderItem in itemList.select_related(
"order__user__profile", "order__user", "item"
).all()
] ]
return JsonResponse({"orderedItems": orderedItems}) return JsonResponse({"orderedItems": orderedItems})
...@@ -635,7 +670,11 @@ class DeliveryView(PermissionRequiredMixin, ListView): ...@@ -635,7 +670,11 @@ class DeliveryView(PermissionRequiredMixin, ListView):
orderitem = queryset.get() orderitem = queryset.get()
except OrderItem.DoesNotExist: except OrderItem.DoesNotExist:
return JsonResponse( return JsonResponse(
{"status": "error", "code": 404, "message": "Commande introuvable ou impayée"}, {
"status": "error",
"code": 404,
"message": "Commande introuvable ou impayée",
},
status=404, status=404,
) )
...@@ -701,8 +740,8 @@ class DeliveryView(PermissionRequiredMixin, ListView): ...@@ -701,8 +740,8 @@ class DeliveryView(PermissionRequiredMixin, ListView):
{ {
"status": "success", "status": "success",
"code": 200, "code": 200,
"message": f"{quantity} {orderitem.item} remis à {orderitem.order.user.profile} " + "message": f"{quantity} {orderitem.item} remis à {orderitem.order.user.profile} "
f"({orderitem.quantity_delivered}/{orderitem.quantity} remis au total)", + f"({orderitem.quantity_delivered}/{orderitem.quantity} remis au total)",
"quantity_delivered": orderitem.quantity_delivered, "quantity_delivered": orderitem.quantity_delivered,
} }
) )
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment