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

Issue:
Custom-Form endpoint does not allow number as the type of input field 
**Describe the bug**
When creating custom form, if we define a field to be of type number. We get 422 Unprocessable Entity Error. Server accepts payload of this type.
```
"attributes": {
      "is-required": true,
      "form": "form",
      "field-identifier": "abc123",
      "is-included": false,
      "is-fixed": false,
      "type": "text"
    },
```
Whereas what I tried sending is : 
```
 "attributes": {
            "field-identifier": "mobile",
            "form": "speaker",
            "type": "number",
            "is-required": false,
            "is-included": true,
            "is-fixed": false
        },
```

**Expected behavior**
Since mobile number should not be a text input. Server should accept number as the type of input field.
Related issue on frontend: https://github.com/fossasia/open-event-frontend/issues/1170



Discussion:

Resolving patch:
diff --git a/app/api/schema/custom_forms.py b/app/api/schema/custom_forms.py
--- a/app/api/schema/custom_forms.py
+++ b/app/api/schema/custom_forms.py
@@ -24,7 +24,8 @@ class Meta:
     field_identifier = fields.Str(required=True)
     form = fields.Str(required=True)
     type = fields.Str(default="text", validate=validate.OneOf(
-        choices=["text", "checkbox", "select", "file", "image", "email"]))
+        choices=["text", "checkbox", "select", "file", "image", "email",
+                 "number"]))
     is_required = fields.Boolean(default=False)
     is_included = fields.Boolean(default=False)
     is_fixed = fields.Boolean(default=False)


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

Issue:
Admin Access required for accessing Order endpoint
**Describe the bug**
Admin access is required for endpoints related to Order. 

**To Reproduce**
GET/POST request to Order endpoints.

**Expected behavior**
The organizer should be able to query the Order endpoints as it was before.

**Stacktrace**
`{
    "errors": [
        {
            "status": 403,
            "source": {
                "source": ""
            },
            "title": "Access Forbidden",
            "detail": "Admin Access Required"
        }
    ],
    "jsonapi": {
        "version": "1.0"
    }
}`





Discussion:
@Masquerade0097 Plan to work on it ?
@srv-twry Yes

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,11 +127,8 @@ def before_get(self, args, kwargs):
         :param kwargs:
         :return:
         """
-        if kwargs.get('event_id') is None:
-            if 'GET' in request.method and has_access('is_admin'):
-                pass
-            else:
-                raise ForbiddenException({'source': ''}, "Admin Access Required")
+        if 'GET' in request.method and kwargs.get('event_id') is None:
+            pass
         elif not has_access('is_coorganizer', event_id=kwargs['event_id']):
             raise ForbiddenException({'source': ''}, "Co-Organizer Access Required")
 


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

Issue:
Change is-ticketing-enabled field of Event to dump_only
**I'm submitting a ...**  (check one with "x")
- [ ] bug report
- [x] feature request
- [ ] support request => Please do not submit support requests here, instead ask your query in out Gitter channel at https://gitter.im/fossasia/open-event-server

**Current behavior:**
It is possible to create tickets for an event in which is-ticketing-enabled field is set to false.

**Expected behavior:**
Either the field should be made dump_only or appropiate constraints must be imposed to ckeck this behaviour.

**Steps to reproduce:**
1. Create an event with is-ticketing-enabled attribute to false.
2. Create Ticket for that Event.



Discussion:
@iamareebjamal @niranjan94 @shubham-padia Should I make the field dump_only or impose constraints to check the above behaviour ?
@poush Please review.
I checked the Ticket Schema, there is no validation for this. So yes this check has to be done in the ticket API schema where on creating ticket, event will be checked first for this flag.

Resolving patch:
diff --git a/app/api/tickets.py b/app/api/tickets.py
--- a/app/api/tickets.py
+++ b/app/api/tickets.py
@@ -11,8 +11,9 @@
 from app.models.access_code import AccessCode
 from app.models.order import Order
 from app.models.ticket import Ticket, TicketTag, ticket_tags_table
+from app.models.event import Event
 from app.models.ticket_holder import TicketHolder
-from app.api.helpers.exceptions import ConflictException
+from app.api.helpers.exceptions import ConflictException, MethodNotAllowed
 from app.api.helpers.db import get_count
 
 
@@ -36,6 +37,9 @@ def before_post(self, args, kwargs, data):
         if get_count(db.session.query(Ticket.id).filter_by(name=data['name'], event_id=int(data['event']))) > 0:
             raise ConflictException({'pointer': '/data/attributes/name'}, "Ticket already exists")
 
+        if get_count(db.session.query(Event).filter_by(id=int(data['event']), is_ticketing_enabled=False)) > 0:
+            raise MethodNotAllowed({'parameter': 'event_id'}, "Ticketing is disabled for this Event")
+
     schema = TicketSchema
     methods = ['POST', ]
     data_layer = {'session': db.session,


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

Issue:
Add create_settings() and create_modules() in populate_without_print()
**Describe the bug**
<!-- A clear and concise description of what the bug is. -->

Addition of create_settings() and create_modules() in populate_without_print()

**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. -->
create_settings() and create_modules() function should be also in populate_without_print()
**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**


Discussion:

Resolving patch:
diff --git a/populate_db.py b/populate_db.py
--- a/populate_db.py
+++ b/populate_db.py
@@ -197,6 +197,8 @@ def populate_without_print():
     create_custom_sys_roles()
     create_panel_permissions()
     create_user_permissions()
+    create_settings()
+    create_modules()
     create_admin_message_settings()
 
     db.session.commit()


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

Issue:
Multiple Speakers call allowed for a single Event.
**Describe the bug**
We can create another Speakers call even when we have created one already. It creates a new one and links it to the event after overwriting the relationship.

**To Reproduce**
Steps to reproduce the behavior:
1. Try to create two speakers call for an event.

**Expected behavior**
Upon attempting to create a second one, It should throw an error.

**Additional details (please complete the following information):**
Doesn't matter here.

**Additional context**
N/A



Discussion:

Resolving patch:
diff --git a/app/api/speakers_calls.py b/app/api/speakers_calls.py
--- a/app/api/speakers_calls.py
+++ b/app/api/speakers_calls.py
@@ -3,7 +3,7 @@
 from sqlalchemy.orm.exc import NoResultFound
 
 from app.api.bootstrap import api
-from app.api.helpers.exceptions import ForbiddenException
+from app.api.helpers.exceptions import ForbiddenException, ConflictException
 from app.api.helpers.permission_manager import has_access
 from app.api.helpers.utilities import require_relationship
 from app.api.schema.speakers_calls import SpeakersCallSchema
@@ -28,10 +28,28 @@ def before_post(self, args, kwargs, data):
         if not has_access('is_coorganizer', event_id=data['event']):
             raise ForbiddenException({'source': ''}, 'Co-organizer access is required.')
 
+    def before_create_object(self, data, view_kwargs):
+        """
+        method to check if speaker calls object already exists for an event
+        :param data:
+        :param view_kwargs:
+        :return:
+        """
+        try:
+            self.session.query(SpeakersCall).filter_by(event_id=data['event']).one()
+        except NoResultFound:
+            pass
+        else:
+            raise ConflictException({'pointer': '/data/relationships/event'},
+                                    "Speakers Call already exists for this event")
+
     schema = SpeakersCallSchema
     methods = ['POST', ]
     data_layer = {'session': db.session,
-                  'model': SpeakersCall}
+                  'model': SpeakersCall,
+                  'methods': {
+                      'before_create_object': before_create_object
+                  }}
 
 
 class SpeakersCallDetail(ResourceDetail):


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

Issue:
We can create Sessions and Speakers even if it is disabled in the Event properties.
**Describe the bug**
We can create Sessions and Speakers even if the variable ```isSessionsSpeakersEnabled``` is set to false.

**To Reproduce**
Steps to reproduce the behavior:
1. Create an event with ```isSessionsSpeakersEnabled``` as false or update an existing one.
2. Now try to create a session or a speaker.

**Expected behavior**
It doesn't make sense to create sessions when it is disabled in the event.

**Additional context**
<!-- Add any other context about the problem here. -->
![in_event_its_false](https://user-images.githubusercontent.com/21277837/40687066-0c05ac4c-63b7-11e8-87d2-8103ab2a4dae.png)
![still_can_create_one](https://user-images.githubusercontent.com/21277837/40687070-106c0010-63b7-11e8-8ab9-de672b455eff.png)



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
@@ -2,7 +2,8 @@
 
 from app.api.bootstrap import api
 from app.api.events import Event
-from app.api.helpers.db import safe_query
+from app.api.helpers.db import safe_query, get_count
+from app.api.helpers.exceptions import ForbiddenException
 from app.api.helpers.mail import send_email_new_session, send_email_session_accept_reject
 from app.api.helpers.notification import send_notif_new_session_organizer, send_notif_session_accept_reject
 from app.api.helpers.permissions import current_identity
@@ -33,6 +34,8 @@ def before_post(self, args, kwargs, data):
         """
         require_relationship(['event'], 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")
 
     def after_create_object(self, session, data, view_kwargs):
         """
diff --git a/app/api/speakers.py b/app/api/speakers.py
--- a/app/api/speakers.py
+++ b/app/api/speakers.py
@@ -3,7 +3,8 @@
 from flask_rest_jsonapi.exceptions import ObjectNotFound
 
 from app.api.bootstrap import api
-from app.api.helpers.db import safe_query
+from app.api.helpers.db import safe_query, get_count
+from app.api.helpers.exceptions import ForbiddenException
 from app.api.helpers.permission_manager import has_access
 from app.api.helpers.query import event_query
 from app.api.helpers.utilities import require_relationship
@@ -36,6 +37,9 @@ def before_post(self, args, kwargs, data):
                     raise ObjectNotFound({'parameter': 'event_id'},
                                          "Event: {} not found".format(data['event_id']))
 
+        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 'sessions' in data:
             session_ids = data['sessions']
             for session_id in session_ids:


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

Issue:
Sponsors can be created even when disabled in Event properties
**Describe the bug**
Sponsors can be created even when disabled in Event properties, i.e. even if the variable `is-sponsors-enabled` is set to false

**To Reproduce**
Steps to reproduce the behavior:
1. Create an event with `is-sponsors-enabled: false` or update an existing one.
2. Now try to create a Sponsor

**Expected behavior**
Sponsor creation shouldn't be allowed if Sponsors are disabled for the event.

**Additional details (please complete the following information):**
 - OS: Ubuntu
 - Python Version: `3.6`
 - `HEAD`: `a84e05ee`

**Additional context**

![screenshot from 2018-05-30 05-37-29](https://user-images.githubusercontent.com/35009811/40691803-b07dcf34-63cb-11e8-9139-1fa7e46667b5.png)

![screenshot from 2018-05-30 05-38-09](https://user-images.githubusercontent.com/35009811/40691802-ae380f00-63cb-11e8-89fd-10b505bc99fb.png)


Discussion:

Resolving patch:
diff --git a/app/api/sponsors.py b/app/api/sponsors.py
--- a/app/api/sponsors.py
+++ b/app/api/sponsors.py
@@ -1,6 +1,8 @@
 from flask_rest_jsonapi import ResourceDetail, ResourceList, ResourceRelationship
 
 from app.api.bootstrap import api
+from app.api.events import Event
+from app.api.helpers.db import get_count
 from app.api.helpers.exceptions import ForbiddenException
 from app.api.helpers.permission_manager import has_access
 from app.api.helpers.query import event_query
@@ -25,6 +27,8 @@ def before_post(self, args, kwargs, data):
         require_relationship(['event'], data)
         if not has_access('is_coorganizer', event_id=data['event']):
             raise ForbiddenException({'source': ''}, 'Co-organizer access is required.')
+        if get_count(db.session.query(Event).filter_by(id=int(data['event']), is_sponsors_enabled=False)) > 0:
+            raise ForbiddenException({'pointer': ''}, "Sponsors are disabled for this Event")
 
     methods = ['POST']
     schema = SponsorSchema
diff --git a/app/factories/event.py b/app/factories/event.py
--- a/app/factories/event.py
+++ b/app/factories/event.py
@@ -42,7 +42,7 @@ class Meta:
     cheque_details = common.string_
     bank_details = common.string_
     onsite_details = common.string_
-    is_sponsors_enabled = False
+    is_sponsors_enabled = True
     pentabarf_url = common.url_
     ical_url = common.url_
     xcal_url = common.url_


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

Issue:
Server does not return hidden tickets
**Describe the bug**
Currently server is returning only those tickets whose `is-hidden` property is false. Whereas server should return all the tickets and frontend should be ready to display them to organizer and not to public. So in current case event organiser is not able to access/edit the ticket that he made hidden during a edit.

**To Reproduce**
Steps to reproduce the behavior:
1. Create a event and have two tickets one hidden and other one as public.
2. Now save the event.
3. Now go back to edit the event and ticket details.
4. You see that ticket you made hidden is not listed.

**Expected behavior**
Even hidden tickets should be available to organiser to edit.



Discussion:
I am working on this.

Resolving patch:
diff --git a/app/api/tickets.py b/app/api/tickets.py
--- a/app/api/tickets.py
+++ b/app/api/tickets.py
@@ -1,5 +1,7 @@
+from flask import request, current_app
 from flask_rest_jsonapi import ResourceDetail, ResourceList, ResourceRelationship
 from flask_rest_jsonapi.exceptions import ObjectNotFound
+from flask_jwt import current_identity as current_user, _jwt_required
 
 from app.api.bootstrap import api
 from app.api.helpers.db import safe_query
@@ -66,7 +68,18 @@ def query(self, view_kwargs):
         :param view_kwargs:
         :return:
         """
-        query_ = self.session.query(Ticket).filter_by(is_hidden=False)
+
+        if 'Authorization' in request.headers:
+            _jwt_required(current_app.config['JWT_DEFAULT_REALM'])
+            if current_user.is_super_admin or current_user.is_admin:
+                query_ = self.session.query(Ticket)
+            elif view_kwargs.get('event_id') and has_access('is_organizer', event_id=view_kwargs['event_id']):
+                query_ = self.session.query(Ticket)
+            else:
+                query_ = self.session.query(Ticket).filter_by(is_hidden=False)
+        else:
+            query_ = self.session.query(Ticket).filter_by(is_hidden=False)
+
         if view_kwargs.get('ticket_tag_id'):
             ticket_tag = safe_query(self, TicketTag, 'id', view_kwargs['ticket_tag_id'], 'ticket_tag_id')
             query_ = query_.join(ticket_tags_table).filter_by(ticket_tag_id=ticket_tag.id)


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

Issue:
Access-Code: Access codes returns HTTP 422 when max and min quantity is equal
**Describe the bug**
<!-- A clear and concise description of what the bug is. -->
Access codes returns HTTP 422 when max and min quantity is equal

**To Reproduce**
Steps to reproduce the behavior:
Create an access code with equal max and min quantity.

**Expected behavior**
<!-- A clear and concise description of what you expected to happen. -->
It should only return 422 when min qty is strictly greater than the max qty.


Discussion:
@srv-twry Can I take this one?
yes, go ahead.

Resolving patch:
diff --git a/app/api/schema/access_codes.py b/app/api/schema/access_codes.py
--- a/app/api/schema/access_codes.py
+++ b/app/api/schema/access_codes.py
@@ -34,7 +34,7 @@ def validate_date(self, data, original_data):
             if 'valid_till' not in data:
                 data['valid_till'] = access_code.valid_till
 
-        if data['valid_from'] >= data['valid_till']:
+        if data['valid_from'] > data['valid_till']:
             raise UnprocessableEntity({'pointer': '/data/attributes/valid-till'},
                                       "valid_till should be after valid_from")
 
@@ -55,7 +55,7 @@ def validate_order_quantity(self, data, original_data):
         min_quantity = data.get('min_quantity', None)
         max_quantity = data.get('max_quantity', None)
         if min_quantity is not None and max_quantity is not None:
-            if min_quantity >= max_quantity:
+            if min_quantity > max_quantity:
                 raise UnprocessableEntity(
                     {'pointer': '/data/attributes/min-quantity'},
                     "min-quantity should be less than max-quantity"


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

Issue:
Events should also have average rating
**Is your feature request related to a problem? Please describe.**
Events should have an average rating attribute

**Describe the solution you'd like**
Will use Postgres aggregate clauses to compute the average, and perhaps some other tools for caching the average value, if need be.

**Additional context**
Discussed in #4728

I'd like to implement this.


Discussion:
@schedutron Working on it ? or may I do it.
@bhaveshAn I'm working on it, but having a hard time mapping aggregates of one model to the field of another. I've discussed this with @srv-twry and he's given me some documentation to read. I'll soon open a WIP PR and if I'm unable to accomplish this, I'll hand over this issue to you soon 😄

By the way, another issue I'm having trouble with is #4744. You can take that up if you want. 👍

Resolving patch:
diff --git a/app/api/schema/events.py b/app/api/schema/events.py
--- a/app/api/schema/events.py
+++ b/app/api/schema/events.py
@@ -106,6 +106,8 @@ def validate_timezone(self, data, original_data):
     pentabarf_url = fields.Url(dump_only=True)
     ical_url = fields.Url(dump_only=True)
     xcal_url = fields.Url(dump_only=True)
+    average_rating = fields.Float(dump_only=True)
+
     tickets = Relationship(attribute='tickets',
                            self_view='v1.event_ticket',
                            self_view_kwargs={'id': '<id>'},
diff --git a/app/models/event.py b/app/models/event.py
--- a/app/models/event.py
+++ b/app/models/event.py
@@ -6,11 +6,13 @@
 import pytz
 from flask import current_app
 from sqlalchemy import event
+from sqlalchemy.sql import func
 
 from app.api.helpers.db import get_count
 from app.models import db
 from app.models.base import SoftDeletionModel
 from app.models.email_notification import EmailNotification
+from app.models.feedback import Feedback
 from app.models.helpers.versioning import clean_up_string, clean_html
 from app.models.user import ATTENDEE, ORGANIZER
 from app.views.redis_store import redis_store
@@ -274,6 +276,16 @@ def notification_settings(self, user_id):
         except:
             return None
 
+    def get_average_rating(self):
+        avg = db.session.query(func.avg(Feedback.rating)).filter_by(event_id=self.id).scalar()
+        if avg is not None:
+            avg = round(avg, 2)
+        return avg
+
+    @property
+    def average_rating(self):
+        return self.get_average_rating()
+
     def get_organizer(self):
         """returns organizer of an event"""
         for role in self.roles:


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

Issue:
HTTP 500 on GET Stripe Authorization without creating it.
**Describe the bug**
<!-- A clear and concise description of what the bug is. -->
The server returns HTTP 500 when we use the /event/<event_id>/stripe-authorization endpoint to fetch Stripe authorization details and no stripe config exists for the event.

**To Reproduce**
Steps to reproduce the behavior:
1. Use the above endpoint as explained.

**Expected behavior**
<!-- A clear and concise description of what you expected to happen. -->
It should send HTTP 404 instead of HTTP 500


Discussion:

Resolving patch:
diff --git a/app/api/stripe_authorization.py b/app/api/stripe_authorization.py
--- a/app/api/stripe_authorization.py
+++ b/app/api/stripe_authorization.py
@@ -84,8 +84,8 @@ def before_get_object(self, view_kwargs):
             view_kwargs['event_id'] = event.id
 
         if view_kwargs.get('event_id'):
-            stripe_authorization = self.session.query(StripeAuthorization).\
-                filter_by(event_id=view_kwargs['event_id']).one()
+            stripe_authorization = \
+                safe_query(self, StripeAuthorization, 'event_id', view_kwargs['event_id'], 'event_id')
             view_kwargs['id'] = stripe_authorization.id
 
     decorators = (api.has_permission('is_coorganizer', fetch="event_id",


Test patch: