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

Issue:
404 error on free orders + paid orders
**Describe the bug**
<!-- A clear and concise description of what the bug is. -->
Admin/Sales page throws a 404 Error when both free orders and paid orders are there

**To Reproduce**
![image (1)](https://user-images.githubusercontent.com/21087061/54866842-fa3d3e80-4d9e-11e9-85db-8e7f9ad2dd47.png)

Steps to reproduce the behavior:
1. Make some free and paid orders
2. Go to Admin/Sales
3. See error

**Expected behavior**
<!-- A clear and concise description of what you expected to happen. -->
It should not throw a 404 error

**Stacktrace**
<!-- If applicable, add stacktrace to help explain your problem. -->
![image](https://user-images.githubusercontent.com/21087061/54866838-eeea1300-4d9e-11e9-8e9f-b72142828d1b.png)

**Additional details (please complete the following information):**
 - OS: [e.g. MacOS, Ubuntu, CentOS] Ubuntu
 - Python Version [e.g. `3.5`, `3.6`] 3.5

**Additional context**
<!-- Add any other context about the problem here. -->
Working on it


Discussion:

Resolving patch:
diff --git a/app/models/order.py b/app/models/order.py
--- a/app/models/order.py
+++ b/app/models/order.py
@@ -38,7 +38,7 @@ class Order(SoftDeletionModel):
 
     id = db.Column(db.Integer, primary_key=True)
     identifier = db.Column(db.String, unique=True)
-    amount = db.Column(db.Float)
+    amount = db.Column(db.Float, nullable=False, default=0)
     address = db.Column(db.String)
     city = db.Column(db.String)
     state = db.Column(db.String)
diff --git a/migrations/versions/6e5c574cbfb8_.py b/migrations/versions/6e5c574cbfb8_.py
new file mode 100644
--- /dev/null
+++ b/migrations/versions/6e5c574cbfb8_.py
@@ -0,0 +1,34 @@
+"""empty message
+
+Revision ID: 6e5c574cbfb8
+Revises: 35f427e85075
+Create Date: 2019-03-24 11:09:42.707206
+
+"""
+
+from alembic import op
+import sqlalchemy as sa
+import sqlalchemy_utils
+from sqlalchemy.dialects import postgresql
+
+# revision identifiers, used by Alembic.
+revision = '6e5c574cbfb8'
+down_revision = '35f427e85075'
+
+
+def upgrade():
+    # ### commands auto generated by Alembic - please adjust! ###
+    op.execute("UPDATE orders SET amount = 0 WHERE amount is NULL", execution_options=None)
+    op.alter_column('orders', 'amount',
+               existing_type=postgresql.DOUBLE_PRECISION(precision=53),
+               nullable=False,
+               )
+    # ### end Alembic commands ###
+
+
+def downgrade():
+    # ### commands auto generated by Alembic - please adjust! ###
+    op.alter_column('orders', 'amount',
+               existing_type=postgresql.DOUBLE_PRECISION(precision=53),
+               nullable=True)
+    # ### end Alembic commands ###


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

Issue:
ElasticSearch object has no attribute 'sync'
**Describe the bug**
<!-- A clear and concise description of what the bug is. -->
ElasticSearch object has no attribute 'sync' which is used to sync all newly created, updated or deleted events

**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error

**Screenshot
![elastic](https://user-images.githubusercontent.com/19776278/55279263-95ed2280-533c-11e9-95d7-42e8cdbcb739.png)


**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. -->
i'm working on it


Discussion:

Resolving patch:
diff --git a/app/views/elastic_cron_helpers.py b/app/views/elastic_cron_helpers.py
--- a/app/views/elastic_cron_helpers.py
+++ b/app/views/elastic_cron_helpers.py
@@ -6,7 +6,7 @@
 """
 
 from app.models.event import Event
-from app.models.search.sync import rebuild_indices, sync_event_from_database
+from app.models.search.sync import rebuild_indices, sync_event_from_database, sync
 from app.views.celery_ import celery
 from app.views.elastic_search import connect_from_config
 from app.views.postgres import get_session_from_config
@@ -25,5 +25,4 @@ def cron_rebuild_events_elasticsearch():
 
 def sync_events_elasticsearch():
     """Sync all newly created, updated or deleted events"""
-    elastic = connect_from_config()
-    elastic.sync()
+    sync()


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

Issue:
Copying of event fails
**Describe the bug**
Copying of event fails

**Expected behavior**
Should be able to copy events.

**Additional context**
Working on this.


Discussion:

Resolving patch:
diff --git a/app/api/event_copy.py b/app/api/event_copy.py
--- a/app/api/event_copy.py
+++ b/app/api/event_copy.py
@@ -126,6 +126,7 @@ def create_event_copy(identifier):
         db.session.commit()
 
     for user_role in user_event_roles:
+        user_role_id = user_role.id
         db.session.expunge(user_role)
         make_transient(user_role)
         user_role.event_id = event.id


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

Issue:
Free orders return a 422 status code due to zero amount.
Placing a free order results in a status of 422 because it fails the validation specified in the schema.

@iamareebjamal Is the validation intentionally for > 0 ? I am not aware, if it is, we can close this issue. Else it can be fixed if I change the comparison to >=0.

It's defined here:
https://github.com/fossasia/open-event-server/blob/8a8af7f9d8b08f86f2211dd1faf0cedbf455a17b/app/api/schema/orders.py#L50

To sum up: Should the amount for free orders be `null` or `0`.


Discussion:
@CosmicCoder96 Probably, this is the aha moment, the `allow_none` needs to be set as `False` and yes `n>=0` should be the case :sweat_smile: 
Working on this 

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
@@ -47,7 +47,7 @@ def initial_values(self, data):
 
     id = fields.Str(dump_only=True)
     identifier = fields.Str(dump_only=True)
-    amount = fields.Float(validate=lambda n: n > 0, allow_none=True)
+    amount = fields.Float(validate=lambda n: n >= 0, allow_none=False)
     address = fields.Str(allow_none=True)
     city = fields.Str(allow_none=True)
     state = fields.Str(db.String, allow_none=True)


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

Issue:
Versioning Error(Relationship missing)
**Describe the bug**
While trying to implement versioning on the `event` model, the following error occurs:

`sqlalchemy.exc.InvalidRequestError: When initializing mapper Mapper|Ticket|tickets, expression 'AccessCode' failed to locate a name ("name 'AccessCode' is not defined"). If this is a class name, consider adding this relationship() to the <class 'app.models.ticket.Ticket'> class after both dependent classes have been defined.`

**Expected behavior**
Should be able to revise to previous versions of the model

**Stacktrace**
`sqlalchemy.exc.InvalidRequestError: When initializing mapper Mapper|Ticket|tickets, expression 'AccessCode' failed to locate a name ("name 'AccessCode' is not defined"). If this is a class name, consider adding this relationship() to the <class 'app.models.ticket.Ticket'> class after both dependent classes have been defined.`

**Additional context**
Working on the fix



Discussion:

Resolving patch:
diff --git a/app/models/access_code.py b/app/models/access_code.py
--- a/app/models/access_code.py
+++ b/app/models/access_code.py
@@ -19,6 +19,8 @@ class AccessCode(SoftDeletionModel):
     max_quantity = db.Column(db.Integer)  # For event level access this holds the months for which it is valid
     valid_from = db.Column(db.DateTime(timezone=True), nullable=True)
     valid_till = db.Column(db.DateTime(timezone=True), nullable=True)
+    ticket_id = db.Column(db.Integer, db.ForeignKey('tickets.id', ondelete='CASCADE'))
+    ticket = db.relationship('Ticket', backref='access_code', foreign_keys=[ticket_id])
     event_id = db.Column(db.Integer, db.ForeignKey('events.id', ondelete='CASCADE'))
     event = db.relationship('Event', backref='access_codes', foreign_keys=[event_id])
     created_at = db.Column(db.DateTime(timezone=True))
diff --git a/migrations/versions/5551af72812f_.py b/migrations/versions/5551af72812f_.py
new file mode 100644
--- /dev/null
+++ b/migrations/versions/5551af72812f_.py
@@ -0,0 +1,30 @@
+"""empty message
+
+Revision ID: 5551af72812f
+Revises: 7bb5891a9f2e
+Create Date: 2019-04-04 23:16:27.618573
+
+"""
+
+from alembic import op
+import sqlalchemy as sa
+import sqlalchemy_utils
+
+
+# revision identifiers, used by Alembic.
+revision = '5551af72812f'
+down_revision = '7bb5891a9f2e'
+
+
+def upgrade():
+    # ### commands auto generated by Alembic - please adjust! ###
+    op.add_column('access_codes', sa.Column('ticket_id', sa.Integer(), nullable=True))
+    op.create_foreign_key(None, 'access_codes', 'tickets', ['ticket_id'], ['id'], ondelete='CASCADE')
+    # ### end Alembic commands ###
+
+
+def downgrade():
+    # ### commands auto generated by Alembic - please adjust! ###
+    op.drop_constraint(None, 'access_codes', type_='foreignkey')
+    op.drop_column('access_codes', 'ticket_id')
+    # ### end Alembic commands ###


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

Issue:
translations download link for frontend 
**Describe the bug**
<!-- A clear and concise description of what the bug is. -->
The translations download link needs to be stored 
**Linked to**
[PR](https://github.com/fossasia/open-event-frontend/pull/2445)
**Additional info**
Working on it


Discussion:
@iamareebjamal Regarding the storage of the link for translations downloads on the frontend, could you please tell me which model should I be storing it at?
Why can't it be created on the fly?
Alright, so when should `url_for('download_translations')` be sent to the front-end ?
Yes
I just had one more doubt, when should it be sent?
I don't understand
The link for downloading .po messages, at what point should it be sent if we are creating it on the fly?
Why can't it be created on frontend?
https://github.com/fossasia/open-event-frontend/pull/2445

On Wed, 3 Apr 2019 at 3:15 PM, Areeb Jamal <notifications@github.com> wrote:

> Why can't it be created on frontend?
>
> —
> You are receiving this because you authored the thread.
> Reply to this email directly, view it on GitHub
> <https://github.com/fossasia/open-event-server/issues/5744#issuecomment-479418330>,
> or mute the thread
> <https://github.com/notifications/unsubscribe-auth/AYB6W8KX6gYhF2t9NTyQYT_pdvQr3HAHks5vdHgygaJpZM4cXrHD>
> .
>

@CosmicCoder96 Will better understand the backend flow here
I guess it was supposed to be stored in one of the models or create a new model for admin. @CosmicCoder96 Your views?
@mrsaicharan1 Can you clarify if the link generated to download the zip file is dynamic and generated each time or is it a static link? If it's dynamic then you need to provide an endpoint to trigger the download on FE, if it's static it can be hardcoded on FE.
The link isn't dynamic as I've kept the translations download logic under a static route `/admin/content/translations/all`.
@mrsaicharan1 
if it's a route then you can just do `this.get('loader').load('/admin/content/translations/all')` on the frontend using the `loader` service. Loader service automatically pre-fixes the rest of the API URL.

Resolving patch:
diff --git a/app/api/admin_translations.py b/app/api/admin_translations.py
--- a/app/api/admin_translations.py
+++ b/app/api/admin_translations.py
@@ -4,7 +4,7 @@
 import tempfile
 import os
 
-admin_blueprint = Blueprint('admin_blueprint', __name__, url_prefix='/admin/content/translations/all')
+admin_blueprint = Blueprint('admin_blueprint', __name__, url_prefix='/v1/admin/content/translations/all')
 temp_dir = tempfile.gettempdir()
 translations_dir = 'app/translations'
 


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

Issue:
Translations zip file deletion(Celery task) not working
**Describe the bug**
Translations donwloads as a zip file are generated properly but the deletion of the file as a celery task fails due to error given in the screenshot.

Reference: https://github.com/fossasia/open-event-frontend/pull/2445
![55771111-47b4ed80-5ab9-11e9-8fbe-d24649d19bc5](https://user-images.githubusercontent.com/25197147/55782349-b601ac00-5ac9-11e9-87c0-3228e9419a39.png)

**To Reproduce**
Steps to reproduce the behavior:
1. Go to 'Admin' Section
2. Click on 'Content tab'
3. Click on 'Download .po files'
4. See error

**Expected behavior**
The deletion needs to happen properly. Adding to this, if we remove/comment the delete_translations code, the download works smoothly but the file must be removed as it shouldn't reside on the server at all.

**Additional context**
Working on it.


Discussion:
@iamareebjamal @CosmicCoder96 I've tried using `delete_translation.delay(path_to_zip)`  and was able to proceed with the normal translations download. Do we need to have a countdown for this?
Yes, or else the file will be deleted before the download is complete
@iamareebjamal When I use `apply_async` for the celery task, the above error occurs. What might be the problem?
Paste the line of error
@iamareebjamal `NoneType object does not support item assignment` is the error and the line causing it is 
 `delete_translations.apply_async(path_to_zip, countdown=600)`

There should be an assignment somewhere near
@iamareebjamal @CosmicCoder96 The assignment error was occurring because apply_async was returning `celery.result.AsyncResult` whihc needed to be stored somehwere. Pushing a PR now as it is now fixed.




Resolving patch:
diff --git a/app/api/admin_translations.py b/app/api/admin_translations.py
--- a/app/api/admin_translations.py
+++ b/app/api/admin_translations.py
@@ -18,7 +18,7 @@ def download_translations():
     shutil.move(zip_file_ext, temp_dir)
     path_to_zip = os.path.join(temp_dir, zip_file_ext)
     from .helpers.tasks import delete_translations
-    delete_translations.apply_async(path_to_zip, countdown=600)
+    delete_translations.apply_async(kwargs={'zip_file_path': path_to_zip}, countdown=600)
     return send_file(path_to_zip,  mimetype='application/zip',
                      as_attachment=True,
                      attachment_filename='translations.zip')


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

Issue:
deletedAt for user is a readonly column and can not be changed 
**Describe the bug**
The admin should be able to restore the deleted users. So changing the value of deleted user from a date to null should be possible (only for an admin).

**Additional context**
Up for grabs



Discussion:
@CosmicCoder96 can I work on this?
@shreyanshdwivedi go ahead.

Resolving patch:
diff --git a/app/api/users.py b/app/api/users.py
--- a/app/api/users.py
+++ b/app/api/users.py
@@ -208,6 +208,9 @@ def before_update_object(self, user, data, view_kwargs):
         #     data['thumbnail_image_url'] = uploaded_images['thumbnail_image_url']
         #     data['icon_image_url'] = uploaded_images['icon_image_url']
 
+        if has_access('is_admin') and data.get('deleted_at') and data['deleted_at'] != user.deleted_at:
+            user.deleted_at = data['deleted_at']
+
         if data.get('email') and data['email'] != user.email:
             try:
                 db.session.query(User).filter_by(email=data['email']).one()


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

Issue:
The condition for restoring deleted user is incorrect
**Describe the bug**
<!-- A clear and concise description of what the bug is. -->
As the title says, the condition for deleted user is buggy due to which deleted users cannot be restored. A PR was merged but the condition was buggy

**Expected behavior**
<!-- A clear and concise description of what you expected to happen. -->
changing the value of deleted user from a date to null should be possible (only for an admin).

**Additional context**
<!-- Add any other context about the problem here. -->
Working on it
Related issue https://github.com/fossasia/open-event-server/issues/5734
Related PR https://github.com/fossasia/open-event-server/pull/5770



Discussion:

Resolving patch:
diff --git a/app/api/users.py b/app/api/users.py
--- a/app/api/users.py
+++ b/app/api/users.py
@@ -208,8 +208,8 @@ def before_update_object(self, user, data, view_kwargs):
         #     data['thumbnail_image_url'] = uploaded_images['thumbnail_image_url']
         #     data['icon_image_url'] = uploaded_images['icon_image_url']
 
-        if has_access('is_admin') and data.get('deleted_at') and data['deleted_at'] != user.deleted_at:
-            user.deleted_at = data['deleted_at']
+        if has_access('is_admin') and data.get('deleted_at') != user.deleted_at:
+            user.deleted_at = data.get('deleted_at')
 
         if data.get('email') and data['email'] != user.email:
             try:


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

Issue:
Un-Authenticated request for Event Feedback List
**Is your feature request related to a problem? Please describe.**
https://api.eventyay.com/v1/events/1/feedbacks?sort=rating&filter=%5B%5D
the request is only allowed for logged in user I guess it shouldn't be right?

**Describe the solution you'd like**
Remove the authentication from event feedback list as each and every user should be able to see the ratings and comments from other users





Discussion:
@aggarwalpulkit596 Would like to work on this.

Resolving patch:
diff --git a/app/api/feedbacks.py b/app/api/feedbacks.py
--- a/app/api/feedbacks.py
+++ b/app/api/feedbacks.py
@@ -61,7 +61,6 @@ def query(self, view_kwargs):
         return query_
 
     view_kwargs = True
-    decorators = (jwt_required,)
     methods = ['GET', ]
     schema = FeedbackSchema
     data_layer = {'session': db.session,


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

Issue:
Un-Authenticated request for Event FAQ List 
Is your feature request related to a problem? Please describe.
https://api.eventyay.com/v1/events/1/faqs
the request is only allowed for logged in user I guess it shouldn't be right?

Describe the solution you'd like
Remove the authentication from event faq list as each and every user should be able to see the faq's related to the event


Discussion:
@mrsaicharan1  
Will take a look into it

On Wed, 17 Apr 2019 at 9:57 AM, Pulkit Aggarwal <notifications@github.com>
wrote:

> Is your feature request related to a problem? Please describe.
> https://api.eventyay.com/v1/events/1/faqs
> the request is only allowed for logged in user I guess it shouldn't be
> right?
>
> Describe the solution you'd like
> Remove the authentication from event faq list as each and every user
> should be able to see the faq's related to the event
>
> —
> You are receiving this because you are subscribed to this thread.
> Reply to this email directly, view it on GitHub
> <https://github.com/fossasia/open-event-server/issues/5810>, or mute the
> thread
> <https://github.com/notifications/unsubscribe-auth/AYB6W2ydHJWBJwbNuGFtyg42jgSrNQPiks5vhqLMgaJpZM4c0K3j>
> .
>


Resolving patch:
diff --git a/app/api/faqs.py b/app/api/faqs.py
--- a/app/api/faqs.py
+++ b/app/api/faqs.py
@@ -56,7 +56,6 @@ def query(self, view_kwargs):
         return query_
 
     view_kwargs = True
-    decorators = (jwt_required, )
     methods = ['GET', ]
     schema = FaqSchema
     data_layer = {'session': db.session,


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

Issue:
Place Order API not working
**Describe the bug**
on hitting `orders?include=event,attendees&fields[event]=id&fields[attendees]=id` endPoint , `HTTP 422 UNPROCESSABLE ENTITY`


### Update 
When Some fields in Body being sent null (Like amount or order-example) this error code is generated . This is the response

```
{
    "errors": [
        {
            "detail": "Field may not be null.",
            "source": {
                "pointer": "/data/attributes/amount"
            },
            "status": "422",
            "title": "Validation error"
        }
    ],
    "jsonapi": {
        "version": "1.0"
    }
}
```




Discussion:
@theLimitBreaker I'll try to fix this blocking issue.
Yes, amount should not be null, but if it is not sent to the server, it should automatically be taken as 0

Resolving patch:
diff --git a/app/api/orders.py b/app/api/orders.py
--- a/app/api/orders.py
+++ b/app/api/orders.py
@@ -87,6 +87,8 @@ def before_create_object(self, data, view_kwargs):
             raise ConflictException({'pointer': '/data/attributes/amount'},
                                     "Amount cannot be null for a paid order")
 
+        if not data.get('amount'):
+            data['amount'] = 0
         # Apply discount only if the user is not event admin
         if data.get('discount') and not has_access('is_coorganizer', event_id=data['event']):
             discount_code = safe_query_without_soft_deleted_entries(self, DiscountCode, 'id', data['discount'],


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

Issue:
Admin translations should only be accessible by admin
**Describe the bug**
Currently, admin translations can be downloaded by anyone who possesses the link. Security issue.

**To Reproduce**
Steps to reproduce the behavior:
1. Go to `/v1/admin/content/translations/all`
2. Unauthenticated/non-admins/admins are able to access admins translations

**Expected behavior**
Only the admins should be able to download the translations as `zip`

**Additional context**
Working on it.


Discussion:

Resolving patch:
diff --git a/app/api/admin_translations.py b/app/api/admin_translations.py
--- a/app/api/admin_translations.py
+++ b/app/api/admin_translations.py
@@ -3,12 +3,14 @@
 import uuid
 import tempfile
 import os
+from app.api.helpers.permissions import is_admin
 
 admin_blueprint = Blueprint('admin_blueprint', __name__, url_prefix='/v1/admin/content/translations/all')
 temp_dir = tempfile.gettempdir()
 translations_dir = 'app/translations'
 
 @admin_blueprint.route('/', methods=['GET'])
+@is_admin
 def download_translations():
     """Admin Translations Downloads"""
     uuid_literal = uuid.uuid4()


Test patch: