Skip to content

Commit

Permalink
refactor move_on_edge function
Browse files Browse the repository at this point in the history
  • Loading branch information
AmooHashem committed May 13, 2024
1 parent 7cfdf9c commit a45a6da
Show file tree
Hide file tree
Showing 6 changed files with 78 additions and 31 deletions.
9 changes: 8 additions & 1 deletion apps/fsm/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from django.http import HttpResponseRedirect, HttpResponse
from import_export.admin import ExportActionMixin

from apps.fsm.models import Choice, DetailBoxWidget, Edge, Paper, ProgramContactInfo, RegistrationForm, Problem, AnswerSheet, RegistrationReceipt, Team, \
from apps.fsm.models import Choice, DetailBoxWidget, Edge, Paper, PlayerTransition, ProgramContactInfo, RegistrationForm, Problem, AnswerSheet, RegistrationReceipt, Team, \
Invitation, CertificateTemplate, Font, FSM, State, WidgetHint, Hint, Widget, Video, Audio, Image, Player, Iframe, SmallAnswerProblem, \
SmallAnswer, BigAnswerProblem, BigAnswer, MultiChoiceProblem, MultiChoiceAnswer, Answer, TextWidget, Event, \
UploadFileAnswer, UploadFileProblem, PlayerStateHistory, Article, Tag, Aparat
Expand Down Expand Up @@ -56,6 +56,13 @@ def delta_time(self, obj):
return "-"


@admin.register(PlayerTransition)
class PlayerTransitionAdmin(admin.ModelAdmin):
model = PlayerTransition
list_display = ['source_state', 'target_state', 'time', 'transited_edge']
list_filter = []


class TextWidgetAdmin(admin.ModelAdmin):
model = TextWidget
list_display = ['paper', 'text']
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Generated by Django 4.1.3 on 2024-05-13 16:33

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('fsm', '0122_rename_playertransitionhistory_playertransition_and_more'),
]

operations = [
migrations.RemoveField(
model_name='playertransition',
name='is_edge_transited_in_reverse',
),
migrations.AlterField(
model_name='playerstatehistory',
name='arrival_time',
field=models.DateTimeField(auto_now_add=True),
),
migrations.AlterField(
model_name='playertransition',
name='time',
field=models.DateTimeField(auto_now_add=True),
),
migrations.AlterField(
model_name='tag',
name='created_at',
field=models.DateTimeField(auto_now_add=True),
),
]
4 changes: 3 additions & 1 deletion apps/fsm/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -410,7 +410,9 @@ class PlayerTransition(models.Model):
time = models.DateTimeField(auto_now_add=True)
transited_edge = models.ForeignKey(Edge, related_name='player_transition_histories', null=True, blank=True,
on_delete=models.SET_NULL)
is_edge_transited_in_reverse = models.BooleanField(null=True, blank=True)

def is_edge_transited_in_reverse(self):
return True # todo: fix


class PlayerStateHistory(models.Model):
Expand Down
37 changes: 26 additions & 11 deletions apps/fsm/utils.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from django.utils import timezone
from errors.error_codes import serialize_error
from rest_framework.exceptions import ParseError
import logging
Expand All @@ -7,7 +8,7 @@
from django.core.files.uploadedfile import InMemoryUploadedFile
from django.db.models import Q

from apps.fsm.models import FSM, Edge, Player, PlayerStateHistory, RegistrationReceipt
from apps.fsm.models import FSM, Edge, Player, PlayerStateHistory, PlayerTransition, RegistrationReceipt, State


def go_next_step(player):
Expand Down Expand Up @@ -63,21 +64,35 @@ def get_player(user, fsm, receipt) -> Player:
return user.players.filter(fsm=fsm, receipt=receipt, is_active=True).first()


def move_on_edge(player: Player, edge: Edge, departure_time, is_forward) -> Player:
player.current_state = edge.head if is_forward else edge.tail
player.last_visit = departure_time
def transit_player_in_fsm(player: Player, source_state: State, target_state: State, edge: Edge) -> Player:
player.current_state = target_state
transition_time = timezone.now()

player.last_visit = transition_time
player.save()

player_transition = PlayerTransition.objects.create(
source_state=source_state,
target_state=target_state,
time=transition_time,
transited_edge=edge
)

try:
last_state_history = PlayerStateHistory.objects.filter(
player=player, state=edge.tail if is_forward else edge.head, departure_time=None).last()
last_state_history.departure_time = departure_time
player=player, state=source_state, departure_time=None).last()
last_state_history.departure_time = transition_time
last_state_history.departure = player_transition
last_state_history.save()
except:
last_state_history = None
PlayerStateHistory.objects.create(player=player,
state=edge.head if is_forward else edge.tail,
transited_edge=edge, arrival_time=departure_time,
is_edge_transited_in_reverse=not is_forward)
pass

