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

Issue:
Change Stripe api endpoint to include s at the end of url
**Describe the bug**
Currently ember by default makes calls to stripe-authorizations whereas server has end point as stripe-authorization

**Expected behavior**
-  All the other endpoints use "s" in the end i.e. the plural sense. There should be consistency.
-  FE is in Ember which follows conventions. If we don't add "s" to it then we will have to unnecessary modifications in the adapter for the FE.

Hence better to follow conventions. It will make life easier for us in the FE.



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
@@ -171,7 +171,7 @@
           '/access-codes/<int:access_code_id>/event', '/email-notifications/<int:email_notification_id>/event',
           '/attendees/<int:attendee_id>/event', '/custom-forms/<int:custom_form_id>/event',
           '/orders/<order_identifier>/event', '/faqs/<int:faq_id>/event', '/faq-types/<int:faq_type_id>/event',
-          '/feedbacks/<int:feedback_id>/event', '/stripe-authorization/<int:stripe_authorization_id>/event')
+          '/feedbacks/<int:feedback_id>/event', '/stripe-authorizations/<int:stripe_authorization_id>/event')
 api.route(EventRelationship, 'event_ticket', '/events/<int:id>/relationships/tickets',
           '/events/<identifier>/relationships/tickets')
 api.route(EventRelationship, 'event_ticket_tag', '/events/<int:id>/relationships/ticket-tags',
@@ -463,11 +463,11 @@
           '/feedbacks/<int:id>/relationships/user')
 
 # Stripe Authorization API
-api.route(StripeAuthorizationListPost, 'stripe_authorization_list_post', '/stripe-authorization')
-api.route(StripeAuthorizationDetail, 'stripe_authorization_detail',  '/stripe-authorization/<int:id>',
+api.route(StripeAuthorizationListPost, 'stripe_authorization_list_post', '/stripe-authorizations')
+api.route(StripeAuthorizationDetail, 'stripe_authorization_detail',  '/stripe-authorizations/<int:id>',
           '/events/<int:event_id>/stripe-authorization', '/events/<event_identifier>/stripe-authorization')
 api.route(StripeAuthorizationRelationship, 'stripe_authorization_event',
-          '/stripe-authorization/<int:id>/relationships/event')
+          '/stripe-authorizations/<int:id>/relationships/event')
 
 # Orders API
 api.route(OrdersListPost, 'order_list_post', '/orders')


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

Issue:
Type Error in Export iCal and xCal from the frontend
**Describe the bug**
When the api is called with the `event_identifier` we get a type error.

**To Reproduce**
Steps to reproduce the behavior:
1. Go to Exports tab in the frontend
2. Click on download ical

**Expected behavior**
Export should happen as usual.

**Stacktrace**
```sh
[2018-06-11 11:59:22,565: WARNING/Worker-7] Traceback (most recent call last):
  File "/home/mayank/OpenSource/open-event-server/app/api/helpers/tasks.py", line 117, in export_ical_task
    filedir = current_app.config.get('BASE_DIR') + '/static/uploads/temp/' + event_id + '/'
TypeError: must be str, not int

```
**Additional details (please complete the following information):**
 - OS: Ubuntu
 - Python Version [e.g. `3.5`, `3.6`]
 - `HEAD` Commit hash [e.g. `4629c62`]

**Additional context**
Works with event_id


Discussion:

Resolving patch:
diff --git a/app/api/exports.py b/app/api/exports.py
--- a/app/api/exports.py
+++ b/app/api/exports.py
@@ -71,7 +71,7 @@ def export_event_xcal(event_identifier):
 
     if not event_identifier.isdigit():
         event = db.session.query(Event).filter_by(identifier=event_identifier).first()
-        event_id = event.id
+        event_id = str(event.id)
     else:
         event_id = event_identifier
 
@@ -99,7 +99,7 @@ def event_export_task_base(event_id, settings):
 def export_event_ical(event_identifier):
     if not event_identifier.isdigit():
         event = db.session.query(Event).filter_by(identifier=event_identifier).first()
-        event_id = event.id
+        event_id = str(event.id)
     else:
         event_id = event_identifier
 


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

Issue:
Session allowed to be created without an associated Track
**Describe the bug**
<!-- A clear and concise description of what the bug is. -->
Sessions can be created without being associated with a Track 

**Expected behavior**
<!-- A clear and concise description of what you expected to happen. -->
It shouldn't be possible


Discussion:

Resolving patch:
diff --git a/app/api/sessions.py b/app/api/sessions.py
--- a/app/api/sessions.py
+++ b/app/api/sessions.py
@@ -32,7 +32,7 @@ def before_post(self, args, kwargs, data):
         :param data:
         :return:
         """
-        require_relationship(['event'], data)
+        require_relationship(['event', 'track'], data)
         data['creator_id'] = current_identity.id
         if get_count(db.session.query(Event).filter_by(id=int(data['event']), is_sessions_speakers_enabled=False)) > 0:
             raise ForbiddenException({'pointer': ''}, "Sessions are disabled for this Event")


Test patch:
diff --git a/tests/hook_main.py b/tests/hook_main.py
--- a/tests/hook_main.py
+++ b/tests/hook_main.py
@@ -996,6 +996,10 @@ def session_post(transaction):
         db.session.add(event)
         db.session.commit()
 
+        track = TrackFactory()
+        db.session.add(track)
+        db.session.commit()
+
 
 @hooks.before("Sessions > Sessions Details > Session Details")
 def session_get_detail(transaction):
Repository: fossasia/open-event-server

Issue:
Admin: Sales: Add invoice route
**Is your feature request related to a problem? Please describe.**
The /admin/sales page has no working invoice endpoint



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
@@ -61,6 +61,7 @@
 from app.api.order_statistics.tickets import OrderStatisticsTicketDetail
 from app.api.faq_types import FaqTypeList, FaqTypeListPost, FaqTypeDetail, FaqTypeRelationshipOptional, \
     FaqTypeRelationshipRequired
+from app.api.admin_sales.invoices import AdminSalesInvoicesList
 
 # users
 api.route(UserList, 'user_list', '/users')
@@ -505,3 +506,6 @@
 api.route(AdminStatisticsEventDetail, 'admin_statistics_event_detail', '/admin/statistics/events')
 api.route(AdminStatisticsUserDetail, 'admin_statistics_user_detail', '/admin/statistics/users')
 api.route(AdminStatisticsMailDetail, 'admin_statistics_mail_detail', '/admin/statistics/mails')
+
+# Admin Sales
+api.route(AdminSalesInvoicesList, 'admin_sales_invoices', '/admin/sales/invoices')
diff --git a/app/api/admin_sales/invoices.py b/app/api/admin_sales/invoices.py
new file mode 100644
--- /dev/null
+++ b/app/api/admin_sales/invoices.py
@@ -0,0 +1,47 @@
+from marshmallow_jsonapi import fields
+from marshmallow_jsonapi.flask import Schema
+from flask_rest_jsonapi import ResourceList
+
+from app.api.bootstrap import api
+from app.api.helpers.utilities import dasherize
+from app.models import db
+from app.models.event_invoice import EventInvoice
+
+
+class AdminSalesInvoicesSchema(Schema):
+    """
+    Sales invoices
+    """
+
+    class Meta:
+        type_ = 'admin-sales-invoices'
+        self_view = 'v1.admin_sales_invoices'
+        inflect = dasherize
+
+    id = fields.String()
+    identifier = fields.String()
+    status = fields.String()
+    amount = fields.Float()
+    created_at = fields.DateTime()
+    completed_at = fields.DateTime()
+    event_name = fields.Method('format_event_name')
+    sent_to = fields.Method('format_sent_to')
+
+    @staticmethod
+    def format_event_name(self):
+        return '{}'.format(self.event.name)
+
+    @staticmethod
+    def format_sent_to(self):
+        return '{} <{}>'.format(self.user.fullname, self.user.email)
+
+
+class AdminSalesInvoicesList(ResourceList):
+    """
+    Resource for sales invoices
+    """
+
+    methods = ['GET']
+    decorators = (api.has_permission('is_admin'), )
+    schema = AdminSalesInvoicesSchema
+    data_layer = {'model': EventInvoice, 'session': db.session}


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

Issue:
Add documentation to helpers in helpers/db.py
**Describe the bug**
The helpers in in db.py don't have associated documentation with them
**Expected behavior**
<!-- A clear and concise description of what you expected to happen. -->
They should have at least a line of text explaining what their inputs and outputs are

**Additional context**
<!-- Add any other context about the problem here. -->
https://github.com/fossasia/open-event-server/blob/1e442e4539339dda46ae93933fff0201310a76f1/app/api/helpers/db.py#L67


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
@@ -52,6 +52,11 @@ def safe_query(self, model, column_name, value, parameter_name):
 
 
 def get_or_create(model, **kwargs):
+    """
+    This function queries a record in the model, if not found it will create one.
+    :param model: db Model to be queried
+    :param **kwargs: Arguments to the filter_by method of sqlalchemy.orm.query.Query.filter_by to be filtered by
+    """
     was_created = False
     instance = db.session.query(model).filter_by(**kwargs).first()
     if instance:
@@ -64,7 +69,12 @@ def get_or_create(model, **kwargs):
         return instance, was_created
 
 
-def get_count(q):
-    count_q = q.statement.with_only_columns([func.count()]).order_by(None)
-    count = q.session.execute(count_q).scalar()
+def get_count(query):
+    """
+    Counts how many records are there in a database table/model
+    :param query: <sqlalchemy.orm.query.Query> a SQLAlchemy query object
+    :return: Number
+    """
+    count_q = query.statement.with_only_columns([func.count()]).order_by(None)
+    count = query.session.execute(count_q).scalar()
     return count


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

Issue:
Migration file for dashboard images has missing import
**Describe the bug**
The migration file for the recent dashboard images PR (#4836) has missing import.

**To Reproduce**
Upgrade your database after pulling from upstream development branch.

**Expected behavior**
Migration should be performed successfully.

**Stacktrace**
This is the error I got while upgrading the database:
```
File "/open-event-server/migrations/versions/dd7968d8d413_.py", line 19, in upgrade
    op.add_column('image_sizes', sa.Column('icon_size_quality', sa.Integer(), nullable=True))
NameError: name 'sa' is not defined
```

I will add the import line via a PR.


Discussion:

Resolving patch:
diff --git a/migrations/versions/dd7968d8d413_.py b/migrations/versions/dd7968d8d413_.py
--- a/migrations/versions/dd7968d8d413_.py
+++ b/migrations/versions/dd7968d8d413_.py
@@ -7,7 +7,7 @@
 """
 
 from alembic import op
-
+import sqlalchemy as sa
 
 # revision identifiers, used by Alembic.
 revision = 'dd7968d8d413'


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

Issue:
Populate DB for Moderator and Track organizer for permissions other then track
**Describe the bug**
<!-- A clear and concise description of what the bug is. -->

Currently, when we access the API `/v1/events-role-permissions` then only 22 objects present instead of 30
Event Roles = 6
Services = 5

In total expected permissions = 6 (Event Roles) X  5 (Services) = 30
This is due to `Moderator` and `Track organizer` having just Track permissions
Check [Moderator track permissions](https://github.com/fossasia/open-event-server/blob/development/populate_db.py#LC153) and [Track organizer permissions](https://github.com/fossasia/open-event-server/blob/development/populate_db.py#LC149)

**Hence other service permissions are missing.**
Then only we can update this permission which will be created while populating DB.

**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error

**Expected behavior**
<!-- A clear and concise description of what you expected to happen. -->

**Stacktrace**
<!-- If applicable, add stacktrace to help explain your problem. -->

**Additional details (please complete the following information):**
 - OS: [e.g. MacOS, Ubuntu, CentOS]
 - Python Version [e.g. `3.5`, `3.6`]
 - `HEAD` Commit hash [e.g. `4629c62`]

**Additional context**
<!-- Add any other context about the problem here. -->

**Wanna work on this issue**


Discussion:

Resolving patch:
diff --git a/populate_db.py b/populate_db.py
--- a/populate_db.py
+++ b/populate_db.py
@@ -146,13 +146,17 @@ def create_permissions():
         db.session.add(perm)
 
     # For TRACK_ORGANIZER
-    perm, _ = get_or_create(Permission, role=track_orgr, service=track)
-    db.session.add(perm)
+    for service in services:
+        perm, _ = get_or_create(Permission, role=track_orgr, service=service)
+        if not service == track:
+            perm.can_create, perm.can_update, perm.can_delete = False, False, False
+        db.session.add(perm)
 
     # For MODERATOR
-    perm, _ = get_or_create(Permission, role=mod, service=track)
-    perm.can_create, perm.can_update, perm.can_delete = False, False, False
-    db.session.add(perm)
+    for service in services:
+        perm, _ = get_or_create(Permission, role=mod, service=service)
+        perm.can_create, perm.can_update, perm.can_delete = False, False, False
+        db.session.add(perm)
 
     # For ATTENDEE and REGISTRAR
     services = [track, session, speaker, sponsor, microlocation]


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

Issue:
Multiple Orders can be linked to an attendee.
**Describe the bug**
<!-- A clear and concise description of what the bug is. -->
Right now we can multiple orders related to an attendee.

**To Reproduce**
Steps to reproduce the behavior:
1. Create two orders relating it to the same attendee.

**Expected behavior**
<!-- A clear and concise description of what you expected to happen. -->
An attendee should have one and only one related order.

**Additional context**
<!-- Add any other context about the problem here. -->
Parent issue: #4852 


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
@@ -5,10 +5,11 @@
 from flask_rest_jsonapi import ResourceDetail, ResourceList, ResourceRelationship
 from marshmallow_jsonapi import fields
 from marshmallow_jsonapi.flask import Schema
+from sqlalchemy.orm.exc import NoResultFound
 
 from app.api.data_layers.ChargesLayer import ChargesLayer
 from app.api.helpers.db import save_to_db, safe_query
-from app.api.helpers.exceptions import ForbiddenException, UnprocessableEntity
+from app.api.helpers.exceptions import ForbiddenException, UnprocessableEntity, ConflictException
 from app.api.helpers.files import create_save_pdf
 from app.api.helpers.files import make_frontend_url
 from app.api.helpers.mail import send_email_to_attendees
@@ -50,6 +51,17 @@ def before_create_object(self, data, view_kwargs):
         :param view_kwargs:
         :return:
         """
+        for ticket_holder in data['ticket_holders']:
+            # Ensuring that the attendee exists and doesn't have an associated order.
+            try:
+                ticket_holder_object = self.session.query(TicketHolder).filter_by(id=int(ticket_holder)).one()
+                if ticket_holder_object.order_id:
+                    raise ConflictException({'pointer': '/data/relationships/attendees'},
+                                            "Order already exists for attendee with id {}".format(str(ticket_holder)))
+            except NoResultFound:
+                raise ConflictException({'pointer': '/data/relationships/attendees'},
+                                        "Attendee with id {} does not exists".format(str(ticket_holder)))
+
         if data.get('cancel_note'):
             del data['cancel_note']
 


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

Issue:
Wrong exception raised in before_post of access code
**Describe the bug**
<!-- A clear and concise description of what the bug is. -->
Right when the user doesn't have the coorganizer access to an event, we are raising object not found exception. 
```Python
if not has_access('is_coorganizer', event_id=data['event']):
            raise ObjectNotFound({'parameter': 'event_id'},
                                 "Event: {} not found".format(data['event']))
```

**Expected behavior**
<!-- A clear and concise description of what you expected to happen. -->
We should raise Forbidden exception.
```Python
if not has_access('is_coorganizer', event_id=data['event']):
            raise ForbiddenException({'source': ''}, "Minimum Organizer access required")
```


Discussion:
can i work on this?

Resolving patch:
diff --git a/app/api/access_codes.py b/app/api/access_codes.py
--- a/app/api/access_codes.py
+++ b/app/api/access_codes.py
@@ -29,8 +29,7 @@ def before_post(self, args, kwargs, data):
         """
         require_relationship(['event', 'user'], data)
         if not has_access('is_coorganizer', event_id=data['event']):
-            raise ObjectNotFound({'parameter': 'event_id'},
-                                 "Event: {} not found".format(data['event']))
+            raise ForbiddenException({'source': ''}, "Minimum Organizer access required")
 
     schema = AccessCodeSchema
     methods = ['POST', ]


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

Issue:
Use UserSchemaPublic if user wants details of others
**Describe the bug**
<!-- A clear and concise description of what the bug is. -->
We are using UserSchema for both UserList and UserDetail so what is the point of having UserSchemaPublic
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error

**Expected behavior**
<!-- A clear and concise description of what you expected to happen. -->
Use UserSchemaPublic if user wants details of his own
**Stacktrace**
<!-- If applicable, add stacktrace to help explain your problem. -->

**Additional details (please complete the following information):**
 - OS: [e.g. MacOS, Ubuntu, CentOS]
 - Python Version [e.g. `3.5`, `3.6`]
 - `HEAD` Commit hash [e.g. `4629c62`]

**Additional context**
<!-- Add any other context about the problem here. -->

**Working on it**


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
@@ -1,6 +1,7 @@
 import base64
 
 from flask_rest_jsonapi import ResourceDetail, ResourceList, ResourceRelationship
+from flask_jwt import current_identity as current_user
 
 from app import get_settings
 from app.api.bootstrap import api
@@ -8,7 +9,7 @@
 from app.api.helpers.mail import send_email_confirmation, send_email_change_user_email, send_email_with_action
 from app.api.helpers.permissions import is_user_itself
 from app.api.helpers.utilities import get_serializer, str_generator
-from app.api.schema.users import UserSchema
+from app.api.schema.users import UserSchema, UserSchemaPublic
 from app.models import db
 from app.models.access_code import AccessCode
 from app.models.discount_code import DiscountCode
@@ -80,6 +81,13 @@ class UserDetail(ResourceDetail):
     """
     User detail by id
     """
+    def before_get(self, args, kwargs):
+
+        if current_user.is_admin or current_user.is_super_admin or current_user:
+            self.schema = UserSchema
+        else:
+            self.schema = UserSchemaPublic
+
     def before_get_object(self, view_kwargs):
         """
         before get method for user object


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

Issue:
Events shouldn't be published if the user is not user e-mail is not confirmed
###### Original issue submitted by @Kreijstal in https://github.com/fossasia/open-event-frontend/issues/1279
---
**Describe the bug**
Events shouldn't be published if the user e-mail is not confirmed 
**To Reproduce**
Steps to reproduce the behavior:
Attempt to log-in as user that is not confirmed

**Expected behavior**
<!-- A clear and concise description of what you expected to happen. -->
Basically, if a user is not confirmed it shouldn't allow them to publish events, but they can still create events.


Discussion:

Resolving patch:
diff --git a/app/api/events.py b/app/api/events.py
--- a/app/api/events.py
+++ b/app/api/events.py
@@ -109,11 +109,16 @@ def query(self, view_kwargs):
     def before_post(self, args, kwargs, data=None):
         """
         before post method to verify if the event location is provided before publishing the event
+        and checks that the user is verified
         :param args:
         :param kwargs:
         :param data:
         :return:
         """
+        is_verified = User.query.filter_by(id=kwargs['user_id']).first().is_verified
+        if (data.get('state', None) == 'published' and not is_verified):
+            raise ForbiddenException({'source': ''},
+                                      "Only verified accounts can publish events")
         if data.get('state', None) == 'published' and not data.get('location_name', None):
             raise ConflictException({'pointer': '/data/attributes/location-name'},
                                     "Location is required to publish the event")
diff --git a/populate_db.py b/populate_db.py
--- a/populate_db.py
+++ b/populate_db.py
@@ -194,7 +194,7 @@ def create_user_permissions():
     # Create Event
     user_perm, _ = get_or_create(UserPermission, name='create_event',
                                  description='Create event')
-    user_perm.verified_user, user_perm.unverified_user = True, True
+    user_perm.verified_user, user_perm.unverified_user = True, False
     db.session.add(user_perm)
 
 


Test patch: