<commit_before># -*- coding: utf-8 -*-

# Akvo Reporting 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 >.
import json

from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from django.test import Client

from akvo.rsr.models import UserProjects, Project, Organisation, Partnership, Employment
from akvo.rsr.models.user_projects import restrict_projects

from akvo.rsr.tests.test_project_access import RestrictedUserProjects

User = get_user_model()


class RestrictedUserProjectsEndpoint(RestrictedUserProjects):

    def setUp(self):
        self.tearDown()

        super(RestrictedUserProjectsEndpoint, self).setUp()

        self.c = Client(HTTP_HOST=settings.RSR_DOMAIN)

        self.password_m = '<PASSWORD>'
        self.user_m.set_password(<PASSWORD>)
        self.user_m.save()

        self.password_n = '<PASSWORD>'
        self.user_n.set_password(<PASSWORD>)
        self.user_n.save()

    def tearDown(self):
        Project.objects.all().delete()
        User.objects.all().delete()
        Organisation.objects.all().delete()
        Group.objects.all().delete()

    @staticmethod
    def _create_user_projects(user, is_restricted=True, projects=None):
        user_projects = UserProjects.objects.create(
            user=user,
            is_restricted=is_restricted,
        )
        if projects is not None:
            for project in projects:
                user_projects.projects.add(project)

    def test_initial_call_to_endpoint_for_user(self):
        """
        User M      User N      User O
        Admin       Admin       User
           \       /    \      /
            \     /      \    /
              Org A       Org B
            /      \     /    \
           /        \   /      \
        Project X   Project Y   Project Z

        Test that a UserProjects object is created on access and returns the organisation_groups
        structure for the objects above
        """
        #  When
        self.c.login(username=self.user_n.username, password=self.password_n)
        response = self.c.get('/rest/v1/user_projects_access/{}/'.format(self.user_o.pk),
                              {'format': 'json'})

        content = json.loads(response.content)

        is_restricted = content['user_projects']['is_restricted']
        org_groups = content['organisation_groups']

        # Then
        self.assertEqual(response.status_code, 200)
        self.assertTrue(is_restricted)

        self.assertEqual(org_groups[0]['organisations'], "A, B")
        self.assertEqual(len(org_groups[0]['projects']), 1)
        self.assertEqual(org_groups[0]['projects'][0]['id'], self.projects['Y'].pk)
        self.assertTrue(org_groups[0]['projects'][0]['access'])

        self.assertEqual(org_groups[1]['organisations'], "B")
        self.assertEqual(len(org_groups[1]['projects']), 1)
        self.assertEqual(org_groups[1]['projects'][0]['id'], self.projects['Z'].pk)
        self.assertTrue(org_groups[1]['projects'][0]['access'])

    def test_endpoint_for_admin_and_user_having_same_org(self):
        """
        /̶ o and \̶ o = project with restricted access for user_o
<commit_msg>[#3414] Sort org_groups by organisation name<commit_after># -*- coding: utf-8 -*-

# Akvo Reporting 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 >.
import json

from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from django.test import Client

from akvo.rsr.models import UserProjects, Project, Organisation, Partnership, Employment
from akvo.rsr.models.user_projects import restrict_projects

from akvo.rsr.tests.test_project_access import RestrictedUserProjects

User = get_user_model()


class RestrictedUserProjectsEndpoint(RestrictedUserProjects):

    def setUp(self):
        self.tearDown()

        super(RestrictedUserProjectsEndpoint, self).setUp()

        self.c = Client(HTTP_HOST=settings.RSR_DOMAIN)

        self.password_m = '<PASSWORD>'
        self.user_m.set_password(self.password_m)
        self.user_m.save()

        self.password_n = '<PASSWORD>'
        self.user_n.set_password(self.password_n)
        self.user_n.save()

    def tearDown(self):
        Project.objects.all().delete()
        User.objects.all().delete()
        Organisation.objects.all().delete()
        Group.objects.all().delete()

    @staticmethod
    def _create_user_projects(user, is_restricted=True, projects=None):
        user_projects = UserProjects.objects.create(
            user=user,
            is_restricted=is_restricted,
        )
        if projects is not None:
            for project in projects:
                user_projects.projects.add(project)

    def test_initial_call_to_endpoint_for_user(self):
        """
        User M      User N      User O
        Admin       Admin       User
           \       /    \      /
            \     /      \    /
              Org A       Org B
            /      \     /    \
           /        \   /      \
        Project X   Project Y   Project Z

        Test that a UserProjects object is created on access and returns the organisation_groups
        structure for the objects above
        """
        #  When
        self.c.login(username=self.user_n.username, password=self.<PASSWORD>)
        response = self.c.get('/rest/v1/user_projects_access/{}/'.format(self.user_o.pk),
                              {'format': 'json'})

        content = json.loads(response.content)

        is_restricted = content['user_projects']['is_restricted']
        org_groups = sorted(content['organisation_groups'], key=lambda x: x['organisations'])

        # Then
        self.assertEqual(response.status_code, 200)
        self.assertTrue(is_restricted)

        self.assertEqual(org_groups[0]['organisations'], "A, B")
        self.assertEqual(len(org_groups[0]['projects']), 1)
        self.assertEqual(org_groups[0]['projects'][0]['id'], self.projects['Y'].pk)
        self.assertTrue(org_groups[0]['projects'][0]['access'])

        self.assertEqual(org_groups[1]['organisations'], "B")
        self.assertEqual(len(org_groups[1]['projects']), 1)
        self.assertEqual(org_groups[1]['projects'][0]['id'], self.projects['Z'].pk)
        self.assertTrue(org_groups[1]['projects'][0]['access'])

    def test_endpoint_for_admin_and_user_having_same_org(self):
        """
        /̶ o and \̶ o = project with restricted access for user_o

{'fraction_non_alphanumeric': 0.11322951535438801, 'fraction_numerical': 0.006112647358463106, 'mean_word_length': 2.551421188630491, 'pattern_counts': {'":': 0, '<': 12, '<?xml version=': 0, '>': 12, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3508438', 'n_tokens_mistral': 2026, 'n_tokens_neox': 1945, 'n_words': 414}