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

Issue:
For the edit action button in admin/users the super admin should be allowed to make the users as an admin.
**Describe the bug**
<!-- A clear and concise description of what the bug is. -->
The patch for the users is working but is_admin is a readonly property even for the super user. Used the patch request for users and changed the value for is_admin from true to false. But there is no change after the request to the value of is_admin. 

**To Reproduce**
Steps to reproduce the behavior:
1. Go to v1/users/user_id
2. Send a patch request
3. Change the value of is_admin for some user from false to true.
4. See error

![image](https://user-images.githubusercontent.com/22127980/42907807-8f6542fc-8afc-11e8-84cd-0fe415042fb2.png)

After the request
![image](https://user-images.githubusercontent.com/22127980/42907825-9ecafdd6-8afc-11e8-8372-5cc65888b08b.png)






Discussion:
`is_super_admin` permission wasn't there at condition hence reopening.

Resolving patch:
diff --git a/app/api/users.py b/app/api/users.py
--- a/app/api/users.py
+++ b/app/api/users.py
@@ -183,7 +183,7 @@ def before_update_object(self, user, data, view_kwargs):
         if data.get('email') and data['email'] != user.email:
             view_kwargs['email_changed'] = user.email
 
-        if data.get('is_admin') != user.is_admin:
+        if has_access('is_super_admin') and data.get('is_admin') != user.is_admin:
             user.is_admin = not user.is_admin
 
     def after_update_object(self, user, data, view_kwargs):


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

Issue:
Export sessions as PDF
**Is your feature request related to a problem? Please describe.**
Add an endpoint to export the list of sessions as a PDF.

**Describe the solution you'd like**
Create a template and follow the steps used by other export endpoints

**Describe alternatives you've considered**
\-


Discussion:

Resolving patch:
diff --git a/app/api/exports.py b/app/api/exports.py
--- a/app/api/exports.py
+++ b/app/api/exports.py
@@ -252,3 +252,23 @@ def export_speakers_csv(event_identifier):
     return jsonify(
         task_url=url_for('tasks.celery_task', task_id=task.id)
     )
+
+
+@export_routes.route('/events/<string:event_identifier>/export/sessions/pdf', methods=['GET'])
+@jwt_required()
+def export_sessions_pdf(event_identifier):
+    if not event_identifier.isdigit():
+        event = db.session.query(Event).filter_by(identifier=event_identifier).first()
+        event_id = str(event.id)
+    else:
+        event_id = event_identifier
+
+    from .helpers.tasks import export_sessions_pdf_task
+
+    task = export_sessions_pdf_task.delay(event_id)
+
+    create_export_job(task.id, event_id)
+
+    return jsonify(
+        task_url=url_for('tasks.celery_task', task_id=task.id)
+    )
diff --git a/app/api/helpers/tasks.py b/app/api/helpers/tasks.py
--- a/app/api/helpers/tasks.py
+++ b/app/api/helpers/tasks.py
@@ -386,3 +386,20 @@ def export_speakers_csv_task(self, event_id):
         result = {'__error': True, 'result': str(e)}
 
     return result
+
+
+@celery.task(base=RequestContextTask, name='export.sessions.pdf', bind=True)
+def export_sessions_pdf_task(self, event_id):
+    sessions = db.session.query(Session).filter_by(event_id=event_id)
+    try:
+        sessions_pdf_url = create_save_pdf(
+            render_template('pdf/sessions_pdf.html', sessions=sessions),
+            UPLOAD_PATHS['exports-temp']['pdf'].format(event_id=event_id, identifier=''))
+        result = {
+            'download_url': sessions_pdf_url
+        }
+    except Exception as e:
+        print(traceback.format_exc())
+        result = {'__error': True, 'result': str(e)}
+
+    return result


Test patch:
diff --git a/tests/hook_main.py b/tests/hook_main.py
--- a/tests/hook_main.py
+++ b/tests/hook_main.py
@@ -3763,6 +3763,19 @@ def event_speakers_export_csv_get(transaction):
         db.session.add(event)
         db.session.commit()
 
+
+@hooks.before(
+    "Event Export > Start Sessions Export as PDF > Start a Task to Export Sessions of an Event as PDF")
+def event_sessions_export_pdf_get(transaction):
+    """
+    :param transaction:
+    :return:
+    """
+    with stash['app'].app_context():
+        event = EventFactoryBasic()
+        db.session.add(event)
+        db.session.commit()
+
 # ------------------------- Import -------------------------
 @hooks.before(
     "Event Import > Start Event Import > Start a Task to Import an Event")
Repository: fossasia/open-event-server

Issue:
Send specific exception message from charges layer
**Describe the bug**
<!-- A clear and concise description of what the bug is. -->
Right now a vague exception message is sent from the charges layer. We should return a more specific exception message.


Discussion:

Resolving patch:
diff --git a/app/api/data_layers/ChargesLayer.py b/app/api/data_layers/ChargesLayer.py
--- a/app/api/data_layers/ChargesLayer.py
+++ b/app/api/data_layers/ChargesLayer.py
@@ -46,9 +46,9 @@ def create_object(self, data, view_kwargs):
                 success, response = TicketingManager.charge_stripe_order_payment(order, data['stripe'])
                 data['status'] = success
                 data['message'] = response
-            except Exception:
+            except Exception as e:
                 data['status'] = False
-                data['message'] = "Stripe hasn't been configured properly."
+                data['message'] = str(e)
 
         # charge through paypal
         elif order.payment_mode == 'paypal':
@@ -60,8 +60,8 @@ def create_object(self, data, view_kwargs):
                 success, response = TicketingManager.charge_paypal_order_payment(order, data['paypal_braintree_nonce'])
                 data['status'] = success
                 data['message'] = response
-            except Exception:
+            except Exception as e:
                 data['status'] = False
-                data['message'] = "Paypal hasn't been configured properly."
+                data['message'] = str(e)
 
         return data
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
@@ -81,7 +81,7 @@ def capture_payment(order_invoice, currency=None, credentials=None):
             credentials = StripePaymentsManager.get_credentials(order_invoice.event)
 
         if not credentials:
-            raise Exception('Stripe is incorrectly configured')
+            raise Exception('Stripe credentials not found for the event.')
         stripe.api_key = credentials['SECRET_KEY']
 
         if not currency:


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

Issue:
Restrict access of adding Order Notes
**Describe the bug**
It is possible to Attendee to add order notes.

**To Reproduce**
Send a POST request to create order and add order notes.

**Expected behavior**
Only Event Organizer should be able to add order notes.

**Would you like to work on it**
Yes



Discussion:
can i take up this issue?

Resolving patch:
diff --git a/app/api/orders.py b/app/api/orders.py
--- a/app/api/orders.py
+++ b/app/api/orders.py
@@ -270,7 +270,7 @@ def before_update_object(self, order, data, view_kwargs):
                         raise ForbiddenException({'pointer': 'data/{}'.format(element)},
                                                  "You cannot update {} of an order".format(element))
 
-        if 'order_notes' in data:
+        if has_access('is_organizer', event_id=order.event_id) and 'order_notes' in data:
             if order.order_notes and data['order_notes'] not in order.order_notes.split(","):
                 data['order_notes'] = '{},{}'.format(order.order_notes, data['order_notes'])
 


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

Issue:
Add properties for paypal and stripe payment enable/disable
**Describe the bug**
Currently, the frontend does this to check whether PayPal and stripe are enabled or disabled.
```javascript
return (this.get('settings.paypalBraintreeSandboxAccessToken') || this.get('settings.paypalBraintreeAccessToken')) && find(paymentCurrencies, ['code', this.get('data.event.paymentCurrency')]).paypal;
```
But these variables are part of the admin schema and hence this check does not work with normal user accounts

**To Reproduce**
Steps to reproduce the behavior:
1. Create a non-admin user
2. Create a new event

**Expected behavior**
It should work

**Additional context**
Will be done after https://github.com/fossasia/open-event-server/pull/5186 is merged


Discussion:

Resolving patch:
diff --git a/app/api/schema/settings.py b/app/api/schema/settings.py
--- a/app/api/schema/settings.py
+++ b/app/api/schema/settings.py
@@ -52,6 +52,12 @@ class Meta:
     cookie_policy = fields.Str(allow_none=True)
     cookie_policy_link = fields.Str(allow_none=True)
 
+    #
+    # Online Payment Flags
+    #
+    is_paypal_activated = fields.Bool(dump_only=True)
+    is_stripe_activated = fields.Bool(dump_only=True)
+
 
 class SettingSchemaNonAdmin(SettingSchemaPublic):
     """
diff --git a/app/models/setting.py b/app/models/setting.py
--- a/app/models/setting.py
+++ b/app/models/setting.py
@@ -1,4 +1,5 @@
 from app.models import db
+from sqlalchemy.ext.hybrid import hybrid_property
 
 
 class Environment:
@@ -224,6 +225,19 @@ def __init__(self,
         self.paypal_sandbox_client = paypal_sandbox_client
         self.paypal_sandbox_secret = paypal_sandbox_secret
 
+    @hybrid_property
+    def is_paypal_activated(self):
+        if self.paypal_mode == 'sandbox' and self.paypal_sandbox_client and self.paypal_sandbox_secret:
+            return True
+        elif self.paypal_client and self.paypal_secret:
+            return True
+        else:
+            return False
+
+    @hybrid_property
+    def is_stripe_activated(self):
+        return self.stripe_client_id is not None
+
     def __repr__(self):
         return 'Settings'
 


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

Issue:
return id instead of request_id in create paypal payment configuration
**Describe the bug**
Currently paypal payment configuration is not properly configured. It gives the error and does not proceed. It is because of returning `request_id` instead of `id` in paypal payment config.



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
@@ -188,7 +188,7 @@ def create_payment(order, return_url, cancel_url):
         })
 
         if payment.create():
-            return True, payment.request_id
+            return True, payment.id
         else:
             return False, payment.error
 


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

Issue:
Bad error type of invalid user for password reset
**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 [...] -->
During password reset, if the provided user email doens't exist, an `UnprocessableEntityError` is raised.

**Describe the solution you'd like**
<!-- A clear and concise description of what you want to happen. -->
Instead, a `NotFoundError` should be raised for better clarity of response.

Will change the error type.


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
@@ -208,7 +208,7 @@ def reset_password_post():
     try:
         user = User.query.filter_by(email=email).one()
     except NoResultFound:
-        return UnprocessableEntityError({'source': ''}, 'User not found').respond()
+        return NotFoundError({'source': ''}, 'User not found').respond()
     else:
         link = make_frontend_url('/reset-password', {'token': user.reset_password})
         send_email_with_action(user, PASSWORD_RESET, app_name=get_settings()['app_name'], link=link)


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

Issue:
Make paid_via equal to 'card' when charging through Stripe
**Describe the bug**
<!-- A clear and concise description of what the bug is. -->
Right now when we're charging the user through stripe, we change the payment mode to 'card' instead of changing paid_via. payment_mode should not be changed as it is used for classifying orders on the frontend.

**Parent**
#4852 


Discussion:

Resolving patch:
diff --git a/app/api/helpers/ticketing.py b/app/api/helpers/ticketing.py
--- a/app/api/helpers/ticketing.py
+++ b/app/api/helpers/ticketing.py
@@ -104,8 +104,7 @@ def charge_stripe_order_payment(order, token_id):
         # charge.paid is true if the charge succeeded, or was successfully authorized for later capture.
         if charge.paid:
             # update the order in the db.
-            order.paid_via = 'stripe'
-            order.payment_mode = charge.source.object
+            order.paid_via = charge.source.object
             order.brand = charge.source.brand
             order.exp_month = charge.source.exp_month
             order.exp_year = charge.source.exp_year


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

Issue:
Update populate_db.py to add Paypal sandbox keys.
**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 populate_db.py to add Paypal sandbox keys.



Discussion:

Resolving patch:
diff --git a/populate_db.py b/populate_db.py
--- a/populate_db.py
+++ b/populate_db.py
@@ -74,6 +74,8 @@ def create_settings():
         stripe_secret_key = env('STRIPE_SECRET_KEY', default=None)
         stripe_publishable_key = env('STRIPE_PUBLISHABLE_KEY', default=None)
         stripe_client_id = env('STRIPE_CLIENT_ID', default=None)
+        paypal_sandbox_client = env('PAYPAL_SANDBOX_CLIENT', default=None)
+        paypal_sandbox_secret = env('PAYPAL_SANDBOX_SECRET', default=None)
         fb_client_id = env('FACEBOOK_CLIENT_ID', default=None)
         fb_client_secret = env('FACEBOOK_CLIENT_SECRET', default=None)
         google_client_id = env('GOOGLE_CLIENT_ID', default=None)
@@ -87,6 +89,8 @@ def create_settings():
         setting.stripe_client_id = stripe_client_id
         setting.stripe_publishable_key = stripe_publishable_key
         setting.stripe_secret_key = stripe_secret_key
+        setting.paypal_sandbox_client = paypal_sandbox_client
+        setting.paypal_sandbox_secret = paypal_sandbox_secret
         setting.fb_client_id = fb_client_id
         setting.fb_client_secret = fb_client_secret
         setting.google_client_id = google_client_id


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

Issue:
Admins, Sales Admin, and Marketers can't be added permanently until fields are dump_only
**Describe the bug**
<!-- A clear and concise description of what the bug is. -->

Currently, Admins, Sales Admin, and Marketers can't be added until fields are dump_only
All the fields have persistent values until they are dump-only
**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. -->



Discussion:

Resolving patch:
diff --git a/app/api/schema/users.py b/app/api/schema/users.py
--- a/app/api/schema/users.py
+++ b/app/api/schema/users.py
@@ -51,12 +51,10 @@ class Meta:
     google_plus_url = fields.Url(allow_none=True)
     password = fields.Str(required=True, load_only=True)
     is_super_admin = fields.Boolean(dump_only=True)
-    is_admin = fields.Boolean(dump_only=True)
+    is_admin = fields.Boolean()
     facebook_id = fields.Integer(dump_only=True)
-
-    is_sales_admin = fields.Boolean(dump_only=True)
-    is_marketer = fields.Boolean(dump_only=True)
-
+    is_sales_admin = fields.Boolean()
+    is_marketer = fields.Boolean()
     is_user_organizer = fields.Boolean(dump_only=True)
     is_user_coorganizer = fields.Boolean(dump_only=True)
     is_user_track_organizer = fields.Boolean(dump_only=True)


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

Issue:
Validate order expiry time to be between 1 to 60 minutes.
**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 [...] -->
The order expiry time should always be between 1 to 60 minutes. Validation error should be raised if not in the specified range.


Discussion:

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
@@ -107,7 +107,7 @@ def validate_timezone(self, data, original_data):
     ical_url = fields.Url(dump_only=True)
     xcal_url = fields.Url(dump_only=True)
     average_rating = fields.Float(dump_only=True)
-    order_expiry_time = fields.Integer(allow_none=True, default=10)
+    order_expiry_time = fields.Integer(allow_none=True, default=10, validate=lambda n: 1 <= n <= 60)
     refund_policy = fields.String(dump_only=True,
                                   default='All sales are final. No refunds shall be issued in any case.')
 


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

Issue:
Allow bank, cheque and onsite for payment_mode in orders schema
**Describe the bug**
Currently setting bank, cheque and onsite for payment_mode returns 422 error.

**Expected behavior**
Payment Mode should allow bank, cheque and onsite as options.


Discussion:

Resolving patch:
diff --git a/app/api/schema/orders.py b/app/api/schema/orders.py
--- a/app/api/schema/orders.py
+++ b/app/api/schema/orders.py
@@ -56,8 +56,10 @@ def initial_values(self, data):
     completed_at = fields.DateTime(dump_only=True)
     created_at = fields.DateTime(dump_only=True)
     transaction_id = fields.Str(dump_only=True)
-    payment_mode = fields.Str(default="free",
-                              validate=validate.OneOf(choices=["free", "stripe", "paypal"]), allow_none=True)
+    payment_mode = fields.Str(
+                            default="free",
+                            validate=validate.OneOf(choices=["free", "stripe", "paypal", "bank", "cheque", "onsite"]),
+                            allow_none=True)
     paid_via = fields.Str(dump_only=True)
     brand = fields.Str(dump_only=True)
     exp_month = fields.Str(dump_only=True)


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

Issue:
is_stripe_linked property does not set on connecting stripe account
**Describe the bug**
is_stripe_linked property does not set on connecting stripe account. It throws error.

**Expected behavior**
Property should set appropriately.

**Error**
```
Class 'sqlalchemy.orm.query.Query' is not mapped Traceback (most recent call last):
  File "/home/rs/Pradeep/github/open-event-server/env/lib/python3.5/site-packages/sqlalchemy/orm/session.py", line 1722, in add
    state = attributes.instance_state(instance)
AttributeError: 'Query' object has no attribute '_sa_instance_state'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/rs/Pradeep/github/open-event-server/app/api/helpers/db.py", line 22, in save_to_db
    db.session.add(item)
  File "/home/rs/Pradeep/github/open-event-server/env/lib/python3.5/site-packages/sqlalchemy/orm/scoping.py", line 157, in do
    return getattr(self.registry(), name)(*args, **kwargs)
  File "/home/rs/Pradeep/github/open-event-server/env/lib/python3.5/site-packages/sqlalchemy/orm/session.py", line 1724, in add
    raise exc.UnmappedInstanceError(instance)
sqlalchemy.orm.exc.UnmappedInstanceError: Class 'sqlalchemy.orm.query.Query' is not mapped
ERROR:root:DB Exception! Class 'sqlalchemy.orm.query.Query' is not mapped
```


Discussion:

Resolving patch:
diff --git a/app/api/stripe_authorization.py b/app/api/stripe_authorization.py
--- a/app/api/stripe_authorization.py
+++ b/app/api/stripe_authorization.py
@@ -64,7 +64,7 @@ def after_create_object(self, stripe_authorization, data, view_kwargs):
         :param view_kwargs:
         :return:
         """
-        event = db.session.query(Event).filter_by(id=int(data['event']))
+        event = db.session.query(Event).filter_by(id=int(data['event'])).one()
         event.is_stripe_linked = True
         save_to_db(event)
 


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

Issue:
Add default order expiry time of 10 minutes for events
**Describe the bug**
The `order_expiry_time` field in the events table does not have a default value.

**Expected behavior**
The `order_expiry_time` field in the events table should have a default value of 10 mins.

**Additional details (please complete the following information):**
 - OS: Ubuntu 18.04
 - Python Version 3.6
 - `HEAD` Commit hash [e.g. `4629c62`]



Discussion:

Resolving patch:
diff --git a/app/models/event.py b/app/models/event.py
--- a/app/models/event.py
+++ b/app/models/event.py
@@ -99,7 +99,7 @@ class Event(SoftDeletionModel):
     xcal_url = db.Column(db.String)
     is_sponsors_enabled = db.Column(db.Boolean, default=False)
     refund_policy = db.Column(db.String, default='All sales are final. No refunds shall be issued in any case.')
-    order_expiry_time = db.Column(db.Integer)
+    order_expiry_time = db.Column(db.Integer, default=10)
     is_stripe_linked = db.Column(db.Boolean, default=False)
     discount_code_id = db.Column(db.Integer, db.ForeignKey(
         'discount_codes.id', ondelete='CASCADE'))
diff --git a/migrations/versions/81ac738516a0_.py b/migrations/versions/81ac738516a0_.py
new file mode 100644
--- /dev/null
+++ b/migrations/versions/81ac738516a0_.py
@@ -0,0 +1,31 @@
+"""empty message
+
+Revision ID: 81ac738516a0
+Revises: 35a4c25f12e5
+Create Date: 2018-07-30 12:57:09.572293
+
+"""
+
+from alembic import op
+import sqlalchemy as sa
+import sqlalchemy_utils
+
+
+# revision identifiers, used by Alembic.
+revision = '81ac738516a0'
+down_revision = '35a4c25f12e5'
+
+
+def upgrade():
+    # ### commands auto generated by Alembic - please adjust! ###
+    # ### end Alembic commands ###
+    events_table = sa.sql.table('events', sa.Column('order_expiry_time', sa.Integer))
+    op.execute(events_table.update()
+               .where(events_table.c.order_expiry_time.is_(None))
+               .values({'order_expiry_time' : 10}))
+
+
+def downgrade():
+    # ### commands auto generated by Alembic - please adjust! ###
+    # ### end Alembic commands ###
+    pass


Test patch: