# -*- coding: utf-8 -*-

# Akvo RSR is covered by the GNU Affero General Public License.
# See more details in the license.txt file located at the root folder of the Akvo RSR module.
# For additional details on the GNU license please see < http://www.gnu.org/licenses/agpl.html >.

from django.db.models import Q
from django.shortcuts import get_object_or_404
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response

from akvo.rsr.models import Report, ReportFormat, Project
from ..serializers import ReportSerializer, ReportFormatSerializer
from ..viewsets import BaseRSRViewSet


class ReportViewSet(BaseRSRViewSet):
    """Viewset providing Result data."""

    queryset = Report.objects.prefetch_related(
        'organisations',
        'formats',
    )
    serializer_class = ReportSerializer

    def get_queryset(self):
        """
        Allow custom filter for sync_owner, since this field has been replaced by the
        reporting org partnership.
        """
        reports = super(ReportViewSet, self).get_queryset()
        user = self.request.user
        is_admin = user.is_active and (user.is_superuser or user.is_admin)
        if not is_admin:
            # Show only those reports that the user is allowed to see
            approved_orgs = user.approved_organisations() if not user.is_anonymous() else []
            reports = reports.filter(
                Q(organisations=None) | Q(organisations__in=approved_orgs)
            ).distinct()
        return reports


@api_view(['GET'])
def report_formats(request):
    """
    A view for displaying all report format information.
    """
    return Response({
        'count': ReportFormat.objects.all().count(),
        'results': [ReportFormatSerializer(f).data for f in ReportFormat.objects.all()],
    })


@api_view(['GET'])
def project_reports(request, project_pk):
    """A view for displaying project specific reports."""

    project = get_object_or_404(Project, pk=project_pk)
    reports = Report.objects.prefetch_related('formats', 'organisations')\
                            .filter(url__icontains='project')

    user = request.user
    if not user.has_perm('rsr.view_project', project):
        return Response('Request not allowed', status=status.HTTP_403_FORBIDDEN)

    is_admin = user.is_active and (user.is_superuser or user.is_admin)

    if not is_admin:
        partners_org = project.partner_organisation_pks()
        reports = reports.filter(
            Q(organisations=None) | Q(organisations__in=partners_org)
        )

    serializer = ReportSerializer(reports.distinct(), many=True)
    return Response(serializer.data)

akvo/rest/views/report.py
# -*- coding: utf-8 -*-

# Akvo RSR is covered by the GNU Affero General Public License.
# See more details in the license.txt file located at the root folder of the Akvo RSR module.
# For additional details on the GNU license please see < http://www.gnu.org/licenses/agpl.html >.

from django.db.models import Q
from django.shortcuts import get_object_or_404
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response

from akvo.rsr.models import Report, ReportFormat, Project
from ..serializers import ReportSerializer, ReportFormatSerializer
from ..viewsets import BaseRSRViewSet


class ReportViewSet(BaseRSRViewSet):
    """Viewset providing Result data."""

    queryset = Report.objects.prefetch_related(
        'organisations',
        'formats',
    )
    serializer_class = ReportSerializer

    def get_queryset(self):
        """
        Allow custom filter for sync_owner, since this field has been replaced by the
        reporting org partnership.
        """
        reports = super(ReportViewSet, self).get_queryset()
        user = self.request.user
        is_admin = user.is_active and (user.is_superuser or user.is_admin)
        if not is_admin:
            # Show only those reports that the user is allowed to see
            approved_orgs = user.approved_organisations() if not user.is_anonymous() else []
            reports = reports.filter(
                Q(organisations=None) | Q(organisations__in=approved_orgs)
            ).distinct()
        return reports


@api_view(['GET'])
def report_formats(request):
    """
    A view for displaying all report format information.
    """
    return Response({
        'count': ReportFormat.objects.all().count(),
        'results': [ReportFormatSerializer(f).data for f in ReportFormat.objects.all()],
    })


@api_view(['GET'])
def project_reports(request, project_pk):
    """A view for displaying project specific reports."""

    project = get_object_or_404(Project, pk=project_pk)
    reports = Report.objects.prefetch_related('formats', 'organisations')\
                            .filter(url__icontains='{project}')

    user = request.user
    if not user.has_perm('rsr.view_project', project):
        return Response('Request not allowed', status=status.HTTP_403_FORBIDDEN)

    is_admin = user.is_active and (user.is_superuser or user.is_admin)

    if not is_admin:
        partners_org = project.partner_organisation_pks()
        reports = reports.filter(
            Q(organisations=None) | Q(organisations__in=partners_org)
        )

    serializer = ReportSerializer(reports.distinct(), many=True)
    return Response(serializer.data)

akvo/rest/views/report.py
diff --git a/akvo/rest/views/report.py b/akvo/rest/views/report.py
index 005b829a79..9060551a8d 100644
--- a/akvo/rest/views/report.py
+++ b/akvo/rest/views/report.py
@@ -58,7 +58,7 @@ def project_reports(request, project_pk):
 
     project = get_object_or_404(Project, pk=project_pk)
     reports = Report.objects.prefetch_related('formats', 'organisations')\
-                            .filter(url__icontains='project')
+                            .filter(url__icontains='{project}')
 
     user = request.user
     if not user.has_perm('rsr.view_project', project):
diff --git a/akvo/rsr/tests/base.py b/akvo/rsr/tests/base.py
index 975a18a596..25766c201f 100644
--- a/akvo/rsr/tests/base.py
+++ b/akvo/rsr/tests/base.py
@@ -60,8 +60,9 @@ def create_project(title, published=True, public=True):
         return project
 
     @staticmethod
-    def create_report(report_name, organisation=None, is_org_report=False):
-        url = '/{organisation}/?format={format}' if is_org_report else '/{project}/?format={format}'
+    def create_report(report_name, organisation=None, is_org_report=False, url=None):
+        if url is None:
+            url = '/{organisation}/?format={format}' if is_org_report else '/{project}/?format={format}'
         report = Report.objects.create(
             name=report_name, title=report_name, url=url)
         if organisation is not None:
diff --git a/akvo/rsr/tests/rest/test_project_reports.py b/akvo/rsr/tests/rest/test_project_reports.py
index 6a1d3eb075..82a03079e6 100644
--- a/akvo/rsr/tests/rest/test_project_reports.py
+++ b/akvo/rsr/tests/rest/test_project_reports.py
@@ -114,6 +114,10 @@ def test_only_reports_with_project_parameter_are_shown(self):
         org1 = self.create_organisation('org-1')
         self.create_report('report-1')
         self.create_report('report-2', is_org_report=True)
+        self.create_report(
+            'projects-overview',
+            url='/en/reports/project_overview/{organisation}?format={format}&download=true'
+        )
 
         self.make_partner(proj1, org1)
         user = self.create_user('foo@example.com', 'secret')

Organisation report shown in project reports page
The "Project overview" report is displayed on the project report page, which is an organisation report  and should not be displayed on the project report page.
