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

Issue:
No check for verified account in event update endpoint
**Describe the bug**
Verified account check is not done while updating an event. So, any unverified user can publish the event in an update request.

**To Reproduce**
Steps to reproduce the behavior:
1. Go to create event in FE
2. Click on "Forward" in the first step.
3. Click on "Publish" in the second step.
4. The event is published successfully

**Expected behavior**
Unverified users should not be allowed to publish events at all.

**Additional details (please complete the following information):**
 - OS: Ubuntu 18.04


Discussion:
can i take up this issue? @mayank8318 

Resolving patch:
diff --git a/app/api/events.py b/app/api/events.py
--- a/app/api/events.py
+++ b/app/api/events.py
@@ -419,12 +419,18 @@ def before_get_object(self, view_kwargs):
 
     def before_patch(self, args, kwargs, data=None):
         """
-        before patch method to verify if the event location is provided before publishing the event
+        before patch method to verify if the event location is provided before publishing the event and checks that
+        the user is verified
         :param args:
         :param kwargs:
         :param data:
         :return:
         """
+        is_verified = current_identity.is_verified
+        if data.get('state', None) == 'published' and not is_verified:
+            raise ForbiddenException({'source': ''},
+                                     "Only verified accounts can publish events")
+
         if data.get('state', None) == 'published' and not data.get('location_name', None):
             raise ConflictException({'pointer': '/data/attributes/location-name'},
                                     "Location is required to publish the event")
@@ -465,7 +471,8 @@ def after_update_object(self, event, data, view_kwargs):
                   'model': Event,
                   'methods': {
                       'before_update_object': before_update_object,
-                      'after_update_object': after_update_object
+                      'after_update_object': after_update_object,
+                      'before_patch': before_patch
                   }}
 
 


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

Issue:
Error Code 403 thrown on sending receipt
**Describe the bug**
When the send-receipt api for orders is called from the orga app, error code 403 is thrown i.e HTTP 403 FORBIDDEN. Event though I am the organizer and I have created the order, I am not able to send the receipt.

**Stacktrace**
```
<-- 403 FORBIDDEN https://open-event-api-dev.herokuapp.com/v1/attendees/send-receipt (382ms)
07-31 11:36:36.427 6773-6821/com.eventyay.organizer D/OkHttp: Connection: keep-alive
    Server: gunicorn/19.8.1
    Date: Tue, 31 Jul 2018 06:06:37 GMT
    Content-Type: application/json
    Content-Length: 73
    Access-Control-Allow-Origin: *
    Via: 1.1 vegur
    {
07-31 11:36:36.428 6773-6821/com.eventyay.organizer D/OkHttp:   "error": "You cannot send reciept for an order not created by you"
    }
    <-- END HTTP (73-byte body)
```


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
@@ -203,8 +203,10 @@ class AttendeeRelationshipOptional(ResourceRelationship):
 @attendee_misc_routes.route('/attendees/send-receipt', methods=['POST'])
 @jwt_required
 def send_receipt():
-    # Function to send receipts to attendees related to the provided order.
-
+    """
+    Send receipts to attendees related to the provided order.
+    :return:
+    """
     order_identifier = request.json.get('order-identifier')
     if order_identifier:
         try:
@@ -212,9 +214,9 @@ def send_receipt():
         except NoResultFound:
             raise ObjectNotFound({'parameter': '{identifier}'}, "Order not found")
 
-        if order.user_id != current_identity.id:
+        if (order.user_id != current_identity.id) and (not has_access('is_registrar', event_id=order.event_id)):
             abort(
-                make_response(jsonify(error="You cannot send reciept for an order not created by you"), 403)
+                make_response(jsonify(error="You need to be the event organizer or order buyer to send receipts."), 403)
             )
         elif order.status != 'completed':
             abort(
diff --git a/app/api/orders.py b/app/api/orders.py
--- a/app/api/orders.py
+++ b/app/api/orders.py
@@ -394,7 +394,7 @@ class ChargeList(ResourceList):
 
 @order_misc_routes.route('/orders/<string:order_identifier>/create-paypal-payment', methods=['POST'])
 @jwt_required
-def create_payment_payment(order_identifier):
+def create_paypal_payment(order_identifier):
     """
     Create a paypal payment.
     :return: The payment id of the created payment.


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

Issue:
Make field_identifiers for attendee custom form consistent with the model  
**Describe the bug**
Field identifier for the fields first-name and last-name are `firstName` and `lastName` respectively but the fields in the ticket_holder model are `firstname` and `lastname` respectively. Hence, there are complications while displaying the form in the frontend.

**Expected behavior**
This should be consistent with the fields in the concerned table.


Discussion:

Resolving patch:
diff --git a/app/api/helpers/events.py b/app/api/helpers/events.py
--- a/app/api/helpers/events.py
+++ b/app/api/helpers/events.py
@@ -17,10 +17,10 @@ def create_custom_forms_for_attendees(event):
     form_type = 'text'
 
     first_name_form = CustomForms(form=form, is_required=is_required, is_included=is_included, is_fixed=is_fixed,
-                                  event_id=event_id, type=form_type, field_identifier='firstName')
+                                  event_id=event_id, type=form_type, field_identifier='firstname')
 
     last_name_form = CustomForms(form=form, is_required=is_required, is_included=is_included, is_fixed=is_fixed,
-                                 event_id=event_id, type=form_type, field_identifier='lastName')
+                                 event_id=event_id, type=form_type, field_identifier='lastname')
 
     email_form = CustomForms(form=form, is_required=is_required, is_included=is_included, is_fixed=is_fixed,
                              event_id=event_id, type='email', field_identifier='email')
diff --git a/migrations/versions/4c687e52449b_.py b/migrations/versions/4c687e52449b_.py
new file mode 100644
--- /dev/null
+++ b/migrations/versions/4c687e52449b_.py
@@ -0,0 +1,34 @@
+"""empty message
+
+Revision ID: 4c687e52449b
+Revises: f375453ca1f6
+Create Date: 2018-08-01 14:49:04.066424
+
+"""
+
+from alembic import op
+import sqlalchemy as sa
+import sqlalchemy_utils
+
+
+# revision identifiers, used by Alembic.
+revision = '4c687e52449b'
+down_revision = 'f375453ca1f6'
+
+
+def upgrade():
+    # ### commands auto generated by Alembic - please adjust! ###
+    # ### end Alembic commands ###
+    custom_forms_table = sa.sql.table('custom_forms', sa.Column('field_identifier', sa.String()))
+    op.execute(custom_forms_table.update()
+               .where(custom_forms_table.c.field_identifier == 'firstName')
+               .values({'field_identifier': 'firstname'}))
+    op.execute(custom_forms_table.update()
+               .where(custom_forms_table.c.field_identifier == 'lastName')
+               .values({'field_identifier': 'lastname'}))
+
+
+def downgrade():
+    # ### commands auto generated by Alembic - please adjust! ###
+    pass
+    # ### end Alembic commands ###


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

Issue:
Inconsistent data on Admin Statistics end points
**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-server

**Current behavior:**
<!-- Describe how the bug manifests. -->
The admin statistics end points return various stats about events, users etc.
Currently they are completely out of sync with the database.
For instance, the `admin/statisitics/events` returns 
![image](https://user-images.githubusercontent.com/17252805/39888957-1a5daf72-54b4-11e8-934c-1d77a9ab66b7.png)

Where as the actual event count when generically querying for events is 92:
![image](https://user-images.githubusercontent.com/17252805/39889011-44af3d9a-54b4-11e8-8fb8-c45b0cef175d.png)

**Expected behavior:**
<!-- Describe what the behavior would be without the bug. -->
The counts should be consistent.


Discussion:
I would like to work on this issue.

Edited: actually, meta -> count tells the no of events in that page. (probably tells how many events schemas returned in that page)
After going to `v1/events?page%5Bnumber%5D=2` one will find that more events are coming which last till page (5 in Insomnia app due to count=88) (4 in Postman app due to count=92 )

```
"links": {
		"self": "/v1/events",
		"next": "/v1/events?page%5Bnumber%5D=2",
		"first": "/v1/events",
		"last": "/v1/events?page%5Bnumber%5D=4"
}
```
Please check this @CosmicCoder96 
@bhaveshAn Yeah, that seems to be true, but I think there is still a mismatch because the admin dashboard shows around 716 events 
![image](https://user-images.githubusercontent.com/17252805/39907157-76db9476-5504-11e8-9408-fee67cf85a6d.png)
Where as according to the returned statistics by the end point total events are 
715 + 410 + 147, Can you have a look :) ? Thanks !
![image](https://user-images.githubusercontent.com/17252805/39907170-90e05d66-5504-11e8-8ad1-c892bd53c808.png)


Resolving patch:
diff --git a/app/api/schema/admin_statistics_schema/events.py b/app/api/schema/admin_statistics_schema/events.py
--- a/app/api/schema/admin_statistics_schema/events.py
+++ b/app/api/schema/admin_statistics_schema/events.py
@@ -25,10 +25,12 @@ class Meta:
     past = fields.Method("events_past_count")
 
     def events_draft_count(self, obj):
-        return get_count(Event.query.filter_by(state='draft'))
+        events = Event.query.filter(Event.ends_at > datetime.now(pytz.utc))
+        return get_count(events.filter_by(state='draft'))
 
     def events_published_count(self, obj):
-        return get_count(Event.query.filter_by(state='published'))
+        events = Event.query.filter(Event.ends_at > datetime.now(pytz.utc))
+        return get_count(events.filter_by(state='published'))
 
     def events_past_count(self, obj):
         return get_count(Event.query.filter(Event.ends_at < datetime.now(pytz.utc)))


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

Issue:
Travis Build failure due to multiple migration  heads
**Describe the bug**
<!-- A clear and concise description of what the bug is. -->
Travis Build failure dure to multiple migration  heads
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error

**Expected behavior**
<!-- A clear and concise description of what you expected to happen. -->

**Stacktrace**
<!-- If applicable, add stacktrace to help explain your problem. -->

**Additional details (please complete the following information):**
 - OS: [e.g. MacOS, Ubuntu, CentOS]
 - Python Version [e.g. `3.5`, `3.6`]
 - `HEAD` Commit hash [e.g. `4629c62`]

**Additional context**
<!-- Add any other context about the problem here. -->
![screenshot from 2018-08-02 12-53-22](https://user-images.githubusercontent.com/22936570/43568785-3167391e-9653-11e8-8c09-3014bd38f130.png)



Discussion:

Resolving patch:
diff --git a/migrations/versions/0044c9631c7e_.py b/migrations/versions/0044c9631c7e_.py
deleted file mode 100644
--- a/migrations/versions/0044c9631c7e_.py
+++ /dev/null
@@ -1,27 +0,0 @@
-"""empty message
-
-Revision ID: 0044c9631c7e
-Revises: 4c687e52449b
-Create Date: 2018-08-01 15:09:21.572471
-
-"""
-
-from alembic import op
-import sqlalchemy as sa
-
-
-# revision identifiers, used by Alembic.
-revision = '0044c9631c7e'
-down_revision = '4c687e52449b'
-
-
-def upgrade():
-    # ### commands auto generated by Alembic - please adjust! ###
-    op.add_column('event_chat_message', sa.Column('label', sa.String(), nullable=False))
-    # ### end Alembic commands ###
-
-
-def downgrade():
-    # ### commands auto generated by Alembic - please adjust! ###
-    op.drop_column('event_chat_message', 'label')
-    # ### end Alembic commands ###
diff --git a/migrations/versions/4c687e52449b_.py b/migrations/versions/4c687e52449b_.py
--- a/migrations/versions/4c687e52449b_.py
+++ b/migrations/versions/4c687e52449b_.py
@@ -13,7 +13,7 @@
 
 # revision identifiers, used by Alembic.
 revision = '4c687e52449b'
-down_revision = 'f375453ca1f6'
+down_revision = '81ac738516a0'
 
 
 def upgrade():


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

Issue:
Inconsistent data on admin users statistics
**Describe the bug**
<!-- A clear and concise description of what the bug is. -->

Inconsistent data on admin users statistics

1. Super admin is also counted in Admin users stats
2. If admins are verified or not, it should neither be included in verified users stats nor unverified users stats.

**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error

**Expected behavior**
<!-- A clear and concise description of what you expected to happen. -->

**Stacktrace**
<!-- If applicable, add stacktrace to help explain your problem. -->

**Additional details (please complete the following information):**
 - OS: [e.g. MacOS, Ubuntu, CentOS]
 - Python Version [e.g. `3.5`, `3.6`]
 - `HEAD` Commit hash [e.g. `4629c62`]

**Additional context**
<!-- Add any other context about the problem here. -->
**Wanna work on this issue**


Discussion:

Resolving patch:
diff --git a/app/api/admin_statistics_api/users.py b/app/api/admin_statistics_api/users.py
--- a/app/api/admin_statistics_api/users.py
+++ b/app/api/admin_statistics_api/users.py
@@ -39,13 +39,13 @@ def super_admin_count(self, obj):
         return get_count(User.query.filter_by(is_super_admin=True))
 
     def admin_count(self, obj):
-        return get_count(User.query.filter_by(is_admin=True))
+        return get_count(User.query.filter_by(is_admin=True, is_super_admin=False))
 
     def verified_count(self, obj):
-        return get_count(User.query.filter_by(is_verified=True))
+        return get_count(User.query.filter_by(is_verified=True, is_super_admin=False, is_admin=False))
 
     def unverified_count(self, obj):
-        return get_count(User.query.filter_by(is_verified=False))
+        return get_count(User.query.filter_by(is_verified=False, is_super_admin=False, is_admin=False))
 
     def get_all_user_roles(self, role_name):
         role = Role.query.filter_by(name=role_name).first()


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

Issue:
HTTP 500 on updating user email
**Describe the bug**
<!-- A clear and concise description of what the bug is. -->
HTTP 500 is raised when email is updated in user contact details

**To Reproduce**
Steps to reproduce the behavior:
1. `PATCH` a user with an email that already exists in the database for a different user.


**Expected behavior**
<!-- A clear and concise description of what you expected to happen. -->
Email should be updated successfully.

Working on fixing this error.


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
@@ -3,6 +3,7 @@
 from flask import Blueprint, request, jsonify, abort, make_response
 from flask_jwt import current_identity as current_user
 from flask_rest_jsonapi import ResourceDetail, ResourceList, ResourceRelationship
+from sqlalchemy.orm.exc import NoResultFound
 
 from app import get_settings
 from app.api.bootstrap import api
@@ -181,7 +182,12 @@ def before_update_object(self, user, data, view_kwargs):
             data['icon_image_url'] = uploaded_images['icon_image_url']
 
         if data.get('email') and data['email'] != user.email:
-            view_kwargs['email_changed'] = user.email
+            try:
+                db.session.query(User).filter_by(email=data['email']).one()
+            except NoResultFound:
+                view_kwargs['email_changed'] = user.email
+            else:
+                raise ConflictException({'pointer': '/data/attributes/email'}, "Email already exists")
 
         if has_access('is_super_admin') and data.get('is_admin') != user.is_admin:
             user.is_admin = not user.is_admin


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

Issue:
Return Notification actions as a relationship rather than an embedded list.
**Is your feature request related to a problem? Please describe.**
<!-- A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] -->
Right now the notification actions as sent as an embedded list rather than as a relationship. The JSON API spec doesn't specify clearly about embedded lists and hence we should switch to actions as a relationship.


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
@@ -120,6 +120,8 @@
 api.route(NotificationDetail, 'notification_detail', '/notifications/<int:id>')
 api.route(NotificationRelationship, 'notification_user',
           '/notifications/<int:id>/relationships/user')
+api.route(NotificationRelationship, 'notification_actions',
+          '/notifications/<int:id>/relationships/actions')
 
 # email_notifications
 api.route(EmailNotificationListAdmin, 'email_notification_list_admin', '/email-notifications')
diff --git a/app/api/schema/notifications.py b/app/api/schema/notifications.py
--- a/app/api/schema/notifications.py
+++ b/app/api/schema/notifications.py
@@ -14,7 +14,7 @@ class Meta:
         """
         Meta class for Notification Action API schema
         """
-        type_ = 'notification_action'
+        type_ = 'notification-action'
         inflect = dasherize
 
     id = fields.Str(dump_only=True)
@@ -44,7 +44,10 @@ class Meta:
     received_at = fields.DateTime(dump_only=True)
     accept = fields.Str(allow_none=True, dump_only=True)
     is_read = fields.Boolean()
-    actions = fields.List(cls_or_instance=fields.Nested(NotificationActionSchema), allow_none=True, dump_only=True)
+    actions = Relationship(attribute='actions',
+                           schema='NotificationActionSchema',
+                           many=True,
+                           type_='notification-action')
     user = Relationship(attribute='user',
                         self_view='v1.notification_user',
                         self_view_kwargs={'id': '<id>'},


Test patch:
diff --git a/tests/hook_main.py b/tests/hook_main.py
--- a/tests/hook_main.py
+++ b/tests/hook_main.py
@@ -2030,6 +2030,24 @@ def notification_get_detail(transaction):
         db.session.commit()
 
 
+@hooks.before("Notifications > Notification Detail with Actions > Notification Detail with Actions")
+def notification_get_detail_with_actions(transaction):
+    """
+    GET /notifications/1?include=actions
+    :param transaction:
+    :return:
+    """
+    with stash['app'].app_context():
+        notification_action = NotificationActionFactory()
+        db.session.add(notification_action)
+        db.session.commit()
+
+        notification = NotificationFactory()
+        notification.actions = [notification_action]
+        db.session.add(notification)
+        db.session.commit()
+
+
 @hooks.before("Notifications > Notification Detail > Update Notification")
 def notification_patch(transaction):
     """
Repository: fossasia/open-event-server

Issue:
Update subject and action-type in notification action for easy integration.
**Is your feature request related to a problem? Please describe.**
<!-- A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] -->
Update subject and action-type in notification action for easy integration in the frontend. 



Discussion:

Resolving patch:
diff --git a/app/api/helpers/system_notifications.py b/app/api/helpers/system_notifications.py
--- a/app/api/helpers/system_notifications.py
+++ b/app/api/helpers/system_notifications.py
@@ -51,7 +51,7 @@ def get_event_imported_actions(event_id, event_url):
     :return: actions
     """
     view_event_action = NotificationAction(
-        subject='event-import',
+        subject='event',  # subject is still 'event' since the action will be to view the imported event.
         link=event_url,
         subject_id=event_id,
         action_type='view'
@@ -85,7 +85,7 @@ def get_monthly_payment_follow_up_notification_actions(event_id, payment_url):
     :return: actions
     """
     view_invoice_action = NotificationAction(
-        subject='event',
+        subject='invoice',
         link=payment_url,
         subject_id=event_id,
         action_type='view'
@@ -118,7 +118,7 @@ def get_ticket_purchased_attendee_notification_actions(pdf_url):
     :return: actions
     """
     view_ticket_action = NotificationAction(
-        subject='order',
+        subject='tickets-pdf',
         link=pdf_url,
         action_type='view'
     )


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

Issue:
type property in schema of event_role_permission has type
**Describe the bug**
type in schema of event_role_permission api should be **event-role-permission** not **event-role-permissions**



Discussion:

Resolving patch:
diff --git a/app/api/schema/event_role_permissions.py b/app/api/schema/event_role_permissions.py
--- a/app/api/schema/event_role_permissions.py
+++ b/app/api/schema/event_role_permissions.py
@@ -15,7 +15,7 @@ class Meta:
         """
         Meta class for Notification API schema
         """
-        type_ = 'event-role-permissions'
+        type_ = 'event-role-permission'
         self_view = 'v1.events_role_detail'
         self_view_kwargs = {'id': '<id>'}
         self_view_many = 'v1.events_role_list'


Test patch: