[chronojump-server] Added a class to retreive and update the tasks
- From: Marcos Venteo Garcia <mventeo src gnome org>
- To: commits-list gnome org
- Cc:
- Subject: [chronojump-server] Added a class to retreive and update the tasks
- Date: Sun, 25 Nov 2018 18:30:46 +0000 (UTC)
commit 2cb57f090dd3e54e7dcfcaca19d820c4dd63ea15
Author: Marcos Venteo García <mventeo gmail com>
Date: Sun Nov 25 19:30:10 2018 +0100
Added a class to retreive and update the tasks
.../chronojump_networks/organizations/api/urls.py | 5 +
.../chronojump_networks/organizations/api/views.py | 52 +++++++++-
.../chronojump_networks/tasks/api/serializers.py | 2 +-
.../chronojump_networks/tasks/api/urls.py | 6 +-
.../chronojump_networks/tasks/api/views.py | 33 ++++++-
.../organizations/groups/group_players_list.html | 106 +++++++++++++++++++--
6 files changed, 189 insertions(+), 15 deletions(-)
---
diff --git a/chronojumpserver-django/chronojump_networks/organizations/api/urls.py
b/chronojumpserver-django/chronojump_networks/organizations/api/urls.py
index 7a20495..48ff2aa 100644
--- a/chronojumpserver-django/chronojump_networks/organizations/api/urls.py
+++ b/chronojumpserver-django/chronojump_networks/organizations/api/urls.py
@@ -47,4 +47,9 @@ urlpatterns = [
view=views.GymStationsListView.as_view(),
name='gym_stations'
),
+ url(
+ regex=r'^register_rfid/$',
+ view=views.register_rfid,
+ name='register_rfid'
+ )
]
diff --git a/chronojumpserver-django/chronojump_networks/organizations/api/views.py
b/chronojumpserver-django/chronojump_networks/organizations/api/views.py
index 90b26b9..acedd9c 100644
--- a/chronojumpserver-django/chronojump_networks/organizations/api/views.py
+++ b/chronojumpserver-django/chronojump_networks/organizations/api/views.py
@@ -1,3 +1,4 @@
+import os
from ..models import Player, GroupPlayer, Group, Station, Gym, Exercise
from ..decorators import check_user_organization
from .serializers import PlayerSerializer, StationSerializer, ExerciseSerializer, GymStationsSerializer
@@ -10,7 +11,7 @@ from rest_framework.mixins import ListModelMixin, CreateModelMixin, DestroyModel
from rest_framework.permissions import IsAuthenticated
from .permissions import IsCoachOfTheGroup
-
+from time import sleep
class GroupPlayerListGenericAPIView(ListAPIView):
permission_classes = (IsAuthenticated, IsCoachOfTheGroup)
@@ -111,3 +112,52 @@ class PlayerListView(ListCreateAPIView):
def get_queryset(self):
organization_id = int(self.kwargs['organization_id'])
return Player.objects.filter(organization_id=organization_id)
+
+
+def register_rfid(request):
+ """Call an external program to read rfid and return the value read."""
+ status_code = 200
+ msg = ""
+ # From original crhonojump-flask source read RFID
+ rfidFile = '/tmp/chronojump_rfid.txt'
+ # Check if we are in development, to read directly the value pass manually
+ # instead of the mono executable
+ if not 'MONO_PATH' in os.environ:
+ no_mono = 1
+ else:
+ no_mono = 0
+
+ #print "DEBUG: NO_MONO = %d" % int(no_mono)
+ if no_mono == 1:
+ sleep(4)
+ else:
+ if os.access(rfidFile, os.W_OK):
+ os.remove(rfidFile)
+ # Call Mono program to read from RFID Reader
+ mono_path = os.path.join(os.environ['MONO_PATH'], 'RFID.exe')
+ rfidReadedStatus = subprocess.call(
+ "mono %s" % mono_path, shell=True)
+ # Debug: Print output status
+ #print rfidReadedStatus
+
+ # Read the RFID read
+ try:
+ with open(rfidFile) as f:
+ rfid = f.read()
+ except Exception, e:
+ print "ERROR: %s" % str(e)
+ rfid = ""
+
+ if rfid:
+ """Check if the RFID exists."""
+ p = RFIDHistory.query.filter(RFIDHistory.rfid == rfid).first()
+ if p:
+ # Aquest RFID ja ha estat registrada amb anterioritat.
+ status_code = 404
+ msg = "El RFID %s ja ha estat registrat amb anterioritat." % rfid
+ else:
+ status_code = 404
+ msg = "ERROR: No s'ha pogut llegir cap RFID en el temps assignat."
+ response = JsonResponse({"rfid":rfid, "msg":msg})
+ response.status_code = status_code
+ return response
diff --git a/chronojumpserver-django/chronojump_networks/tasks/api/serializers.py
b/chronojumpserver-django/chronojump_networks/tasks/api/serializers.py
index db161db..736630c 100644
--- a/chronojumpserver-django/chronojump_networks/tasks/api/serializers.py
+++ b/chronojumpserver-django/chronojump_networks/tasks/api/serializers.py
@@ -18,6 +18,6 @@ class TaskSerializer(serializers.ModelSerializer):
model = Task
fields = [ 'id', 'ts', 'person', 'coach',
'gym', 'station', 'exercise',
- 'sets', 'nreps', 'load', 'speed',
+ 'sets', 'nreps', 'load', 'speed', 'laterality',
'percentMaxSpeed', 'lossBySpeed', 'lossByPower',
'comment']
diff --git a/chronojumpserver-django/chronojump_networks/tasks/api/urls.py
b/chronojumpserver-django/chronojump_networks/tasks/api/urls.py
index 1164cbc..c3d4104 100644
--- a/chronojumpserver-django/chronojump_networks/tasks/api/urls.py
+++ b/chronojumpserver-django/chronojump_networks/tasks/api/urls.py
@@ -8,12 +8,12 @@ from . import views
urlpatterns = [
url(
regex=r'^$',
- view=views.ListCreateAPIView.as_view(),
+ view=views.TaskListView.as_view(),
name='tasks'
),
url(
- regex=r'^(?P<taskId>\d+)$',
+ regex=r'^(?P<task_id>\d+)/$',
view=views.TaskRetrieveUpdateDestroyAPIView.as_view(),
- name='tasks'
+ name='task_detail'
),
]
diff --git a/chronojumpserver-django/chronojump_networks/tasks/api/views.py
b/chronojumpserver-django/chronojump_networks/tasks/api/views.py
index ce980d0..700ca2f 100644
--- a/chronojumpserver-django/chronojump_networks/tasks/api/views.py
+++ b/chronojumpserver-django/chronojump_networks/tasks/api/views.py
@@ -9,7 +9,10 @@ from rest_framework.mixins import ListModelMixin, CreateModelMixin, DestroyModel
from rest_framework.permissions import IsAuthenticated
-class ListCreateAPIView(ListCreateAPIView):
+class TaskListView(ListCreateAPIView):
+ """
+ Get All Tasks or create a new One
+ """
permission_classes = (IsAuthenticated, )
serializer_class = TaskSerializer
@@ -41,6 +44,9 @@ class ListCreateAPIView(ListCreateAPIView):
return Response(s.data)
class TaskRetrieveUpdateDestroyAPIView(RetrieveUpdateDestroyAPIView):
+ """
+ Get a task, update or delete it
+ """
permission_classes = (IsAuthenticated, )
serializer_class = TaskSerializer
lookup_field = 'taskId'
@@ -49,6 +55,29 @@ class TaskRetrieveUpdateDestroyAPIView(RetrieveUpdateDestroyAPIView):
def retrieve(self, request, *args, **kwars):
#print(self.kwargs['task_id'])
print("arriba a aqui")
- o = get_object_or_404(Task, id=self.kwargs['taskId'])
+ o = get_object_or_404(Task, id=self.kwargs['task_id'])
s = TaskSerializer(o)
return Response(s.data)
+
+ def update(self, request, *args, **kwars):
+ print("HI THERE!")
+ data = dict(request.data)
+ o = get_object_or_404(Task, id=self.kwargs['task_id'])
+ o.person_id = int(data['personId'][0])
+ o.coach_id = int(data['coachId'][0])
+ o.gym_id = int(data['gymId'][0])
+ o.station_id = int(data['stationId'][0])
+ o.exercise_id = int(data['exerciseId'][0])
+ o.type = data['type'][0]
+ o.load = float(data['load'][0])
+ o.speed = float(data['speed'][0])
+ o.percentMaxSpeed = data['percentMaxSpeed'][0]
+ o.laterality = data['laterality'][0]
+ o.sets = int(data['sets'][0])
+ o.nreps = int(data['nreps'][0])
+ o.lossBySpeed = int(data['lossBySpeed'][0])
+ o.lossByPower = int(data['lossByPower'][0])
+ o.comment = data['comment'][0]
+ o.save()
+
+ return JsonResponse({}, status=200, safe=False)
diff --git
a/chronojumpserver-django/chronojump_networks/templates/organizations/groups/group_players_list.html
b/chronojumpserver-django/chronojump_networks/templates/organizations/groups/group_players_list.html
index 569af0a..fa633a0 100644
--- a/chronojumpserver-django/chronojump_networks/templates/organizations/groups/group_players_list.html
+++ b/chronojumpserver-django/chronojump_networks/templates/organizations/groups/group_players_list.html
@@ -307,11 +307,29 @@
tr.addClass('shown');
}
- //WATCH OUT, CODI MAX
-
- $('.task-modify-link').on('click', function() {
- console.log("Clicant modificar botó");
+
+ $('.task-modify-link').on('click', function() {
+ var task_id = $(this).attr('data-task-id');
+ var task_type = $(this).attr('data-task-type');
+ console.log(task_id);
+ console.log(task_type);
+ // Get The task trough Ajax and fill the modal form before show it
+
+ // Marcos: Trick to use a javascript variable in DRY url handled by Django
+ var task_url = "{% url 'api_tasks:task_detail' task_id=0 %}".replace("0", task_id)
+ console.log(task_url);
+
+ $.ajax({
+ url: task_url,
+ success: function(task) {
+ deserializeTask(task);
+ $('#btnAddModifyTask').text("{% trans 'Update task' %}");
$('#taskModalForm').modal('show');
+
+ }
+ })
+
+
});
$('.task-duplicate-link').on('click', function() {
@@ -321,12 +339,12 @@
$('.task-delete-link').on('click', function() {
console.log("Clicant esborrar botó");
});
-
- //FI CODI MAX
-
+
} );
+
+
function enablePlayersTableFunctionality() {
// Enanble checkboxes
$('.removePlayerBtn').removeClass('disabled').addClass('disabled');
@@ -343,6 +361,7 @@
var player = table_players.row($(this).parents('tr')).data();
// newTaskOperation
newTaskInitialOperations(player.id);
+ $('#btnAddModifyTask').text("{% trans 'Add task' %}");
$('#taskModalForm').modal('show');
});
@@ -556,7 +575,16 @@
console.log("botó addmodifytask 0");
e.preventDefault();
var task = serializeTask();
- putTask(task);
+ console.log(task.id);
+ if (task.id ) {
+ // Update Task
+ updateTask(task);
+ } else {
+ // Add task
+ putTask(task);
+ }
+
+
})
/* If value is empty set -1 as value */
@@ -572,6 +600,7 @@
/* Get all the values in the form into json object */
function serializeTask() {
+ let task_id = $('#taskId').val();
let gym_id = $('#gymSelect').val();
let station_id = $('#stationSelect').val();
let exercise_id = $('#exerciseSelect').val();
@@ -587,6 +616,7 @@
let lossByPower = safe_task_value('#taskLossByPower');
let coach_id = {{ user.id }};
var task = {
+ 'id': task_id,
'type' : 'S',
'personId': person_id,
'gymId': gym_id,
@@ -607,6 +637,50 @@
return task;
}
+ // Dump values from task into Modal Form
+ function deserializeTask(task) {
+ console.log(task);
+
+ $('#gymSelect').val(task.gym);
+ loadGymStations(task.gym);
+ $('#stationSelect').val(task.station);
+ loadStationExercises(task.station);
+ $('#exerciseSelect').val(task.exercise);
+ $('#personId').val(task.person);
+ $('#numSets').val(task.sets);
+ $('#numReps').val(task.nreps);
+ $('#taskLoad').val(task.load);
+ $('#taskSpeed').val(task.speed);
+ $('#taskPercentMaxSpeed').val(task.percentMaxSpeed);
+ $('#taskLaterality').val(task.laterality);
+ $('#taskCoachComment').val(task.comment);
+ $('#lossBySpeed').val(task.lossBySpeed);
+ $('#lossByPower').val(task.lossByPower);
+ $('#taskId').val(task.id);
+ $('#coachId').val(task.coach);
+
+ }
+
+ function clearModalForm() {
+
+ $('#gymSelect').val();
+ $('#stationSelect').val();
+ $('#exerciseSelect').val();
+ $('#personId').val();
+ $('#numSets').val();
+ $('#numReps').val();
+ $('#taskLoad').val();
+ $('#taskSpeed').val();
+ $('#taskPercentMaxSpeed').val();
+ $('#taskLaterality').val();
+ $('#taskCoachComment').val();
+ $('#lossBySpeed').val();
+ $('#lossByPower').val();
+ $('#taskId').val("-1"); // To set as new task
+ $('#coachId').val();
+
+ }
+
function validateTask(task) {
return task;
}
@@ -627,6 +701,22 @@
})
}
+ function updateTask(task) {
+ /* TODO: Add validation */
+ console.log("botó addmodifytask 0");
+ $.ajax({
+ 'url': "{% url 'api_tasks:task_detail' task_id=0 %}".replace("0", task.id),
+ 'method': 'PUT',
+ 'data': task,
+ success: function(data) {
+ alert("The task has been updated");
+ table_players.ajax.reload(enablePlayersTableFunctionality, false);
+ $('#taskModalForm').modal('hide');
+ }
+
+ })
+ }
+
// Enable tooltips
$(function () {
$('[data-toggle="tooltip"]').tooltip();
[
Date Prev][
Date Next] [
Thread Prev][
Thread Next]
[
Thread Index]
[
Date Index]
[
Author Index]