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

Issue:
Internal server error during email verification
Error when a wrong token is used for email verification.

POST `/v1/auth/verify-email`
```
{
  "data": {
    "token": "your token"
  }
}
```

Response for `https://open-event-api-dev.herokuapp.com`:
```
<html>
    <head>
        <title>Internal Server Error</title>
    </head>
    <body>
        <h1>
            <p>Internal Server Error</p>
        </h1>
    </body>
</html>
```

Response for `https://api.eventyay.com`:
```
{
    "errors": [
        {
            "detail": "Unknown error",
            "source": {
                "pointer": ""
            },
            "status": 500,
            "title": "Unknown error"
        }
    ],
    "jsonapi": {
        "version": "1.0"
    }
}
```


Discussion:
Issue-Label Bot is automatically applying the label `bug` to this issue, with a confidence of 0.97. Please mark this comment with :thumbsup: or :thumbsdown: to give our bot feedback! 

 Links: [app homepage](https://github.com/marketplace/issue-label-bot), [dashboard](https://mlbot.net/data/fossasia/open-event-server) and [code](https://github.com/hamelsmu/MLapp) for this bot.
This is on dev server? Please post complete URL and payload. How else will we reproduce the error?
Updated.
I'd like to work on this.
For now, I've tried reproducing it locally and it's the `binascii` error.
`binascii.Error: Incorrect padding` 
Usually, this error occurs when the length of the base64 encoded string is not divisible by 4. We usually add padding by appending `==` or `====` to enable divisibility by 4.
But the problem is that the encoded string's length is 168. Any pointers on this? @shreyanshdwivedi @uds5501 ?
Any invalid base64 string throws this exception, it should be handled and response sent that it is an invalid token
@mrsaicharan1 May I take this one?

Resolving patch:
diff --git a/app/api/auth.py b/app/api/auth.py
--- a/app/api/auth.py
+++ b/app/api/auth.py
@@ -174,7 +174,10 @@ def login_user(provider):
 
 @auth_routes.route('/verify-email', methods=['POST'])
 def verify_email():
-    token = base64.b64decode(request.json['data']['token'])
+    try:
+        token = base64.b64decode(request.json['data']['token'])
+    except base64.binascii.Error:
+        return BadRequestError({'source': ''}, 'Invalid Token').respond()
     s = get_serializer()
 
     try:


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

Issue:
Make discount code & access code URL follow json api conventions
`/event/<int:access_event_id>/access-code/<code>`==>`/events/<int:access_event_id>/access-codes/<code>`

`/event/<int:discount_event_id>/discount-codes/<code>`==>`/events/<int:discount_event_id>/discount-codes/<code>`


Discussion:

Resolving patch:
diff --git a/app/api/__init__.py b/app/api/__init__.py
--- a/app/api/__init__.py
+++ b/app/api/__init__.py
@@ -474,7 +474,7 @@
           '/tickets/<int:ticket_id>/discount-codes')
 api.route(DiscountCodeDetail, 'discount_code_detail', '/discount-codes/<int:id>',
           '/events/<int:event_id>/discount-code', '/event-invoices/<int:event_invoice_id>/discount-code',
-          '/event/<int:discount_event_id>/discount-code/<code>')
+          '/events/<int:discount_event_id>/discount-codes/<code>')
 api.route(DiscountCodeRelationshipRequired, 'discount_code_event',
           '/discount-codes/<int:id>/relationships/event')
 api.route(DiscountCodeRelationshipOptional, 'discount_code_events',
@@ -542,7 +542,7 @@
           '/events/<event_identifier>/access-codes', '/users/<int:user_id>/access-codes',
           '/tickets/<int:ticket_id>/access-codes')
 api.route(AccessCodeDetail, 'access_code_detail', '/access-codes/<int:id>',
-          '/event/<int:access_event_id>/access-code/<code>')
+          '/events/<int:access_event_id>/access-codes/<code>')
 api.route(AccessCodeRelationshipRequired, 'access_code_event',
           '/access-codes/<int:id>/relationships/event')
 api.route(AccessCodeRelationshipOptional, 'access_code_user',


Test patch:
diff --git a/tests/hook_main.py b/tests/hook_main.py
--- a/tests/hook_main.py
+++ b/tests/hook_main.py
@@ -2804,7 +2804,7 @@ def discount_delete(transaction):
 @hooks.before("Discount Codes > Get Discount Code Detail using the code > Get Discount Code Detail")
 def discount_code_get_detail_using_code(transaction):
     """
-    GET event/1/discount-codes/DC101
+    GET events/1/discount-codes/DC101
     :param transaction:
     :return:
     """
@@ -2941,7 +2941,7 @@ def access_code_delete(transaction):
 @hooks.before("Access Codes > Access Code Detail using the Code > Access Code Detail")
 def access_code_get_detail_using_code(transaction):
     """
-    GET event/1/access-code/AC101
+    GET events/1/access-codes/AC101
     :param transaction:
     :return:
     """
Repository: fossasia/open-event-server

Issue:
Verify any user automatically if clicks on a reset password link
If a user is using reset password link to reset his password, he is by default verifying his account


Discussion:
Issue-Label Bot is automatically applying the label `feature` to this issue, with a confidence of 0.79. Please mark this comment with :thumbsup: or :thumbsdown: to give our bot feedback! 

 Links: [app homepage](https://github.com/marketplace/issue-label-bot), [dashboard](https://mlbot.net/data/fossasia/open-event-server) and [code](https://github.com/hamelsmu/MLapp) for this bot.

Resolving patch:
diff --git a/app/api/auth.py b/app/api/auth.py
--- a/app/api/auth.py
+++ b/app/api/auth.py
@@ -278,7 +278,7 @@ def reset_password_patch():
         return NotFoundError({'source': ''}, 'User Not Found').respond()
     else:
         user.password = password
-        if user.was_registered_with_order:
+        if not user.is_verified:
             user.is_verified = True
         save_to_db(user)
 


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

Issue:
Server checks for ticket prices are missing
**Describe the bug**
Server checks are required for ticket prices. This would also allow decimal values greater than zero to pass through [similar to eventbrite]

**Additional context**
Corresponding FE PR which requires these checks : https://github.com/fossasia/open-event-frontend/pull/3341


Discussion:

Resolving patch:
diff --git a/app/api/tickets.py b/app/api/tickets.py
--- a/app/api/tickets.py
+++ b/app/api/tickets.py
@@ -20,6 +20,13 @@
 from app.api.helpers.exceptions import ConflictException, MethodNotAllowed, UnprocessableEntity
 from app.api.helpers.db import get_count
 
+
+def validate_ticket_price(data):
+    if data.get('type') != 'free' and int(data.get('price')) <= 0:
+        raise UnprocessableEntity(
+            {'price': data.get('price')}, "Price of a paid/donation ticket must be greater than zero")
+
+
 class TicketListPost(ResourceList):
     """
     Create and List Tickets
@@ -51,6 +58,8 @@ def before_create_object(self, data, view_kwargs):
         :param view_kwargs:
         :return:
         """
+        if not data.get('price') or not data.get('type'):
+            raise UnprocessableEntity({}, "Type/price of ticket is missing")
         if data.get('type') == 'paid' and data.get('event'):
             try:
                 event = db.session.query(Event).filter_by(id=data['event'], deleted_at=None).one()
@@ -59,6 +68,7 @@ def before_create_object(self, data, view_kwargs):
             if not event.is_payment_enabled():
                 raise UnprocessableEntity(
                     {'event_id': data['event']}, "Event having paid ticket must have a payment method")
+        validate_ticket_price(data)
 
     schema = TicketSchema
     methods = ['POST', ]
@@ -181,7 +191,8 @@ def before_update_object(self, ticket, data, view_kwargs):
             if not event.is_payment_enabled():
                 raise UnprocessableEntity(
                     {'event_id': ticket.event.id}, "Event having paid ticket must have a payment method")
-
+        if data.get('type') and data.get('price'):
+            validate_ticket_price(data)
     decorators = (api.has_permission('is_coorganizer', fetch='event_id',
                   fetch_as="event_id", model=Ticket, methods="PATCH,DELETE"),)
     schema = TicketSchema


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

Issue:
After successful charge, order redirection to success page fails
![image](https://user-images.githubusercontent.com/17252805/62267475-d32c0300-b449-11e9-853c-35930f1904df.png)



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
@@ -10,6 +10,7 @@
 from app.models import db
 from app.models.ticket_fee import TicketFees
 from app.models.ticket_holder import TicketHolder
+from flask_jwt_extended import current_user
 
 
 class TicketingManager(object):


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

Issue:
 Implement function for tickets sold in previous month
**Describe the feature**
A method is required to output the info related to tickets sold in the previous month. Should be present in the schema as well

**Additional context**
Required for invoice flow in the app


Discussion:
Issue-Label Bot is automatically applying the label `feature` to this issue, with a confidence of 0.94. Please mark this comment with :thumbsup: or :thumbsdown: to give our bot feedback! 

 Links: [app homepage](https://github.com/marketplace/issue-label-bot), [dashboard](https://mlbot.net/data/fossasia/open-event-server) and [code](https://github.com/hamelsmu/MLapp) for this bot.

Resolving patch:
diff --git a/app/models/event.py b/app/models/event.py
--- a/app/models/event.py
+++ b/app/models/event.py
@@ -396,10 +396,19 @@ def get_staff_roles(self):
     def as_dict(self):
         return {c.name: getattr(self, c.name) for c in self.__table__.columns}
 
+    @property
+    def tickets_sold_object(self):
+        obj = db.session.query(Order.event_id).filter_by(event_id=self.id, status='completed').join(TicketHolder)
+        return obj
+
     def calc_tickets_sold_count(self):
         """Calculate total number of tickets sold for the event"""
-        return db.session.query(Order.event_id).filter_by(event_id=self.id, status='completed').join(TicketHolder)\
-            .count()
+        return self.tickets_sold_object.count()
+
+    def calc_tickets_sold_prev_month(self):
+        """Calculate tickets sold in the previous month"""
+        previous_month = datetime.datetime.now().month - 1
+        return self.tickets_sold.filter_by(completed_at=previous_month).count()
 
     def calc_total_tickets_count(self):
         """Calculate total available tickets for all types of tickets"""


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

Issue:
Allow unverified user to buy `Free Ticket`
Since we already have a check for free orders, It's useless to check if a user wants to buy a free ticket or not.


Discussion:

Resolving patch:
diff --git a/app/api/attendees.py b/app/api/attendees.py
--- a/app/api/attendees.py
+++ b/app/api/attendees.py
@@ -179,11 +179,6 @@ def before_update_object(self, obj, data, kwargs):
                 raise UnprocessableEntity(
                     {'pointer': '/data/relationships/ticket'}, "Invalid Ticket"
                 )
-            if not user.is_verified and ticket.price == 0:
-                raise UnprocessableEntity(
-                    {'pointer': '/data/relationships/ticket'},
-                    "Unverified user cannot buy free tickets"
-                )
 
         if 'device_name_checkin' in data:
             if 'checkin_times' not in data or data['checkin_times'] is None:


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

Issue:
Missing condition to avoid speaker email check on being overridden
**Describe the bug**
<!-- A clear and concise description of what the bug is. -->
When email is overridden, a check is still being called and `is-email-overridden` missing in docs

**Expected behavior**
<!-- A clear and concise description of what you expected to happen. -->
If email is overridden, the check should be avoided

**Additional context**
<!-- Add any other context about the problem here. -->
On it



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
@@ -42,8 +42,9 @@ def before_post(self, args, kwargs, data=None):
         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")
 
-        if get_count(db.session.query(Speaker).filter_by(event_id=int(data['event']), email=data['email'],
-                                                         deleted_at=None)) > 0:
+        if not data.get('is_email_overridden') and \
+            get_count(db.session.query(Speaker).filter_by(event_id=int(data['event']), email=data['email'],
+                                                          deleted_at=None)) > 0:
             raise ForbiddenException({'pointer': ''}, 'Speaker with this Email ID already exists')
 
         if data.get('is_email_overriden') and not has_access('is_organizer', event_id=data['event']):


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

Issue:
Wrong event invoice status fields in db schema
**Describe the bug**
The values allowed for invoices are paid, due &incoming [schema choices]. They are currently equal to those of orders.




Discussion:

Resolving patch:
diff --git a/app/api/schema/event_invoices.py b/app/api/schema/event_invoices.py
--- a/app/api/schema/event_invoices.py
+++ b/app/api/schema/event_invoices.py
@@ -39,8 +39,7 @@ class Meta:
     last4 = fields.Str(allow_none=True)
     stripe_token = fields.Str(allow_none=True)
     paypal_token = fields.Str(allow_none=True)
-    status = fields.Str(validate=validate.OneOf(
-        choices=["expired", "deleted", "initialized" "completed", "placed", "pending", "cancelled"]), allow_none=True)
+    status = fields.Str(validate=validate.OneOf(choices=["paid", "due"]), allow_none=True)
     invoice_pdf_url = fields.Url(allow_none=True)
     user = Relationship(attribute='user',
                         self_view='v1.event_invoice_user',


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

Issue:
Billing Information not showing up in placed orders PDF
**Describe the bug**
<!-- A clear and concise description of what the bug is. -->
After the compulsion of inclusion of billing information in paid orders, the `orders.is_billing_enabled` is not being used, thus billing information is skipped

![Screenshot from 2019-08-06 01-26-15](https://user-images.githubusercontent.com/21087061/62491383-5a320000-b7e9-11e9-9082-5786434fde0a.png)

**Expected behavior**
<!-- A clear and concise description of what you expected to happen. -->
Being a paid order, it should've contained billing information.

**Additional context**
<!-- Add any other context about the problem here. -->
Working 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
@@ -68,7 +68,7 @@ def check_billing_info(data):
         raise UnprocessableEntity({'pointer': '/data/attributes/is_billing_enabled'},
                                   "Billing information is mandatory for paid orders")
     if data.get('is_billing_enabled') and not (data.get('company') and data.get('address') and data.get('city') and
-                                               data.get('zip') and data.get('country')):
+                                               data.get('zipcode') and data.get('country')):
         raise UnprocessableEntity({'pointer': '/data/attributes/is_billing_enabled'},
                                   "Billing information incomplete")
 
@@ -106,7 +106,8 @@ def before_create_object(self, data, view_kwargs):
         :param view_kwargs:
         :return:
         """
-        check_billing_info(data)
+        if data.get('amount') > 0 and not data.get('is_billing_enabled'):
+            data['is_billing_enabled'] = True
 
         free_ticket_quantity = 0
 


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

Issue:
Emails: Not showing "from Name" specified in admin settings
On eventyay in the email settings the from name specified is "Eventyay". However the emails received do not show the name. They only show the from email.

![Screenshot from 2019-08-05 12-48-04](https://user-images.githubusercontent.com/1583873/62459371-76995280-b77f-11e9-8ce7-cd7191cd2f77.png)



Discussion:
On it

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
@@ -10,7 +10,7 @@
 from app import get_settings
 from sendgrid import SendGridAPIClient
 from sendgrid.helpers.mail import (
-    Mail, Attachment, FileContent, FileName,
+    Mail, Attachment, FileContent, FileName, From,
     FileType, Disposition)
 
 from app import make_celery
@@ -55,7 +55,7 @@
 @celery.task(name='send.email.post.sendgrid')
 def send_email_task_sendgrid(payload, headers, smtp_config):
     try:
-        message = Mail(from_email=payload['from'],
+        message = Mail(from_email=From(payload['from'], payload['fromname']),
                        to_emails=payload['to'],
                        subject=payload['subject'],
                        html_content=payload["html"])


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

Issue:
attachments showing up as not found
**Describe the bug**
FIleNotFoundError is coming up when attachments are trying to be sent out. 
Stack Trace:
```
FileNotFoundError: [Errno 2] No such file or directory: 'generated/tickets/attendees/tickets/pdf/4f8be7df-5bba-4017-a15c-70335dd306bd/aW05V1NNSG/4f8be7df-5bba-4017-a15c-70335dd306bd.pdf'

```

**Expected behavior**
Mail should be sent along with attachments



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
@@ -64,7 +64,7 @@ def create_pdf_tickets_for_holder(order):
             if (not holder.user) or holder.user.id != order.user_id:
                 # holder is not the order buyer.
                 pdf = create_save_pdf(render_template('pdf/ticket_attendee.html', order=order, holder=holder),
-                                      UPLOAD_PATHS['pdf']['ticket_attendee'],
+                                      UPLOAD_PATHS['pdf']['tickets_all'],
                                       dir_path='/static/uploads/pdf/tickets/', identifier=order.identifier, upload_dir='generated/tickets/')
             else:
                 # holder is the order buyer.
diff --git a/app/api/orders.py b/app/api/orders.py
--- a/app/api/orders.py
+++ b/app/api/orders.py
@@ -401,7 +401,7 @@ def after_update_object(self, order, data, view_kwargs):
             # Send email to attendees with invoices and tickets attached
             order_identifier = order.identifier
 
-            key = UPLOAD_PATHS['pdf']['ticket_attendee'].format(identifier=order_identifier)
+            key = UPLOAD_PATHS['pdf']['tickets_all'].format(identifier=order_identifier)
             ticket_path = 'generated/tickets/{}/{}/'.format(key, generate_hash(key)) + order_identifier + '.pdf'
 
             key = UPLOAD_PATHS['pdf']['order'].format(identifier=order_identifier)


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

Issue:
Previous month's ticket sales' object bug
**Describe the bug**
For the previous month ticket sales function, the filter should be applied on the ticket_sales_object. Follow up on #6287 



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
@@ -408,7 +408,7 @@ def calc_tickets_sold_count(self):
     def calc_tickets_sold_prev_month(self):
         """Calculate tickets sold in the previous month"""
         previous_month = datetime.datetime.now().month - 1
-        return self.tickets_sold.filter_by(completed_at=previous_month).count()
+        return self.tickets_sold_object.filter_by(completed_at=previous_month).count()
 
     def calc_total_tickets_count(self):
         """Calculate total available tickets for all types of tickets"""


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

Issue:
Send notification to all organizers/co-organizers for ticket sales
**Describe the bug**
When there are ticket sales for an event, all the co-organizers must receive notifications

**Additional context**
Working on it.


Discussion:
@uds5501 Please add this to the milestone

Resolving patch:
diff --git a/app/api/orders.py b/app/api/orders.py
--- a/app/api/orders.py
+++ b/app/api/orders.py
@@ -211,6 +211,9 @@ def after_create_object(self, order, data, view_kwargs):
             for organizer in order.event.organizers:
                 send_notif_ticket_purchase_organizer(organizer, order.invoice_number, order_url, order.event.name,
                                                      order.identifier)
+            for coorganizer in order.event.coorganizers:
+                send_notif_ticket_purchase_organizer(coorganizer, order.invoice_number, order_url, order.event.name,
+                                                     order.identifier)
             if order.event.owner:
                 send_notif_ticket_purchase_organizer(order.event.owner, order.invoice_number, order_url,
                                                      order.event.name, order.identifier)


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

Issue:
Users can create duplicate rating for session
**Describe the bug**
<!-- A clear and concise description of what the bug is. -->
Currently, there is no check to stop a user from creating a new rating for the same session.

**Expected behavior**
<!-- A clear and concise description of what you expected to happen. -->
If a user already has a rating for a session, then an error should be raised if the creation of rating for the same session is tried again

**Additional context**
<!-- Add any other context about the problem here. -->
On it


Discussion:

Resolving patch:
diff --git a/app/models/feedback.py b/app/models/feedback.py
--- a/app/models/feedback.py
+++ b/app/models/feedback.py
@@ -5,6 +5,8 @@
 class Feedback(SoftDeletionModel):
     """Feedback model class"""
     __tablename__ = 'feedback'
+    __table_args__ = (db.UniqueConstraint('session_id', 'user_id', name='session_user_uc'),)
+
     id = db.Column(db.Integer, primary_key=True)
     rating = db.Column(db.Float, nullable=False)
     comment = db.Column(db.String, nullable=True)
diff --git a/migrations/versions/rev-2019-08-10-00:08:43-9d5753192ac9_.py b/migrations/versions/rev-2019-08-10-00:08:43-9d5753192ac9_.py
new file mode 100644
--- /dev/null
+++ b/migrations/versions/rev-2019-08-10-00:08:43-9d5753192ac9_.py
@@ -0,0 +1,28 @@
+"""unique constraint on feedback
+
+Revision ID: 9d5753192ac9
+Revises: f5c3a4fd23fb
+Create Date: 2019-08-10 00:08:43.135975
+
+"""
+
+from alembic import op
+import sqlalchemy as sa
+import sqlalchemy_utils
+
+
+# revision identifiers, used by Alembic.
+revision = '9d5753192ac9'
+down_revision = 'f5c3a4fd23fb'
+
+
+def upgrade():
+    # ### commands auto generated by Alembic - please adjust! ###
+    op.create_unique_constraint('session_user_uc', 'feedback', ['session_id', 'user_id'])
+    # ### end Alembic commands ###
+
+
+def downgrade():
+    # ### commands auto generated by Alembic - please adjust! ###
+    op.drop_constraint('session_user_uc', 'feedback', type_='unique')
+    # ### end Alembic commands ###


Test patch: