internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: fossasia/open-event-server

Issue:
Microlocation: Add related endpoints to docs and dredd tests
Parent issue : #4009.



Discussion:

Resolving patch:
diff --git a/app/api/__init__.py b/app/api/__init__.py
--- a/app/api/__init__.py
+++ b/app/api/__init__.py
@@ -228,9 +228,9 @@
 
 
 # microlocations
+api.route(MicrolocationListPost, 'microlocation_list_post', '/microlocations')
 api.route(MicrolocationList, 'microlocation_list', '/events/<int:event_id>/microlocations',
           '/events/<event_identifier>/microlocations')
-api.route(MicrolocationListPost, 'microlocation_list_post', '/microlocations')
 api.route(MicrolocationDetail, 'microlocation_detail', '/microlocations/<int:id>',
           '/sessions/<int:session_id>/microlocation')
 api.route(MicrolocationRelationshipOptional, 'microlocation_session',


Test patch:
diff --git a/tests/hook_main.py b/tests/hook_main.py
--- a/tests/hook_main.py
+++ b/tests/hook_main.py
@@ -808,19 +808,6 @@ def user_event_invoice_get_list(transaction):
 
 
 # ------------------------- Microlocation -------------------------
-@hooks.before("Microlocations > Microlocation Collection > List All Microlocations")
-def microlocation_get_list(transaction):
-    """
-    GET /events/1/microlocations
-    :param transaction:
-    :return:
-    """
-    with stash['app'].app_context():
-        microlocation = MicrolocationFactory()
-        db.session.add(microlocation)
-        db.session.commit()
-
-
 @hooks.before("Microlocations > Microlocation Collection > Create Microlocation")
 def microlocation_post(transaction):
     """
@@ -873,6 +860,32 @@ def microlocation_delete(transaction):
         db.session.commit()
 
 
+@hooks.before("Microlocations > Microlocations under an Event > Get List of Mictolocations under an Event")
+def event_microlocation_get_list(transaction):
+    """
+    GET /events/1/microlocations
+    :param transaction:
+    :return:
+    """
+    with stash['app'].app_context():
+        microlocation = MicrolocationFactory()
+        db.session.add(microlocation)
+        db.session.commit()
+
+
+@hooks.before("Microlocations > Microlocation Details of a Session > Get Mictolocation Details of a Session")
+def session_microlocation_get_detail(transaction):
+    """
+    GET /sessions/1/microlocation
+    :param transaction:
+    :return:
+    """
+    with stash['app'].app_context():
+        session = SessionFactory()
+        db.session.add(session)
+        db.session.commit()
+
+
 # ------------------------- Sessions -------------------------
 @hooks.before("Sessions > Sessions Collection > Create Sessions")
 def session_post(transaction):
Repository: fossasia/open-event-server

Issue:
Bug: KeyError on /v1/users/<int:user_id>/attendees
https://sentry.eventyay.com/eventyay/dev-api/issues/52/ 

```
KeyError /v1/users/<int:user_id>/attendees
error'id'
```


Discussion:

Resolving patch:
diff --git a/app/api/attendees.py b/app/api/attendees.py
--- a/app/api/attendees.py
+++ b/app/api/attendees.py
@@ -42,7 +42,7 @@ def query(self, view_kwargs):
         if view_kwargs.get('order_identifier'):
             order = safe_query(self, Order, 'identifier', view_kwargs['order_identifier'], 'order_identifier')
             if not has_access('is_registrar', event_id=order.event_id) or not has_access('is_user_itself',
-                                                                                         user_id=order.user_id):
+                                                                                         id=order.user_id):
                 raise ForbiddenException({'source': ''}, 'Access Forbidden')
             query_ = query_.join(Order).filter(Order.id == order.id)
 


Test patch:
Repository: fossasia/open-event-server

Issue:
Attendee : user/<id>/attendee gives Error 400
**I'm submitting a ...**  (check one with "x")
- [x] bug report
- [ ] feature request
- [ ] support request => Please do not submit support requests here, instead ask your query in out Gitter channel at https://gitter.im/fossasia/open-event-orga-server

URL
```
https://open-event-api.herokuapp.com/v1/users/5/attendees?include=ticket,event,order
```

ERROR
```
{
   "errors":[
      {
         "title":"Invalid include querystring parameter.",
         "source":{
            "parameter":"include"
         },
         "status":400,
         "detail":"AttendeeSchemaPublic has no attribute ticket"
      }
   ],
   "jsonapi":{
      "version":"1.0"
   }
}
```
Related Front-end route
```
https://open-event-frontend.herokuapp.com/my-tickets
```
Due to recent changes the URL gives ERROR 400.
@poush @shubham-padia @enigmaeth @magdalenesuo Please have a look at it


Discussion:

Resolving patch:
diff --git a/app/api/attendees.py b/app/api/attendees.py
--- a/app/api/attendees.py
+++ b/app/api/attendees.py
@@ -36,10 +36,6 @@ class AttendeeList(ResourceList):
     """
     List Attendees
     """
-    def before_get(self, args, kwargs):
-        if kwargs.get('user_id'):
-            self.schema = AttendeeSchemaPublic
-
     def query(self, view_kwargs):
         query_ = self.session.query(TicketHolder)
 


Test patch:
Repository: fossasia/open-event-server

Issue:
User-Session: user/<id>/sessions returns all the sessions in system
**I'm submitting a ...**  (check one with "x")
- [x] bug report
- [ ] feature request
- [ ] support request => Please do not submit support requests here, instead ask your query in out Gitter channel at https://gitter.im/fossasia/open-event-orga-server

The user API returns all the sessions in the system instead of sessions under the user
eg
URL
```
https://open-event-api.herokuapp.com/v1/users/5/sessions
```

Query Params:
```
include:event
sort:starts-at
```

@poush @shubham-padia @enigmaeth @magdalenesuo Please have a look at it


Discussion:

Resolving patch:
diff --git a/app/api/sessions.py b/app/api/sessions.py
--- a/app/api/sessions.py
+++ b/app/api/sessions.py
@@ -15,6 +15,7 @@
 from app.models.session_type import SessionType
 from app.models.speaker import Speaker
 from app.models.track import Track
+from app.models.user import User
 from app.settings import get_settings
 
 
@@ -61,11 +62,15 @@ def query(self, view_kwargs):
         if view_kwargs.get('microlocation_id') is not None:
             microlocation = safe_query(self, Microlocation, 'id', view_kwargs['microlocation_id'], 'microlocation_id')
             query_ = query_.join(Microlocation).filter(Microlocation.id == microlocation.id)
+        if view_kwargs.get('user_id') is not None:
+            user = safe_query(self, User, 'id', view_kwargs['user_id'], 'user_id')
+            query_ = query_.join(User).filter(User.id == user.id)
         query_ = event_query(self, query_, view_kwargs)
         if view_kwargs.get('speaker_id'):
             speaker = safe_query(self, Speaker, 'id', view_kwargs['speaker_id'], 'speaker_id')
             # session-speaker :: many-to-many relationship
             query_ = Session.query.filter(Session.speakers.any(id=speaker.id))
+
         return query_
 
     view_kwargs = True


Test patch:
Repository: fossasia/open-event-server

Issue:
 Verify Email endpoint doesn’t work.
**I'm submitting a ...**  (check one with "x")
- [X] bug report
- [ ] feature request
- [ ] support request => Please do not submit support requests here, instead ask your query in out Gitter channel at https://gitter.im/fossasia/open-event-orga-server

There are two specific errors in the function.
- [x] Firstly the email verification state change isn’t saved in db
- [x] Response for the view function is missing.



Discussion:

Resolving patch:
diff --git a/app/api/auth.py b/app/api/auth.py
--- a/app/api/auth.py
+++ b/app/api/auth.py
@@ -35,6 +35,8 @@ def verify_email():
         )
     else:
         user.is_verified = True
+        save_to_db(user)
+        return make_response(jsonify(message="Email Verified"), 200)
 
 
 @auth_routes.route('/reset-password', methods=['POST'])
@@ -94,7 +96,9 @@ def change_password():
             user.password = new_password
             save_to_db(user)
         else:
-            return make_response(jsonify(error="Wrong Password"), 400)
+            return abort(
+                make_response(jsonify(error="Wrong Password"), 400)
+            )
 
     return jsonify({
         "id": user.id,


Test patch:
Repository: fossasia/open-event-server

Issue:
[sentry] KeyError/v1/users/<int:user_id>/access-codes
**I'm submitting a ...**  (check one with "x")
- [x] bug report
- [ ] feature request
- [ ] support request => Please do not submit support requests here, instead ask your query in out Gitter channel at https://gitter.im/fossasia/open-event-orga-server

```
KeyError: 'id'
  File "flask/app.py", line 1982, in wsgi_app
    response = self.full_dispatch_request()
  File "flask/app.py", line 1614, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "flask_cors/extension.py", line 161, in wrapped_function
    return cors_after_request(app.make_response(f(*args, **kwargs)))
  File "flask/app.py", line 1517, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "flask/app.py", line 1612, in full_dispatch_request
    rv = self.dispatch_request()
  File "flask/app.py", line 1598, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "flask_rest_jsonapi/decorators.py", line 32, in wrapper
    return func(*args, **kwargs)
  File "flask/views.py", line 84, in view
    return self.dispatch_request(*args, **kwargs)
  File "flask_rest_jsonapi/resource.py", line 68, in dispatch_request
    response = method(*args, **kwargs)
  File "flask_rest_jsonapi/decorators.py", line 56, in wrapper
    return func(*args, **kwargs)
  File "flask_rest_jsonapi/resource.py", line 145, in get
    objects_count, objects = self._data_layer.get_collection(qs, kwargs)
  File "flask_rest_jsonapi/data_layers/alchemy.py", line 92, in get_collection
    query = self.query(view_kwargs)
  File "app/api/access_codes.py", line 56, in query
    if not has_access('is_user_itself', user_id=user.id):
  File "app/api/helpers/permission_manager.py", line 450, in has_access
    auth = permissions[access_level](lambda *a, **b: True, (), {}, (), **kwargs)
  File "app/api/helpers/permissions.py", line 43, in decorator
    return fn(*args, **kwargs)
  File "app/api/helpers/permission_manager.py", line 109, in is_user_itself
    if not user.is_admin and not user.is_super_admin and user.id != kwargs['id']:
```


Discussion:

Resolving patch:
diff --git a/app/api/access_codes.py b/app/api/access_codes.py
--- a/app/api/access_codes.py
+++ b/app/api/access_codes.py
@@ -53,7 +53,7 @@ def query(self, view_kwargs):
         query_ = event_query(self, query_, view_kwargs, permission='is_coorganizer')
         if view_kwargs.get('user_id'):
             user = safe_query(self, User, 'id', view_kwargs['user_id'], 'user_id')
-            if not has_access('is_user_itself', user_id=user.id):
+            if not has_access('is_user_itself', id=user.id):
                 raise ForbiddenException({'source': ''}, 'Access Forbidden')
             query_ = query_.join(User).filter(User.id == user.id)
         if view_kwargs.get('ticket_id'):


Test patch:
Repository: fossasia/open-event-server

Issue:
Broken User Events Relationship
**I'm submitting a ...**
- [x] bug report

**Current behavior:**
Created an event. 
It is available using events endpoint - `http://open-event-api.herokuapp.com/v1/events/326`
but events for the user is returning 0 items - `http://open-event-api.herokuapp.com/v1/users/81/events`


Discussion:
Can you make sure the proper "UsersEventsRole" entries are there because this endpoint is working fine here on my nextgen branch. Ensure that user with ID 81 has any access on any events other than just Attendee

Resolving patch:
diff --git a/app/api/roles.py b/app/api/roles.py
--- a/app/api/roles.py
+++ b/app/api/roles.py
@@ -7,6 +7,7 @@
 from app.models.role import Role
 from app.models.role_invite import RoleInvite
 from app.models.users_events_role import UsersEventsRoles
+from app.api.helpers.exceptions import UnprocessableEntity
 
 
 class RoleList(ResourceList):
@@ -39,6 +40,22 @@ def before_get_object(self, view_kwargs):
                 else:
                     view_kwargs['id'] = None
 
+    def before_update_object(self, role, data, view_kwargs):
+        """
+        Method to edit object
+        :param role:
+        :param data:
+        :param view_kwargs:
+        :return:
+        """
+        if data.get('name'):
+            if data['name'] in ['organizer', 'coorganizer', 'registrar', 'moderator', 'attendee', 'track_organizer']:
+                raise UnprocessableEntity({'data': 'name'}, "The given name cannot be updated")
+
+    def before_delete_object(self, obj, kwargs):
+        if obj.name in ['organizer', 'coorganizer', 'registrar', 'moderator', 'attendee', 'track_organizer']:
+            raise UnprocessableEntity({'data': 'name'}, "The resource with given name cannot be deleted")
+
     decorators = (api.has_permission('is_admin', methods="PATCH,DELETE"),)
     schema = RoleSchema
     data_layer = {'session': db.session,


Test patch:
Repository: fossasia/open-event-server

Issue:
Add frontend_url field in the documentation of settings API
###### Original issue submitted by @CosmicCoder96 in https://github.com/fossasia/open-event-frontend/issues/705
---
The signup link people receive signing up on the front-end is not a link.

![screenshot from 2017-08-13 20-56-03](https://user-images.githubusercontent.com/1583873/29252545-e7dc5662-8069-11e7-93be-dd02b3e318b6.png)


Discussion:
@CosmicCoder96 please re-check this. The frontend_url was missing from the settings table. I have added it now. The docs need to be updated about the frontend_url field.

Also there might be some issue in the code. @poush can you please look into it?
@SaptakS  Sure

Resolving patch:
diff --git a/app/factories/setting.py b/app/factories/setting.py
--- a/app/factories/setting.py
+++ b/app/factories/setting.py
@@ -103,3 +103,5 @@ class Meta:
     #
     android_app_url = common.url_
     web_app_url = common.url_
+
+    frontend_url = common.url_


Test patch:
Repository: fossasia/open-event-server

Issue:
Not allowing attendee POST request
**I'm submitting a ...**
- [x] bug report

**Current behavior:**
Created a new event with new user account. Created a free ticket for the event. for create attendee request the response is:
```
"errors": [
        {
            "status": 403,
            "source": {
                "source": "event_id"
            },
            "detail": "Access Forbidden",
            "title": "Access Forbidden"
        }
    ],
    "jsonapi": {
        "version": "1.0"
    }
}
```


Discussion:

Resolving patch:
diff --git a/app/api/attendees.py b/app/api/attendees.py
--- a/app/api/attendees.py
+++ b/app/api/attendees.py
@@ -30,9 +30,8 @@ def before_post(self, args, kwargs, data):
         :return:
         """
         require_relationship(['ticket', 'event'], data)
-        if not has_access('is_coorganizer', event_id=data['event']):
-            raise ForbiddenException({'source': 'event_id'}, "Access Forbidden")
 
+    decorators = (jwt_required,)
     methods = ['POST']
     schema = AttendeeSchema
     data_layer = {'session': db.session,


Test patch:
Repository: fossasia/open-event-server

Issue:
User API: The 'last-accessed-at' attribute in user api response is null for every user.
**I'm submitting a ...**  (check one with "x")
- [x] bug report
- [ ] feature request
- [ ] support request => Please do not submit support requests here, instead ask your query in out Gitter channel at https://gitter.im/fossasia/open-event-orga-server

For every user, I am getting the 'last-accessed-at' as null.


Discussion:
@poush Any ETA on this one?

Resolving patch:
diff --git a/app/api/helpers/permissions.py b/app/api/helpers/permissions.py
--- a/app/api/helpers/permissions.py
+++ b/app/api/helpers/permissions.py
@@ -1,11 +1,11 @@
 from functools import wraps
 from flask import current_app as app
 from flask_jwt import _jwt_required, current_identity
-from app.api.helpers.errors import ForbiddenError, NotFoundError
+
+from app.api.helpers.db import save_to_db
+from app.api.helpers.errors import ForbiddenError
 from flask import request
-from sqlalchemy.orm.exc import NoResultFound
-from app.models import db
-from app.models.email_notification import EmailNotification
+from datetime import datetime
 
 
 def second_order_decorator(inner_dec):
@@ -40,6 +40,8 @@ def jwt_required(fn, realm=None):
     @wraps(fn)
     def decorator(*args, **kwargs):
         _jwt_required(realm or app.config['JWT_DEFAULT_REALM'])
+        current_identity.last_accessed_at = datetime.utcnow()
+        save_to_db(current_identity)
         return fn(*args, **kwargs)
 
     return decorator


Test patch:
Repository: fossasia/open-event-server

Issue:
AttributeError: 'unicode' object has no attribute 'id'
https://sentry.eventyay.com/eventyay/dev-api/issues/128/

```
AttributeError: 'unicode' object has no attribute 'id'
(13 additional frame(s) were not displayed)
...
  File "app/api/helpers/permission_manager.py", line 436, in permission_manager
    return permissions[args[0]](view, view_args, view_kwargs, *args, **kwargs)
  File "app/api/helpers/permissions.py", line 45, in decorator
    return fn(*args, **kwargs)
  File "app/api/helpers/permission_manager.py", line 111, in is_user_itself
    return view(*view_args, **view_kwargs)
  File "app/api/users.py", line 182, in after_update_object
    send_email_change_user_email(user.email, view_kwargs.get('email_changed'))
  File "app/api/helpers/mail.py", line 275, in send_email_change_user_email
    link = make_frontend_url('/email/verify'.format(id=user.id), {'token': hash})

AttributeError: 'unicode' object has no attribute 'id'
```


Discussion:

Resolving patch:
diff --git a/app/api/users.py b/app/api/users.py
--- a/app/api/users.py
+++ b/app/api/users.py
@@ -179,7 +179,7 @@ def after_update_object(self, user, data, view_kwargs):
         :return:
         """
         if view_kwargs.get('email_changed'):
-            send_email_change_user_email(user.email, view_kwargs.get('email_changed'))
+            send_email_change_user_email(user, view_kwargs.get('email_changed'))
 
     decorators = (api.has_permission('is_user_itself', fetch="user_id,id", fetch_as="id",
                   model=[Notification, Feedback, UsersEventsRoles, Session, EventInvoice, AccessCode,


Test patch:
Repository: fossasia/open-event-server

Issue:
NoResultFound: No row was found for one()
https://sentry.eventyay.com/eventyay/dev-api/issues/96/

```
NoResultFound: No row was found for one()
(16 additional frame(s) were not displayed)
...
  File "app/api/helpers/permission_manager.py", line 436, in permission_manager
    return permissions[args[0]](view, view_args, view_kwargs, *args, **kwargs)
  File "app/api/helpers/permission_manager.py", line 286, in create_event
    return view(*view_args, **view_kwargs)
  File "app/api/schema/events.py", line 23, in validate_date
    event = Event.query.filter_by(id=original_data['data']['id']).one()

NoResultFound: No row was found for one()
```


Discussion:
Can i take up this issue?
@vaibhavsingh97 Have you setup the nextgen branch locally? If you've setup the nextgen branch locally, please go ahead.
@shubham-padia I am trying to setup but faiing while installing requirements from `requirement.txt`.
```
Collecting librabbitmq==1.5.1 (from -r requirements/common.txt (line 24))
  Using cached librabbitmq-1.5.1.tar.gz
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-build-4xlg7rh9/librabbitmq/setup.py", line 199
        except Exception, exc:
                        ^
    SyntaxError: invalid syntax
    
    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-4xlg7rh9/librabbitmq/
```
I tried all the possible way, i failed 😞 
OS: Arch Linux
Python version: 3.6.2
`Linux deathping 4.12.12-1-ARCH #1 SMP PREEMPT Sun Sep 10 09:41:14 CEST 2017 x86_64 GNU/Linux`

The project uses python2, please make sure you're not using python 3. Use `pip2` instead of `pip`.
@shubham-padia How to reproduce? Please guide

Resolving patch:
diff --git a/app/api/schema/events.py b/app/api/schema/events.py
--- a/app/api/schema/events.py
+++ b/app/api/schema/events.py
@@ -20,7 +20,7 @@ class Meta:
     @validates_schema(pass_original=True)
     def validate_date(self, data, original_data):
         if 'id' in original_data['data']:
-            event = Event.query.filter_by(id=original_data['data']['id']).one()
+            event = Event.query.filter_by(id=original_data['data']['id']).first()
 
             if 'starts_at' not in data:
                 data['starts_at'] = event.starts_at


Test patch:
Repository: fossasia/open-event-server

Issue:
KeyError: 'checkin_times'
https://sentry.eventyay.com/eventyay/dev-api/issues/102/

```
KeyError: 'checkin_times'
(9 additional frame(s) were not displayed)
...
  File "app/api/helpers/permissions.py", line 43, in decorator
    return fn(*args, **kwargs)
  File "app/api/attendees.py", line 125, in before_update_object
    if obj.checkin_times and data['checkin_times'] not in obj.checkin_times.split(","):

KeyError: 'checkin_times'
```


Discussion:
I have done the Local installation. I would like to work on this. How do we get access to the link mentioned in the issue ?
All the info required is mentioned in the issue itself. The link is only for reference purposes for maintainers. Cheers :)
@shubham-padia Can you help me to reproduce the error. Currently when a send `PATCH` request at `/v1/attendees/{attendee_id}` it successfully executes.
I want to work on this bug.
@bhaveshtyagi Please look for a different issue to work upon :smile:
@ananyo2012 is already working on this
@shubham-padia Can you please review my PR #4486 ?

Resolving patch:
diff --git a/app/api/attendees.py b/app/api/attendees.py
--- a/app/api/attendees.py
+++ b/app/api/attendees.py
@@ -117,13 +117,13 @@ def before_update_object(self, obj, data, kwargs):
         if not has_access('is_registrar', event_id=obj.event_id):
             raise ForbiddenException({'source': 'User'}, 'You are not authorized to access this.')
 
-        if 'is_checked_in' in data:
-            if data['is_checked_in'] and 'checkin_times' not in data:
+        if 'is_checked_in' in data and data['is_checked_in']:
+            if 'checkin_times' not in data:
                 raise UnprocessableEntity({'pointer': '/data/attributes/checkin_times'},
                                           "Check in time missing while trying to check in attendee")
-
-            if obj.checkin_times and data['checkin_times'] not in obj.checkin_times.split(","):
-                data['checkin_times'] = '{},{}'.format(obj.checkin_times, data['checkin_times'])
+            else:
+                if obj.checkin_times and data['checkin_times'] not in obj.checkin_times.split(","):
+                    data['checkin_times'] = '{},{}'.format(obj.checkin_times, data['checkin_times'])
 
     decorators = (jwt_required,)
     schema = AttendeeSchema


Test patch: