[chronojump-server] Added button in player_group page for multiple task creation and implemented taskMaxSpeed and taskPe



commit 1885c86b8837446cd228c2c022dbd07bd63173be
Author: Max Ros i Morejon <mros33 gmail com>
Date:   Tue Jul 9 11:57:45 2019 +0200

    Added button in player_group page for multiple task creation and implemented taskMaxSpeed and 
taskPercentMaxSpeed functionallity

 .../chronojump_networks/organizations/models.py    |   3 +-
 .../chronojump_networks/results/api/urls.py        |   5 +
 .../chronojump_networks/results/api/views.py       |  19 +++
 .../chronojump_networks/static/js/chronojump.js    |  16 +++
 .../chronojump_networks/tasks/api/views.py         |  42 ++++---
 .../organizations/groups/group_players_list.html   | 139 +++++++++++++++++----
 .../organizations/groups/task_modal_form.html      |   2 +-
 7 files changed, 183 insertions(+), 43 deletions(-)
---
diff --git a/chronojumpserver-django/chronojump_networks/organizations/models.py 
b/chronojumpserver-django/chronojump_networks/organizations/models.py
index fe3ef4d..ee52c51 100644
--- a/chronojumpserver-django/chronojump_networks/organizations/models.py
+++ b/chronojumpserver-django/chronojump_networks/organizations/models.py
@@ -13,7 +13,6 @@ from django.utils.translation import ugettext_lazy as _
 from chronojump_networks.core.models import ChronojumpBaseModel, ChronojumpBaseModelWithUUID
 
 
-
 class User(AbstractUser):
     # Language Code
     LANGUAGE_SPANISH = 'es'
@@ -274,7 +273,7 @@ class Player(ChronojumpBaseModel):
     height = models.FloatField(default=0)
     weight = models.FloatField(default=0)
     rfid = models.CharField(max_length=23, unique=True)
-    imageName = models.FileField(upload_to='players', null=True, blank=True, 
default='../static/images/player.png')
+    imageName = models.FileField(upload_to='players', null=True, blank=True, 
default='../static/images/default_player.png')
     is_available = models.BooleanField(default=True)
     number = models.IntegerField(null=True,blank=True)
 
diff --git a/chronojumpserver-django/chronojump_networks/results/api/urls.py 
b/chronojumpserver-django/chronojump_networks/results/api/urls.py
index c1bfd97..0a00ed6 100644
--- a/chronojumpserver-django/chronojump_networks/results/api/urls.py
+++ b/chronojumpserver-django/chronojump_networks/results/api/urls.py
@@ -37,5 +37,10 @@ urlpatterns = [
         regex=r'^sprint/delete$',
         view=views.ResultSprintDestroyAPIView.as_view(),
         name='sprints_delete'
+    ),
+    url(
+        regex=r'^get_maximum_velocity/$',
+        view=views.max_vel,
+        name='max_vel'
     )
 ]
diff --git a/chronojumpserver-django/chronojump_networks/results/api/views.py 
b/chronojumpserver-django/chronojump_networks/results/api/views.py
index 0e7a2bf..a1040bd 100644
--- a/chronojumpserver-django/chronojump_networks/results/api/views.py
+++ b/chronojumpserver-django/chronojump_networks/results/api/views.py
@@ -6,6 +6,7 @@ from django.shortcuts import get_object_or_404
 from rest_framework.response import Response
 from rest_framework.generics import ListAPIView, RetrieveAPIView, DestroyAPIView, 
RetrieveUpdateDestroyAPIView
 from rest_framework.permissions import IsAuthenticated
+from django.db.models import Max
 
 from chronojump_networks.organizations.models import User, Group, Player, GroupPlayer, Station, Exercise, 
Organization, Gym
 
@@ -197,3 +198,21 @@ class ResultSprintDestroyAPIView(DestroyAPIView):
             o.delete()
             print("Result %d removed" % (int(result_id), ))
         return JsonResponse({}, status=204, safe=False)
+    
+def max_vel(request):
+    stationId = request.GET['station_id']
+    personId = request.GET['personId']
+    exerciseId = request.GET['exerciseId']
+    resistance = request.GET['resistance']
+    laterality = request.GET['laterality']
+    res = ResultEncoder.objects.filter(station_id__exact = stationId, person_id__exact = personId, 
exercise_id__exact =         exerciseId, laterality__exact = laterality, resistance__exact = resistance)
+    maxx = res.aggregate(Max('vmeanBySpeed'))
+    print "maxx"
+    print maxx
+    maximum_mean_velocity = 0
+    if res:
+        maximum_mean_velocity = maxx
+    print maximum_mean_velocity
+    resp = JsonResponse(maximum_mean_velocity, safe=False)
+    print resp
+    return resp
diff --git a/chronojumpserver-django/chronojump_networks/static/js/chronojump.js 
b/chronojumpserver-django/chronojump_networks/static/js/chronojump.js
index 4e82731..5b89807 100644
--- a/chronojumpserver-django/chronojump_networks/static/js/chronojump.js
+++ b/chronojumpserver-django/chronojump_networks/static/js/chronojump.js
@@ -36,6 +36,22 @@ function enableCheckboxSelection(selectClass, buttonClass) {
   });
 }
 
+/* Enable Task Button Selection */
+function enableTaskCheckboxSelection(selectClass, buttonClass) {
+  var selector = '.' + selectClass;
+  var button = '.' + buttonClass;
+  $(selector).on('change', function() {
+    var totalChecked = $(selector+':checked').length;
+    if (totalChecked > 1) {
+      // Enable button
+      $(button).removeClass('disabled');
+    } else {
+      // Disable button
+      $(button).addClass('disabled');
+    }
+  });
+}
+
 
 
 console.log("Chronojump Networks ready");
diff --git a/chronojumpserver-django/chronojump_networks/tasks/api/views.py 
b/chronojumpserver-django/chronojump_networks/tasks/api/views.py
index c851e97..2ff66d6 100644
--- a/chronojumpserver-django/chronojump_networks/tasks/api/views.py
+++ b/chronojumpserver-django/chronojump_networks/tasks/api/views.py
@@ -23,25 +23,29 @@ class TaskListView(ListCreateAPIView):
         print("crea task")
         data = dict(request.data)
         # TODO: Sure there is a better way to do this
-        o = Task.objects.create(
-            person_id = int(data['personId'][0]),
-            coach_id = int(data['coachId'][0]),
-            gym_id = int(data['gymId'][0]),
-            station_id = int(data['stationId'][0]),
-            exercise_id = int(data['exerciseId'][0]),
-            type = data['type'][0],
-            load = float(data['load'][0]),
-            speed = float(data['speed'][0]),
-            percentMaxSpeed = data['percentMaxSpeed'][0],
-            laterality = data['laterality'][0],
-            sets = int(data['sets'][0]),
-            nreps = int(data['nreps'][0]),
-            lossBySpeed = int(data['lossBySpeed'][0]),
-            lossByPower = int(data['lossByPower'][0]),
-            comment = data['comment'][0]
-        )
-        s = TaskSerializer(o)
-        return Response(s.data)
+        tasks = []
+        players = data['personId[]']
+        for p in players:
+            o = Task.objects.create(
+                person_id = int(p),
+                coach_id = int(data['coachId'][0]),
+                gym_id = int(data['gymId'][0]),
+                station_id = int(data['stationId'][0]),
+                exercise_id = int(data['exerciseId'][0]),
+                type = data['type'][0],
+                load = float(data['load'][0]),
+                speed = float(data['speed'][0]),
+                percentMaxSpeed = data['percentMaxSpeed'][0],
+                laterality = data['laterality'][0],
+                sets = int(data['sets'][0]),
+                nreps = int(data['nreps'][0]),
+                lossBySpeed = int(data['lossBySpeed'][0]),
+                lossByPower = int(data['lossByPower'][0]),
+                comment = data['comment'][0]
+            )
+            s = TaskSerializer(o)
+            tasks.append(s.data)
+        return Response(tasks)
 
 class TaskRetrieveUpdateDestroyAPIView(RetrieveUpdateDestroyAPIView):
     """
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 214ec56..a92a861 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
@@ -205,8 +205,28 @@
             });
             removePlayersFromGroup(player_ids);
           }
+        }{% endif %},
+        { /* Assign task to group */
+            text: "{% trans 'Assign task to group' %}",
+            className: "btn btn-success disabled addTaskGroupBtn",
+            action: function( e, dt, node, config ) {
+                var player_ids = [];
+                $.each($('.selectPlayerCheckbox:checked'), function(index, value) {
+                var v = $(value);
+                        player_ids.push(v.attr('data-player-id'));
+                });
+                
+                // Set the title for new player task
+                var title = "{% trans 'Add new task to group'%}";
+                $('#taskModalTitle').text(title);
+
+                // newTaskOperation
+                newTaskInitialOperations(player_ids);
+                $('#btnAddModifyTask').text("{% trans 'Add task' %}");
+                
+                $('#taskModalForm').modal('show');
+            }
         }
-        {% endif %}
       ],
       initComplete: function() {
         // Enable the remove player selection the first time data is loaded
@@ -339,6 +359,9 @@
           success: function(task) {
             deserializeTask(task);
             $('#btnAddModifyTask').text("{% trans 'Update task' %}");
+            $('#taskPercentMaxSpeed').prop("disabled", true);
+            $('#taskPercentMaxSpeed').val('');
+            $('#taskMaxSpeed').val('');
             $('#taskModalForm').modal('show');
             
           }
@@ -371,14 +394,13 @@
 
     } );
     
-    
-
-    
     function enablePlayersTableFunctionality() {
       // Enanble checkboxes
       $('.removePlayerBtn').removeClass('disabled').addClass('disabled');
       enableCheckboxSelection('selectPlayerCheckbox', 'removePlayerBtn');
-
+      $('.addTaskGroupBtn').removeClass('disabled').addClass('disabled');
+      enableTaskCheckboxSelection('selectPlayerCheckbox', 'addTaskGroupBtn');
+      
       // Enabling add task buttons
       $('.addTaskBtn').on('click', function(){
         var player = table_players.row($(this).parents('tr')).data();
@@ -509,7 +531,7 @@
     /* Source for Tasks */
 
     /* initials operations for task */
-    function newTaskInitialOperations(player_id) {
+    function newTaskInitialOperations(player_ids) {
       // Load station from assigned gym to group
       console.log("nom grup -{{ group.name}}-");
       console.log("nom gym -{{ group.gym}}-");      
@@ -522,17 +544,21 @@
       $('#taskCoachComment').val('');
       $('#lossBySpeed').val('');
       $('#lossByPower').val('');
+      $('#taskPercentMaxSpeed').prop("disabled", true);
+      $('#taskPercentMaxSpeed').val('');
+      $('#taskMaxSpeed').val('');
       
       var group_id = {{ group.gym.id }};
       console.log('Look for gym with id ' + {{ group.gym.id }});
       $('#gymSelect').val(group_id);
       // Set the player Id
-      $('#personId').val(player_id);
+      $('#personId').val(player_ids);
       // Set taskId empty representing a new task
       $('#taskId').val('');
 
       loadGymStations(group_id);
     }
+    
 
     $('#gymSelect').on('change', function() {
        //Ajax call to retrieve all the stations. Call the function below.
@@ -579,7 +605,19 @@
        // Show the exercises of this station
        loadStationExercises(station_id);
     });
+    
+    $('#exerciseSelect').on('change', function() {
+        get_maximum_mean_velocity();
+    });
+    
+    $('#taskLoad').change(function() {
+        get_maximum_mean_velocity()
+    });
 
+    $('#taskLaterality').change(function() {
+        get_maximum_mean_velocity();
+    });
+        
     /* Load stations from the gym into selectStation control */
     function loadStationExercises(station_id) {
       $('#exerciseSelect').find('option').remove().end();
@@ -590,7 +628,6 @@
           'station_id': station_id
         },
         success: function(data) {
-          console.log(data);
           var count = 0;
                        $.each(data, function(i, item) {
                                count ++;
@@ -603,12 +640,71 @@
             $('#exerciseSelect').removeAttr('disabled');
             // Load exercises from first station loaded
             $('#exerciseSelect').val($('#exerciseSelect option:first').val());
+            console.log("exercise = " + $('#exerciseSelect').val());
+            get_maximum_mean_velocity();
           } else {
             // Disable task creation
+            console.log("task creation disabled");
           }
         }
       });
     }
+    
+    
+    /* Get max velocity when user selects station, exercice and resistance */
+    function get_maximum_mean_velocity() {
+        var resistance = $('#taskLoad').val();
+        var stationId = $('#stationSelect').val();
+        var personId = $('#personId').val();
+        var exerciseId = $('#exerciseSelect').val();
+        var laterality = $('#taskLaterality').val();
+        console.log("Check velocity max");
+        console.log("Resistance: " + resistance);
+        console.log("Station Id: " + stationId);
+        console.log("Exercise Id: " + exerciseId);
+        console.log("Person Id: " + personId);
+        console.log("Laterality:" + laterality);
+        if (resistance) {
+            $.ajax({
+                'url': "{% url 'api_results:max_vel'%}",
+                method: "GET",
+                data: {
+                    station_id: stationId,
+                    exerciseId: exerciseId,
+                    personId: personId,
+                    resistance: resistance,
+                    laterality: laterality
+                },
+                success: function(data) {
+                    // Ok, add options in exercise Select
+                    // First remove previous options
+                    console.log(data.vmeanBySpeed__max); 
+
+                    if (data.vmeanBySpeed__max > 0 ) {
+                        console.log("Enable taskPercentMaxSpeed");
+                        $('#taskMaxSpeed').val(data.vmeanBySpeed__max.toFixed(2));
+                        $('#taskPercentMaxSpeed').prop("disabled", false);
+                    } else {
+                        // No velocity max, means disable velocityMAx control
+                        console.log("Disable taskPercentMaxSpeed");
+                        $('#taskMaxSpeed').val('');
+                        $('#taskPercentMaxSpeed').prop('disabled', true);
+                    }
+                }
+            });
+        } else {
+                // Wait until user enters resistance
+        }
+    }
+    
+    $('#taskPercentMaxSpeed').change(function(){
+        // Calculate the max velocity
+        var maxVelocity = $('#taskMaxSpeed').val();
+        var percent = $(this).val();
+        var calculateVelocity = (percent * maxVelocity) / 100;
+        $('#taskSpeed').val(calculateVelocity.toFixed(2));
+    });
+
 
     $('#btnAddModifyTask').on('click', function(e) {
     console.log("botó addmodifytask 0");
@@ -624,7 +720,7 @@
       }
      
       
-    })
+    });
 
     /* If value is empty set -1 as value */
     function safe_task_value(selector) {
@@ -654,10 +750,12 @@
       let lossBySpeed = safe_task_value('#taskLossBySpeed');
       let lossByPower = safe_task_value('#taskLossByPower');
       let coach_id = {{ user.id }};
+      let persons = [];
+      persons = person_id.split(",");
       var task = {
         'id': task_id, 
         'type' : 'S',
-        'personId': person_id,
+        'personId[]': persons,
         'gymId': gym_id,
         'stationId': station_id,
         'exerciseId': exercise_id,
@@ -706,18 +804,17 @@
 
     function putTask(task) {
       /* TODO: Add validation */
-          console.log("botó addmodifytask 1");
-      $.ajax({
-        'url': "{% url 'api_tasks:tasks' %}",
-        'method': 'POST',
-        'data': task,
-        success: function(data) {
-          alert("The task has been added");
-          table_players.ajax.reload(enablePlayersTableFunctionality, false);
-          $('#taskModalForm').modal('hide');
-        }
+        $.ajax({
+            'url': "{% url 'api_tasks:tasks' %}",
+            'method': 'POST',
+            'data': task,
+            success: function(data) {
+                alert("The task has been added");
+                table_players.ajax.reload(enablePlayersTableFunctionality, false);
+                $('#taskModalForm').modal('hide');
+            }
 
-      })
+        });
     }
 
     function updateTask(task) {
diff --git a/chronojumpserver-django/chronojump_networks/templates/organizations/groups/task_modal_form.html 
b/chronojumpserver-django/chronojump_networks/templates/organizations/groups/task_modal_form.html
index 42a8681..758e654 100644
--- a/chronojumpserver-django/chronojump_networks/templates/organizations/groups/task_modal_form.html
+++ b/chronojumpserver-django/chronojump_networks/templates/organizations/groups/task_modal_form.html
@@ -65,7 +65,7 @@
             </div>
             <div class="form-group col-sm-4">
               <label for="taskSpeed">{% trans 'Speed (m/s)' %}</label>
-              <input id="taskSpeed" name="taskSpeed" type="number" class="form-control" min="-1" 
step="0.1"></input>
+              <input id="taskSpeed" name="taskSpeed" type="number" class="form-control" min="-1" 
step="0.01"></input>
             </div>
           </div>
           <div class="form-row">


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]