PlayerStateHistory.objects.create(
player=player,
state=target_state,
arrival=player_transition,
)

return player


Expand Down
13 changes: 4 additions & 9 deletions apps/fsm/views/edge_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
from apps.fsm.permissions import IsEdgeModifier
from apps.fsm.serializers.fsm_serializers import EdgeSerializer, KeySerializer, TeamGetSerializer
from apps.fsm.serializers.player_serializer import PlayerSerializer
from apps.fsm.utils import get_receipt, get_player, move_on_edge, get_a_player_from_team
from apps.fsm.utils import get_receipt, get_player, transit_player_in_fsm, get_a_player_from_team

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -72,12 +72,10 @@ def go_forward(self, request, pk):

# todo - handle scoring things

departure_time = timezone.now()
for member in team.members.all():
player = member.get_player_of(fsm=fsm)
if player:
player = move_on_edge(
player, edge, departure_time, is_forward=True)
player = transit_player_in_fsm(player, edge.tail, edge.head, edge)
if player.id == player.id:
player = player

Expand All @@ -92,9 +90,7 @@ def go_forward(self, request, pk):
raise ParseError(serialize_error('4083'))
elif fsm.fsm_p_type in [FSM.FSMPType.Individual, FSM.FSMPType.Hybrid]:
if player.current_state == edge.tail:
departure_time = timezone.now()
player = move_on_edge(
player, edge, departure_time, is_forward=True)
player = transit_player_in_fsm(player, edge.tail, edge.head, edge)
return Response(PlayerSerializer(context=self.get_serializer_context()).to_representation(player),
status=status.HTTP_200_OK)
elif player.current_state == edge.head:
Expand All @@ -120,7 +116,6 @@ def mentor_move_forward(self, request, pk):
for member in team.members.all():
player = member.get_player_of(fsm=fsm)
if player:
player = move_on_edge(
player, edge, departure_time=timezone.now(), is_forward=True)
player = transit_player_in_fsm(player, edge.tail, edge.head, edge)

return Response({'message': 'ok'}, status=status.HTTP_200_OK)
14 changes: 5 additions & 9 deletions apps/fsm/views/player_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
from apps.fsm.models import FSM
from apps.fsm.serializers.fsm_serializers import KeySerializer, TeamGetSerializer
from apps.fsm.serializers.player_serializer import PlayerSerializer
from apps.fsm.utils import move_on_edge, get_player_latest_taken_edge
from apps.fsm.utils import transit_player_in_fsm, get_player_latest_taken_edge


class PlayerViewSet(viewsets.GenericViewSet, RetrieveModelMixin):
Expand Down Expand Up @@ -58,12 +58,10 @@ def go_backward(self, request, pk):
raise ParseError(serialize_error('4089'))

if player.current_state == edge.head:
departure_time = timezone.now()
for member in team.members.all():
player = member.get_player_of(fsm=fsm)
if player:
player = move_on_edge(
player, edge, departure_time, is_forward=False)
player = transit_player_in_fsm(player, edge.head, edge.tail, edge)
if player.id == player.id:
player = player
return Response(PlayerSerializer(context=self.get_serializer_context()).to_representation(player),
Expand All @@ -76,9 +74,7 @@ def go_backward(self, request, pk):

elif fsm.fsm_p_type in [FSM.FSMPType.Individual, FSM.FSMPType.Hybrid]:
if player.current_state == edge.head:
departure_time = timezone.now()
player = move_on_edge(
player, edge, departure_time, is_forward=False)
player = transit_player_in_fsm(player, edge.head, edge.tail, edge)
return Response(PlayerSerializer(context=self.get_serializer_context()).to_representation(player),
status=status.HTTP_200_OK)
elif player.current_state == edge.tail:
Expand Down Expand Up @@ -108,8 +104,8 @@ def mentor_move_backward(self, request, pk):
for member in team.members.all():
player = member.get_player_of(fsm=fsm)
if player:
player = move_on_edge(
player, edge, departure_time, is_forward=False)
player = transit_player_in_fsm(
player, edge.head, edge.tail, edge, departure_time)
if player.id == player.id:
player = player
return Response(PlayerSerializer(context=self.get_serializer_context()).to_representation(player),
Expand Down

0 comments on commit a45a6da

Please sign in to comment.