internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: akvo/akvo-rsr

Issue:
File upload for Indicator Period Data requires Django login
When uploading a photo/file to the /rest/v1/indicator_period_data/nnn/upload_file/ endpoint, a Django login is required, which is not the case for the rest of the API; an API key should be sufficient.



Discussion:

Resolving patch:
diff --git a/akvo/rest/views/indicator_period_data.py b/akvo/rest/views/indicator_period_data.py
--- a/akvo/rest/views/indicator_period_data.py
+++ b/akvo/rest/views/indicator_period_data.py
@@ -11,8 +11,10 @@
                            IndicatorPeriodDataCommentSerializer)
 from ..viewsets import PublicProjectViewSet
 
+from django.http import HttpResponseForbidden
+
+from rest_framework import status
 from rest_framework.decorators import api_view, permission_classes
-from rest_framework.permissions import IsAuthenticated
 from rest_framework.response import Response
 
 
@@ -80,7 +82,6 @@ class IndicatorPeriodDataCommentViewSet(PublicProjectViewSet):
 
 
 @api_view(['POST'])
-@permission_classes((IsAuthenticated, ))
 def indicator_upload_file(request, pk=None):
     """
     Special API call for directly uploading a file.
@@ -91,18 +92,24 @@ def indicator_upload_file(request, pk=None):
     update = IndicatorPeriodData.objects.get(pk=pk)
     upload_file = request.FILES['file']
 
-    # TODO: Permissions
-    # user = request.user
-
-    file_type = request.POST.copy()['type']
-    if file_type == 'photo':
-        update.photo = upload_file
-        update.save(update_fields=['photo'])
-        return Response({'file': update.photo.url})
-    elif file_type == 'file':
-        update.file = upload_file
-        update.save(update_fields=['file'])
-        return Response({'file': update.file.url})
-
-    # TODO: Error response
-    return Response({})
+    # Permissions
+    user = getattr(request, 'user', None)
+    if not user:
+        return Response({'error': 'User is not logged in'}, status=status.HTTP_403_FORBIDDEN)
+
+    if not user.has_perm('rsr.change_project', update.period.indicator.result.project):
+        return Response({'error': 'User has no permission to place an update'},
+                        status=status.HTTP_403_FORBIDDEN)
+
+    try:
+        file_type = request.POST.copy()['type']
+        if file_type == 'photo':
+            update.photo = upload_file
+            update.save(update_fields=['photo'])
+            return Response({'file': update.photo.url})
+        elif file_type == 'file':
+            update.file = upload_file
+            update.save(update_fields=['file'])
+            return Response({'file': update.file.url})
+    except Exception as e:
+        return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)


Test patch:
Repository: akvo/akvo-rsr

Issue:
Tests broken
## Test plan

GIVEN multiple similar IATI versions in the DB
WHEN accessing the project page or directory
THEN it should not give an internal server error
## Issue description

Apparently, the test database has incorrect IATI versions. However, this might possibly happen in RSR itself too, so this should be fixed.



Discussion:

Resolving patch:
diff --git a/akvo/rsr/views/project.py b/akvo/rsr/views/project.py
--- a/akvo/rsr/views/project.py
+++ b/akvo/rsr/views/project.py
@@ -122,9 +122,13 @@ def directory(request):
     )
 
     # Get all sector categories in a dict
-    iati_version_obj = Version.objects.get(code=settings.IATI_VERSION)
-    sector_cats = SectorCategory.objects.filter(version=iati_version_obj)
-    sectors = Sector.objects.filter(version=iati_version_obj)
+    try:
+        iati_version_obj = Version.objects.get(code=settings.IATI_VERSION)
+        sector_cats = SectorCategory.objects.filter(version=iati_version_obj)
+        sectors = Sector.objects.filter(version=iati_version_obj)
+    except (Version.MultipleObjectsReturned, Version.DoesNotExist):
+        sector_cats = []
+        sectors = []
 
     sectors_dict = {}
     for sector_cat in sector_cats:


Test patch:
Repository: akvo/akvo-rsr

Issue:
IATI role to partner type gives TypeError
## Test plan

GIVEN a partnership without an IATI role
WHEN trying to view that partnership in the API (/rest/v1/partnership/../)
THEN it should not give an internal server error
## Issue description

See http://sentry.support.akvo-ops.org/rsr/live/group/789/



Discussion:

Resolving patch:
diff --git a/akvo/rsr/models/partnership.py b/akvo/rsr/models/partnership.py
--- a/akvo/rsr/models/partnership.py
+++ b/akvo/rsr/models/partnership.py
@@ -149,10 +149,16 @@ class Partnership(models.Model):
     )
 
     def iati_organisation_role_label(self):
-        return dict(self.IATI_ROLES).get(self.iati_organisation_role)
+        if self.iati_organisation_role:
+            return dict(self.IATI_ROLES).get(self.iati_organisation_role)
+        else:
+            return ''
 
     def iati_role_to_partner_type(self):
-        return dict(self.ROLES_TO_PARTNER_TYPES_MAP).get(int(self.iati_organisation_role))
+        if self.iati_organisation_role:
+            return dict(self.ROLES_TO_PARTNER_TYPES_MAP).get(int(self.iati_organisation_role))
+        else:
+            return None
 
     class Meta:
         app_label = 'rsr'


Test patch:
Repository: akvo/akvo-rsr

Issue:
Block Google from Indexing our Development Environments
## Test plan

GIVEN all dev environments (Test / UAT)
WHEN looking at the _head_ tag
THEN a _meta name="robots" content="none"_ node should be added

GIVEN the live environment
WHEN looking at the _head_ tag
THEN a _meta name="robots" content="none"_ node should not be added
## Issue description

We should add a robots.txt to all NON LIVE machines that prevents Google from indexing the site and displaying the content in search results.

This looks to be pretty simple: https://support.google.com/webmasters/answer/156449?rd=1



Discussion:
@adriancollier Added it to the provisioning repo after talk with @carlio, see https://github.com/akvo/akvo-provisioning/issues/79


Resolving patch:
diff --git a/akvo/rsr/context_processors.py b/akvo/rsr/context_processors.py
--- a/akvo/rsr/context_processors.py
+++ b/akvo/rsr/context_processors.py
@@ -22,6 +22,7 @@ def extra_context(request, protocol="http"):
         current_site = None
 
     django_version = django.get_version()
+    debug = getattr(settings, 'DEBUG', False)
     deploy_tag = getattr(settings, 'DEPLOY_TAG', 'Unknown')
     deploy_branch = getattr(settings, 'DEPLOY_BRANCH', 'Unknown')
     deploy_commit_id = getattr(settings, 'DEPLOY_COMMIT_ID', 'Unknown')
@@ -30,6 +31,7 @@ def extra_context(request, protocol="http"):
     return dict(
         current_site=current_site,
         django_version=django_version,
+        debug=debug,
         deploy_tag=deploy_tag,
         deploy_branch=deploy_branch,
         deploy_commit_id=deploy_commit_id,


Test patch:
Repository: akvo/akvo-rsr

Issue:
Publish directly to IATI registry
## Test plan

GIVEN an organisation with a public IATI file
WHEN visiting the /organisation/1/iati/ link
THEN the latest public IATI file should be shown
## Issue description

In the future we might want to think of a way to make it possible for partners to directly publish their IATI xml files to the IATI registry. Now they can create an xml in My IATI, but they still need to upload the file manually.



Discussion:

Resolving patch:
diff --git a/akvo/rsr/views/organisation.py b/akvo/rsr/views/organisation.py
--- a/akvo/rsr/views/organisation.py
+++ b/akvo/rsr/views/organisation.py
@@ -13,7 +13,7 @@
 from akvo.rsr.views.utils import apply_keywords, org_projects, show_filter_class
 from akvo.utils import pagination, filter_query_string
 
-from django.http import HttpResponse
+from django.http import Http404, HttpResponse
 from django.shortcuts import get_object_or_404, render
 
 from lxml import etree
@@ -107,8 +107,19 @@ def main(request, organisation_id):
 # Organisation IATI files
 ###############################################################################
 
+def iati(request, organisation_id):
+    """Retrieve the latest public IATI XML file."""
+    organisation = get_object_or_404(Organisation, pk=organisation_id)
+    if organisation.public_iati_file:
+        exports = organisation.iati_exports.filter(is_public=True)
+        if exports:
+            latest_export = exports.order_by('-id')[0]
+            return HttpResponse(latest_export.iati_file, content_type="text/xml")
+    raise Http404
+
+
 def iati_org(request, organisation_id):
-    """Generate the IATI file on-the-fly and return the XML."""
+    """Generate the IATI Organisation file on-the-fly and return the XML."""
     organisation = get_object_or_404(Organisation, pk=organisation_id)
     xml_data = etree.tostring(etree.ElementTree(
         IatiOrgXML(request, [organisation]).iati_organisations))
diff --git a/akvo/urls.py b/akvo/urls.py
--- a/akvo/urls.py
+++ b/akvo/urls.py
@@ -179,6 +179,9 @@
     url(r'^project/(?P<project_id>\d+)/iati/$',
         'akvo.rsr.views.project.iati', name='project-iati'),
 
+    url(r'^organisation/(?P<organisation_id>\d+)/iati/$',
+        'akvo.rsr.views.organisation.iati', name='projects-iati'),
+
     # IATI organisation file
     url(r'^organisation/(?P<organisation_id>\d+)/iati-org/$',
         'akvo.rsr.views.organisation.iati_org', name='org-iati'),


Test patch:
Repository: akvo/akvo-rsr

Issue:
Results framework bugs Safari
## Test plan

GIVEN an indicator or period has been opened in the results framework
WHEN refreshing the page, or clicking on the same URL from a mail client
THEN the same indicator or period should be opened _(in Safari as well)_
## Issue description

As an ME manager I receive email notifications when new data is submitted in My results. If I click the ‘edit the update’ link in the automatic email message, I don’t get redirected to the update directly, but to the results overview. Then I need to search for the relevant indicator. 

Works in Chrome.



Discussion:

Resolving patch:
diff --git a/akvo/rest/serializers/result.py b/akvo/rest/serializers/result.py
--- a/akvo/rest/serializers/result.py
+++ b/akvo/rest/serializers/result.py
@@ -15,6 +15,8 @@ class ResultSerializer(BaseRSRSerializer):
 
     project_title = serializers.Field(source='project.title')
     type_label = serializers.Field(source='iati_type')
+    parent_project = serializers.Field(source='parent_project')
+    child_projects = serializers.Field(source='child_projects')
 
     class Meta:
         model = Result
@@ -24,6 +26,8 @@ class ResultsFrameworkSerializer(BaseRSRSerializer):
 
     indicators = IndicatorFrameworkSerializer(many=True, required=False, allow_add_remove=True)
     project_title = serializers.Field(source='project.title')
+    parent_project = serializers.Field(source='parent_project')
+    child_projects = serializers.Field(source='child_projects')
 
     class Meta:
         model = Result
diff --git a/akvo/rsr/models/result.py b/akvo/rsr/models/result.py
--- a/akvo/rsr/models/result.py
+++ b/akvo/rsr/models/result.py
@@ -112,6 +112,23 @@ def has_info(self):
     def is_calculated(self):
         return self.project.is_impact_project
 
+    def parent_project(self):
+        """
+        Return a dictionary of this result's parent project.
+        """
+        if self.parent_result:
+            return {self.parent_result.project.id: self.parent_result.project.title}
+        return {}
+
+    def child_projects(self):
+        """
+        Return a dictionary of this result's child projects.
+        """
+        projects = {}
+        for result in Result.objects.filter(parent_result=self):
+            projects[result.project.id] = result.project.title
+        return projects
+
     class Meta:
         app_label = 'rsr'
         verbose_name = _(u'result')


Test patch:
Repository: akvo/akvo-rsr

Issue:
Can't save actual value of indicator period
## Test plan

GIVEN any indicator period
WHEN no indicator updates have been made for that period
THEN it should be possible to edit the actual value of that period in the project editor
## Issue description

It's not possible to save the actual value of an indicator period, because you get an error message stating that it is a 'calculated' value. This is a bug and should be fixed before we can release.



Discussion:

Resolving patch:
diff --git a/akvo/rsr/models/indicator.py b/akvo/rsr/models/indicator.py
--- a/akvo/rsr/models/indicator.py
+++ b/akvo/rsr/models/indicator.py
@@ -359,10 +359,11 @@ def clean(self):
 
     def is_calculated(self):
         """
-        When a project is set as an RSR Impact project, the actual values of the indicator
-        periods are calculated through updates.
+        When a period has got indicator updates, we consider the actual value to be a
+        'calculated' value, meaning that it's not possible to update the actual value directly.
+        Only through indicator updates.
         """
-        return self.indicator.result.project.is_impact_project
+        return self.data.exists()
 
     def is_child_period(self):
         """


Test patch:
Repository: akvo/akvo-rsr

Issue:
Take latest IATI export file that is finished
## Test plan

GIVEN the `/organisation/..org_id../iati/` URL
WHEN an IATI export for that organisation is running
THEN the URL should return the previously generated lATI file (if available)
## Issue description

Currently, when you go to `/organisation/../iati/`, the latest published IATI export is taken. However, when an export is still running (or has crashed), it doesn't have a file yet. Therefore we should take the latest published IATI export **with a file**.



Discussion:

Resolving patch:
diff --git a/akvo/rsr/forms.py b/akvo/rsr/forms.py
--- a/akvo/rsr/forms.py
+++ b/akvo/rsr/forms.py
@@ -487,6 +487,7 @@ def save(self, reporting_organisation=None, user=None):
             iati_export = super(IatiExportForm, self).save(commit=False)
             iati_export.reporting_organisation = reporting_organisation
             iati_export.user = user
+            iati_export.version = settings.IATI_VERSION
             iati_export.save()
             self.save_m2m()
             iati_export.save()
diff --git a/akvo/rsr/views/organisation.py b/akvo/rsr/views/organisation.py
--- a/akvo/rsr/views/organisation.py
+++ b/akvo/rsr/views/organisation.py
@@ -111,7 +111,7 @@ def iati(request, organisation_id):
     """Retrieve the latest public IATI XML file."""
     organisation = get_object_or_404(Organisation, pk=organisation_id)
     if organisation.public_iati_file:
-        exports = organisation.iati_exports.filter(is_public=True)
+        exports = organisation.iati_exports.filter(is_public=True).exclude(iati_file='')
         if exports:
             latest_export = exports.order_by('-id')[0]
             return HttpResponse(latest_export.iati_file, content_type="text/xml")


Test patch:
Repository: akvo/akvo-rsr

Issue:
Budget without value makes IATI export crash
## Test plan

GIVEN the IATI export (bottom right on project page)
WHEN a budget of the project has no value, but does have a value date / currency / label
THEN the `value` tag of the budget item should not be generated
AND no internal server error should be shown
## Issue description

See http://sentry.support.akvo-ops.org/rsr/live/group/832/



Discussion:

Resolving patch:
diff --git a/akvo/iati/exports/elements/budget.py b/akvo/iati/exports/elements/budget.py
--- a/akvo/iati/exports/elements/budget.py
+++ b/akvo/iati/exports/elements/budget.py
@@ -40,18 +40,17 @@ def budget(project):
                 value_element = etree.SubElement(element, "value")
                 value_element.text = str(budget_item.amount)
 
-            if budget_item.value_date:
-                value_element.attrib['value-date'] = str(budget_item.value_date)
-
-            if budget_item.currency:
-                value_element.attrib['currency'] = budget_item.currency
-
-            if budget_item.other_extra:
-                value_element.attrib['{http://akvo.org/iati-activities}label'] = budget_item.\
-                    other_extra
-            elif budget_item.label and budget_item.label.label:
-                value_element.attrib['{http://akvo.org/iati-activities}label'] = budget_item.label.\
-                    label
+                if budget_item.value_date:
+                    value_element.attrib['value-date'] = str(budget_item.value_date)
+
+                if budget_item.currency:
+                    value_element.attrib['currency'] = budget_item.currency
+
+                akvo_label = '{http://akvo.org/iati-activities}label'
+                if budget_item.other_extra:
+                    value_element.attrib[akvo_label] = budget_item.other_extra
+                elif budget_item.label and budget_item.label.label:
+                    value_element.attrib[akvo_label] = budget_item.label.label
 
             budget_elements.append(element)
 


Test patch:
Repository: akvo/akvo-rsr

Issue:
Indicator period data comment API endpoint breaks
## Test plan

GIVEN the indicator period data comment API endpoint: `/rest/v1/indicator_period_data_comment/`
WHEN the user is not logged in
THEN the indicator period data comments should be shown
AND no internal server error should be shown
## Issue description

The indicator period data comment API endpoint is not setup correctly. See http://sentry.support.akvo-ops.org/rsr/live/group/831/.



Discussion:

Resolving patch:
diff --git a/akvo/rest/views/indicator_period_data.py b/akvo/rest/views/indicator_period_data.py
--- a/akvo/rest/views/indicator_period_data.py
+++ b/akvo/rest/views/indicator_period_data.py
@@ -78,7 +78,7 @@ class IndicatorPeriodDataCommentViewSet(PublicProjectViewSet):
         'created_at': ['exact', 'gt', 'gte', 'lt', 'lte', ],
         'last_modified_at': ['exact', 'gt', 'gte', 'lt', 'lte', ]
     }
-    project_relation = 'period__indicator__result__project__'
+    project_relation = 'data__period__indicator__result__project__'
 
 
 @api_view(['POST'])


Test patch:
Repository: akvo/akvo-rsr

Issue:
Show results framework for private projects
## Test plan

GIVEN the 'My results' tab in MyRSR
WHEN searching for a private project
THEN the project should appear in the list

WHEN the private project is opened in 'My results'
THEN the user should have full access to the results framework, just like a regular public project
## Issue description

Currently, we have disabled the results framework in MyRSR for private projects. However, it should be possible to enter results data for private projects as well.



Discussion:

Resolving patch:
diff --git a/akvo/rest/views/typeahead.py b/akvo/rest/views/typeahead.py
--- a/akvo/rest/views/typeahead.py
+++ b/akvo/rest/views/typeahead.py
@@ -78,7 +78,7 @@ def typeahead_user_projects(request):
 def typeahead_impact_projects(request):
     user = request.user
     projects = Project.objects.all() if user.is_admin or user.is_superuser else user.my_projects()
-    projects = projects.published().filter(is_impact_project=True, is_public=True).order_by('title')
+    projects = projects.published().filter(is_impact_project=True).order_by('title')
 
     return Response(
         rejig(projects, TypeaheadProjectSerializer(projects, many=True))


Test patch:
Repository: akvo/akvo-rsr

Issue:
Employment application requires Django login
## Test plan

GIVEN the `/rest/v1/user/../request_organisation/` endpoint
WHEN POSTing a request from outside of RSR
AND the correct authentication details are provided
THEN the request should be process accordingly, instead trying to authenticate through Django's auth system
## Issue description

Just as for #2037, when posting a request for employment to the /rest/v1/user/request_organisation/ endpoint, a Django login is required, which is not the case for the rest of the API; an API key should be sufficient.



Discussion:
This does not seem to work right. Looks like access is checked against anonymous user when not logged into Django; the API key is never checked.


Resolving patch:
diff --git a/akvo/rest/views/user.py b/akvo/rest/views/user.py
--- a/akvo/rest/views/user.py
+++ b/akvo/rest/views/user.py
@@ -10,10 +10,12 @@
 from django.utils.translation import ugettext_lazy as _
 
 from rest_framework import status
-from rest_framework.decorators import api_view, permission_classes
+from rest_framework.authentication import SessionAuthentication
+from rest_framework.decorators import api_view, permission_classes, authentication_classes
 from rest_framework.exceptions import PermissionDenied
 from rest_framework.response import Response
 
+from akvo.rest.models import TastyTokenAuthentication
 from ...rsr.models import Country, Employment, Organisation
 from ..viewsets import BaseRSRViewSet
 from ..serializers import EmploymentSerializer, OrganisationSerializer, CountrySerializer
@@ -88,16 +90,19 @@ def update_details(request, pk=None):
 
 
 @api_view(['POST'])
+@authentication_classes([SessionAuthentication, TastyTokenAuthentication])
 def request_organisation(request, pk=None):
+
     # Get the user, or return an error if the user does not exist
     try:
-        user = get_user_model().objects.get(pk=pk)
+        user_by_pk = get_user_model().objects.get(pk=pk)
     except get_user_model().DoesNotExist:
         return Response({'user': _('User does not exist')}, status=status.HTTP_400_BAD_REQUEST)
 
+    # request.user is the user identified by the auth token
+    user = request.user
     # Users themselves are only allowed to request to join an organisation
-    request_user = getattr(request, 'user', None)
-    if not user == request_user:
+    if not user_by_pk == request.user:
         raise PermissionDenied()
     request.DATA['user'] = pk
 


Test patch:
Repository: akvo/akvo-rsr

Issue:
Show results framework for private projects
## Test plan

GIVEN the 'My results' tab in MyRSR
WHEN searching for a private project
THEN the project should appear in the list

WHEN the private project is opened in 'My results'
THEN the user should have full access to the results framework, just like a regular public project
## Issue description

Currently, we have disabled the results framework in MyRSR for private projects. However, it should be possible to enter results data for private projects as well.



Discussion:
We decided not to take this along in the hotfix, so rescheduled it for next release.


Resolving patch:
diff --git a/akvo/rest/views/typeahead.py b/akvo/rest/views/typeahead.py
--- a/akvo/rest/views/typeahead.py
+++ b/akvo/rest/views/typeahead.py
@@ -78,7 +78,7 @@ def typeahead_user_projects(request):
 def typeahead_impact_projects(request):
     user = request.user
     projects = Project.objects.all() if user.is_admin or user.is_superuser else user.my_projects()
-    projects = projects.published().filter(is_impact_project=True, is_public=True).order_by('title')
+    projects = projects.published().filter(is_impact_project=True).order_by('title')
 
     return Response(
         rejig(projects, TypeaheadProjectSerializer(projects, many=True))


Test patch: