Skip to content

Commit

Permalink
Improve code quality
Browse files Browse the repository at this point in the history
  • Loading branch information
KwikKill committed Nov 15, 2024
1 parent 39cb554 commit 0a48215
Show file tree
Hide file tree
Showing 38 changed files with 179 additions and 180 deletions.
2 changes: 1 addition & 1 deletion insalan/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ def get_app_list(self, request, app_label=None):
continue
app = app_dict[app_name]
# Sort the models
app['models'].sort(key=lambda x: object_list.index(x['object_name']))
app['models'].sort(key=lambda x, object_list=object_list: object_list.index(x['object_name']))
app_list.append(app)

return app_list
Expand Down
5 changes: 3 additions & 2 deletions insalan/mailer.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
import logging
import sys
from django.contrib.auth.models import Permission
from django.core.mail import EmailMessage, get_connection, send_mail
from django.core.mail import EmailMessage, get_connection
from django.contrib.auth.tokens import (
PasswordResetTokenGenerator,
default_token_generator,
)
from django.utils.translation import gettext_lazy as _

from apscheduler.schedulers.background import BackgroundScheduler

import insalan.settings
from insalan.user.models import User
from insalan.tickets.models import TicketManager
from apscheduler.schedulers.background import BackgroundScheduler

class EmailConfirmationTokenGenerator(PasswordResetTokenGenerator):
"""
Expand Down
11 changes: 5 additions & 6 deletions insalan/payment/serializers.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import logging

from rest_framework import serializers
from .models import Transaction, TransactionStatus, Product
from insalan.user.models import User
import logging

from .models import Transaction, Product

logger = logging.getLogger(__name__)

Expand All @@ -12,7 +14,7 @@ class Meta:
model=Transaction
fields = "__all__"
read_only_fields = ["amount", "payer", "payment_status", "intent_id", "creation_date", "last_modification_date"]

def create(self, validated_data):
""" Create a transaction with products based on the request"""
logger.debug(f"in the serializer {validated_data}")
Expand All @@ -23,6 +25,3 @@ class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = "__all__"



11 changes: 4 additions & 7 deletions insalan/payment/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,8 @@

import requests

from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
from django.http import JsonResponse, HttpResponseRedirect
from django.shortcuts import render
from django.http import JsonResponse
from django.utils.translation import gettext_lazy as _
from django.views.decorators.csrf import csrf_exempt
from rest_framework import generics, permissions, status
from rest_framework.views import APIView
from rest_framework.response import Response
Expand Down Expand Up @@ -47,7 +44,7 @@ def get(self, request, *args, **kwargs):
Get all products
"""
return super().get(request, *args, **kwargs)


class ProductDetails(generics.RetrieveUpdateDestroyAPIView):
"""
Expand All @@ -68,7 +65,7 @@ def get(self, request, *args, **kwargs):
Get a product
"""
return super().get(request, *args, **kwargs)

@swagger_auto_schema(
request_body=serializers.ProductSerializer,
responses={
Expand Down Expand Up @@ -528,4 +525,4 @@ def create(self, request):
)
def post(self, request, *args, **kwargs):
"""Process a payment request"""
return super().post(request, *args, **kwargs)
return super().post(request, *args, **kwargs)
4 changes: 2 additions & 2 deletions insalan/tickets/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@

from insalan.tournament.models import Team, Player, Substitute, Manager, PaymentStatus
from insalan.user.models import User
from .models import Ticket, TicketManager
from insalan.mailer import MailManager
from insalan.settings import EMAIL_AUTH
from .models import Ticket, TicketManager

@swagger_auto_schema(
method='get',
Expand Down Expand Up @@ -441,7 +441,7 @@ def unpaid(request: HttpRequest) -> JsonResponse:
"""
# Get all the registrations that are not paid
players = Player.objects.filter(
team__validated=True,
team__validated=True,
team__tournament__event__ongoing=True
).exclude(payment_status=PaymentStatus.PAID)
substitutes = Substitute.objects.filter(
Expand Down
25 changes: 12 additions & 13 deletions insalan/tournament/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
create_group_matchs,
create_swiss_matchs,
)
from insalan.admin import ADMIN_ORDERING

from .models import (
BestofType,
Expand Down Expand Up @@ -66,8 +67,6 @@

sensitive_post_parameters_m = method_decorator(sensitive_post_parameters())

from insalan.admin import ADMIN_ORDERING

ADMIN_ORDERING += [
('tournament', [
'Event',
Expand Down Expand Up @@ -97,9 +96,9 @@ class SeatCanvasWidget(forms.Widget):
Custom widget for the seat canvas
"""
def render(self, name, value, attrs=None, renderer=None):
id = attrs["id"] if attrs else "id_" + name
element_id = attrs["id"] if attrs else "id_" + name
return (
f'<input id="{id}" type="hidden" name="{name}" value="" />'
f'<input id="{element_id}" type="hidden" name="{name}" value="" />'
'<canvas id="seat_canvas" width="900" height="900" />'
)

Expand Down Expand Up @@ -163,7 +162,7 @@ class EventAdmin(admin.ModelAdmin):

list_display = ("id", "name", "description", "year", "month", "ongoing")
search_fields = ["name", "year", "month", "ongoing"]

class Media:
css = {
'all': ('css/seat_canvas.css',)
Expand Down Expand Up @@ -594,9 +593,9 @@ def get_urls(self):
change_password_form = AdminPasswordChangeForm

@sensitive_post_parameters_m
def team_change_password(self, request, id, form_url=""):
def team_change_password(self, request, team_id, form_url=""):
"""Change the password of a team"""
team = Team.objects.get(pk=id)
team = Team.objects.get(pk=team_id)
if not self.has_change_permission(request, team):
raise PermissionDenied
if team is None:
Expand Down Expand Up @@ -903,9 +902,9 @@ def create_group_matchs_action(self,request,queryset):
for group in queryset:
matchs_status = GroupMatch.objects.filter(group=group).values_list("status", flat=True)
if MatchStatus.ONGOING in matchs_status or MatchStatus.COMPLETED in matchs_status:
self.message_user(request,_("Impossible de créer les matchs, des matchs existent déjà et sont en cours ou terminés."),messages.ERROR)
return
self.message_user(request,_("Impossible de créer les matchs, des matchs existent déjà et sont en cours ou terminés."),messages.ERROR)
return

create_group_matchs(group)
self.message_user(request,_("Matchs créés avec succes"))

Expand Down Expand Up @@ -1024,6 +1023,7 @@ def create_empty_knockout_matchs_action(self,request,queryset):
@admin.action(description=_("Remplir les matchs"))
def fill_knockout_matchs_action(self,request,queryset):
for bracket in queryset:
# TODO: Fix this
# fill_knockout_matchs(bracket)
pass

Expand Down Expand Up @@ -1087,7 +1087,7 @@ class SwissRoundAdmin(admin.ModelAdmin):
search_fields = ["tournament"]
inlines = [SwissSeedingInline]
actions = ["create_swiss_matchs_action"]

list_filter = ["tournament","tournament__game","tournament__event"]

@admin.action(description=_("Créer les matchs du système suisse"))
Expand Down Expand Up @@ -1179,7 +1179,7 @@ def clean(self):
raise ValidationError(
_("Les places doivent être dans le même événement")
)

# Ensure that all seats are not part of another slot
if seats:
other_slots = SeatSlot.objects.exclude(id=self.instance.id)
Expand All @@ -1202,4 +1202,3 @@ def get_seats(self, obj):
return ", ".join([f"({seat.x}, {seat.y})" for seat in obj.seats.all()])

admin.site.register(SeatSlot, SeatSlotAdmin)

7 changes: 4 additions & 3 deletions insalan/tournament/models/bracket.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import math
from typing import List

from django.db import models
from django.utils.translation import gettext_lazy as _
from django.core.validators import MinValueValidator
import math

from typing import List

from . import match, team

Expand Down Expand Up @@ -100,4 +101,4 @@ class Meta:
verbose_name_plural = _("Matchs d'arbre")

def get_tournament(self):
return self.bracket.tournament
return self.bracket.tournament
2 changes: 1 addition & 1 deletion insalan/tournament/models/caster.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,4 @@ class Caster(models.Model):
verbose_name=_("Lien twitch ou autre"),
blank=True,
null=True,
)
)
2 changes: 1 addition & 1 deletion insalan/tournament/models/event.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,4 +78,4 @@ def get_tournaments(self) -> List["Tournament"]:
@staticmethod
def get_ongoing_ids() -> List[int]:
"""Return the identifiers of ongoing events"""
return __class__.objects.filter(ongoing=True).values_list("id", flat=True)
return __class__.objects.filter(ongoing=True).values_list("id", flat=True)
4 changes: 2 additions & 2 deletions insalan/tournament/models/game.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ def get_substitute_players_per_team(self) -> int:
def get_team_per_match(self) -> int:
"""Return the maximum number of teams in a match"""
return self.team_per_match

def get_name_validator(self):
"""Return the validators of the game"""
return get_validator(self.validators)
return get_validator(self.validators)
8 changes: 4 additions & 4 deletions insalan/tournament/models/group.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,15 +57,15 @@ def get_teams_id(self) -> List[int]:

def get_teams_seeding(self) -> List[Tuple["Team",int]]:
return [(seeding.team,seeding.seeding) for seeding in Seeding.objects.filter(group=self)]

def get_sorted_teams(self) -> List["Team"]:
teams = self.get_teams_seeding()
teams.sort(key=lambda e: e[1])
return [team[0] for team in teams]

def get_round_count(self) -> int:
return self.round_count

def get_leaderboard(self) -> Dict["Team",int]:
leaderboard = {}

Expand All @@ -78,7 +78,7 @@ def get_leaderboard(self) -> Dict["Team",int]:

def get_scores(self) -> Dict[int,int]:
leaderboard = self.get_leaderboard()

return {team.id : score for team, score in leaderboard.items()}

def get_matchs(self) -> List["GroupMatch"]:
Expand Down Expand Up @@ -120,4 +120,4 @@ def get_tournament(self):
# team = models.ForeignKey(
# "Team",
# on_delete=models.CASCADE
# )
# )
2 changes: 1 addition & 1 deletion insalan/tournament/models/mailer.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,4 +101,4 @@ def save(self, *args, **kwargs):
self.title,
self.content,
self.attachment,
)
)
2 changes: 1 addition & 1 deletion insalan/tournament/models/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,4 +77,4 @@ def clean(self):
if not validators.tournament_announced(self.team.get_tournament()):
raise ValidationError(
_("Tournoi non annoncé")
)
)
10 changes: 5 additions & 5 deletions insalan/tournament/models/match.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ class Meta:
models.Index(fields=["round_number"]),
models.Index(fields=["index_in_round"]),
]

def get_team_count(self) -> int:
return len(self.get_teams())

Expand All @@ -89,7 +89,7 @@ def get_winning_score(self) -> int:
"""Minimum score for a team to be considered a winner"""
if self.bo_type == BestofType.RANKING:
return math.ceil(self.get_team_count()/2)

return math.ceil(self.get_total_max_score()/2)

def is_user_in_match(self, user: User) -> bool:
Expand All @@ -98,7 +98,7 @@ def is_user_in_match(self, user: User) -> bool:
for player in team.get_players():
if player.as_user() == user:
return True

return False

def get_scores(self) -> Dict[int,int]:
Expand All @@ -120,7 +120,7 @@ def get_winners_loosers(self) -> List[List[int]]:

for team in self.get_teams_id():
if self.bo_type == BestofType.RANKING and scores[team] <= self.get_winning_score():
winners.append((team,scores[team]))
winners.append((team,scores[team]))
elif self.bo_type != BestofType.RANKING and scores[team] >= self.get_winning_score():
winners.append((team,scores[team]))
else:
Expand Down Expand Up @@ -163,4 +163,4 @@ def clean(self):
if self.score > self.match.get_max_score():
raise ValidationError({
"score" :_(f"Le score est trop grand, il doit être inférieur ou égale à {self.match.get_max_score()}")
})
})
4 changes: 3 additions & 1 deletion insalan/tournament/models/name_validator.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@
"""
from django.utils.translation import gettext_lazy as _
from django.db import models
from insalan.settings import RIOT_API_KEY

import requests

from insalan.settings import RIOT_API_KEY

class EmptyNameValidator:
"""
NameValidator class
Expand Down
2 changes: 1 addition & 1 deletion insalan/tournament/models/payement_status.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@ class PaymentStatus(models.TextChoices):

NOT_PAID = "NOTPAID", _("Pas payé")
PAID = "PAID", _("Payé")
PAY_LATER = "LATER", _("Payera sur place")
PAY_LATER = "LATER", _("Payera sur place")
2 changes: 1 addition & 1 deletion insalan/tournament/models/player.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,4 +114,4 @@ def delete(self,*args,**kwargs):
if self.team.captain == self:
self.team.captain = None
super().delete(*args,**kwargs)
self.team.refresh_validation()
self.team.refresh_validation()
1 change: 0 additions & 1 deletion insalan/tournament/models/seat_slot.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,3 @@ class Meta:

verbose_name = _("Slot")
verbose_name_plural = _("Slots")

Loading

0 comments on commit 0a48215

Please sign in to comment.