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

Issue:
403 error when adding new project
## Test plan

GIVEN the 'My projects' page in MyRSR
AS an organisation Admin of an organisation that can 'create new projects'
WHEN clicking 'Add new project'
THEN no 403 'Forbidden' error should be shown
## Issue description

The issue here is that we create a project and then redirect the user to the project editor immediately, while adding the reporting partner to the project as well. However, when the project editor is opened before a partner is added to the project, the organisation Admin is not allowed to edit the project (since their organisation is not linked to the project yet), so they get a 403.

This can be solved by making sure that project creation _and_ the addition of partners is successful before redirecting the user to the project editor.



Discussion:

Resolving patch:
diff --git a/akvo/rest/views/project_editor.py b/akvo/rest/views/project_editor.py
--- a/akvo/rest/views/project_editor.py
+++ b/akvo/rest/views/project_editor.py
@@ -27,6 +27,7 @@
 from django.http import HttpResponseForbidden
 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.permissions import IsAuthenticated
 from rest_framework.response import Response
@@ -771,4 +772,5 @@ def log_project_addition(request, project_pk=None):
         change_message=message
     )
 
-    return Response({})
+    content = {'log_entry': 'added successfully'}
+    return Response(content, status=status.HTTP_201_CREATED)


Test patch:
Repository: akvo/akvo-rsr

Issue:
Bug in project document category API
## Test plan

The project_document_category should not give an error. E.g. `http://rsr.localdev.akvo.org/rest/v1/project_document_category/` should load.
## Issue description

The project document category API gives an error. See http://sentry.support.akvo-ops.org/rsr/test/group/879/, or on the Test server: http://rsr.test.akvo.org/rest/v1/project_document_category/.



Discussion:

Resolving patch:
diff --git a/akvo/rest/views/project_document.py b/akvo/rest/views/project_document.py
--- a/akvo/rest/views/project_document.py
+++ b/akvo/rest/views/project_document.py
@@ -24,3 +24,4 @@ class ProjectDocumentCategoryViewSet(PublicProjectViewSet):
     queryset = ProjectDocumentCategory.objects.all()
     serializer_class = ProjectDocumentCategorySerializer
     filter_fields = ('document__project', 'document', 'category', )
+    project_relation = 'document__project__'


Test patch:
Repository: akvo/akvo-rsr

Issue:
MyRSR - API key
API key is unavailable via the new Admin area.



Discussion:
@damienallen We should add the API key of a user to the 'My details' page in MyRSR. Underneath the 'My organisations' box would be a nice place, just a header with a short description and the API key underneath.

Short description: "For more information on how to use the RSR API, please check the [support page](https://akvorsr.supporthero.io/container/show/api)."


Resolving patch:
diff --git a/akvo/rsr/views/my_rsr.py b/akvo/rsr/views/my_rsr.py
--- a/akvo/rsr/views/my_rsr.py
+++ b/akvo/rsr/views/my_rsr.py
@@ -15,6 +15,8 @@
 from django.http import HttpResponseRedirect, Http404
 from django.shortcuts import get_object_or_404, render
 
+from tastypie.models import ApiKey
+
 from ..forms import (PasswordForm, ProfileForm, UserOrganisationForm, UserAvatarForm,
                      SelectOrgForm)
 from ..filters import remove_empty_querydict_items
@@ -67,6 +69,8 @@ def my_details(request):
 
     change_password_form = PasswordForm(request.user)
 
+    api_key = ApiKey.objects.get_or_create(user=request.user)[0].key
+
     context = {
         'organisation_count': organisation_count,
         'country_count': country_count,
@@ -75,6 +79,7 @@ def my_details(request):
         'organisationform': organisation_form,
         'avatarform': avatar_form,
         'change_password_form': change_password_form,
+        'api_key': api_key,
     }
 
     return render(request, 'myrsr/my_details.html', context)


Test patch:
Repository: akvo/akvo-rsr

Issue:
Akvo Pages
When RSR 3.0 was launched, the layout of the Akvo Pages changed too. In  http://rsr.akvo.org/en/admin/rsr/partnersite/add/ there are quite some fields that are not relevant anymore with this new layout. 

E.g. 'About box text' and 'About box image' are not relevant anymore. These are not visible at the current Akvo Pages. 



Discussion:

Resolving patch:
diff --git a/akvo/rsr/admin.py b/akvo/rsr/admin.py
--- a/akvo/rsr/admin.py
+++ b/akvo/rsr/admin.py
@@ -1265,13 +1265,6 @@ class PartnerSiteAdmin(TimestampsAdminDisplayMixin, admin.ModelAdmin):
 
     fieldsets = (
         (u'General', dict(fields=('organisation', 'enabled',))),
-        (u'HTTP', dict(fields=('hostname', 'cname', 'custom_return_url', 'custom_return_url_text',
-                               'piwik_id',))),
-        (u'Style and content',
-            dict(fields=('all_maps', 'about_box', 'about_image', 'custom_css', 'custom_logo',
-                         'custom_favicon', 'show_keyword_logos',))),
-        (u'Languages and translation', dict(fields=('google_translation',))),
-        (u'Social', dict(fields=('twitter_button', 'facebook_button', 'facebook_app_id',))),
         (_(u'Project selection'), {
             'description': u'{}'.format(
                 u'<p style="margin-left:0; padding-left:0; margin-top:1em; width:75%%;">'
@@ -1294,7 +1287,17 @@ class PartnerSiteAdmin(TimestampsAdminDisplayMixin, admin.ModelAdmin):
             ),
             'fields': ('partner_projects', 'exclude_keywords', 'keywords'),
         }),
+        (u'HTTP', dict(fields=('hostname', 'cname', 'custom_return_url', 'custom_return_url_text',
+                               'piwik_id',))),
+        (u'Style and content',
+            dict(fields=('all_maps', 'custom_css', 'custom_logo',
+                         'custom_favicon', 'show_keyword_logos',))),
+        (u'Languages and translation', dict(fields=('google_translation',))),
+        (u'Social', dict(fields=('twitter_button', 'facebook_button', 'facebook_app_id',))),
     )
+
+    # exclude deprecated fields
+    exclude = ('about_box', 'about_image')
     filter_horizontal = ('keywords',)
     list_display = ('__unicode__', 'full_domain', 'enabled', 'show_keywords')
     list_filter = ('enabled', 'keywords')


Test patch:
Repository: akvo/akvo-rsr

Issue:
Missing space between words in model help text
At the end of the string on line
https://github.com/akvo/akvo-rsr/blob/master/akvo/rsr/models/sector.py#L23
there should be a space.



Discussion:

Resolving patch:
diff --git a/akvo/rsr/models/sector.py b/akvo/rsr/models/sector.py
--- a/akvo/rsr/models/sector.py
+++ b/akvo/rsr/models/sector.py
@@ -20,7 +20,7 @@ class Sector(models.Model):
     project = models.ForeignKey('Project', verbose_name=_(u'project'), related_name='sectors')
     sector_code = ValidXMLCharField(
         _(u'sector code'), blank=True, max_length=25,
-        help_text=_(u'Please select DAC-5 or DAC-3 as the sector vocabulary first, then this field'
+        help_text=_(u'Please select DAC-5 or DAC-3 as the sector vocabulary first, then this field '
                     u'will be populated with the corresponding codes. For other vocabularies, it '
                     u'is possible to fill in any code. '
                     u'See these lists for the DAC-5 and DAC-3 sector codes: '


Test patch:
Repository: akvo/akvo-rsr

Issue:
RSS feeds give a 504
For example: 
- http://rsr.akvo.org/rss/org-updates/273/
- http://rsr.akvo.org/rss/updates/788/



Discussion:
Number of items currently limited to 50 most recent updates but only ~35 items will load reliably before timeout. A limit of 25 is suggested and included in PR.


Resolving patch:
diff --git a/akvo/rsr/feeds.py b/akvo/rsr/feeds.py
--- a/akvo/rsr/feeds.py
+++ b/akvo/rsr/feeds.py
@@ -185,7 +185,7 @@ def item_extra_kwargs(self, item):
 
 
 class ProjectUpdates(UpdateFeed):
-    """RSS feed for last 50 RSR updates of a project."""
+    """RSS feed for last 25 RSR updates of a project."""
     def get_object(self, request, project_id):
         return Project.objects.get(pk__exact=project_id)
 
@@ -201,12 +201,12 @@ def description(self, obj):
         }
 
     def items(self, obj):
-        # Limited to 50 items to prevent gateway timeouts.
-        return ProjectUpdate.objects.filter(project__id=obj.id).order_by('-id')[:50]
+        # Limited to 25 items to prevent gateway timeouts.
+        return ProjectUpdate.objects.filter(project__id=obj.id).order_by('-id')[:25]
 
 
 class OrganisationUpdates(UpdateFeed):
-    """RSS feed for last 50 RSR updates of an organisation."""
+    """RSS feed for last 25 RSR updates of an organisation."""
     feed_type = RSRMediaRssFeed
 
     def get_object(self, request, org_id):
@@ -226,8 +226,8 @@ def description(self, obj):
             ) % {'org_name': obj.name, 'long_name': obj.long_name}
 
     def items(self, obj):
-        # Limited to 50 items to prevent gateway timeouts.
-        return obj.published_projects().all_updates()[:50]
+        # Limited to 25 items to prevent gateway timeouts.
+        return obj.published_projects().all_updates()[:25]
 
     def item_title(self, item):
         return _(
@@ -240,8 +240,8 @@ def item_title(self, item):
 
 
 class AllProjectUpdates(UpdateFeed):
-    """RSS feed for last 50 RSR updates."""
-    title = _(u'Last 50 RSR project updates')
+    """RSS feed for last 25 RSR updates."""
+    title = _(u'Last 25 RSR project updates')
     
     def link(self):
         return reverse('update-directory')
@@ -249,8 +249,8 @@ def link(self):
     description = _(u'Project updates for all Akvo RSR projects')
 
     def items(self):
-        # Limited to 50 items to prevent gateway timeouts.
-        return ProjectUpdate.objects.select_related().order_by('-id')[:50]
+        # Limited to 25 items to prevent gateway timeouts.
+        return ProjectUpdate.objects.select_related().order_by('-id')[:25]
 
     def item_title(self, item):
         return _(


Test patch:
Repository: akvo/akvo-rsr

Issue:
Unknown API methods return a KeyError
See http://sentry.support.akvo-ops.org/rsr/live/group/884/.

This was very probably caused when trying to delete a project document in the project editor.



Discussion:

Resolving patch:
diff --git a/akvo/rsr/models/project_document.py b/akvo/rsr/models/project_document.py
--- a/akvo/rsr/models/project_document.py
+++ b/akvo/rsr/models/project_document.py
@@ -45,7 +45,7 @@ class ProjectDocument(models.Model):
                     u'mime-types-summary-list/</a>.')
     )
     title = ValidXMLCharField(
-        _(u'document title'), max_length=100, blank=True,
+        _(u'document title'), max_length=100, blank=True, default=_(u'Untitled document'),
         help_text=_(u'Enter the title of your document.')
     )
     title_language = ValidXMLCharField(


Test patch:
Repository: akvo/akvo-rsr

Issue:
Unnecessary parameters in API cause MultipleObjectsReturned
See http://sentry.support.akvo-ops.org/rsr/live/group/887/.
- `/rest/v1/project_extra/2649/` works fine.
- `/rest/v1/project_extra/2649/?partners=1` returns a MultipleObjectsReturned error.

In these cases, the parameter should be ignored. There are exceptions though, such as the `limit` parameter (and maybe more?).



Discussion:

Resolving patch:
diff --git a/akvo/rest/viewsets.py b/akvo/rest/viewsets.py
--- a/akvo/rest/viewsets.py
+++ b/akvo/rest/viewsets.py
@@ -87,18 +87,19 @@ def get_lookups_from_filters(legacy_filters):
 
         queryset = super(BaseRSRViewSet, self).get_queryset()
 
-        # support for old DjangoFilterBackend-based filtering
-        # find all "old styled" filters
-        legacy_filters = django_filter_filters(self.request)
-        # create lookup dicts from the filters found
-        lookups = get_lookups_from_filters(legacy_filters)
-        for lookup in lookups:
-            try:
-                queryset = queryset.filter(**lookup)
-            except (FieldError, ValueError):
-                # In order to mimick 'old' behaviour of the API, we should ignore non-valid
-                # parameters or values. Returning a warning would be more preferable.
-                pass
+        # support for old DjangoFilterBackend-based filtering if not pk is given
+        if not self.kwargs.get(u'pk'):
+            # find all "old styled" filters
+            legacy_filters = django_filter_filters(self.request)
+            # create lookup dicts from the filters found
+            lookups = get_lookups_from_filters(legacy_filters)
+            for lookup in lookups:
+                try:
+                    queryset = queryset.filter(**lookup)
+                except (FieldError, ValueError):
+                    # In order to mimick 'old' behaviour of the API, we should ignore non-valid
+                    # parameters or values. Returning a warning would be more preferable.
+                    pass
 
         return queryset
 
diff --git a/akvo/rsr/admin.py b/akvo/rsr/admin.py
--- a/akvo/rsr/admin.py
+++ b/akvo/rsr/admin.py
@@ -1327,11 +1327,9 @@ def get_list_display(self, request):
 
     def get_queryset(self, request):
         if request.user.is_admin or request.user.is_superuser:
-            print "is admin or superuser"
             return super(PartnerSiteAdmin, self).get_queryset(
                 request).select_related('organisation')
 
-        print "was not admin or superuser"
         from .models import PartnerSite
         qs = PartnerSite.objects.none()
         for employment in request.user.employers.approved():


Test patch:
Repository: akvo/akvo-rsr

Issue:
Show project documents in project page footer
We currently always show "No related documents" in the project footer. This should display a list of (maximum 5) project documents.



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
@@ -273,6 +273,13 @@ def main(request, project_id):
     page = request.GET.get('page')
     page, paginator, page_range = pagination(page, updates, 10)
 
+    # Related documents
+    related_documents = []
+    for d in project.documents.all():
+        if d.url or d.document:
+            related_documents += [d]
+    related_documents = related_documents[:5]
+
     # JSON data
     carousel_data = json.dumps(_get_carousel_data(project, updates[:9]))
     accordion_data = json.dumps({
@@ -293,6 +300,7 @@ def main(request, project_id):
         'paginator': paginator,
         'pledged': project.get_pledged(),
         'project': project,
+        'related_documents': related_documents,
         'updates': updates[:5] if updates else None,
         'update_timeout': settings.PROJECT_UPDATE_TIMEOUT,
         'parent_projects_ids': [parent_project.id for parent_project in project.parents()],


Test patch:
Repository: akvo/akvo-rsr

Issue:
API crashes when a non-valid date is entered
E.g. `http://rsr.akvo.org/rest/v1/project_update_extra/?created_at__gt=2015-07`



Discussion:
Test plan:

Open: http://rsr.localdev.akvo.org/rest/v1/project_update_extra/?created_at__gt=2015-02-01
No error should be raised

Open: http://rsr.localdev.akvo.org/rest/v1/project_update_extra/?created_at__gt=2015-02
Date will be changed to yyyy-mm-01 (internally), no error should be raised

Open: http://rsr.localdev.akvo.org/rest/v1/project_update_extra/?created_at__gt=2015-99
400 error should be raised for values not matching yyyy-mm(-dd)

Date-time values are no longer accepted for the filter parameters

As a result, Up fetching of Updates is broken, as it uses a URL like this:
http://rsr.test.akvo.org/rest/v1/project_update/?format=xml&project=1336&last_modified_at__gt=1970-01-01T00:00:00

which returns:
400 BAD REQUEST
<?xml version="1.0" encoding="utf-8"?>
<root><detail>created_at and last_modified_at dates must be in format: yyyy-mm-dd</detail></root>


Resolving patch:
diff --git a/akvo/rest/views/project_update.py b/akvo/rest/views/project_update.py
--- a/akvo/rest/views/project_update.py
+++ b/akvo/rest/views/project_update.py
@@ -117,6 +117,11 @@ def validate_date(date):
 
     if date is None:
         return None
+    # if yyyy-mm-ddThh:mm:ss
+    elif match(
+            '^\d{4}\-(0?[1-9]|1[012])\-(0?[1-9]|[12][0-9]|3[01])T[0-2]\d{1}:[0-5]\d{1}:[0-5]\d{1}$',
+            date) is not None:
+        return date
     # if yyyy-mm-dd
     elif match('^\d{4}\-(0?[1-9]|1[012])\-(0?[1-9]|[12][0-9]|3[01])$', date) is not None:
         return date
@@ -124,7 +129,10 @@ def validate_date(date):
     elif match('^\d{4}\-(0?[1-9]|1[012])$', date) is not None:
         return date + '-01'
     else:
-        raise ParseError('created_at and last_modified_at dates must be in format: yyyy-mm-dd')
+        raise ParseError(
+            'Invalid date: created_at and last_modified_at dates must be in one of the following '
+            'formats: yyyy-mm, yyyy-mm-dd or yyyy-mm-ddThh:mm:ss'
+        )
 
 
 @api_view(['POST'])


Test patch:
Repository: akvo/akvo-rsr

Issue:
Add organisation pop-up
Add new organisation pop-up:
- [x] Show mandatory fields.
- [x] Check layout issue.
- [x] Organisations disappear after adding organisation.
- [x] Update country list to IATI countries.



Discussion:

Resolving patch:
diff --git a/akvo/rsr/views/my_rsr.py b/akvo/rsr/views/my_rsr.py
--- a/akvo/rsr/views/my_rsr.py
+++ b/akvo/rsr/views/my_rsr.py
@@ -7,6 +7,7 @@
 see < http://www.gnu.org/licenses/agpl.html >.
 """
 
+from django.conf import settings
 from django.contrib.auth.decorators import login_required
 from django.contrib.auth.models import Group
 from django.core.exceptions import PermissionDenied
@@ -17,11 +18,13 @@
 
 from tastypie.models import ApiKey
 
+from akvo.codelists.models import Country, Version
+
 from ..forms import (PasswordForm, ProfileForm, UserOrganisationForm, UserAvatarForm,
                      SelectOrgForm)
 from ..filters import remove_empty_querydict_items
 from ...utils import pagination, filter_query_string
-from ..models import (Country, Employment, Organisation, OrganisationCustomField, Project,
+from ..models import (Employment, Organisation, OrganisationCustomField, Project,
                       ProjectEditorValidation, ProjectEditorValidationSet)
 
 import json
@@ -267,7 +270,7 @@ def project_editor(request, project_id):
     project_validation_sets = project.validations.all()
 
     # Countries
-    countries = Country.objects.all()
+    countries = Country.objects.filter(version=Version.objects.get(code=settings.IATI_VERSION))
 
     context = {
         'id': project_id,


Test patch:
Repository: akvo/akvo-rsr

Issue:
Add reporting template for Plan Finland
We should add the reporting template that @stellanl and @Geerts are working on to the "My reports" section. Preferably so that only superusers / admins / Plan Finland employees can see this, but we might need a little hack for that.



Discussion:
There are no Plan Finland "secrets" in the report template, but as it will be almost useless if you don't have a 3-level hierarchy under the selected project, it could be confusing to other users.

Yup, @mato74 requested it to be Plan Finland visible only. We will need to see what's possible there.

Had a short chat with @stellanl earlier, but not all parameters are clear at the moment:
- What will be the key of the report (e.g. 'plan-finland')?
- Which formats will be supported (only PDF, or Excel / Word / HTML as well)?


Resolving patch:
diff --git a/akvo/rsr/reports.py b/akvo/rsr/reports.py
--- a/akvo/rsr/reports.py
+++ b/akvo/rsr/reports.py
@@ -52,6 +52,15 @@
         'formats': ['pdf', 'excel'],
         'parameters': ['organisation', ],
         'url': '/en/reports/data_quality/{organisation}?format={format}&download=true'
+    },
+    {
+        'key': 'plan-finland',
+        'title': unicode(_('Plan Finland report')),
+        'description': unicode(_('This custom MFA report for Plan Finland gives an overview of the '
+                                 'hierarchy of Plan Finland\'s projects and their results.')),
+        'formats': ['pdf', ],
+        'parameters': ['project', ],
+        'url': '/en/reports/plan_finland/{project}?format={format}&download=true'
     }
 ]
 


Test patch:
Repository: akvo/akvo-rsr

Issue:
Do not show unpublished projects in My projects list for Users
As a User, you can't edit / update / view a project when it is unpublished. Therefore we should hide these projects from the list in My projects.



Discussion:

Resolving patch:
diff --git a/akvo/rsr/views/my_rsr.py b/akvo/rsr/views/my_rsr.py
--- a/akvo/rsr/views/my_rsr.py
+++ b/akvo/rsr/views/my_rsr.py
@@ -124,16 +124,29 @@ def my_projects(request):
     :param request; A Django request.
     """
 
+    # User groups
+    not_allowed_to_edit = ['Users', 'User Managers', ]
+
     # Get user organisation information
-    organisations = request.user.approved_employments().organisations()
+    employments = request.user.approved_employments()
+    organisations = employments.organisations()
     creator_organisations = organisations.filter(can_create_projects=True).\
         values_list('id', flat=True)
 
     # Get project list
     if request.user.is_superuser or request.user.is_admin:
+        # Superuser and general admins are allowed to see all projects
         projects = Project.objects.all()
     else:
-        projects = organisations.all_projects().distinct()
+        # For each employment, check if the user is allowed to edit projects (e.g. not a 'User' or
+        # 'User Manager'). If not, do not show the unpublished projects of that organisation.
+        projects = Project.objects.none()
+        for employment in employments:
+            if employment.group and employment.group.name not in not_allowed_to_edit:
+                projects = projects | employment.organisation.all_projects()
+            else:
+                projects = projects | employment.organisation.all_projects().published()
+        projects = projects.distinct()
 
     # Custom filter on project id or (sub)title
     q = request.GET.get('q')


Test patch:
Repository: akvo/akvo-rsr

Issue:
Latest IATI file cannot be found
See http://rsr.uat.akvo.org/organisation/42/iati/. 

This is due to the "Show latest activity file on the organisation page of Akvo Foundation" checkbox. The file should not show on the organisation page in this case, but the above link should still be available.



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
@@ -108,11 +108,10 @@ def main(request, organisation_id):
 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).exclude(iati_file='')
-        if exports:
-            latest_export = exports.order_by('-id')[0]
-            return HttpResponse(latest_export.iati_file, content_type="text/xml")
+    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")
     raise Http404
 
 


Test patch: