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

Issue:
Internal Server Error thrown for patching a nonexistent session
**Describe the bug**
<!-- A clear and concise description of what the bug is. -->
HTTP 500 error is thrown when a patch request is sent for a session which doesn't exist.

**To Reproduce**
Steps to reproduce the behavior:
1. Send a patch request for a session which doesn't exist

**Expected behavior**
<!-- A clear and concise description of what you expected to happen. -->
A proper error should be sent.

Working on fixing this.


Discussion:

Resolving patch:
diff --git a/app/api/schema/sessions.py b/app/api/schema/sessions.py
--- a/app/api/schema/sessions.py
+++ b/app/api/schema/sessions.py
@@ -1,6 +1,8 @@
+from flask_rest_jsonapi.exceptions import ObjectNotFound
 from marshmallow import validates_schema, validate
 from marshmallow_jsonapi import fields
 from marshmallow_jsonapi.flask import Relationship
+from sqlalchemy.orm.exc import NoResultFound
 
 from app.api.helpers.exceptions import UnprocessableEntity, ForbiddenException
 from app.api.helpers.permission_manager import has_access
@@ -28,7 +30,10 @@ class Meta:
     @validates_schema(pass_original=True)
     def validate_date(self, data, original_data):
         if 'id' in original_data['data']:
-            session = Session.query.filter_by(id=original_data['data']['id']).one()
+            try:
+                session = Session.query.filter_by(id=original_data['data']['id']).one()
+            except NoResultFound:
+                raise ObjectNotFound({'parameter': '{id}'}, "Session: not found")
 
             if 'starts_at' not in data:
                 data['starts_at'] = session.starts_at


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

Issue:
Orders export tasks fails as a column name has been changed
**Describe the bug**
Orders export tasks fail as a method `get_tickets_count()` was removed and added as a property `tickets_count`.

**To Reproduce**
Steps to reproduce the behavior:
1. Use any of the orders export endpoints

**Expected behavior**
Export should work normally

**Stacktrace**
```sh
  File "/home/mayank/OpenSource/open-event-server/app/api/helpers/tasks.py", line 275, in export_order_pdf_task
    discount_code=discount_code),
  File "/home/mayank/anaconda3/envs/openevent3/lib/python3.6/site-packages/flask/templating.py", line 135, in render_template
    context, ctx.app)
  File "/home/mayank/anaconda3/envs/openevent3/lib/python3.6/site-packages/flask/templating.py", line 117, in _render
    rv = template.render(context)
  File "/home/mayank/anaconda3/envs/openevent3/lib/python3.6/site-packages/jinja2/asyncsupport.py", line 76, in render
    return original_render(self, *args, **kwargs)
  File "/home/mayank/anaconda3/envs/openevent3/lib/python3.6/site-packages/jinja2/environment.py", line 1008, in render
    return self.environment.handle_exception(exc_info, True)
  File "/home/mayank/anaconda3/envs/openevent3/lib/python3.6/site-packages/jinja2/environment.py", line 780, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/home/mayank/anaconda3/envs/openevent3/lib/python3.6/site-packages/jinja2/_compat.py", line 37, in reraise
    raise value.with_traceback(tb)
  File "/home/mayank/OpenSource/open-event-server/app/templates/pdf/orders.html", line 93, in top-level template code
    {{ order.get_tickets_count() }}<br>
jinja2.exceptions.UndefinedError: 'app.models.order.Order object' has no attribute 'get_tickets_count'
```


Discussion:

Resolving patch:
diff --git a/app/api/helpers/csv_jobs_util.py b/app/api/helpers/csv_jobs_util.py
--- a/app/api/helpers/csv_jobs_util.py
+++ b/app/api/helpers/csv_jobs_util.py
@@ -10,7 +10,7 @@ def export_orders_csv(orders):
         if order.status != "deleted":
             column = [str(order.get_invoice_number()), str(order.created_at) if order.created_at else '',
                       str(order.status) if order.status else '', str(order.paid_via) if order.paid_via else '',
-                      str(order.amount) if order.amount else '', str(order.get_tickets_count()),
+                      str(order.amount) if order.amount else '', str(order.tickets_count),
                       str(order.discount_code.code) if order.discount_code else '',
                       str(order.user.first_name)
                       if order.user and order.user.first_name else '',


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

Issue:
Discount code api response does not contain tickets
**Describe the bug**
A request to http://localhost:5000/v1/discount-codes/DC-102 does not return tickets 

**Expected behavior**
Tickets should be there in api response.


Discussion:

Resolving patch:
diff --git a/app/api/discount_codes.py b/app/api/discount_codes.py
--- a/app/api/discount_codes.py
+++ b/app/api/discount_codes.py
@@ -320,7 +320,7 @@ def before_delete_object(self, discount, view_kwargs):
             raise UnprocessableEntity({'source': ''}, "Please verify your permission")
 
     decorators = (jwt_required,)
-    schema = DiscountCodeSchemaPublic
+    schema = DiscountCodeSchemaTicket
     data_layer = {'session': db.session,
                   'model': DiscountCode,
                   'methods': {


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

Issue:
Unverified users can place an order
**Describe the bug**
Unverified users are allowed to place an order. This is a big security flaw and needs to be addressed immediately.

**Expected behavior**
Unverified users should be allowed to place an order.

**Additional context**
https://github.com/fossasia/open-event-frontend/issues/1616


Discussion:

Resolving patch:
diff --git a/app/api/orders.py b/app/api/orders.py
--- a/app/api/orders.py
+++ b/app/api/orders.py
@@ -50,6 +50,10 @@ def before_post(self, args, kwargs, data=None):
         """
         require_relationship(['event'], data)
 
+        if not current_user.is_verified:
+            raise ForbiddenException({'source': ''},
+                                     "Only verified accounts can place orders")
+
         # Create on site attendees.
         if request.args.get('onsite', False):
             create_onsite_attendees_for_order(data)


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

Issue:
Use DiscountCodeSchemaTicket when fetching Discount code via it's code.
**Describe the bug**
<!-- A clear and concise description of what the bug is. -->
We need to use DiscountCodeSchemaTicket when fetching Discount code via it's code.


Discussion:

Resolving patch:
diff --git a/app/api/discount_codes.py b/app/api/discount_codes.py
--- a/app/api/discount_codes.py
+++ b/app/api/discount_codes.py
@@ -211,7 +211,7 @@ def before_get(self, args, kwargs):
             else:
                 raise ObjectNotFound({'parameter': '{code}'}, "DiscountCode: not found")
 
-            self.schema = DiscountCodeSchemaPublic
+            self.schema = DiscountCodeSchemaTicket
             return
 
         if kwargs.get('id'):


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

Issue:
Sort message-settings by id
**Describe the bug**
<!-- A clear and concise description of what the bug is. -->
Sort message-settings by id

**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/message_settings.py b/app/api/message_settings.py
--- a/app/api/message_settings.py
+++ b/app/api/message_settings.py
@@ -10,11 +10,23 @@ class MessageSettingsList(ResourceList):
     """
     List Events Role Permission
     """
+    def query(self, view_kwargs):
+        """
+        query method for Message Setting List
+        :param view_kwargs:
+        :return:
+        """
+        query_ = db.session.query(MessageSettings).order_by(MessageSettings.id)
+        return query_
+
     decorators = (api.has_permission('is_admin', methods="GET"),)
     methods = ['GET']
     schema = MessageSettingSchema
     data_layer = {'session': db.session,
-                  'model': MessageSettings}
+                  'model': MessageSettings,
+                  'methods': {
+                      'query': query
+                  }}
 
 
 class MessageSettingsDetail(ResourceDetail):


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

Issue:
Add checker in modules to not support donations in system
**Describe the bug**
<!-- A clear and concise description of what the bug is. -->
Add checker in modules to not support donations in system

**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/modules.py b/app/api/modules.py
--- a/app/api/modules.py
+++ b/app/api/modules.py
@@ -4,6 +4,7 @@
 from app.api.schema.modules import ModuleSchema
 from app.models import db
 from app.models.module import Module
+from app.api.helpers.exceptions import ConflictException
 
 
 class ModuleDetail(ResourceDetail):
@@ -20,8 +21,21 @@ def before_get(self, args, kwargs):
         """
         kwargs['id'] = 1
 
+    def before_patch(self, args, kwargs, data=None):
+        """
+        before patch method to verify if admin enables the donations in system
+        :param args:
+        :param kwargs:
+        :param data:
+        :return:
+        """
+        if data.get('donation_include'):
+            raise ConflictException({'pointer': '/data/attributes/donation-include'},
+                                    "No donation support in the system")
+
     decorators = (api.has_permission('is_admin', methods='PATCH', id='1'),)
     methods = ['GET', 'PATCH']
     schema = ModuleSchema
     data_layer = {'session': db.session,
-                  'model': Module}
+                  'model': Module,
+                  'methods': {'before_patch': before_patch}}


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

Issue:
Unverified user not able to create event even if settings are changed
**Describe the bug**
Currently unverified accounts are not able to create event even if settings allow so.

**Expected behavior**
If settings allow unverified accounts to create events then there should not be any error message.



Discussion:
Working on it.

Resolving patch:
diff --git a/app/api/events.py b/app/api/events.py
--- a/app/api/events.py
+++ b/app/api/events.py
@@ -117,8 +117,12 @@ def before_post(self, args, kwargs, data=None):
         :param data:
         :return:
         """
-        is_verified = User.query.filter_by(id=kwargs['user_id']).first().is_verified
-        if data.get('state', None) == 'published' and not is_verified:
+        user = User.query.filter_by(id=kwargs['user_id']).first()
+        if not user.can_create_event():
+            raise ForbiddenException({'source': ''},
+                                     "Only verified accounts can create events")
+
+        if data.get('state', None) == 'published' and not user.can_publish_event():
             raise ForbiddenException({'source': ''},
                                      "Only verified accounts can publish events")
 
@@ -445,8 +449,7 @@ def before_patch(self, args, kwargs, data=None):
         :param data:
         :return:
         """
-        is_verified = current_identity.is_verified
-        if data.get('state', None) == 'published' and not is_verified:
+        if data.get('state', None) == 'published' and not current_identity.can_publish_event():
             raise ForbiddenException({'source': ''},
                                      "Only verified accounts can publish events")
 


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

Issue:
Bug in can_publish_event method in user model
**Describe the bug**
<!-- A clear and concise description of what the bug is. -->

Bug in can_publish_event method in user model

**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/models/user.py b/app/models/user.py
--- a/app/models/user.py
+++ b/app/models/user.py
@@ -149,7 +149,10 @@ def can_publish_event(self):
         if not perm:
             return self.is_verified
 
-        return perm.unverified_user
+        if self.is_verified is False:
+            return perm.unverified_user
+
+        return True
 
     def can_create_event(self):
         """


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

Issue:
Access Forbidden on updating order
**Describe the bug**
Currently on updating order which contains discount code we get access forbidden error related to discount codes.

**Expected behavior**
Request should succeed.



Discussion:

Resolving patch:
diff --git a/app/models/order.py b/app/models/order.py
--- a/app/models/order.py
+++ b/app/models/order.py
@@ -22,7 +22,7 @@ def get_updatable_fields():
     :return: The list of fields which can be modified by the order user using the pre payment form.
     """
     return ['country', 'address', 'city', 'state', 'zipcode', 'status', 'paid_via', 'order_notes', 'deleted_at', 'user',
-            'payment_mode', 'event', 'ticket_holders', 'user', 'tickets_pdf_url']
+            'payment_mode', 'event', 'discount_code_id', 'discount_code', 'ticket_holders', 'user', 'tickets_pdf_url']
 
 
 class OrderTicket(SoftDeletionModel):


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

Issue:
Password confirmation while creating tables in local installation 
When I was installing the project locally, after running create_db.py, it didn't ask me to re-confirm the password, and password can easily be mistyped in the first time.  

So it would be better if we add password confirmation in that part.


Discussion:
Would you like to work on it? 
Yes. 
Go ahead.

Resolving patch:
diff --git a/create_db.py b/create_db.py
--- a/create_db.py
+++ b/create_db.py
@@ -17,20 +17,23 @@ def _validate_email(email):
         sys.exit(1)
 
 
-def _validate_password(password):
-    if len(password) < 4:
-        print('\nPassword should have minimum 4 characters')
-        sys.exit(1)
-
-
 def create_default_user(email, password):
     print("Your login is 'super_admin'.")
     if not email:
         email = input("Enter email for super_admin    : ")
     _validate_email(email)
     if not password:
-        password = getpass.getpass("Enter password for super_admin : ")
-    _validate_password(password)
+        ask_password = True
+        while ask_password:
+            password = getpass.getpass("Enter password for super_admin : ")
+            if len(password) < 4:
+                print('\nPassword should have minimum 4 characters')
+                continue
+            repassword = getpass.getpass("Enter your password again to confirm : ")
+            if password != repassword:
+                print('\nPassword did not match')
+                continue
+            ask_password = False
     create_super_admin(email, password)
 
 


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

Issue:
create_db.py should not exit on entering wrong e-mail
Just as we did with the password feature in create_db.py, we should allow the user to re-enter the e-mail if entered wrong. 


Discussion:

Resolving patch:
diff --git a/create_db.py b/create_db.py
--- a/create_db.py
+++ b/create_db.py
@@ -1,7 +1,6 @@
 import argparse
 import getpass
 import re
-import sys
 
 from flask_migrate import stamp
 
@@ -11,17 +10,16 @@
 from tests.unittests.auth_helper import create_super_admin
 
 
-def _validate_email(email):
-    if not re.match(r'[^@]+@[^@]+\.[^@]+', email):
-        print('\nInvalid email address')
-        sys.exit(1)
-
-
 def create_default_user(email, password):
     print("Your login is 'super_admin'.")
     if not email:
-        email = input("Enter email for super_admin    : ")
-    _validate_email(email)
+        ask_email = True
+        while ask_email:
+            email = input("Enter email for super_admin    : ")
+            if not re.match(r'[^@]+@[^@]+\.[^@]+', email):
+                print('\nInvalid email address\n')
+                continue
+            ask_email = False
     if not password:
         ask_password = True
         while ask_password:


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

Issue:
Improper exception handling in manage.py
**Describe the bug**
Exceptions are not handled properly in `initialize_db` method of `manage` module.

**To Reproduce**
Steps to reproduce the behavior:
1. Open 'manage.py'
2. See https://github.com/fossasia/open-event-server/blob/05cbd1abee0d81dd24d701420c3530e3b9bd645f/manage.py#L77

**Expected behavior**
It should follow standard exception handling format using `Exception` class.


Discussion:

Resolving patch:
diff --git a/manage.py b/manage.py
--- a/manage.py
+++ b/manage.py
@@ -74,7 +74,7 @@ def initialize_db(credentials):
             try:
                 db.create_all()
                 stamp()
-            except:
+            except Exception:
                 populate_data = False
                 print("[LOG] Could not create tables. Either database does not exist or tables already created")
             if populate_data:


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

Issue:
No verification email 
**Describe the bug**
No verification email is being sent 
**To Reproduce**
Sign up and you won't receive a verification mail

**Expected behavior**
You should receive a verification email






Discussion:
@nikit19  Actually email is also not delivered in the local setup of server.
Can i be assigned this issue


Sure. Please fix it asap.
@sladyn98 Any update ?
Ya I'm working on it I cloned the repo and it should be done by midnight.

On Thu, Sep 20, 2018, 7:12 PM Bhavesh Anand <notifications@github.com>
wrote:

> @sladyn98 <https://github.com/sladyn98> Any update ?
>
> —
> You are receiving this because you were mentioned.
> Reply to this email directly, view it on GitHub
> <https://github.com/fossasia/open-event-server/issues/5379#issuecomment-423187609>,
> or mute the thread
> <https://github.com/notifications/unsubscribe-auth/AbgGHlQjka7vDOkH5PgrFJ3pyhxC44anks5uc5s4gaJpZM4Wqs2B>
> .
>

@sladyn98 this is a high priority issue. Are you still working on it?
Yes I am


On Fri, Sep 21, 2018, 1:13 PM Nikit Bhandari <notifications@github.com>
wrote:

> @sladyn98 <https://github.com/sladyn98> this is a high priority issue.
> Are you still working on it?
>
> —
> You are receiving this because you were mentioned.
> Reply to this email directly, view it on GitHub
> <https://github.com/fossasia/open-event-server/issues/5379#issuecomment-423444451>,
> or mute the thread
> <https://github.com/notifications/unsubscribe-auth/AbgGHniXn-6d0qJ5_62npbITTUawt0iyks5udJiigaJpZM4Wqs2B>
> .
>

Where exactly is the function located?

Resolving patch:
diff --git a/app/api/helpers/mail.py b/app/api/helpers/mail.py
--- a/app/api/helpers/mail.py
+++ b/app/api/helpers/mail.py
@@ -66,7 +66,8 @@ def send_email(to, action, subject, html):
                     "Content-Type": "application/json"
                 }
                 from .tasks import send_email_task
-                send_email_task.delay(payload, headers)
+                # TODO use of send_email_task.delay() to make it asynchronous
+                send_email_task(payload, headers)
 
         # record_mail(to, action, subject, html)
         mail = Mail(


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

Issue:
Docstring in elastic_cron_helpers.py
**Describe the bug**
<!-- A clear and concise description of what the bug is. -->
Docstring in elastic_cron_helpers.py

**To Reproduce**
Steps to reproduce the behavior:
1. Go to 'Line no: 17 add Triple Quotes """ Docstring """ '
2. Repeat the same on 'Line no: 27'

**Expected behavior**
<!-- A clear and concise description of what you expected to happen. -->
Docstring or Comment. Not a String.

**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. -->



Discussion:

Resolving patch:
diff --git a/app/views/elastic_cron_helpers.py b/app/views/elastic_cron_helpers.py
--- a/app/views/elastic_cron_helpers.py
+++ b/app/views/elastic_cron_helpers.py
@@ -14,7 +14,7 @@
 
 @celery.task(name='rebuild.events.elasticsearch')
 def cron_rebuild_events_elasticsearch():
-    "Re-inserts all eligible events into elasticsearch, deletes existing events"
+    """Re-inserts all eligible events into elasticsearch, deletes existing events"""
     elastic = connect_from_config()
     session = get_session_from_config()
     rebuild_indices(client=elastic)
@@ -24,6 +24,6 @@ def cron_rebuild_events_elasticsearch():
 
 
 def sync_events_elasticsearch():
-    "Sync all newly created, updated or deleted events"
+    """Sync all newly created, updated or deleted events"""
     elastic = connect_from_config()
     elastic.sync()
diff --git a/app/views/postgres.py b/app/views/postgres.py
--- a/app/views/postgres.py
+++ b/app/views/postgres.py
@@ -4,7 +4,7 @@
 
 
 def get_session_from_config():
-    "Create a postgres session using the application config"
+    """Create a postgres session using the application config"""
     engine = create_engine(Config.SQLALCHEMY_DATABASE_URI)
     maker = sessionmaker()
     maker.configure(bind=engine)


Test patch: