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

Issue:
User order_expiry_time as the parameter to expire orders
**Describe the bug**
Currently we are expiring orders after 10 minutes. We should change it to order_expiry_time parameter. 


Discussion:

Resolving patch:
diff --git a/app/api/helpers/order.py b/app/api/helpers/order.py
--- a/app/api/helpers/order.py
+++ b/app/api/helpers/order.py
@@ -38,7 +38,7 @@ def set_expiry_for_order(order, override=False):
     """
     if order and not order.paid_via and (override or (order.status == 'pending' and (
                 order.created_at +
-                timedelta(minutes=ticketing.TicketingManager.get_order_expiry())) < datetime.now(timezone.utc))):
+                timedelta(minutes=order.event.order_expiry_time)) < datetime.now(timezone.utc))):
             order.status = 'expired'
             delete_related_attendees_for_order(order)
             save_to_db(order)


Test patch:
diff --git a/tests/unittests/api/helpers/test_order.py b/tests/unittests/api/helpers/test_order.py
--- a/tests/unittests/api/helpers/test_order.py
+++ b/tests/unittests/api/helpers/test_order.py
@@ -5,6 +5,7 @@
 from app.api.helpers import ticketing
 from app.api.helpers.order import set_expiry_for_order, delete_related_attendees_for_order
 from app.factories.attendee import AttendeeFactory
+from app.factories.event import EventFactoryBasic
 from app.factories.order import OrderFactory
 from app.models.order import Order
 from tests.unittests.setup_database import Setup
@@ -18,14 +19,18 @@ def setUp(self):
     def test_should_expire_outdated_order(self):
         with app.test_request_context():
             obj = OrderFactory()
+            event = EventFactoryBasic()
+            obj.event = event
             obj.created_at = datetime.now(timezone.utc) - timedelta(
-                minutes=ticketing.TicketingManager.get_order_expiry() + 10)
+                minutes=obj.event.order_expiry_time)
             set_expiry_for_order(obj)
             self.assertEqual(obj.status, 'expired')
 
     def test_should_not_expire_valid_orders(self):
         with app.test_request_context():
             obj = OrderFactory()
+            event = EventFactoryBasic()
+            obj.event = event
             set_expiry_for_order(obj)
             self.assertEqual(obj.status, 'pending')
Repository: fossasia/open-event-server

Issue:
Raise error message when paypal keys are not added on the server.
**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 [...] -->
Raise conflict exception when paypal keys aren't added on the server.



Discussion:

Resolving patch:
diff --git a/app/api/helpers/payment.py b/app/api/helpers/payment.py
--- a/app/api/helpers/payment.py
+++ b/app/api/helpers/payment.py
@@ -139,14 +139,14 @@ def configure_paypal():
         # Use Sandbox by default.
         settings = get_settings()
         paypal_mode = 'sandbox'
-        paypal_client = settings['paypal_sandbox_client']
-        paypal_secret = settings['paypal_sandbox_secret']
+        paypal_client = settings.get('paypal_sandbox_client', None)
+        paypal_secret = settings.get('paypal_sandbox_secret', None)
 
         # Switch to production if paypal_mode is production.
         if settings['paypal_mode'] == Environment.PRODUCTION:
             paypal_mode = 'live'
-            paypal_client = settings['paypal_client']
-            paypal_secret = settings['paypal_secret']
+            paypal_client = settings.get('paypal_client', None)
+            paypal_secret = settings.get('paypal_secret', None)
 
         if not paypal_client or not paypal_secret:
             raise ConflictException({'pointer': ''}, "Payments through Paypal hasn't been configured on the platform")


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

Issue:
Migration error while upgrading the database
**Describe the bug**
While upgrading the database, I get an error that says revision `f375453ca1f6` is absent.

**To Reproduce**
Steps to reproduce the behavior:
1. Upgrade the database using `python manage.py db upgrade`
**Expected behavior**
<!-- A clear and concise description of what you expected to happen. -->
Database should be upgraded successfully.

Working on fixing this.


Discussion:

Resolving patch:
diff --git a/migrations/versions/4c687e52449b_.py b/migrations/versions/4c687e52449b_.py
--- a/migrations/versions/4c687e52449b_.py
+++ b/migrations/versions/4c687e52449b_.py
@@ -1,7 +1,7 @@
 """empty message
 
 Revision ID: 4c687e52449b
-Revises: f375453ca1f6
+Revises: 81ac738516a0
 Create Date: 2018-08-01 14:49:04.066424
 
 """


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

Issue:
Internal Server Error due to migration problem
**Describe the bug**
<!-- A clear and concise description of what the bug is. -->

Internal Server Error due to migration problem

**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-06 01-54-57](https://user-images.githubusercontent.com/22936570/43689682-da2773f0-991b-11e8-9ef7-be9822537061.png)



Discussion:

Resolving patch:
diff --git a/migrations/versions/akl592fe692n_.py b/migrations/versions/akl592fe692n_.py
new file mode 100644
--- /dev/null
+++ b/migrations/versions/akl592fe692n_.py
@@ -0,0 +1,27 @@
+"""empty message
+
+Revision ID: akl592fe692n
+Revises: 2453426d2a35
+Create Date: 2018-08-06 01:36:13.491209
+
+"""
+
+from alembic import op
+import sqlalchemy as sa
+
+
+# revision identifiers, used by Alembic.
+revision = 'akl592fe692n'
+down_revision = '2453426d2a35'
+
+
+def upgrade():
+    # ### commands auto generated by Alembic - please adjust! ###
+    op.add_column('user_favourite_events', sa.Column('deleted_at', sa.DateTime(timezone=True), nullable=True))
+    # ### end Alembic commands ###
+
+
+def downgrade():
+    # ### commands auto generated by Alembic - please adjust! ###
+    op.drop_column('user_favourite_events', 'deleted_at')
+    # ### end Alembic commands ###


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

Issue:
Internal server error while creating speaker for a normal user(no event role)
**Describe the bug**
When a normal user(no event role) tries to submit speaker details, an internal server error is thrown.

**To Reproduce**
Steps to reproduce the behavior:
1. Login via a normal(no event role) user
2. Submit speaker details
3. See error

**Expected behavior**
There should be no error.

**Stacktrace**
![screenshot from 2018-08-06 16-51-07](https://user-images.githubusercontent.com/22395998/43713979-160ddf76-9999-11e8-94ce-d897f390ddb3.png)


Discussion:

Resolving patch:
diff --git a/app/api/speakers.py b/app/api/speakers.py
--- a/app/api/speakers.py
+++ b/app/api/speakers.py
@@ -21,7 +21,7 @@ class SpeakerListPost(ResourceList):
     List and create speakers
     """
 
-    def before_post(self, args, kwargs, data):
+    def before_post(self, args, kwargs, data=None):
         """
         method to add user_id to view_kwargs before post
         :param args:
@@ -32,10 +32,10 @@ def before_post(self, args, kwargs, data):
         require_relationship(['event', 'user'], data)
 
         if not has_access('is_coorganizer', event_id=data['event']):
-                event = safe_query(self, Event, 'id', data['event'], 'event_id')
-                if event.state == "draft":
-                    raise ObjectNotFound({'parameter': 'event_id'},
-                                         "Event: {} not found".format(data['event_id']))
+            event = db.session.query(Event).filter_by(id=data['event']).one()
+            if event.state == "draft":
+                raise ObjectNotFound({'parameter': 'event_id'},
+                                     "Event: {} not found".format(data['event_id']))
 
         if get_count(db.session.query(Event).filter_by(id=int(data['event']), is_sessions_speakers_enabled=False)) > 0:
             raise ForbiddenException({'pointer': ''}, "Speakers are disabled for this Event")


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

Issue:
Return Notification id in the actions
**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 [...] -->
Return Notification id in the actions



Discussion:

Resolving patch:
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
@@ -23,6 +23,7 @@ class Meta:
     action_type = fields.Str(allow_none=True, dump_only=True)
     subject = fields.Str(allow_none=True, dump_only=True)
     subject_id = fields.Str(allow_none=True, dump_only=True)
+    notification_id = fields.Str(allow_none=True, dump_only=True)
     notification = Relationship(attribute='notification',
                                 self_view='v1.notification_actions_notification',
                                 self_view_kwargs={'id': '<id>'},


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

Issue:
Return subject_id as a string instead of a number
**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 [...] -->
Return subject_id as a string instead of a number



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
@@ -143,7 +143,7 @@ def after_create_object(self, order, data, view_kwargs):
             order_url = make_frontend_url(path='/orders/{identifier}'.format(identifier=order.identifier))
             for organizer in order.event.organizers:
                 send_notif_ticket_purchase_organizer(organizer, order.invoice_number, order_url, order.event.name,
-                                                     order.id)
+                                                     order.identifier)
 
         data['user_id'] = current_user.id
 
diff --git a/app/models/notification.py b/app/models/notification.py
--- a/app/models/notification.py
+++ b/app/models/notification.py
@@ -39,7 +39,7 @@ class NotificationAction(db.Model):
 
     action_type = db.Column(db.String)
     subject = db.Column(db.String)
-    subject_id = db.Column(db.Integer)  # Contains the ID of the related subject, eg. session_id in case of new session.
+    subject_id = db.Column(db.String)  # Contains the ID of the related subject, eg. session_id in case of new session.
     link = db.Column(db.String)  # Contains the link if required to take action. Null in other cases.
 
     notification_id = db.Column(db.Integer, db.ForeignKey('notifications.id', ondelete='CASCADE'))
diff --git a/migrations/versions/55fd4c6ae8b2_.py b/migrations/versions/55fd4c6ae8b2_.py
new file mode 100644
--- /dev/null
+++ b/migrations/versions/55fd4c6ae8b2_.py
@@ -0,0 +1,32 @@
+"""empty message
+
+Revision ID: 55fd4c6ae8b2
+Revises: a0c63733e5d2
+Create Date: 2018-08-06 23:35:34.202111
+
+"""
+
+import sqlalchemy as sa
+from alembic import op
+
+# revision identifiers, used by Alembic.
+revision = '55fd4c6ae8b2'
+down_revision = 'a0c63733e5d2'
+
+
+def upgrade():
+    # ### commands auto generated by Alembic - please adjust! ###
+    op.alter_column('notification_actions', 'subject_id',
+                    existing_type=sa.INTEGER(),
+                    type_=sa.String(),
+                    existing_nullable=True)
+    # ### end Alembic commands ###
+
+
+def downgrade():
+    # ### commands auto generated by Alembic - please adjust! ###
+    op.alter_column('notification_actions', 'subject_id',
+                    existing_type=sa.String(),
+                    type_=sa.INTEGER(),
+                    existing_nullable=True)
+    # ### end Alembic commands ###


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

Issue:
Inconsistent Email Verification on BE
**Describe the bug**
<!-- A clear and concise description of what the bug is. -->
Currently, BE sends email confirmation link on the `/email/verify` endpoint and also sends the welcome message every time a verification is requested. This should be fixed.

**To Reproduce**
Steps to reproduce the behavior:
1. Create a new user and notice the verification link sent on the user's email

**Expected behavior**
<!-- A clear and concise description of what you expected to happen. -->
The link should have the `/verify` endpoint instead, where the verification code executes on FE. Also, the welcome mail should be sent only once.


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
@@ -188,10 +188,7 @@ def resend_verification_email():
         hash_ = str(base64.b64encode(str(serializer.dumps(
             [user.email, str_generator()])).encode()), 'utf-8')
         link = make_frontend_url(
-            '/email/verify'.format(id=user.id), {'token': hash_})
-        send_email_with_action(
-            user, USER_REGISTER_WITH_PASSWORD,
-            app_name=get_settings()['app_name'], email=user.email)
+            '/verify'.format(id=user.id), {'token': hash_})
         send_email_confirmation(user.email, link)
 
         return make_response(jsonify(message="Verification email resent"), 200)
diff --git a/app/api/users.py b/app/api/users.py
--- a/app/api/users.py
+++ b/app/api/users.py
@@ -60,7 +60,7 @@ def after_create_object(self, user, data, view_kwargs):
         """
         s = get_serializer()
         hash = str(base64.b64encode(str(s.dumps([user.email, str_generator()])).encode()), 'utf-8')
-        link = make_frontend_url('/email/verify'.format(id=user.id), {'token': hash})
+        link = make_frontend_url('/verify'.format(id=user.id), {'token': hash})
         send_email_with_action(user, USER_REGISTER_WITH_PASSWORD, app_name=get_settings()['app_name'],
                                email=user.email)
         send_email_confirmation(user.email, link)


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

Issue:
Wrong Mail Statistics which troubles it to work completely
**Describe the bug**
<!-- A clear and concise description of what the bug is. -->
Wrong Mail Statistics which troubles it to work completely

**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/mails.py b/app/api/admin_statistics_api/mails.py
--- a/app/api/admin_statistics_api/mails.py
+++ b/app/api/admin_statistics_api/mails.py
@@ -31,16 +31,24 @@ class Meta:
     thirty_days = fields.Method("mail_last_30_days")
 
     def mail_last_1_day(self, obj):
-        return get_count(Mail.query.filter(datetime.now(pytz.utc) - Mail.time <= timedelta(days=1)))
+        all_mails = get_count(Mail.query.filter_by(time=datetime.now(pytz.utc)))
+        mails_till_last_1_day = get_count(Mail.query.filter(Mail.time <= datetime.now(pytz.utc) - timedelta(days=1)))
+        return all_mails - mails_till_last_1_day
 
     def mail_last_3_days(self, obj):
-        return get_count(Mail.query.filter(datetime.now(pytz.utc) - Mail.time <= timedelta(days=3)))
+        all_mails = get_count(Mail.query.filter_by(time=datetime.now(pytz.utc)))
+        mails_till_last_3_day = get_count(Mail.query.filter(Mail.time <= datetime.now(pytz.utc) - timedelta(days=3)))
+        return all_mails - mails_till_last_3_day
 
     def mail_last_7_days(self, obj):
-        return get_count(Mail.query.filter(datetime.now(pytz.utc) - Mail.time <= timedelta(days=7)))
+        all_mails = get_count(Mail.query.filter_by(time=datetime.now(pytz.utc)))
+        mails_till_last_7_day = get_count(Mail.query.filter(Mail.time <= datetime.now(pytz.utc) - timedelta(days=7)))
+        return all_mails - mails_till_last_7_day
 
     def mail_last_30_days(self, obj):
-        return get_count(Mail.query.filter(datetime.now(pytz.utc) - Mail.time <= timedelta(days=30)))
+        all_mails = get_count(Mail.query.filter_by(time=datetime.now(pytz.utc)))
+        mails_till_last_30_day = get_count(Mail.query.filter(Mail.time <= datetime.now(pytz.utc) - timedelta(days=30)))
+        return all_mails - mails_till_last_30_day
 
 
 class AdminStatisticsMailDetail(ResourceDetail):


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

Issue:
Disallow creating users with same email.
**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 we can create users with the same email. If we soft-delete a user account and try to create an account with the same email again, the server allows creating it but sends HTTP 500 when doing so since it voilates the unique constraint in the db.

![image](https://user-images.githubusercontent.com/21277837/43689278-8f3072b2-9915-11e8-94c9-56fce267f5fc.png)



Discussion:
@srv-twry can I take this?
@mishuvs could you please do this quickly. Need this. Moreover it's a simple bug so shouldn't take long.

Resolving patch:
diff --git a/app/api/users.py b/app/api/users.py
--- a/app/api/users.py
+++ b/app/api/users.py
@@ -44,7 +44,7 @@ def before_create_object(self, data, view_kwargs):
         :param view_kwargs:
         :return:
         """
-        if db.session.query(User.id).filter_by(email=data['email'], deleted_at=None).scalar() is not None:
+        if db.session.query(User.id).filter_by(email=data['email']).scalar() is not None:
             raise ConflictException({'pointer': '/data/attributes/email'}, "Email already exists")
 
     def after_create_object(self, user, data, view_kwargs):


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

Issue:
Add unit test for Event helpers
**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 [...] -->
We should add unit tests for event helpers.

**Additional context**
<!-- Add any other context or screenshots about the feature request here. -->
Parent: #5320 


Discussion:

Resolving patch:
diff --git a/app/api/helpers/errors.py b/app/api/helpers/errors.py
--- a/app/api/helpers/errors.py
+++ b/app/api/helpers/errors.py
@@ -65,10 +65,16 @@ class ServerError(ErrorResponse):
 
 
 class UnprocessableEntityError(ErrorResponse):
+    """
+    Default class for 422 Error
+    """
     status = 422
     title = 'Unprocessable Entity'
 
 
 class BadRequestError(ErrorResponse):
+    """
+    Default class for 400 Error
+    """
     status = 400
     title = 'Bad Request'
diff --git a/app/api/helpers/exceptions.py b/app/api/helpers/exceptions.py
--- a/app/api/helpers/exceptions.py
+++ b/app/api/helpers/exceptions.py
@@ -2,11 +2,17 @@
 
 
 class UnprocessableEntity(JsonApiException):
+    """
+    Default class for 422 Error
+    """
     title = "Unprocessable Entity"
     status = 422
 
 
 class ConflictException(JsonApiException):
+    """
+    Default class for 409 Error
+    """
     title = "Conflict"
     status = 409
 


Test patch:
diff --git a/tests/unittests/api/helpers/test_events.py b/tests/unittests/api/helpers/test_events.py
new file mode 100644
--- /dev/null
+++ b/tests/unittests/api/helpers/test_events.py
@@ -0,0 +1,25 @@
+import unittest
+
+from app import current_app as app
+from app.api.helpers.db import save_to_db, get_count
+from app.api.helpers.events import create_custom_forms_for_attendees
+from app.factories.event import EventFactoryBasic
+from app.models.custom_form import CustomForms
+from tests.unittests.setup_database import Setup
+from tests.unittests.utils import OpenEventTestCase
+
+
+class TestEventUtilities(OpenEventTestCase):
+    def setUp(self):
+        self.app = Setup.create_app()
+
+    def test_should_create_attendee_forms(self):
+        with app.test_request_context():
+            event = EventFactoryBasic()
+            save_to_db(event)
+            create_custom_forms_for_attendees(event)
+            self.assertEqual(get_count(CustomForms.query), 3)
+
+
+if __name__ == '__main__':
+    unittest.main()
diff --git a/tests/unittests/api/helpers/test_order.py b/tests/unittests/api/helpers/test_order.py
--- a/tests/unittests/api/helpers/test_order.py
+++ b/tests/unittests/api/helpers/test_order.py
@@ -2,7 +2,6 @@
 from datetime import timedelta, datetime, timezone
 
 from app import current_app as app, db
-from app.api.helpers import ticketing
 from app.api.helpers.order import set_expiry_for_order, delete_related_attendees_for_order
 from app.factories.attendee import AttendeeFactory
 from app.factories.event import EventFactoryBasic
Repository: fossasia/open-event-server

Issue:
Buggy endpoint for microlocation detail of a session
**Describe the bug**
<!-- A clear and concise description of what the bug is. -->
The endpoint to get the micro location of a session gives incorrect data.

**To Reproduce**
Steps to reproduce the behavior:
1. Make a GET request on the `/v1/sessions/<session_id>/microlocation` endpoint

**Expected behavior**
<!-- A clear and concise description of what you expected to happen. -->
Microlocation detail should be fetched successfully.

Working on fixing this.


Discussion:

Resolving patch:
diff --git a/app/api/microlocations.py b/app/api/microlocations.py
--- a/app/api/microlocations.py
+++ b/app/api/microlocations.py
@@ -73,9 +73,9 @@ def before_get_object(self, view_kwargs):
         :return:
         """
         if view_kwargs.get('session_id') is not None:
-            sessions = safe_query(self, Session, 'id', view_kwargs['session_id'], 'session_id')
-            if sessions.event_id is not None:
-                view_kwargs['id'] = sessions.event_id
+            session = safe_query(self, Session, 'id', view_kwargs['session_id'], 'session_id')
+            if session.microlocation_id is not None:
+                view_kwargs['id'] = session.microlocation_id
             else:
                 view_kwargs['id'] = None
 


Test patch: