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

Issue:
Write migration file for gender in attendee custom form from text to select
Referrence : https://github.com/fossasia/open-event-frontend/pull/3180


Discussion:

Resolving patch:
diff --git a/migrations/versions/43e8c59339af_.py b/migrations/versions/43e8c59339af_.py
new file mode 100644
--- /dev/null
+++ b/migrations/versions/43e8c59339af_.py
@@ -0,0 +1,25 @@
+"""Changing field type of gender from `Text` to `Select`
+
+Revision ID: 43e8c59337af
+Revises: b2aca7268345
+Create Date: 2019-06-27 20:31:58.92665
+
+"""
+
+from alembic import op
+import sqlalchemy as sa
+import sqlalchemy_utils
+
+
+ # revision identifiers, used by Alembic.
+revision = '43e8c59337af'
+down_revision = 'b2aca7268345'
+
+
+def upgrade():
+    op.execute("UPDATE custom_forms SET type = 'select' where field_identifier = 'gender' and form = 'attendee';", execution_options=None)
+
+
+
+def downgrade():
+    op.execute("UPDATE custom_forms SET type = 'text' where field_identifier = 'gender' and form = 'attendee';", execution_options=None)


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

Issue:
order_expiry_time migration error
**Describe the bug**
The latest migration, `2c7ff9781032` had a bug where the server_default was supposed to be a string. 


**Additional context**
Working on it.


Discussion:

Resolving patch:
diff --git a/migrations/versions/2c7ff9781032_.py b/migrations/versions/2c7ff9781032_.py
--- a/migrations/versions/2c7ff9781032_.py
+++ b/migrations/versions/2c7ff9781032_.py
@@ -20,13 +20,13 @@ def upgrade():
     # ### commands auto generated by Alembic - please adjust! ###
     op.drop_column('events', 'order_expiry_time')
     op.drop_column('events_version', 'order_expiry_time')
-    op.add_column('settings', sa.Column('order_expiry_time', sa.Integer(), default=15, nullable=False))
+    op.add_column('settings', sa.Column('order_expiry_time', sa.Integer(), server_default='15', nullable=False))
     # ### end Alembic commands ###
 
 
 def downgrade():
     # ### commands auto generated by Alembic - please adjust! ###
     op.drop_column('settings', 'order_expiry_time')
-    op.add_column('events_version', sa.Column('order_expiry_time', sa.INTEGER(), autoincrement=False, nullable=False))
-    op.add_column('events', sa.Column('order_expiry_time', sa.INTEGER(), autoincrement=False, nullable=False))
+    op.add_column('events_version', sa.Column('order_expiry_time', sa.INTEGER(), autoincrement=False, nullable=True))
+    op.add_column('events', sa.Column('order_expiry_time', sa.INTEGER(), autoincrement=False, nullable=True))
     # ### end Alembic commands ###


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

Issue:
Unable to order multiple types of tickets at once
**Describe the bug**
An order which is being placed with multiple types of tickets gives the following error:

```
  File "/Users/saicharan/Desktop/open-event-server/app/api/helpers/order.py", line 76, in create_pdf_tickets_for_holder
    order_ticket_info = OrderTicket.query.filter_by(order_id=order.id).one()
  File "/usr/local/lib/python3.7/site-packages/sqlalchemy/orm/query.py", line 3284, in one
    "Multiple rows were found for one()"
sqlalchemy.orm.exc.MultipleResultsFound: Multiple rows were found for one()
```
**To Reproduce**
Steps to reproduce the behavior:
1. Go to any event with paid & free tickets
2. Place an order with paid & free tickets
3. See error

**Expected behavior**
The order should go through

**Additional context**
Working on it.


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
@@ -73,9 +73,10 @@ def create_pdf_tickets_for_holder(order):
             save_to_db(holder)
 
         # create order invoices pdf
-        order_ticket_info = OrderTicket.query.filter_by(order_id=order.id).one()
+        order_tickets = OrderTicket.query.filter_by(order_id=order.id, deleted_at=None).all()
+
         create_save_pdf(render_template('pdf/order_invoice.html', order=order, event=order.event,
-                        tax=order.event.tax, tickets=order.tickets, order_tickets_info=order_ticket_info),
+                        tax=order.event.tax, order_tickets=order_tickets),
                         UPLOAD_PATHS['pdf']['order'], dir_path='/static/uploads/pdf/tickets/',
                         identifier=order.identifier, upload_dir='generated/invoices/')
         save_to_db(order)


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

Issue:
feedback query always returns all the feedbacks
**Describe the bug**
<!-- A clear and concise description of what the bug is. -->
Currently, there is no filter in the `query` method of `FeedbackList` in `app/api/feedbacks.py`.
Query should be introduced to fiter the feedbacks

**To Reproduce**
Steps to reproduce the behavior:
1. Go to `/events/<int:event_id>/feedbacks` or `/users/<int:user_id>/feedbacks` or `/events/<event_identifier>/feedbacks` or `/sessions/<int:session_id>/feedbacks` in postman
2. See error

**Expected behavior**
<!-- A clear and concise description of what you expected to happen. -->
Feedbacks related to specified user, event or session should be returned

**Additional context**
<!-- Add any other context about the problem here. -->
On it



Discussion:

Resolving patch:
diff --git a/app/api/feedbacks.py b/app/api/feedbacks.py
--- a/app/api/feedbacks.py
+++ b/app/api/feedbacks.py
@@ -14,6 +14,7 @@
 from app.models.feedback import Feedback
 from app.models.event import Event
 from app.models.session import Session
+from app.models.user import User
 
 
 class FeedbackListPost(ResourceList):
@@ -72,7 +73,17 @@ def query(self, view_kwargs):
         :return:
         """
         query_ = self.session.query(Feedback)
-        query_ = event_query(self, query_, view_kwargs)
+        if view_kwargs.get('user_id'):
+            # feedbacks under an user
+            user = safe_query(self, User, 'id', view_kwargs['user_id'], 'user_id')
+            query_ = query_.join(User, User.id == Feedback.user_id).filter(User.id == user.id)
+        elif view_kwargs.get('session_id'):
+            # feedbacks under a session
+            session = safe_query(self, Session, 'id', view_kwargs['session_id'], 'session_id')
+            query_ = query_.join(Session, Session.id == Feedback.session_id).filter(Session.id == session.id)
+        else:
+            # feedbacks under an event
+            query_ = event_query(self, query_, view_kwargs)
         return query_
 
     view_kwargs = True
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
@@ -90,7 +90,7 @@ class Meta:
         many=True,
         type_='notification')
     feedbacks = Relationship(
-        attribute='feedbacks',
+        attribute='feedback',
         self_view='v1.user_feedback',
         self_view_kwargs={'id': '<id>'},
         related_view='v1.feedback_list',


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

Issue:
No hard delete for feedback
**Describe the bug**
<!-- A clear and concise description of what the bug is. -->
Currently there is hard delete for feedback. When a user sets his/her rating to 0 again, the feedback of the user should be removed completely from the db.
This issue needs to be solved to merge https://github.com/fossasia/open-event-frontend/pull/3198

**Expected behavior**
<!-- A clear and concise description of what you expected to happen. -->
When the user clears his/her rating (i.e. sets it to 0 again), the feedback must be removed.

**Additional context**
<!-- Add any other context about the problem here. -->
On it



Discussion:

Resolving patch:
diff --git a/app/api/feedbacks.py b/app/api/feedbacks.py
--- a/app/api/feedbacks.py
+++ b/app/api/feedbacks.py
@@ -5,6 +5,7 @@
 from app.api.bootstrap import api
 from app.api.helpers.db import safe_query
 from app.api.helpers.exceptions import UnprocessableEntity, ForbiddenException
+from app.api.helpers.feedback import delete_feedback
 from app.api.helpers.permission_manager import has_access
 from app.api.helpers.permissions import jwt_required
 from app.api.helpers.query import event_query
@@ -133,6 +134,12 @@ def before_update_object(self, feedback, data, view_kwargs):
             if session and not has_access('is_coorganizer', event_id=session.event_id):
                 raise ForbiddenException({'source': ''},
                                          "Event co-organizer access required")
+        if feedback and data.get('deleted_at'):
+            if has_access('is_user_itself', user_id=feedback.user_id):
+                delete_feedback(feedback)
+            else:
+                raise ForbiddenException({'source': ''},
+                                         "Feedback can be deleted only by user himself")
 
     decorators = (api.has_permission('is_user_itself', fetch='user_id',
                                      fetch_as="user_id", model=Feedback, methods="PATCH,DELETE"),)
diff --git a/app/api/helpers/feedback.py b/app/api/helpers/feedback.py
new file mode 100644
--- /dev/null
+++ b/app/api/helpers/feedback.py
@@ -0,0 +1,18 @@
+import logging
+from app.models import db
+
+logger = logging.getLogger(__name__)
+
+
+def delete_feedback(feedback):
+    """
+    Delete the feedback if rating is zero
+    :param feedback: Feedback to be deleted
+    :return:
+    """
+    db.session.delete(feedback)
+    try:
+        db.session.commit()
+    except Exception:
+        logger.exception('Feedback delete exception!')
+        db.session.rollback()
diff --git a/app/api/schema/feedbacks.py b/app/api/schema/feedbacks.py
--- a/app/api/schema/feedbacks.py
+++ b/app/api/schema/feedbacks.py
@@ -23,7 +23,7 @@ class Meta:
         inflect = dasherize
 
     id = fields.Str(dump_only=True)
-    rating = fields.Float(required=True, validate=Range(min=0, max=5))
+    rating = fields.Float(required=True, validate=Range(min=1, max=5))
     comment = fields.Str(required=False)
     event = Relationship(attribute='event',
                          self_view='v1.feedback_event',


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

Issue:
Ticket attachments for attendee emails are not working.
**Describe the bug**
After adding support for multi attendee ticket downloads, the storage path was changed. Due to this, the tickets weren't being attached. Ergo, the email wasn't being sent. 

**Reference**
The key was changed in this PR. https://github.com/fossasia/open-event-server/pull/6095
**To Reproduce**
Steps to reproduce the behavior:
1. Place any order
2. Email is not sent


**Expected behavior**
 Emails & attachments should work as expected.
**Stacktrace**
```
/open-event-server/app/api/helpers/tasks.py", line 64, in send_email_task_sendgrid
    with open(attachment, 'rb') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'generated/tickets/attendees/tickets/pdf/4c0b138f-fd0c-489b-a30b-57c971014861/dDlYVnIrN1/4c0b138f-fd0c-489b-a30b-57c971014861.pdf'
```



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
@@ -148,7 +148,7 @@ def after_create_object(self, order, data, view_kwargs):
             # fetch tickets attachment
             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:
Scheduled task for marking event invoices as Due
**Sub feature Description**
For event invoices, as soon as the invoice becomes 30 days old from issued date, it should be marked as due. 

Parent Issue: #6101 

**Additional context**
Working on it


Discussion:
Issue-Label Bot is automatically applying the label `feature` to this issue, with a confidence of 0.69. 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/__init__.py b/app/__init__.py
--- a/app/__init__.py
+++ b/app/__init__.py
@@ -33,7 +33,7 @@
 from app.api.helpers.auth import AuthManager
 from app.api.helpers.scheduled_jobs import send_after_event_mail, send_event_fee_notification, \
     send_event_fee_notification_followup, change_session_state_on_event_completion, \
-    expire_pending_tickets, send_monthly_event_invoice
+    expire_pending_tickets, send_monthly_event_invoice, event_invoices_mark_due
 from app.models.event import Event
 from app.models.role_invite import RoleInvite
 from app.views.healthcheck import health_check_celery, health_check_db, health_check_migrations, check_migrations
@@ -243,6 +243,7 @@ def update_sent_state(sender=None, headers=None, **kwargs):
 scheduler.add_job(change_session_state_on_event_completion, 'cron', hour=5, minute=30)
 scheduler.add_job(expire_pending_tickets, 'cron', minute=45)
 scheduler.add_job(send_monthly_event_invoice, 'cron', day=1, month='1-12')
+scheduler.add_job(event_invoices_mark_due, 'cron', hour=5)
 scheduler.start()
 
 
diff --git a/app/api/helpers/scheduled_jobs.py b/app/api/helpers/scheduled_jobs.py
--- a/app/api/helpers/scheduled_jobs.py
+++ b/app/api/helpers/scheduled_jobs.py
@@ -160,6 +160,19 @@ def expire_pending_tickets():
         db.session.commit()
 
 
+def event_invoices_mark_due():
+    from app import current_app as app
+    with app.app_context():
+        db.session.query(EventInvoice).\
+                    filter(EventInvoice.status == 'upcoming',
+                           EventInvoice.event.ends_at >= datetime.datetime.now(),
+                           (EventInvoice.created_at + datetime.timedelta(days=30) <=
+                            datetime.datetime.now())).\
+                    update({'status': 'due'})
+
+        db.session.commit()
+
+
 def send_monthly_event_invoice():
     from app import current_app as app
     with app.app_context():


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

Issue:
Organizer/co-organizer/owner cannot delete expired orders
403: Cannot update deleted-at of an order.


Discussion:
Issue-Label Bot is automatically applying the label `bug` to this issue, with a confidence of 0.96. 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/orders.py b/app/api/orders.py
--- a/app/api/orders.py
+++ b/app/api/orders.py
@@ -282,7 +282,7 @@ def before_update_object(self, order, data, view_kwargs):
                 # Order created from the public pages.
                 for element in data:
                     if data[element] and data[element] != getattr(order, element, None):
-                        if element != 'status':
+                        if element != 'status' and element != 'deleted_at':
                             raise ForbiddenException({'pointer': 'data/{}'.format(element)},
                                                      "You cannot update {} of an order".format(element))
                         elif element == 'status' and order.amount and order.status == 'completed':


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

Issue:
Coorganizer and owners can't download tickets, invoices
Current config only allows the organizer role to download the tickets


Discussion:
Issue-Label Bot is automatically applying the label `bug` to this issue, with a confidence of 0.77. 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/user.py b/app/models/user.py
--- a/app/models/user.py
+++ b/app/models/user.py
@@ -387,7 +387,7 @@ def first_access_panel(self):
 
     def can_download_tickets(self, order):
         permissible_users = [holder.id for holder in order.ticket_holders] + [order.user.id]
-        if self.is_staff or self.is_organizer(order.event.id) or self.id in permissible_users:
+        if self.is_staff or self.has_event_access(order.event.id) or self.id in permissible_users:
             return True
         return False
 


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

Issue:
User with organizer or coorganizer role can delete other roles too
**Describe the bug**
<!-- A clear and concise description of what the bug is. -->
Currently, a user with coorganizer access to an event can delete other organizers/coorganizers/owners too. But the user should be allowed to delete users with roles smaller than the user itself.

**Expected behavior**
<!-- A clear and concise description of what you expected to happen. -->
User should be able to delete another user (having a role in the event), only if the user 

**Additional context**
<!-- Add any other context about the problem here. -->
On it



Discussion:
> But the user should be allowed to delete users with roles smaller than the user itself.

In my opinion, either only owner should have the access to create/delete roles or only owner and organizers should have that access, with organizers being allowed to create/delete roles except that of owner.
So, only users with organizer access can create role-invites. The only problem lies with the delete function. Creating a PR for it 

Resolving patch:
diff --git a/app/api/role_invites.py b/app/api/role_invites.py
--- a/app/api/role_invites.py
+++ b/app/api/role_invites.py
@@ -135,6 +135,11 @@ def before_update_object(self, role_invite, data, view_kwargs):
         if not has_access('is_organizer', event_id=role_invite.event_id) and (len(list(data.keys())) > 1 or
                                                                               'status' not in data):
             raise UnprocessableEntity({'source': ''}, "You can only change your status")
+        if data.get('deleted_at'):
+            if role_invite.role_name == 'owner' and not has_access('is_owner', event_id=role_invite.event_id):
+                raise ForbiddenException({'source': ''}, 'Owner access is required.')
+            if role_invite.role_name != 'owner' and not has_access('is_organizer', event_id=role_invite.event_id):
+                raise ForbiddenException({'source': ''}, 'Organizer access is required.')
 
     decorators = (api.has_permission('is_organizer', methods="DELETE", fetch="event_id", fetch_as="event_id",
                                      model=RoleInvite),)


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

Issue:
Make billing information mandatory for paid orders



Discussion:
@CosmicCoder96 Wont this be handled in FE Validations ?
@kushthedude Handling anything on frontend is equivalent to handing a blank cheque with your signature to a thief and hoping he won't cash it. Seems like you missed my message a month back in the gitter channel about frontend validations === useless validations

Resolving patch:
diff --git a/app/api/orders.py b/app/api/orders.py
--- a/app/api/orders.py
+++ b/app/api/orders.py
@@ -63,6 +63,16 @@ def is_payment_valid(order, mode):
         return (order.paid_via == 'paypal') and order.transaction_id
 
 
+def check_billing_info(data):
+    if data.get('amount') > 0 and not data.get('is_billing_enabled'):
+        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')):
+        raise UnprocessableEntity({'pointer': '/data/attributes/is_billing_enabled'},
+                                  "Billing information incomplete")
+
+
 class OrdersListPost(ResourceList):
     """
     OrderListPost class for OrderSchema
@@ -96,6 +106,7 @@ def before_create_object(self, data, view_kwargs):
         :param view_kwargs:
         :return:
         """
+        check_billing_info(data)
 
         free_ticket_quantity = 0
 
@@ -299,6 +310,7 @@ def before_update_object(self, order, data, view_kwargs):
         :param view_kwargs:
         :return:
         """
+        check_billing_info(data)
         if (not has_access('is_coorganizer', event_id=order.event_id)) and (not current_user.id == order.user_id):
             raise ForbiddenException({'pointer': ''}, "Access Forbidden")
 


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

Issue:
Events without name can be published
Disable publishing of event without a name .


Discussion:
Issue-Label Bot is automatically applying the label `bug` to this issue, with a confidence of 0.72. 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/events.py b/app/api/events.py
--- a/app/api/events.py
+++ b/app/api/events.py
@@ -79,6 +79,10 @@ def validate_event(user, modules, data):
         raise ConflictException({'pointer': '/data/attributes/location-name'},
                                 "Online Event does not have any locaton")
 
+    if not data.get('name', None) and data.get('state', None) == 'published':
+        raise ConflictException({'pointer': '/data/attributes/location-name'},
+                                "Event Name is required to publish the event")
+
     if data.get('searchable_location_name') and data.get('is_event_online'):
         raise ConflictException({'pointer': '/data/attributes/searchable-location-name'},
                                 "Online Event does not have any locaton")


Test patch: