From 1271e4a33567fc94b1f348fce83120e96e609af9 Mon Sep 17 00:00:00 2001
From: Mattia Mancini <mancini@astron.nl>
Date: Wed, 17 Oct 2018 13:40:09 +0000
Subject: [PATCH] OSB-28: slight change in the query syntax and shape of the
 output

---
 .../DBInterface/monitoringdb/urls.py          |  1 +
 .../monitoringdb/views/controllers.py         | 64 +++++++++----------
 2 files changed, 33 insertions(+), 32 deletions(-)

diff --git a/LCU/Maintenance/DBInterface/monitoringdb/urls.py b/LCU/Maintenance/DBInterface/monitoringdb/urls.py
index a1c55045875..bf97b6fc0ef 100644
--- a/LCU/Maintenance/DBInterface/monitoringdb/urls.py
+++ b/LCU/Maintenance/DBInterface/monitoringdb/urls.py
@@ -41,6 +41,7 @@ urlpatterns = [
     url(r'^api/view/ctrl_stationtestsummary', ControllerStationTestsSummary.as_view()),
     url(r'^api/view/ctrl_latest_observation', ControllerLatestObservations.as_view()),
     url(r'^api/view/ctrl_stationtest_statistics', ControllerStationTestStatistics.as_view()),
+    url(r'^api/view/ctrl_list_component_error_types', ControllerAllComponentErrorTypes.as_view()),
 
     url(r'^api/docs', include_docs_urls(title='Monitoring DB API'))
 ]
diff --git a/LCU/Maintenance/DBInterface/monitoringdb/views/controllers.py b/LCU/Maintenance/DBInterface/monitoringdb/views/controllers.py
index 92ff755234e..5d8cceba8ef 100644
--- a/LCU/Maintenance/DBInterface/monitoringdb/views/controllers.py
+++ b/LCU/Maintenance/DBInterface/monitoringdb/views/controllers.py
@@ -84,9 +84,9 @@ class ControllerStationOverview(APIView):
             station_payload['station_name'] = station_entity.name
 
             station_test_list = StationTest.objects.filter(
-                station__name=station_entity.name).order_by('-end_datetime')[:n_station_tests - 1]
+                station__name=station_entity.name).order_by('-end_datetime')[:n_station_tests]
             rtsm_list = RTSMObservation.objects.filter(
-                station__name=station_entity.name).order_by('-end_datetime')[:n_rtsm - 1]
+                station__name=station_entity.name).order_by('-end_datetime')[:n_rtsm]
 
             station_payload['station_tests'] = list()
             for station_test in station_test_list:
@@ -155,6 +155,7 @@ class ControllerStationTestsSummary(APIView):
 
     DEFAULT_STATION_GROUP = 'A'
     DEFAULT_ONLY_ERRORS = True
+    DEFAULT_N_STATION_TESTS = 4
 
     queryset = StationTest.objects.all()
     schema = ManualSchema(fields=[
@@ -173,18 +174,11 @@ class ControllerStationTestsSummary(APIView):
                 description='displays or not only the station with more than one error')
         ),
         coreapi.Field(
-            "start_date",
-            required=True,
-            location='query',
-            schema=coreschema.String(
-                description='select station tests from date (ex. YYYY-MM-DD)')
-        ),
-        coreapi.Field(
-            "end_date",
-            required=True,
+            "n_station_tests",
+            required=False,
             location='query',
-            schema=coreschema.String(
-                description='select station tests to date (ex. YYYY-MM-DD)')
+            schema=coreschema.Integer(description='number of station tests to select',
+                                      minimum=1)
         )
     ]
     )
@@ -202,21 +196,18 @@ class ControllerStationTestsSummary(APIView):
         self.errors_only = request.query_params.get('errors_only', self.DEFAULT_ONLY_ERRORS)
         self.station_group = request.query_params.get('station_group', self.DEFAULT_STATION_GROUP)
 
-        start_date = request.query_params.get('start_date')
-        self.start_date = ControllerStationTestsSummary.parse_date(start_date)
-
-        end_date = request.query_params.get('end_date')
-        self.end_date = ControllerStationTestsSummary.parse_date(end_date)
+        self.n_station_tests = int(request.query_params.get('n_station_tests',
+                                                            self.DEFAULT_N_STATION_TESTS))
 
     def get(self, request, format=None):
         try:
             self.validate_query_parameters(request)
         except ValueError as e:
             return Response(status=status.HTTP_406_NOT_ACCEPTABLE,
-                            data='Please specify the date in the format YYYY-MM-DD: %s' % (e,))
+                            data='Please specify the correct parameters: %s' % (e,))
         except KeyError as e:
             return Response(status=status.HTTP_406_NOT_ACCEPTABLE,
-                            data='Please specify both the start and the end date: %s' % (e,))
+                            data='Please specify all the required parameters: %s' % (e,))
 
         station_entities = Station.objects.all()
         for group in self.station_group:
@@ -226,22 +217,21 @@ class ControllerStationTestsSummary(APIView):
         # Since django preferes a ordered dict over a dict we make it happy... for now
         response_payload = list()
         for station_entity in station_entities:
-            station_payload = OrderedDict()
 
-            station_payload['station_name'] = station_entity.name
 
-            station_test_list = StationTest.objects.filter(
-                start_datetime__gte=self.start_date,
-                end_datetime__lte=self.end_date,
-                station__name=station_entity.name).order_by('-end_datetime')
-            station_payload['station_tests'] = list()
+
+            station_test_list = StationTest.objects.\
+            filter(station__name=station_entity.name).order_by('-end_datetime')[:self.n_station_tests]
+
             for station_test in station_test_list:
 
                 station_test_payload = OrderedDict()
                 component_errors = station_test.component_errors
+                station_test_payload['station_name'] = station_entity.name
 
                 station_test_payload[
                     'total_component_errors'] = station_test.component_errors.count()
+                station_test_payload['date'] = station_test.start_datetime.strftime('%Y-%m-%d')
                 station_test_payload['start_datetime'] = station_test.start_datetime
                 station_test_payload['end_datetime'] = station_test.end_datetime
                 station_test_payload['checks'] = station_test.checks
@@ -261,15 +251,15 @@ class ControllerStationTestsSummary(APIView):
                         item_error_total
                 station_test_payload['component_error_summary'] = component_errors_summary_dict
 
-                station_payload['station_tests'].append(station_test_payload)
-
-            response_payload.append(station_payload)
+                response_payload.append(station_test_payload)
         if self.errors_only and self.errors_only is not 'false':
             response_payload = filter(
-                lambda station_entry:
-                len(station_entry['station_tests']) > 0,
+                lambda station_test_entry:
+                station_test_entry['total_component_errors'] > 0,
                 response_payload)
         response_payload = sorted(response_payload, key=lambda item: item['station_name'])
+        response_payload = sorted(response_payload, key=lambda item: item['date'], reverse=True)
+
         return Response(status=status.HTTP_200_OK, data=response_payload)
 
 
@@ -640,3 +630,13 @@ result:
         response_payload['errors_per_type'] = errors_per_type
 
         return Response(status=status.HTTP_200_OK, data=response_payload)
+
+
+class ControllerAllComponentErrorTypes(APIView):
+    """
+    Returns all distinct component errors
+    """
+
+    def get(self, request, format=None):
+        data = [item['type'] for item in ComponentError.objects.values('type').distinct()]
+        return Response(status=status.HTTP_200_OK, data=data)
\ No newline at end of file
-- 
GitLab