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

Issue:
Discount codes patch: 500 internal server error
```
 File "/data/app/app/api/schema/discount_codes.py", line 153, in validate_quantity
2019-08-10T16:48:03.322594701Z     if data['tickets_number'] < data['max_quantity']:
2019-08-10T16:48:03.322599976Z TypeError: '<' not supported between instances of 'int' and 'NoneType'
```


Discussion:

Resolving patch:
diff --git a/app/api/schema/discount_codes.py b/app/api/schema/discount_codes.py
--- a/app/api/schema/discount_codes.py
+++ b/app/api/schema/discount_codes.py
@@ -86,7 +86,7 @@ def validate_quantity(self, data, original_data):
 
         DiscountCodeSchemaEvent.quantity_validation_helper(data)
 
-        if 'tickets_number' in data and 'max_quantity' in data:
+        if data.get('tickets_number') and data.get('max_quantity'):
             if data['tickets_number'] < data['max_quantity']:
                 raise UnprocessableEntity({'pointer': '/data/attributes/tickets-number'},
                                           "tickets-number should be greater than max-quantity")
@@ -149,7 +149,7 @@ def validate_quantity(self, data, original_data):
 
         DiscountCodeSchemaTicket.quantity_validation_helper(data)
 
-        if 'tickets_number' in data and 'max_quantity' in data:
+        if data.get('tickets_number') and data.get('max_quantity'):
             if data['tickets_number'] < data['max_quantity']:
                 raise UnprocessableEntity({'pointer': '/data/attributes/tickets-number'},
                                           "tickets-number should be greater than max-quantity")


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

Issue:
Typo in the notification invitation message
**Describe the bug**
<!-- A clear and concise description of what the bug is. -->
Currently, one user gets the notification-<b>You've been invited to be `a` attendee at TEST EVENT2.</b> But for attendees and for organizer, it should be changed to-<b> You've been invited to be `an` attendee at TEST EVENT2.</b> according to standards.


**To Reproduce**
Steps to reproduce the behaviour:
1. Go to 'notification panel.'
2. Scroll down.
4. See error.

**Expected behaviour**
<!-- A clear and concise description of what you expected to happen. -->
 Typo needs to be fixed for the case of attendees and organizer.


**Screenshots**
<!-- If applicable, add screenshots to help explain your problem. -->
![Screenshot 2019-04-20 17:21:55](https://user-images.githubusercontent.com/35539313/56456935-02ce6800-6391-11e9-907b-d8bd1f7895c2.png)

**Desktop (please complete the following information):**
 - OS: Ubuntu 18.04
 - Browser Chrome
 - Version71.0398

**Additional context**
<!-- Add any other context about the problem here. -->
Working on it.




Discussion:
@mohitm15 Are you on it or should i overtake ?
On it @kushthedude
Its been 20 days
Encountered a bug..so gets delayed
@CosmicCoder96 @iamareebjamal Can we put a beginner friendly issue tag on this? I guess it will be great issue for new comers
Hi there, I have experience with Python, but have never made a PR, or worked with OS. Could I give this a try? I might have a few stupid questions, but it seems like something I could manage.
@QuietDilletante sure, go ahead!
Great, I'll let you know if I have issues.
@QuietDilletante any update?
@prateekj117 May I work on this?
@muznahaftab Go ahead.
Can I work on this issue?
@smcri Go ahead

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
@@ -392,7 +392,7 @@ def get_invite_papers_notification_actions(cfs_link, submit_link):
     },
     EVENT_ROLE: {
         'title': u'Invitation to be {role_name} at {event_name}',
-        'message': u"You've been invited to be a <strong>{role_name}</strong>" +
+        'message': u"You've been invited to be one of the <strong>{role_name}s</strong>" +
                    u" at <strong>{event_name}</strong>.",
         'recipient': 'User',
     },


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

Issue:
Multiple rows with same value allowed in ticket-tags
**Describe the bug**
It should check if the same ticket-tag already exists for the specified event.

**Expected behavior**
Should throw an error that entry already exists in case it does.

**Additional context**
Working on it.


Discussion:

Resolving patch:
diff --git a/app/models/ticket.py b/app/models/ticket.py
--- a/app/models/ticket.py
+++ b/app/models/ticket.py
@@ -172,6 +172,9 @@ class TicketTag(SoftDeletionModel):
     Tags to group tickets
     """
     __tablename__ = 'ticket_tag'
+    __table_args__ = (
+        db.UniqueConstraint('name', 'event_id', name='unique_ticket_tag'),
+    )
 
     id = db.Column(db.Integer, primary_key=True)
     name = db.Column(db.String)
diff --git a/migrations/versions/rev-2019-08-13-14:38:26-1bdf23be63bd_.py b/migrations/versions/rev-2019-08-13-14:38:26-1bdf23be63bd_.py
new file mode 100644
--- /dev/null
+++ b/migrations/versions/rev-2019-08-13-14:38:26-1bdf23be63bd_.py
@@ -0,0 +1,28 @@
+"""empty message
+
+Revision ID: 1bdf23be63bd
+Revises: 246b5b6123af
+Create Date: 2019-08-13 14:38:26.081952
+
+"""
+
+from alembic import op
+import sqlalchemy as sa
+import sqlalchemy_utils
+
+
+# revision identifiers, used by Alembic.
+revision = '1bdf23be63bd'
+down_revision = '246b5b6123af'
+
+
+def upgrade():
+    # ### commands auto generated by Alembic - please adjust! ###
+    op.create_unique_constraint('unique_ticket_tag', 'ticket_tag', ['name', 'event_id'])
+    # ### end Alembic commands ###
+
+
+def downgrade():
+    # ### commands auto generated by Alembic - please adjust! ###
+    op.drop_constraint('unique_ticket_tag', 'ticket_tag', type_='unique')
+    # ### end Alembic commands ###


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

Issue:
Stripe client ID disappears automagically
Stripe client ID disappears from the setting table from DB automatically after some time. Most likely when a new PR is merged and the deployment is made on heroku

Happened thrice by now.
Live secret and publishable key also vanish :tada: but test keys remain.

This is a very neat trick, but we need to get this resolved


Discussion:
@iamareebjamal 
culprit 😈 : https://github.com/fossasia/open-event-server/blob/735dac3f8bb00f63659e5ecd1f7f2322f9cfcac9/populate_db.py#L90

Should we remove them from there or add config vars for heroku?
Thought so. 

Remove this code. As there will always be a conflict on whether to pick value from DB or environment variable. Since we are preferring the frontend UI, it should not be picked up from environment variable

Resolving patch:
diff --git a/populate_db.py b/populate_db.py
--- a/populate_db.py
+++ b/populate_db.py
@@ -84,40 +84,6 @@ def create_services():
 def create_settings():
     get_or_create(Setting, app_name='Open Event')
 
-    if current_app.config['DEVELOPMENT']:
-        # get the stripe keys from the env file and save it in the settings.
-        env.read_envfile()
-        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)
-        google_client_secret = env('GOOGLE_CLIENT_SECRET', default=None)
-        tw_consumer_key = env('TWITTER_CONSUMER_KEY', default=None)
-        tw_consumer_secret = env('TWITTER_CONSUMER_SECRET', default=None)
-        in_client_id = env('INSTAGRAM_CLIENT_ID', default=None)
-        in_client_secret = env('INSTAGRAM_CLIENT_SECRET', default=None)
-
-        setting, _ = get_or_create(Setting, app_name='Open Event')
-        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
-        setting.google_client_secret = google_client_secret
-        setting.tw_consumer_key = tw_consumer_key
-        setting.tw_consumer_secret = tw_consumer_secret
-        setting.in_client_id = in_client_id
-        setting.in_client_secret = in_client_secret
-        save_to_db(setting)
-
-
 def create_event_image_sizes():
     get_or_create(
         ImageSizes, type='event-image', full_width=1300,


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

Issue:
is_paytm_activated shouldn't be a read only attribute
**Describe the bug**
 Alipay, Omise, and PayPal have a property to enable them(e.g. `is_paypal_activated`). They were hybrid properties(condition was like `if client_key and secret_key then true`), so they had a dump_only=True. We need to remove this as we've moved away from such a practice. The reason for this is because we need the keys to be stored, whether the property is enabled/disabled

**Additional context**
Working on this.


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
@@ -58,7 +58,7 @@ class Meta:
     #
     # Online Payment Flags
     #
-    is_paytm_activated = fields.Bool(dump_only=True, allow_none=False, default=False)
+    is_paytm_activated = fields.Bool(default=False)
     is_paypal_activated = fields.Bool(dump_only=True)
     is_stripe_activated = fields.Bool(dump_only=True)
     is_omise_activated = fields.Bool(dump_only=True)


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

Issue:
flask-rest-jsonapi returning fields related to a deleted field
**Describe the bug**
Say we want tickets under a ticket-tag, we use the endpoint `/ticket-tags/{ticket_tag_id}/tickets`, but if say that ticket_tag_id is deleted, flask-rest-jsonapi does not check for that, and returns the tickets (not deleted ones) under that ticket_tag_id.

**Expected behavior**
Flask-Rest-JsonAPI should not return fields related to a deleted field. 

**Additional context**
Working on it.


Discussion:

Resolving patch:
diff --git a/app/api/helpers/db.py b/app/api/helpers/db.py
--- a/app/api/helpers/db.py
+++ b/app/api/helpers/db.py
@@ -1,6 +1,7 @@
 import logging
 import traceback
 
+from flask import request
 from flask_rest_jsonapi.exceptions import ObjectNotFound
 from sqlalchemy import func
 from sqlalchemy.orm.exc import NoResultFound
@@ -66,7 +67,11 @@ def safe_query(self, model, column_name, value, parameter_name):
     :return:
     """
     try:
-        record = self.session.query(model).filter(getattr(model, column_name) == value).one()
+        record = self.session.query(model).filter(getattr(model, column_name) == value)
+        if request.args.get('get_trashed') != 'true':
+            if hasattr(model, 'deleted_at'):
+                record = record.filter(model.deleted_at == None)
+        record = record.one()
     except NoResultFound:
         raise ObjectNotFound({'parameter': '{}'.format(parameter_name)},
                              "{}: {} not found".format(model.__name__, value))


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

Issue:
Generated event invoices have a default state of 'pending'
**Describe the bug**
<!-- A clear and concise description of what the bug is. -->
Any new event invoice being generated have a default state of `pending` which shouldn't be the case.

![Screenshot from 2019-08-16 17-30-12](https://user-images.githubusercontent.com/21087061/63166368-d3ccb800-c04b-11e9-833d-a17c8da3d8c0.png)

**Expected behavior**
<!-- A clear and concise description of what you expected to happen. -->
The default state should be of `due`



Discussion:

Resolving patch:
diff --git a/app/models/event_invoice.py b/app/models/event_invoice.py
--- a/app/models/event_invoice.py
+++ b/app/models/event_invoice.py
@@ -79,7 +79,8 @@ def __init__(self,
                  last4=None,
                  stripe_token=None,
                  paypal_token=None,
-                 deleted_at=None
+                 deleted_at=None,
+                 status='due'
                  ):
         self.identifier = get_new_identifier()
         self.amount = amount
@@ -94,7 +95,7 @@ def __init__(self,
         self.paid_via = paid_via
         self.created_at = datetime.utcnow()
         self.discount_code_id = discount_code_id
-        self.status = 'pending'
+        self.status = status
         self.invoice_pdf_url = invoice_pdf_url
         self.payment_mode = payment_mode
         self.brand = brand
diff --git a/migrations/versions/rev-2019-08-17-16:59:44-90d62fe3b5e3_change_pending_invoices.py b/migrations/versions/rev-2019-08-17-16:59:44-90d62fe3b5e3_change_pending_invoices.py
new file mode 100644
--- /dev/null
+++ b/migrations/versions/rev-2019-08-17-16:59:44-90d62fe3b5e3_change_pending_invoices.py
@@ -0,0 +1,26 @@
+"""change pending invoices
+
+Revision ID: 90d62fe3b5e3
+Revises: cd3beca1951a
+Create Date: 2019-08-17 16:59:44.044872
+
+"""
+
+from alembic import op
+import sqlalchemy as sa
+import sqlalchemy_utils
+
+
+# revision identifiers, used by Alembic.
+revision = '90d62fe3b5e3'
+down_revision = 'cd3beca1951a'
+
+
+def upgrade():
+	op.execute("UPDATE event_invoices SET status = 'due' where status = 'pending';",
+               execution_options=None)
+
+
+def downgrade():
+    op.execute("UPDATE event_invoices SET status = 'pending' where status = 'due';",
+               execution_options=None)


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

Issue:
Mails should be sent even though attachments are being blocked
**Describe the bug**
A mail containing the link to eventyay should be sent event though the attachments are blocked.

**To Reproduce**
Steps to reproduce the behavior:
1. Place any order 
2. When attachments are blocked, mails are not sent

**Expected behavior**
Simple mail must be sent.

**Additional context**
Working on it.


Discussion:
@uds5501 Please add this to the milestone

Resolving patch:
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
@@ -52,6 +52,14 @@
 celery = make_celery()
 
 
+def empty_attachments_send(mail_client, message):
+    """
+    Empty attachments and send mail
+    """
+    logging.warning("Attachments could not be sent. Sending confirmation mail without attachments...")
+    message.attachments = []
+    mail_client.send(message)
+
 @celery.task(name='send.email.post.sendgrid')
 def send_email_task_sendgrid(payload, headers, smtp_config):
     try:
@@ -79,6 +87,8 @@ def send_email_task_sendgrid(payload, headers, smtp_config):
         if e.code == 429:
             logging.warning("Sendgrid quota has exceeded")
             send_email_task_smtp.delay(payload=payload, headers=None, smtp_config=smtp_config)
+        elif e.code == 554:
+            empty_attachments_send(sendgrid_client, message)
         else:
             logging.exception("The following error has occurred with sendgrid-{}".format(str(e)))
 
@@ -96,17 +106,21 @@ def send_email_task_smtp(payload, smtp_config, headers=None):
             }
         }
 
-    mailer = Mailer(mailer_config)
-    mailer.start()
-    message = Message(author=payload['from'], to=payload['to'])
-    message.subject = payload['subject']
-    message.plain = strip_tags(payload['html'])
-    message.rich = payload['html']
-    if payload['attachments'] is not None:
-        for attachment in payload['attachments']:
-            message.attach(name=attachment)
-    mailer.send(message)
-    logging.info('Message sent via SMTP')
+    try:
+        mailer = Mailer(mailer_config)
+        mailer.start()
+        message = Message(author=payload['from'], to=payload['to'])
+        message.subject = payload['subject']
+        message.plain = strip_tags(payload['html'])
+        message.rich = payload['html']
+        if payload['attachments'] is not None:
+            for attachment in payload['attachments']:
+                message.attach(name=attachment)
+        mailer.send(message)
+        logging.info('Message sent via SMTP')
+    except urllib.error.HTTPError as e:
+        if e.code == 554:
+            empty_attachments_send(mailer, message)
     mailer.stop()
 
 @celery.task(base=RequestContextTask, name='resize.event.images', bind=True)


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

Issue:
Ticket tag migrations failing for production data
```
sqlalchemy.exc.IntegrityError: (psycopg2.errors.UniqueViolation) could not create unique index "unique_ticket_tag"
DETAIL:  Key (name, event_id)=(free, 498) is duplicated.

[SQL: ALTER TABLE ticket_tag ADD CONSTRAINT unique_ticket_tag UNIQUE (name, event_id)]
```


Discussion:
@CosmicCoder96 Will push a PR in an hour.
Please do it ASAP and think about things which may break regardless of if they don't break locally

Resolving patch:
diff --git a/migrations/versions/rev-2019-08-13-14:38:26-1bdf23be63bd_.py b/migrations/versions/rev-2019-08-13-14:38:26-1bdf23be63bd_.py
--- a/migrations/versions/rev-2019-08-13-14:38:26-1bdf23be63bd_.py
+++ b/migrations/versions/rev-2019-08-13-14:38:26-1bdf23be63bd_.py
@@ -13,7 +13,7 @@
 
 # revision identifiers, used by Alembic.
 revision = '1bdf23be63bd'
-down_revision = '246b5b6123af'
+down_revision = '90d62fe3b5e3'
 
 
 def upgrade():
diff --git a/migrations/versions/rev-2019-08-17-20:46:39-9172ceb350b8_duplicate_ticket_tag.py b/migrations/versions/rev-2019-08-17-20:46:39-9172ceb350b8_duplicate_ticket_tag.py
new file mode 100644
--- /dev/null
+++ b/migrations/versions/rev-2019-08-17-20:46:39-9172ceb350b8_duplicate_ticket_tag.py
@@ -0,0 +1,27 @@
+"""duplicate ticket tag
+
+Revision ID: 9172ceb350b8
+Revises: cd3beca1951a
+Create Date: 2019-08-17 20:46:39.773326
+
+"""
+
+from alembic import op
+import sqlalchemy as sa
+import sqlalchemy_utils
+
+# revision identifiers, used by Alembic.
+revision = '9172ceb350b8'
+down_revision = '246b5b6123af'
+
+
+def upgrade():
+    op.execute(
+        "UPDATE ticket_tag SET deleted_at = current_timestamp, name = concat(name, id, '.deleted') where id in (SELECT ticket_tag.id FROM ticket_tag LEFT OUTER JOIN (SELECT MIN(id) as id, name, event_id FROM ticket_tag GROUP BY name, event_id) as KeepRows ON ticket_tag.id = KeepRows.id WHERE KeepRows.id IS NULL);",
+        execution_options=None)
+
+
+def downgrade():
+    op.execute(
+        "UPDATE ticket_tag SET deleted_at = null, name = left(name, length(name)-length(cast(id as varchar))-8) where right(name, 8) = '.deleted';",
+        execution_options=None)


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

Issue:
Wrong error and pointer for unverified user
Reference: https://github.com/fossasia/open-event-attendee-android/pull/2287#discussion_r314992174

![image](https://user-images.githubusercontent.com/27783786/63244440-027ca580-c27b-11e9-8f69-552c0596d74d.png)
![image](https://user-images.githubusercontent.com/27783786/63244456-0c9ea400-c27b-11e9-985e-154010904a27.png)



Discussion:
So you need error `Please verify your account to order free tickets`? And pointer?
> So you need error `Please verify your account to order free tickets`? And pointer?

@iamareebjamal 
user should be pointer. UNAUTHORIZED should be the error

Resolving patch:
diff --git a/app/api/orders.py b/app/api/orders.py
--- a/app/api/orders.py
+++ b/app/api/orders.py
@@ -127,8 +127,8 @@ def before_create_object(self, data, view_kwargs):
                 free_ticket_quantity += 1
 
         if not current_user.is_verified and free_ticket_quantity == len(data['ticket_holders']):
-            raise UnprocessableEntity(
-                {'pointer': '/data/relationships/order'},
+            raise ForbiddenException(
+                {'pointer': '/data/relationships/user', 'code': 'unverified-user'},
                 "Unverified user cannot place free orders"
             )
 


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

Issue:
Unique constraint migration not being called.
**Describe the bug**
I was going through migration history and realized 3-4 last migrations were not being called.


Discussion:

Resolving patch:
diff --git a/migrations/versions/rev-2019-08-13-14:38:26-1bdf23be63bd_.py b/migrations/versions/rev-2019-08-13-14:38:26-1bdf23be63bd_.py
--- a/migrations/versions/rev-2019-08-13-14:38:26-1bdf23be63bd_.py
+++ b/migrations/versions/rev-2019-08-13-14:38:26-1bdf23be63bd_.py
@@ -13,7 +13,7 @@
 
 # revision identifiers, used by Alembic.
 revision = '1bdf23be63bd'
-down_revision = '90d62fe3b5e3'
+down_revision = '9172ceb350b8'
 
 
 def upgrade():


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

Issue:
Implement route to get transaction status of the payment
**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 [...] -->
Parent Issue - #6247 
Implement route to get transaction status of the payment to verify if payment is actually made or not

**Additional context**
<!-- Add any other context or screenshots about the feature request here. -->
On it


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
@@ -766,3 +766,30 @@ def process_transaction(order_identifier, txn_token):
 
     response = PaytmPaymentsManager.hit_paytm_endpoint(url=url, head=head, body=body)
     return response
+
+
+@order_misc_routes.route('/orders/<string:order_identifier>/paytm/transaction-status', methods=['GET'])
+def get_transaction_status(order_identifier):
+    paytm_params = dict()
+    paytm_checksum_params = dict()
+    url = ""
+    paytm_mode = get_settings()['paytm_mode']
+    merchant_id = (get_settings()['paytm_sandbox_merchant'] if paytm_mode == 'test'
+                   else get_settings()['paytm_live_merchant'])
+    paytm_checksum_params["body"] = {
+        "mid": merchant_id,
+        "orderId": order_identifier
+    }
+    checksum = PaytmPaymentsManager.generate_checksum(paytm_checksum_params)
+
+    paytm_params["MID"] = merchant_id
+    paytm_params["ORDERID"] = order_identifier
+    paytm_params["CHECKSUMHASH"] = checksum
+    post_data = json.dumps(paytm_params)
+
+    if paytm_mode == 'test':
+        url = "https://securegw-stage.paytm.in/order/status"
+    else:
+        url = "https://securegw.paytm.in/order/status"
+    response = requests.post(url, data=post_data, headers={"Content-type": "application/json"}).json()
+    return response


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

Issue:
Wrong type to compare when verifying PayPal order
**Describe the bug**
In verify paypal payment, the type of order amount from PayPal is a string, which make function always return False



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
@@ -223,7 +223,7 @@ def verify_payment(payment_id, order):
             currency_server = transaction.amount.currency
             sale_state = transaction.related_resources[0].sale.state
 
-            if amount_server != order.amount:
+            if float(amount_server) != order.amount:
                 return False, 'Payment amount does not match order'
             elif currency_server != order.event.payment_currency:
                 return False, 'Payment currency does not match order'


Test patch: