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

Issue:
Server crashing on order PATCH
```
KeyError: 'mytickets_url'
(16 additional frame(s) were not displayed)
...
  File "flask_rest_jsonapi/decorators.py", line 56, in wrapper
    return func(*args, **kwargs)
  File "flask_rest_jsonapi/resource.py", line 310, in patch
    self._data_layer.update_object(obj, data, kwargs)
  File "flask_rest_jsonapi/data_layers/alchemy.py", line 144, in update_object
    self.after_update_object(obj, data, view_kwargs)
  File "app/api/orders.py", line 601, in after_update_object
    attachments=[ticket_path, invoice_path],
  File "app/api/helpers/mail.py", line 354, in send_email_to_attendees
    event_name=order.event.name,
```

Rolled back the release


Discussion:
@iamareebjamal I tried patching an order . It worked successfully. Any specific endpoint ? I used `PATCH /v1/orders/{identifier}`

Edit: Reproduced error

Resolving patch:
diff --git a/app/api/helpers/system_mails.py b/app/api/helpers/system_mails.py
--- a/app/api/helpers/system_mails.py
+++ b/app/api/helpers/system_mails.py
@@ -190,7 +190,7 @@
             u"<br/>Your order has been processed successfully."
             + u"<br/> Your tickets & invoice have been enclosed."
             u"<br><br>You can also download your tickets in <b>My Tickets</b> section."
-            u"<br/>Login to manage the orders at <a href='{mytickets_url}' target='_blank'>{mytickets_url}</a> </em>"
+            u"<br/>Login to manage the orders at <a href='{my_tickets_url}' target='_blank'>{my_tickets_url}</a> </em>"
             u"<br><br><em>Looking forward to seeing you at the event."
         ),
     },


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

Issue:
Integrate Sentry APM tracing
https://docs.sentry.io/performance/distributed-tracing/#python

And enable SQLAlchemy integration


Discussion:
I would like to fix this!  Assign me
Please go ahead. We don't assign external contributors

Resolving patch:
diff --git a/app/instance.py b/app/instance.py
--- a/app/instance.py
+++ b/app/instance.py
@@ -200,6 +200,7 @@ def create_app():
                 CeleryIntegration(),
                 SqlalchemyIntegration(),
             ],
+            traces_sample_rate=0.1
         )
 
     # redis


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

Issue:
PATCH in old session raises date error
`starts-at should be after current date-time`

Later, it should only validate changed data and not existing one


Discussion:

Resolving patch:
diff --git a/app/api/schema/sessions.py b/app/api/schema/sessions.py
--- a/app/api/schema/sessions.py
+++ b/app/api/schema/sessions.py
@@ -33,7 +33,8 @@ class Meta:
 
     @validates_schema(pass_original=True)
     def validate_fields(self, data, original_data):
-        if 'id' in original_data['data']:
+        is_patch_request = 'id' in original_data['data']
+        if is_patch_request:
             try:
                 session = Session.query.filter_by(id=original_data['data']['id']).one()
             except NoResultFound:
@@ -54,9 +55,9 @@ def validate_fields(self, data, original_data):
                     {'pointer': '/data/attributes/ends-at'},
                     "ends-at should be after starts-at",
                 )
-            if datetime.timestamp(data['starts_at']) <= datetime.timestamp(
-                datetime.now()
-            ):
+            if not is_patch_request and datetime.timestamp(
+                data['starts_at']
+            ) <= datetime.timestamp(datetime.now()):
                 raise UnprocessableEntity(
                     {'pointer': '/data/attributes/starts-at'},
                     "starts-at should be after current date-time",


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

Issue:
Error while sending monthly invoice
```
NoResultFound: No row was found for one()
  File "app/api/helpers/scheduled_jobs.py", line 256, in send_monthly_event_invoice
    db.session.query(TicketFees).filter_by(currency=currency).one()
  File "sqlalchemy/orm/query.py", line 3354, in one
    raise orm_exc.NoResultFound("No row was found for one()")
ObjectNotFound: ({'source': ''}, 'Ticket Fee not set for None')
  File "app/api/helpers/scheduled_jobs.py", line 260, in send_monthly_event_invoice
    {'source': ''}, 'Ticket Fee not set for {}'.format(currency)
```

We should never be throwing unhandled exceptions in jobs where no one can handle them

```
events = [
<Event 'Yogesh Sharma'>
, 
<Event '"/><img src="x" onerror="alert(document.domain)">'>
, 
<Event 'testing'>
, 
<Event 'Hackathon'>
, 
<Event 'Jamia Hamdard Convocation'>
, 
<Event 'OpenTechSummit Day Mekong'>
, 
<Event 'FOSSASIA Meetup - PSLab'>
, 
<Event 'Introduction to open source'>
, 
<Event 'Yogesh Sharma'>
, 
<Event 'OpenTechSummit India'>
]

event = <Event 'Yogesh Sharma'>
```


Discussion:
IMO as can be seen from logs Ticket Fee is not set in the Admin Panel .
So, should the task crash because of it?
@iamareebjamal - When ticketFee is not found, then 
what shall be the value of them below .. 0 ?

>  ticket_fee_percentage = ticket_fee_object.service_fee
     ticket_fee_maximum = ticket_fee_object.maximum_fee 

Skip that entry and log an error

Resolving patch:
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
@@ -3,7 +3,6 @@
 import pytz
 from dateutil.relativedelta import relativedelta
 from sqlalchemy.orm.exc import NoResultFound
-from flask_rest_jsonapi.exceptions import ObjectNotFound
 from flask import render_template
 from flask_celeryext import RequestContextTask
 
@@ -32,7 +31,9 @@
 from app.models.ticket_fee import TicketFees, get_fee
 from app.models.ticket_holder import TicketHolder
 from app.settings import get_settings
+import logging
 
+logger = logging.getLogger(__name__)
 
 @celery.task(base=RequestContextTask, name='send.after.event.mail')
 def send_after_event_mail():
@@ -256,9 +257,9 @@ def send_monthly_event_invoice():
                     db.session.query(TicketFees).filter_by(currency=currency).one()
                 )
             except NoResultFound:
-                raise ObjectNotFound(
-                    {'source': ''}, 'Ticket Fee not set for {}'.format(currency)
-                )
+                logger.error('Ticket Fee not found for event id {id}'.format(id=event.id))
+                continue
+
             ticket_fee_percentage = ticket_fee_object.service_fee
             ticket_fee_maximum = ticket_fee_object.maximum_fee
             orders = Order.query.filter_by(event=event).all()


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

Issue:
Discount Code creation failed
After merging of #6985, discount code creation fails:

For some bizarre reason, user_id was passed in constructor of DiscountCode and then set to marketer_id :man_shrugging: 
Anyway it was still working because for another bizarre reason, marketer passed from the API was changed to user_id on server :man_shrugging: :shrug: 

So now, because the constructor is removed, there is no user_id kwarg in Discount Code and it throws. ~~The build didn't break because no dredd test was present for passing marketer ID.~~ I am not sure why is it even needed, but add the test for now to ensure it doesn't break in future

Edit: It was present in Dredd tests but disabled in #4854


Discussion:
See #4964 and #4911 for relevant changes

Resolving patch:
diff --git a/app/__init__.py b/app/__init__.py
--- a/app/__init__.py
+++ b/app/__init__.py
@@ -0,0 +1,4 @@
+def create_app():
+    from .instance import app
+
+    return app
diff --git a/app/api/discount_codes.py b/app/api/discount_codes.py
--- a/app/api/discount_codes.py
+++ b/app/api/discount_codes.py
@@ -69,7 +69,7 @@ def before_post(self, args, kwargs, data):
                 {'source': ''}, "Please verify your permission or check your relationship"
             )
 
-        data['user_id'] = current_user.id
+        data['marketer_id'] = current_user.id
 
     def before_create_object(self, data, view_kwargs):
         if data['used_for'] == '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
@@ -72,7 +72,7 @@
 stash = {}
 api_username = "open_event_test_user@fossasia.org"
 api_password = "fossasia"
-api_uri = "http://localhost:5000/v1/auth/login"
+api_uri = "http://localhost:5555/v1/auth/login"
 
 
 def obtain_token():
@@ -2872,14 +2872,9 @@ def event_discount_code_post(transaction):
     :param transaction:
     :return:
     """
-    transaction['skip'] = True
-
-
-#   TODO: This is breaking the build, we need to repair it eventually.
-#   with stash['app'].app_context():	+    transaction['skip'] = True
-#        event = EventFactoryBasic()
-#        db.session.add(event)
-#        db.session.commit()
+    with stash['app'].app_context():
+        EventFactoryBasic()
+        db.session.commit()
 
 
 @hooks.before(
@@ -2891,11 +2886,9 @@ def ticket_discount_code_post(transaction):
     :param transaction:
     :return:
     """
-    transaction['skip'] = True
-    # with stash['app'].app_context():
-    #     event = EventFactoryBasic()
-    #     db.session.add(event)
-    #     db.session.commit()
+    with stash['app'].app_context():
+        TicketFactory()
+        db.session.commit()
 
 
 @hooks.before(
Repository: fossasia/open-event-server

Issue:
Speaker Schema should not receive user relationship
Unless entered by the admin, the user relationship in speaker schema in POST and PATCH should be rejected and replaced with currently logged in user.


Discussion:

Resolving patch:
diff --git a/app/api/schema/speakers.py b/app/api/schema/speakers.py
--- a/app/api/schema/speakers.py
+++ b/app/api/schema/speakers.py
@@ -73,6 +73,7 @@ class Meta:
         related_view_kwargs={'speaker_id': '<id>'},
         schema='UserSchemaPublic',
         type_='user',
+        dump_only=True,
     )
     sessions = Relationship(
         attribute='sessions',


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

Issue:
Session accept reject email sent without state changes
In session after_update_object, session accept reject email is sent if the final state of session is 'accepted' or 'rejected'. This is not desirable as the email will be sent even when there is any update about the session and not necessarily change in state. Thus, email should only be sent when there a change in 'state' of session, and not any change in session data itself


Discussion:
@iamareebjamal I get that here we want to remove `accepted` and `rejected` check. But do I also need to check that the status has actually changed?
Yes

Resolving patch:
diff --git a/app/api/sessions.py b/app/api/sessions.py
--- a/app/api/sessions.py
+++ b/app/api/sessions.py
@@ -1,4 +1,4 @@
-from flask import request
+from flask import request, g
 from flask_jwt_extended import current_user
 from flask_rest_jsonapi import ResourceDetail, ResourceList, ResourceRelationship
 from flask_rest_jsonapi.querystring import QueryStringManager as QSManager
@@ -256,8 +256,10 @@ def before_update_object(self, session, data, view_kwargs):
             )
 
         new_state = data.get('state')
+
         if new_state and new_state != session.state:
             # State change detected. Verify that state change is allowed
+            g.send_email = new_state == 'accepted' or new_state == 'rejected'
             key = 'speaker'
             if is_organizer:
                 key = 'organizer'
@@ -282,12 +284,7 @@ def before_update_object(self, session, data, view_kwargs):
     def after_update_object(self, session, data, view_kwargs):
         """ Send email if session accepted or rejected """
 
-        if (
-            'state' in data
-            and data.get('send_email', None)
-            and (session.state == 'accepted' or session.state == 'rejected')
-        ):
-
+        if data.get('send_email', None) and g.get('send_email'):
             event = session.event
             # Email for speaker
             speakers = session.speakers


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

Issue:
Stripe publishable key should be accessible to non-admin user
The settings schema for non-admin user does not contain stripe publishable key and hence non-admin user cannot add stripe to its event.

https://api.eventyay.com/v1/settings should contain stripe publishable key

See #6277 as well


Discussion:

Resolving patch:
diff --git a/app/api/schema/settings.py b/app/api/schema/settings.py
--- a/app/api/schema/settings.py
+++ b/app/api/schema/settings.py
@@ -74,6 +74,34 @@ class Meta:
     is_omise_activated = fields.Bool(dump_only=True)
     is_alipay_activated = fields.Bool(dump_only=True)
 
+    #
+    # Payment Gateways
+    #
+
+    # Stripe Credantials
+    stripe_client_id = fields.Str(dump_only=True)
+    stripe_publishable_key = fields.Str(dump_only=True)
+    stripe_test_client_id = fields.Str(dump_only=True)
+    stripe_test_publishable_key = fields.Str(dump_only=True)
+
+    # PayPal Credentials
+    paypal_mode = fields.Str(dump_only=True)
+    paypal_client = fields.Str(dump_only=True)
+    paypal_sandbox_client = fields.Str(dump_only=True)
+
+    # Omise Credentials
+    omise_mode = fields.Str(dump_only=True)
+    omise_test_public = fields.Str(dump_only=True)
+    omise_live_public = fields.Str(dump_only=True)
+
+    # Alipay Credentials
+    alipay_publishable_key = fields.Str(dump_only=True)
+
+    # payTM credentials
+    paytm_mode = fields.Str(dump_only=True)
+    paytm_live_merchant = fields.Str(dump_only=True)
+    paytm_sandbox_merchant = fields.Str(dump_only=True)
+
 
 class SettingSchemaNonAdmin(SettingSchemaPublic):
     """


Test patch:
diff --git a/tests/all/integration/api/test_settings.py b/tests/all/integration/api/test_settings.py
new file mode 100644
--- /dev/null
+++ b/tests/all/integration/api/test_settings.py
@@ -0,0 +1,16 @@
+import json
+
+
+def test_payment_gateway(db, client):
+    response = client.get('/v1/settings')
+    assert response.status_code == 200
+    data = json.loads(response.data)["data"]["attributes"]
+    assert "stripe-client-id" in data
+    assert "stripe-publishable-key" in data
+    assert "stripe-test-client-id" in data
+    assert "stripe-test-publishable-key" in data
+    assert "paypal-client" in data
+
+    # Negative test cases
+    assert "stripe_secret_key" not in data
+    assert "stripe_test_secret_key" not in data
Repository: fossasia/open-event-server

Issue:
Previously set fields are not nullable in event
The use_defaults decorator doesn't work as expected. 


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
@@ -72,7 +72,7 @@ def validate_event(user, data):
 
     if not data.get('name', None) and data.get('state', None) == 'published':
         raise ConflictError(
-            {'pointer': '/data/attributes/location-name'},
+            {'pointer': '/data/attributes/name'},
             "Event Name is required to publish the event",
         )
 
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
@@ -10,10 +10,8 @@
 from app.api.helpers.utilities import dasherize
 from app.api.schema.base import SoftDeletionSchema
 from app.models.event import Event
-from utils.common import use_defaults
 
 
-@use_defaults()
 class EventSchemaPublic(SoftDeletionSchema):
     class Meta:
         type_ = 'event'


Test patch:
diff --git a/tests/all/integration/api/event/__init__.py b/tests/all/integration/api/event/__init__.py
new file mode 100644
diff --git a/tests/all/integration/api/event/test_event_patch.py b/tests/all/integration/api/event/test_event_patch.py
new file mode 100644
--- /dev/null
+++ b/tests/all/integration/api/event/test_event_patch.py
@@ -0,0 +1,67 @@
+import json
+
+from tests.factories.event import EventFactoryBasic
+
+
+def get_event(db):
+    event = EventFactoryBasic(location_name='Amsterdam')
+    db.session.commit()
+
+    return event
+
+
+def test_edit_event_default_field(db, client, admin_jwt):
+    # Should let the previous value remain unchanged if field is not present in data
+    event = get_event(db)
+
+    data = json.dumps(
+        {
+            'data': {
+                'type': 'event',
+                'id': str(event.id),
+                'attributes': {'timezone': 'Europe/Berlin'},
+            }
+        }
+    )
+
+    response = client.patch(
+        f'/v1/events/{event.id}',
+        content_type='application/vnd.api+json',
+        headers=admin_jwt,
+        data=data,
+    )
+
+    db.session.refresh(event)
+
+    assert response.status_code == 200
+    assert event.location_name == 'Amsterdam'
+    assert event.timezone == 'Europe/Berlin'
+
+
+def test_edit_event_null_field(db, client, admin_jwt):
+    # Should let the previous value be nulled if field is null in data
+    event = get_event(db)
+
+    assert event.location_name == 'Amsterdam'
+
+    data = json.dumps(
+        {
+            'data': {
+                'type': 'event',
+                'id': str(event.id),
+                'attributes': {'location-name': None},
+            }
+        }
+    )
+
+    response = client.patch(
+        f'/v1/events/{event.id}',
+        content_type='application/vnd.api+json',
+        headers=admin_jwt,
+        data=data,
+    )
+
+    db.session.refresh(event)
+
+    assert response.status_code == 200
+    assert event.location_name is None
Repository: fossasia/open-event-server

Issue:
Feat: Allow User Verification through API request
To add [this](https://github.com/fossasia/open-event-frontend/issues/5040) feature, changes need to be made at the server, to allow `is-verified` field to be changed through API request.


**Additional Context:**
I am willing to work on this issue


Discussion:

Resolving patch:
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
@@ -67,7 +67,7 @@ class Meta:
     is_user_moderator = fields.Boolean(dump_only=True)
     is_user_registrar = fields.Boolean(dump_only=True)
     is_user_attendee = fields.Boolean(dump_only=True)
-    is_verified = fields.Boolean(dump_only=True)
+    is_verified = fields.Boolean()
     last_accessed_at = fields.DateTime(dump_only=True)
     created_at = fields.DateTime(dump_only=True)
     deleted_at = fields.DateTime(dump_only=True)
diff --git a/app/api/users.py b/app/api/users.py
--- a/app/api/users.py
+++ b/app/api/users.py
@@ -67,6 +67,12 @@ def before_create_object(self, data, view_kwargs):
                 {'pointer': '/data/attributes/email'}, "Email already exists"
             )
 
+        if data.get('is_verified'):
+            raise UnprocessableEntityError(
+                {'pointer': '/data/attributes/is-verified'},
+                "You are not allowed to submit this field"
+            )
+
     def after_create_object(self, user, data, view_kwargs):
         """
         method to send-
@@ -284,6 +290,16 @@ def before_update_object(self, user, data, view_kwargs):
                     {'source': ''}, "You are not authorized to update this information."
                 )
 
+        if (
+            not has_access('is_admin')
+            and data.get('is_verified') is not None
+            and data.get('is_verified') != user.is_verified
+        ):
+            raise ForbiddenError(
+                {'pointer': '/data/attributes/is-verified'},
+                "Admin access is required to update this information."
+            )
+
         users_email = data.get('email', None)
         if users_email is not None:
             users_email = users_email.strip()


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

Issue:
Allow user to view their own event's invoices
Currently, users can view their account's invoices `/users/6/event-invoices`, but not able to see their event's invoices `/events/34/event-invoices`. Even though it is the same data. It is only possible for admin to do this. Allow users to access event invoice API for an event


Discussion:

Resolving patch:
diff --git a/app/api/event_invoices.py b/app/api/event_invoices.py
--- a/app/api/event_invoices.py
+++ b/app/api/event_invoices.py
@@ -30,7 +30,9 @@ def query(self, view_kwargs):
         """
         user = current_user
         user_id = view_kwargs.get('user_id')
-        if user_id != user.id and not user.is_staff:
+        forbidden = (user_id and user_id != user.id) \
+            or not view_kwargs
+        if forbidden and not user.is_staff:
             raise ForbiddenError({'source': ''}, 'Admin access is required')
 
         query_ = self.session.query(EventInvoice)


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

Issue:
Change email and PDF datetimes to event timezone
They are currently shown in server timezone


Discussion:
Can you elaborate more please? 
Do they also need to be changed in csv files? @iamareebjamal 
That can be handled in another PR

Resolving patch:
diff --git a/app/models/event_invoice.py b/app/models/event_invoice.py
--- a/app/models/event_invoice.py
+++ b/app/models/event_invoice.py
@@ -1,6 +1,7 @@
 import logging
 from datetime import datetime, timedelta
 
+import pytz
 from flask.templating import render_template
 from sqlalchemy.sql import func
 
@@ -166,7 +167,11 @@ def generate_pdf(self, force=False):
         return self.invoice_pdf_url
 
     def send_notification(self, follow_up=False):
-        prev_month = self.previous_month_date.strftime("%b %Y")  # Displayed as Aug 2016
+        prev_month = self.previous_month_date.astimezone(
+            pytz.timezone(self.event.timezone)
+        ).strftime(
+            "%b %Y"
+        )  # Displayed as Aug 2016
         app_name = get_settings()['app_name']
         frontend_url = get_settings()['frontend_url']
         link = f'{frontend_url}/event-invoice/{self.identifier}/review'
diff --git a/app/templates/flask_ext/jinja/filters.py b/app/templates/flask_ext/jinja/filters.py
--- a/app/templates/flask_ext/jinja/filters.py
+++ b/app/templates/flask_ext/jinja/filters.py
@@ -30,10 +30,8 @@ def simple_datetime_display(date, timezone='UTC', format='%B %d, %Y %I:%M %p'):
         return date.astimezone(pytz.timezone(timezone)).strftime(format)
 
     @app.template_filter('date')
-    def simple_date_display(date):
-        if not date:
-            return ''
-        return date.strftime('%B %d, %Y')
+    def simple_date_display(date, timezone='UTC'):
+        return simple_datetime_display(date, timezone, '%B %d, %Y')
 
     @app.template_filter('humanize')
     def humanize_filter(time):


Test patch: