[chronojump-server] Adds buttons and functions to manage the exercices of a gym



commit 082296267c9599d1d2eeec25ef4955df7a936f01
Author: Max Ros i Morejon <mros33 gmail com>
Date:   Fri May 24 14:37:23 2019 +0200

    Adds buttons and functions to manage the exercices of a gym

 .../chronojump_networks/organizations/api/urls.py  |   1 -
 .../chronojump_networks/organizations/api/views.py |  33 ++-
 .../organizations/gyms/exercise_modal_form.html    | 116 +++-------
 .../templates/organizations/gyms/gym_detail.html   | 237 ++++++++++++++++++---
 4 files changed, 264 insertions(+), 123 deletions(-)
---
diff --git a/chronojumpserver-django/chronojump_networks/organizations/api/urls.py 
b/chronojumpserver-django/chronojump_networks/organizations/api/urls.py
index 48ff2aa..1a89c3b 100644
--- a/chronojumpserver-django/chronojump_networks/organizations/api/urls.py
+++ b/chronojumpserver-django/chronojump_networks/organizations/api/urls.py
@@ -26,7 +26,6 @@ urlpatterns = [
         view=views.PlayerListView.as_view(),
         name='players_list'
     ),
-    # Get Stations from Gym
     url(
         regex=r'^(?P<organization_id>\d+)/gym_stations/$',
         view=views.GymStationsListView.as_view(),
diff --git a/chronojumpserver-django/chronojump_networks/organizations/api/views.py 
b/chronojumpserver-django/chronojump_networks/organizations/api/views.py
index 4d61d6a..d977a0c 100644
--- a/chronojumpserver-django/chronojump_networks/organizations/api/views.py
+++ b/chronojumpserver-django/chronojump_networks/organizations/api/views.py
@@ -94,7 +94,7 @@ class StationsListView(ListAPIView):
         gym = get_object_or_404(Gym, pk=gym_id)
         return gym.stations.all()
 
-class StationExercisesListView(ListAPIView):
+class StationExercisesListView(ListCreateAPIView):
     """List exercises from station """
     permission_classes = (IsAuthenticated, )
     serializer_class = ExerciseSerializer
@@ -107,6 +107,37 @@ class StationExercisesListView(ListAPIView):
         queryset = station.exercises.all()
         serializer = ExerciseSerializer(queryset, many=True)
         return Response(serializer.data)
+    
+    def create(self, request, *args, **kwargs):
+        print("create exercise")
+        data = dict(request.data)
+        # TODO: Sure there is a better way to do this
+        o = Exercise.objects.create(
+            station_id = int(data['station_id'][0]),
+            percentBodyMassDisplaced = int(data['massp'][0]),
+            name = str(data['name'][0])
+        )
+        s = ExerciseSerializer(o)
+        return Response(s.data)
+    
+    def put(self, request, *args, **kwars):
+        print("update exercise")
+        data = dict(request.data)
+        o = Exercise.objects.get(id=int(data['id'][0]))
+        o.name = str(data['name'][0])
+        o.station_id = int(data['station_id'][0])
+        o.percentBodyMassDisplaced = float(data['massp'][0])
+        o.organization_id = int(self.kwargs['organization_id'])
+        o.save()
+        return JsonResponse({}, status=200, safe=False)
+    
+    def delete(self, request, *args, **kwargs):
+        print("delete exercise")        
+        data = dict(request.data)
+        o = Exercise.objects.get(id=int(data['id'][0]))
+        o.delete()
+        print("Removed exercise")
+        return JsonResponse({}, status=204, safe=False)
 
 
 class PlayerListView(ListCreateAPIView):
diff --git 
a/chronojumpserver-django/chronojump_networks/templates/organizations/gyms/exercise_modal_form.html 
b/chronojumpserver-django/chronojump_networks/templates/organizations/gyms/exercise_modal_form.html
index 8a2dbed..e1f661a 100644
--- a/chronojumpserver-django/chronojump_networks/templates/organizations/gyms/exercise_modal_form.html
+++ b/chronojumpserver-django/chronojump_networks/templates/organizations/gyms/exercise_modal_form.html
@@ -4,105 +4,43 @@
 <div id="exerciseModalForm" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="{% trans 'Add 
Exercise' %}" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-lg" role="document">
                <div class="modal-content">
-      <div class="modal-header">
-        <h5 class="modal-title" id="exerciseModalTitle"></h5>
-        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
-          <span aria-hidden="true">&times;</span>
-        </button>
-      </div>
-                       
+            <div class="modal-header">
+                <h5 class="modal-title" id="exerciseModalTitle">{% trans 'Create new exercise' %}</h5>
+                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
+                    <span aria-hidden="true">&times;</span>
+                </button>
+            </div>
                        
                        <div class="modal-body">
 
-                               <input type="hidden" id="personId" />
-                               <input type="hidden" id="taskId" />
-                               <input type="hidden" id="coachId" value="{{ user.id }}"/>
+                               <input type="hidden" id="exerciseId" />
 
-       <form>
-          <div class="form-row">
-                                               <div class="form-group col-sm-4">
-                                                       <label for="gym">{% trans 'Gym' %}</label>
-                                                       <select name="gym" class="form-control" 
id="gymSelect">
-                                                               {% for gym in user.organization.gyms.all %}
-                                                               <option value={{gym.id}}>{{gym.name}}</option>
-                                                               {% endfor %}
-                                                       </select>
-                                               </div>
-            <div class="form-group col-sm-4">
-                                                       <label for="station">{% trans 'Station' %}</label>
-                                                       <select name="station" class="form-control" 
id="stationSelect">
-              <!-- Load dynamically -->
-                                                       </select>
-                                               </div>
-            <div class="form-group col-sm-4">
-                                                       <label for="exercise">{% trans 'Exercise' %}</label>
-                                                       <select name="exercise" class="form-control" 
id="exerciseSelect">
-              <!-- Load dynamically -->
-                                                       </select>
-                                               </div>
-          </div>
-                                 <hr>
-          <div class="form-row">
-            <div class="form-group col-sm-4">
-              <label for="numSets">{% trans '# Sets' %}</label>
-              <input id="numSets" name="numSets" type="number" class="form-control taskParameter" value="1" 
min="1"></input>
-            </div>
-            <div class="form-group col-sm-4 ">
-              <label for="numReps">{% trans '# Repeats' %}</label>
-              <input id="numReps" name="numReps" type="number" class="form-control taskParameter" value="1" 
min="1"></input>
-            </div>
-            <div class="form-group col-sm-4">
-              <label for="taskLoad">{% trans 'Load (Kg)' %}</label>
-              <input id="taskLoad" name="taskLoad" type="number" class="form-control taskParameter"></input>
-            </div>
-          </div>
-          <div class="form-row">
-            <div class="form-group col-sm-4">
-              <label for="taskMaxSpeed">{% trans 'Max Vm registered (m/s)' %}</label>
-              <input id="taskMaxSpeed" name="taskMaxSpeed" type="number" class="form-control taskParameter" 
disabled readonly></input>
-            </div>
-            <div class="form-group col-sm-4 ">
-              <label for="taskPercentMax">{% trans 'Max Vm registered (%)' %}</label>
-              <input id="taskPercentMaxSpeed" name="taskPercentMaxSpeed" type="number" class="form-control" 
disabled max="100" min="0"></input>
-            </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>
-            </div>
-          </div>
-          <div class="form-row">
-            <div class="form-group col-sm-4">
-              <label for="taskLossByPower">{% trans 'Loss by power' %}</label>
-              <input id="taskLossByPower" name="taskLossByPower" type="number" class="form-control"></input>
-            </div>
-            <div class="form-group col-sm-4">
-              <label for="taskLossBySpeed">{% trans 'Loss by speed' %}</label>
-              <input id="taskLossBySpeed" name="taskLossBySpeed" type="number" class="form-control"></input>
-            </div>
-            <div class="form-group col-sm-4">
-              <label for="taskLaterality">{% trans 'Laterality' %}</label>
-              <select class="form-control" id="taskLaterality" name="taskLaterality">
-                <option value="RL">{% trans 'RL - both extremities' %}</option>
-                <option value="R,L">{% trans 'R,L - First right, then left' %}</option>
-                <option value="R">{% trans 'R - Only right extremity' %}</option>
-                <option value="L">{% trans 'L - Only left extremity' %}</option>
-              </select>
-            </div>
-          </div>
-          <hr>
-          <div class="form-group">
-            <label for="taskCoachComment">{% trans 'Comments from coach' %}</label>
-            <textarea rows=2 class="form-control" id="taskCoachComment"></textarea>
-          </div>
-        </form>
+                <form>
+                    <div class="form-row">
+                            <div class="form-group col-sm-12">
+                                <label for="station">{% trans 'Station' %}</label>
+                                <select name="station" class="form-control" id="stationSelect">
+                                <!-- Load dynamically -->
+                                </select>
+                            </div>
+                            <div class="form-group col-sm-6">
+                                <label for="name">{% trans 'Exercise name' %}</label>
+                                <input id="name" name="name" type="text" class="form-control"></input>
+                            </div>
+                            <div class="form-group col-sm-6">
+                                <label for="massp">{% trans '% mass body displaced' %}</label>
+                                <input id="massp" name="massp" type="number" class="form-control" value="0" 
min="0" max="100"></input>
+                            </div>
+                    </div>
+                </form>
 
 
-                       </div> <!-- .modal-body -->
+            </div> <!-- .modal-body -->
                        
                        
                        <div class="modal-footer"> 
                                <button type="button" class="btn btn-outline-secondary" 
data-dismiss="modal">{% trans 'Cancel' %}</button>
-        <button id="btnAddExercise" type="button" class="btn btn-outline-primary" >{% trans 'Add exercise' 
%}</button>
+                <button id="btnAddExercise" type="button" class="btn btn-outline-primary" >{% trans 'Add 
exercise' %}</button>
                        </div>
                </div>
                <!-- /.modal-content -->
diff --git a/chronojumpserver-django/chronojump_networks/templates/organizations/gyms/gym_detail.html 
b/chronojumpserver-django/chronojump_networks/templates/organizations/gyms/gym_detail.html
index 6a27fde..b92763f 100644
--- a/chronojumpserver-django/chronojump_networks/templates/organizations/gyms/gym_detail.html
+++ b/chronojumpserver-django/chronojump_networks/templates/organizations/gyms/gym_detail.html
@@ -39,6 +39,8 @@
   </div>
 </div>
 
+<!-- Include Modal Exercise Form -->
+{% include 'organizations/gyms/exercise_modal_form.html' %}
 
 {% endblock %}
 
@@ -104,38 +106,42 @@
               html += '<th>{% trans "% Mass body displaced" %}</th>';
               html += '</thead><tbody>';
               $.each(value, function(index, exercise) {
-                html += '<tr><td>'+ exercise.name + '</td><td class="text-right">' + 
exercise.percentBodyMassDisplaced +'</tr>';
+                html += '<tr><td>'+ exercise.name + '</td><td class="text-right">' + 
exercise.percentBodyMassDisplaced +'</td><td>'; 
+                //EDIT BUTTON
+                html += '<a class="task-link exercise-modify-link" data-toogle="tooltip" 
data-placement="right" title="' + "{% trans 'Modify this exercise' %}" +'"';
+                html += 'data-exercise-id="' + exercise.id + '"';
+                html += 'data-exercise-massp="' + exercise.percentBodyMassDisplaced + '"';
+                html += 'data-exercise-station="' + row.id + '"';
+                html += 'data-exercise-name="' + exercise.name + '">';
+                html += '<i class="material-icons">mode_edit</i></a>';
+                html += '&nbsp;';
+                
+                /*html += '<button type="button" id="modifyExerciseBtn" class="modifyExerciseBtn btn 
btn-outline-info btn-sm" ';
+                html += 'data-exercise-id="' + row.id + '" ';
+                html += 'data-exercise-name="' + exercise.name + '" ';
+                html += 'data-toggle="tooltip" data-placement="right" ';
+                html += 'title="{% trans "Edit exercise" %}">';
+                html += '<i class="material-icons" 
style="margin-top:3px;font-size:16px;">edit</i></button>';*/
+                //REMOVE BUTTON
+                html += '<a class="task-link exercise-delete-link" data-toogle="tooltip" 
data-placement="right" title="' + "{% trans 'Delete this task' %}" +'"';
+                html += 'data-exercise-id="' + exercise.id + '">';
+                html += '<i class="material-icons">delete_sweep</i></a>';
+                
+                /*html += '<button type="button" id="deleteExerciseBtn" class="deleteExerciseBtn btn 
btn-outline-danger btn-sm" ';
+                html += 'data-exercise-id="' + row.id + '" ';
+                html += 'data-exercise-name="' + exercise.name + '" ';
+                html += 'data-toggle="tooltip" data-placement="right" ';
+                html += 'title="{% trans "Delete exercise" %}">';
+                html += '<i class="material-icons" 
style="margin-top:3px;font-size:16px;">delete</i></button>';*/
               });
-              html += '</tbody></table>';
+              html += '</td></tr></tbody></table>';
 
             } else {
               html = '<h6 class="font-weight-bold font-italic">{% trans "Station has not exercises" %}</h6>';
             }
             return html;
           }
-        },
-        /*{
-          type: 'html',
-          className: 'align-top',
-          render: function(value, type, row) {
-            var html = "";
-            // Single Task Button
-            html += '<button type="button" class="addTaskBtn btn btn-outline-success btn-sm" ';
-            html += 'data-player-id="' + row.id + '" ';
-            html += 'data-player-name="' + row.name + '" ';
-            html += 'data-toggle="tooltip" data-placement="right" ';
-            html += 'title="{% trans "Add new exercise" %}">';
-            html += '<i class="material-icons" style="margin-top:3px;font-size:16px;">add</i></button>';
-            // Multiple Tasks
-            html += '&nbsp;<button type="button" class="addMultipleTaskBtn btn btn-outline-danger btn-sm" ';
-            html += 'data-player-id="' + row.id + '" ';
-            html += 'data-player-name="' + row.name + '" ';
-            html += 'data-toggle="tooltip" data-placement="right" ';
-            html += 'title="{% trans "Disable station" %}">';
-            html += '<i class="material-icons" style="margin-top:3px;font-size:16px;">block</i></button>';
-            return html;
-          }
-        }*/
+        }
       ],
       "drawCallback" : function ( settings ) {
             var api = this.api();
@@ -165,15 +171,19 @@
       },
       "dom": "<'row'<'col-sm-6'B><'col-sm-6'f>>rtip",
       buttons: [
-        /*{% if user.id == gym.responsible.id %}
+        {% if user.id == gym.responsible.id %}
         {
             text: "{% trans 'Add new exercise' %}",
-            className: "btn addTaskBtn",
-            action: function() {
-                $('#taskModalForm').modal('show');
+            className: "btn btn-primary",
+            action: function( e, dt, node, config ) {
+                newExerciseInitialOperations();
+                var title = "{% trans 'Create new exercise '%}";
+                $('#exerciseModalTitle').text(title);
+                $('#btnAddExercise').text("{% trans 'Create exercise' %}");
+                $('#exerciseModalForm').modal('show');
             }
         }
-        {% endif %}*/
+        {% endif %}
       
       ],
       initComplete: function() {
@@ -201,9 +211,172 @@
         }
       });
       
-      /*$('.addTaskBtn').on('click', function() {
+      $('.exercise-modify-link').on('click', function() {
+        console.log("modifica");
+        var exercise_id = $(this).attr('data-exercise-id');
+        var exercise_massp = $(this).attr('data-exercise-massp');
+        var exercise_station = $(this).attr('data-exercise-station');
+        var exercise_name = $(this).attr('data-exercise-name');
+        console.log(exercise_id);
+        console.log(exercise_massp);
+        console.log(exercise_station);
+        console.log(exercise_name);
+        
+        $('#massp').val(exercise_massp);
+        $('#name').val(exercise_name);
+        $('#exerciseId').val(exercise_id);
+        loadGymStations();
+        
+        var title = "{% trans 'Edit exercise '%}" + exercise_name;
+        $('#exerciseModalTitle').text(title);
+        
+        $('#btnAddExercise').text("{% trans 'Update exercise' %}");
         $('#exerciseModalForm').modal('show');
-      });*/
+           
+      });
+      
+      $('.exercise-delete-link').on('click', function() {
+        console.log("elimina");
+        var exercise_id = $(this).attr('data-exercise-id');
+        console.log(exercise_id);
+        
+        $.ajax({
+            'url': "{% url 'api_organizations:station_exercises' organization_id=user.organization.id %}",
+            'method': 'DELETE',
+            'data': {
+                'id': exercise_id,
+            },
+            success: function(data) {
+                alert("{% trans 'The exercise has been deleted' %}");
+                table_station.ajax.reload(enableStationsTableFunctionality, false);
+            },
+            error: function(request, status, error) { 
+                //var parts = request.responseText.split('\n');
+                //alert(parts[1]); 
+                alert(request.responseText);
+            }
+
+        });
+      });
+      
+    }
+    
+    function newExerciseInitialOperations() {
+      // Load station from assigned gym to group
+      $('#massp').val('0');
+      $('#name').val('');
+      $('#exerciseId').val('');
+      loadGymStations();
+    }
+    
+    function loadGymStations() {
+      $('#stationSelect').find('option').remove().end();
+      var gymId = {{ gym.id }};
+      console.log("Estem buscant: " + gymId);
+      $.ajax({
+        'url': "{% url 'api_organizations:gym_stations' organization_id=user.organization.id %}",
+        data: {
+          'gym_id': gymId
+        },
+        success: function(data) {
+          console.log(data);
+          var count = 0;
+                       $.each(data, function(i, item) {
+            count ++;
+                               $('#stationSelect').append($('<option>', {
+                                       value: item.id,
+                                       text: item.name
+                               }));
+                       })
+          if (count > 0) {
+            $('#stationSelect').removeAttr('disabled');
+            // Load exercises from first station loaded
+            var station_id = $('#stationSelect option:first').val();
+            $('#stationSelect').val(station_id);
+          } else {
+            // Disable exercise creation
+          }
+        }
+      });
+    }
+    
+    $('#btnAddExercise').on('click', function(e) {
+        e.preventDefault();
+        if($('#name').val()=="") alert("{% trans 'Exercise must have a name' %}");
+        else {
+            var exercise = serializeExercise();
+            if($('#exerciseId').val()) {
+                console.log("update");
+                //update exercise
+                updateExercise(exercise);
+            } else {
+                console.log("create");
+                //create exercise
+                putExercise(exercise);
+            }
+        }
+    })
+
+
+    /* Get all the values in the form into json object */
+    function serializeExercise() {
+      let exercise_id = $('#exerciseId').val();
+      let station_id = $('#stationSelect').val();
+      let massp = $('#massp').val();
+      let name = $('#name').val();
+      var exercise = {
+        'id': exercise_id, 
+        'station_id': station_id,
+        'massp' : massp,
+        'name': name
+      }
+      console.log(exercise);
+      return exercise;
+    }
+    
+    
+    function putExercise(exercise) {
+      /* TODO: Add validation */
+      console.log("botó create exercise");
+      $.ajax({
+        'url': "{% url 'api_organizations:station_exercises' organization_id=user.organization.id %}",
+        'method': 'POST',
+        'data': exercise,
+        success: function(data) {
+          alert("{% trans 'The exercise has been created' %}");
+          console.log(exercise);
+          table_station.ajax.reload(enableStationsTableFunctionality, false);
+          $('#exerciseModalForm').modal('hide');
+        },
+        error: function(request, status, error) { 
+            //var parts = request.responseText.split('\n');
+            //alert(parts[1]); 
+            alert(request.responseText);
+        }
+
+      });
+    }
+    
+    function updateExercise(exercise) {
+      /* TODO: Add validation */
+      console.log("botó update exercise");
+      $.ajax({
+        'url': "{% url 'api_organizations:station_exercises' organization_id=user.organization.id %}",
+        'method': 'PUT',
+        'data': exercise,
+        success: function(data) {
+          alert("{% trans 'The exercise has been updated' %}");
+          console.log(exercise);
+          table_station.ajax.reload(enableStationsTableFunctionality, false);
+          $('#exerciseModalForm').modal('hide');
+        },
+        error: function(request, status, error) { 
+            //var parts = request.responseText.split('\n');
+            //alert(parts[1]); 
+            alert(request.responseText);
+        }
+
+      });
     }
 
   }); /* End of Document ready */


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