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

Issue:
Organizer and admin should be able to see ticket holders and PDF
After recent changes, only people who bought the ticket can see that


Discussion:

Resolving patch:
diff --git a/app/api/attendees.py b/app/api/attendees.py
--- a/app/api/attendees.py
+++ b/app/api/attendees.py
@@ -132,17 +132,19 @@ def query(self, view_kwargs):
                 'order_identifier',
                 'identifier',
             )
+
+            is_coorganizer = has_access(
+                'is_coorganizer',
+                event_id=order.event_id,
+            )
             if not (
-                has_access(
-                    'is_coorganizer_or_user_itself',
-                    event_id=order.event_id,
-                    user_id=order.user_id,
-                )
+                is_coorganizer
+                or current_user.id == order.user_id
                 or order.is_attendee(current_user)
             ):
                 raise ForbiddenError({'source': ''}, 'Access Forbidden')
             query_ = query_.join(Order).filter(Order.id == order.id)
-            if current_user.id != order.user_id:
+            if not is_coorganizer and current_user.id != order.user_id:
                 query_ = query_.filter(TicketHolder.user == current_user)
 
         if view_kwargs.get('ticket_id'):
diff --git a/app/models/order.py b/app/models/order.py
--- a/app/models/order.py
+++ b/app/models/order.py
@@ -157,8 +157,16 @@ def invoice_pdf_path(self) -> str:
 
     @property
     def filtered_ticket_holders(self):
+        from app.api.helpers.permission_manager import has_access
+
         query_ = TicketHolder.query.filter_by(order_id=self.id, deleted_at=None)
-        if current_user.id != self.user_id:
+        if (
+            not has_access(
+                'is_coorganizer',
+                event_id=self.event_id,
+            )
+            and current_user.id != self.user_id
+        ):
             query_ = query_.filter(TicketHolder.user == current_user)
         return query_.all()
 


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

Issue:
Error in discount code fetch API
```
AttributeError: 'NoneType' object has no attribute 'tzinfo'
  File "flask/app.py", line 2446, in wsgi_app
    response = self.full_dispatch_request()
  File "flask/app.py", line 1951, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "flask_cors/extension.py", line 161, in wrapped_function
    return cors_after_request(app.make_response(f(*args, **kwargs)))
  File "flask_cors/extension.py", line 161, in wrapped_function
    return cors_after_request(app.make_response(f(*args, **kwargs)))
  File "flask/app.py", line 1820, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "flask/_compat.py", line 39, in reraise
    raise value
  File "flask/app.py", line 1949, in full_dispatch_request
    rv = self.dispatch_request()
  File "flask/app.py", line 1935, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "flask_rest_jsonapi/decorators.py", line 32, in wrapper
    return func(*args, **kwargs)
  File "flask/views.py", line 89, in view
    return self.dispatch_request(*args, **kwargs)
  File "flask_rest_jsonapi/resource.py", line 68, in dispatch_request
    response = method(*args, **kwargs)
  File "flask_rest_jsonapi/decorators.py", line 56, in wrapper
    return func(*args, **kwargs)
  File "flask_rest_jsonapi/resource.py", line 231, in get
    self.before_get(args, kwargs)
  File "/data/app/app/api/discount_codes.py", line 223, in before_get
    discount_tz = discount.valid_from.tzinfo

```


Discussion:
I would like to work on this issue

Resolving patch:
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
@@ -3,6 +3,7 @@
 from flask_jwt_extended import current_user
 from flask_rest_jsonapi import ResourceDetail, ResourceList, ResourceRelationship
 from flask_rest_jsonapi.exceptions import ObjectNotFound
+from pytz import timezone
 from sqlalchemy.orm.exc import NoResultFound
 
 from app.api.helpers.db import safe_query, safe_query_kwargs
@@ -271,8 +272,11 @@ def before_get(self, args, kwargs):
             )
             if discount:
                 kwargs['id'] = discount.id
-                discount_tz = discount.valid_from.tzinfo
-                current_time = datetime.now().replace(tzinfo=discount_tz)
+                if discount.valid_from:
+                    discount_tz = discount.valid_from.tzinfo
+                current_time = datetime.now().replace(
+                    tzinfo=discount_tz or timezone('UTC')
+                )
                 if not discount.is_active:
                     raise MethodNotAllowed(
                         {'parameter': '{code}'}, "Discount Code is not active"


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

Issue:
Return dummy user for deleted ones except for admin user endpoint
Organizers/Admins can access user info such as for attendees. In cases a user deletes its account, they can still view their name and email and such. Please return a dummy user for such cases except on the admin page which shows deleted users.

Dummy user's name can be 'Deleted User' and email 'deleted.account@eventyay'


Discussion:
can I take this?

Take one issue at a time
where do you suggest I should begin?

@PawanVerma1337  I actually didn't get an update, maybe we can both take it up if you want 

can I work on this issue I really want to work on it 

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
@@ -1,8 +1,12 @@
+from flask_jwt_extended import current_user
+from marshmallow import pre_dump
 from marshmallow_jsonapi import fields
 from marshmallow_jsonapi.flask import Relationship
 
+from app.api.helpers.permission_manager import is_logged_in
 from app.api.helpers.utilities import dasherize
 from app.api.schema.base import SoftDeletionSchema
+from app.models.user import User
 from utils.common import use_defaults
 
 
@@ -272,3 +276,18 @@ class Meta:
         type_='event',
         many=True,
     )
+
+    @pre_dump
+    def handle_deleted_users(self, data):
+        if not data:
+            return data
+        if data.deleted_at != None and not (
+            is_logged_in
+            and current_user
+            and (current_user.is_staff or current_user.id == data.id)
+        ):
+            user = User(
+                id=0, email='deleted@eventyay.com', first_name='deleted', last_name='user'
+            )
+            return user
+        return data


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

Issue:
Add users_events_roles relationship to events schema
**Is your feature request related to a problem? Please describe.**
Currently we don't have the means to access a url like `events/2?include=roles.role` Adding users_events_roles relationship to events schema can solve this issue for us.

Ref: #7562 


Discussion:
@iamareebjamal @mariobehling can you please approve this issue? :sweat_smile: 

Resolving patch:
diff --git a/app/api/routes.py b/app/api/routes.py
--- a/app/api/routes.py
+++ b/app/api/routes.py
@@ -856,6 +856,12 @@
     '/events/<identifier>/relationships/general-statistics',
 )
 # Events -> roles:
+api.route(
+    EventRelationship,
+    'event_users_events_roles',
+    '/events/<int:id>/relationships/roles',
+    '/events/<identifier>/relationships/roles',
+)
 api.route(
     EventRelationship,
     'event_owner',
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
@@ -420,3 +420,12 @@ class Meta:
         many=True,
         type_='attendee',
     )
+    roles = Relationship(
+        self_view='v1.event_users_events_roles',
+        self_view_kwargs={'id': '<id>'},
+        related_view='v1.users_events_roles_list',
+        related_view_kwargs={'event_id': '<id>'},
+        schema='UsersEventsRolesSchema',
+        type_='users-events-roles',
+        many=True,
+    )


Test patch:
diff --git a/tests/all/integration/api/event/test_event_view_access.py b/tests/all/integration/api/event/test_event_view_access.py
--- a/tests/all/integration/api/event/test_event_view_access.py
+++ b/tests/all/integration/api/event/test_event_view_access.py
@@ -1,3 +1,5 @@
+import json
+
 from app.api.helpers.db import get_or_create
 from app.models.role import Role
 from app.models.users_events_role import UsersEventsRoles
@@ -59,3 +61,16 @@ def test_event_draft_get_admin(db, client, admin_jwt):
     )
 
     assert response.status_code == 200
+
+
+def test_event_get_user_role(client, db, user, jwt):
+    event = get_event(db, user)
+
+    response = client.get(
+        f'/v1/events/{event.id}?include=roles.user',
+        content_type='application/vnd.api+json',
+        headers=jwt,
+    )
+
+    assert response.status_code == 200
+    assert json.loads(response.data)['included'][1]['type'] == 'user'
Repository: fossasia/open-event-server

Issue:
test_multiple_heads is not raising the expected error
**Describe the bug**
<!-- A clear and concise description of what the bug is. -->
On having multiple heads, the travis build fails with error -
```
error: Hooks handler process 'dredd-hooks-python ./tests/hook_main.py' exited with status: 1
warn: Hook handling timed out.
error: Hooks handler process 'dredd-hooks-python ./tests/hook_main.py' exited with status: 1
info: Backend server process exited
The command "dredd" failed and exited with 1 during .
```
It should raise error as expected in - https://github.com/fossasia/open-event-server/blob/development/scripts/test_multiple_heads.sh

**Expected behavior**
<!-- A clear and concise description of what you expected to happen. -->
Expected error should be raised - `Error: Multiple Migration Heads`

<!-- If applicable, add stacktrace to help explain your problem. -->


**Additional context**
<!-- Add any other context about the problem here. -->
On it


Discussion:
@iamareebjamal  I think this issue is non-existent now. I just got error for this travis failure - https://travis-ci.org/fossasia/open-event-server/builds/547072348?utm_source=github_status&utm_medium=notification

Error: `Multiple heads are present; please specify a single target revision`  
Sometimes it fails correctly, sometimes it doesn't
@iamareebjamal what should be done then? I'm unable to reproduce it for now
Increase the milestone
@iamareebjamal I don't have access. 😅
Please do so
It is not reproducible till now. Encountered correct error message twice this week
https://travis-ci.org/fossasia/open-event-server/builds/553157177?utm_source=github_status&utm_medium=notification
@iamareebjamal I saw correct error message in this travis failure -
`info: Hooks handler stderr: ERROR [root] Error: Multiple heads are present; please specify a single target revision`
That's not the point of the script. That's flask failure, unrelated to script. The script is meant to stop the build ASAP as it encounters multiple heads and not continue dredd tests and others
https://travis-ci.org/fossasia/open-event-server/builds/553303214?utm_source=github_status&utm_medium=notification 
Occurred here too
Nope. That's failure during installing dredd

Resolving patch:
diff --git a/migrations/versions/rev-2021-01-07-05:19:49-3b29ea38f0cb_.py b/migrations/versions/rev-2021-01-07-05:19:49-3b29ea38f0cb_.py
--- a/migrations/versions/rev-2021-01-07-05:19:49-3b29ea38f0cb_.py
+++ b/migrations/versions/rev-2021-01-07-05:19:49-3b29ea38f0cb_.py
@@ -13,7 +13,7 @@
 
 # revision identifiers, used by Alembic.
 revision = '3b29ea38f0cb'
-down_revision = '2d0760003a8a'
+down_revision = '4e61d4df3516'
 
 
 def upgrade():


Test patch:
diff --git a/scripts/test_multiple_heads.sh b/scripts/test_multiple_heads.sh
old mode 100644
new mode 100755
--- a/scripts/test_multiple_heads.sh
+++ b/scripts/test_multiple_heads.sh
@@ -1,4 +1,5 @@
-lines=`python3 manage.py db heads | grep -c "head" | wc | awk '{print $1}'`
+#!/bin/bash
+lines=`python3 manage.py db heads | grep -c "head"`
 if [ $lines -ne 1 ]
 then
     echo "Error: Multiple Migration Heads"
Repository: fossasia/open-event-server

Issue:
Event Order Mail: Time of event wrong
In the order email of events the timing is wrong. 

It is:
Datum: February 12, 2021 01:00 PM - February 12, 2021 03:00 PM

It should be 
Datum: February 12, 2021 02:00 PM - February 12, 2021 04:00 PM

compare https://eventyay.com/e/e366f5ca


Discussion:
Also the dates are not translated.

Question: Should they have the timezone added as in other views maybe?
Translation of dates is not that easy in server, I'll add timezone though

Resolving patch:
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
@@ -2,6 +2,7 @@
 
 import humanize
 import pytz
+from flask_babel import format_datetime
 from forex_python.converter import CurrencyCodes
 
 
@@ -24,14 +25,16 @@ def money_filter(string):
         return '{:20,.2f}'.format(float(string))
 
     @app.template_filter('datetime')
-    def simple_datetime_display(date, timezone='UTC', format='%B %d, %Y %I:%M %p'):
+    def simple_datetime_display(date, timezone=None, format='MMMM d, yyyy hh:mm a'):
         if not date:
             return ''
-        return date.astimezone(pytz.timezone(timezone)).strftime(format)
+        if timezone:
+            date = date.astimezone(pytz.timezone(timezone))
+        return format_datetime(date, format, rebase=False)
 
     @app.template_filter('date')
-    def simple_date_display(date, timezone='UTC'):
-        return simple_datetime_display(date, timezone, '%B %d, %Y')
+    def simple_date_display(date, timezone=None):
+        return simple_datetime_display(date, timezone, 'MMMM d, yyyy')
 
     @app.template_filter('humanize')
     def humanize_filter(time):


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

Issue:
Ticket PDF distorted and organizer message missing line breaks
Since the organizer message has been added to the ticket PDF the document is distorted for longer organizer messages.

Tested with https://eventyay.com/e/e366f5ca

![Screenshot from 2021-01-20 13-35-54](https://user-images.githubusercontent.com/1583873/105175939-dbd43580-5b24-11eb-9470-45d23c1940d4.png)



Discussion:

Resolving patch:
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
@@ -5,6 +5,8 @@
 from flask_babel import format_datetime
 from forex_python.converter import CurrencyCodes
 
+from app.api.helpers.utilities import strip_tags
+
 
 def humanize_helper(time):
     """Returns time passed from now in a human readable duration"""
@@ -39,3 +41,15 @@ def simple_date_display(date, timezone=None):
     @app.template_filter('humanize')
     def humanize_filter(time):
         return humanize_helper(time)
+
+    @app.template_filter('nl2br')
+    def nl2br(text):
+        if not text:
+            return text
+        return text.replace('\n', '<br/>')
+
+    @app.template_filter('strip_tags')
+    def strip(text):
+        if not text:
+            return text
+        return strip_tags(text)


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

Issue:
Preset roles deletion is allowed
**Describe the bug**
Currently the preset roles like "organizer, coorganizer etc" should not be deleted from the db. But right now it is possible to delete these entries.

**To Reproduce**
Steps to reproduce the behavior:
1. Hit the delete endpoint for role 
2. Choose any of the ids pointing to any of the 7 preset roles
3. You can find deletion to be successful

**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. -->



Discussion:

Resolving patch:
diff --git a/app/api/roles.py b/app/api/roles.py
--- a/app/api/roles.py
+++ b/app/api/roles.py
@@ -97,5 +97,8 @@ def before_delete_object(self, obj, kwargs):
     data_layer = {
         'session': db.session,
         'model': Role,
-        'methods': {'before_get_object': before_get_object},
+        'methods': {
+            'before_get_object': before_get_object,
+            'before_delete_object': before_delete_object,
+        },
     }


Test patch:
diff --git a/tests/hook_main.py b/tests/hook_main.py
--- a/tests/hook_main.py
+++ b/tests/hook_main.py
@@ -2524,7 +2524,7 @@ def role_delete(transaction):
     :return:
     """
     with stash['app'].app_context():
-        role = RoleFactory()
+        role = RoleFactory(name="example role")
         db.session.add(role)
         db.session.commit()
Repository: fossasia/open-event-server

Issue:
Invoice Email: Amount not showing two digits after dot
In the invoice emails the invoice amount shows only one digit after the dot, e.g. 180.6 USD instead of 180.60 USD.

![Screenshot from 2021-02-14 08-26-16](https://user-images.githubusercontent.com/1583873/107871260-318bcb80-6ea0-11eb-82da-16edd7bd6e4a.png)



Discussion:
Hey @mariobehling can I work on this issue?
I would like to contribute if no one else is working on this. Any tips would be great to start with.
Since it was defined as Float in database so I believe the bug is the value getting type-casted in calculation of invoice_amount. I would like to debug this if it is not assigned to somone yet.
Can I work on this issue?
@iamareebjamal @mariobehling I noticed this is only happening when the second digit after the decimal is zero. In case the amount is say something like `180.66`, it does not happen.
Yes

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
@@ -185,7 +185,7 @@ def send_notification(self, follow_up=False):
         frontend_url = get_settings()['frontend_url']
         link = f'{frontend_url}/event-invoice/{self.identifier}/review'
         currency = self.event.payment_currency
-        amount = f"{currency} {self.amount}"
+        amount = f"{currency} {self.amount:.2f}"
         send_email_for_monthly_fee_payment(
             self.user,
             self.event.name,


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

Issue:
Add favourite_count to sessions
**Is your feature request related to a problem? Please describe.**
<!-- A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] -->
As part of the issue [fossasia/open-event-frontend#6814](https://github.com/fossasia/open-event-frontend/issues/6814), we need to get favourite-count of each session.

**Describe the solution you'd like**
<!-- A clear and concise description of what you want to happen. -->
Add an aggregate function to sessions for column `favourite_count`. Solution similar to #7712. 

**Additional context**
<!-- Add any other context or screenshots about the feature request here. -->
Working on this.


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
@@ -116,6 +116,7 @@ def validate_fields(self, data, original_data):
     send_email = fields.Boolean(load_only=True, allow_none=True)
     average_rating = fields.Float(dump_only=True)
     rating_count = fields.Integer(dump_only=True)
+    favourite_count = fields.Integer(dump_only=True)
     complex_field_values = CustomFormValueField(allow_none=True)
     microlocation = Relationship(
         self_view='v1.session_microlocation',
diff --git a/app/models/session.py b/app/models/session.py
--- a/app/models/session.py
+++ b/app/models/session.py
@@ -106,6 +106,12 @@ def average_rating(self):
     def rating_count(self):
         return func.count('1')
 
+    @aggregated(
+        'favourites', db.Column(db.Integer, default=0, server_default='0', nullable=False)
+    )
+    def favourite_count(self):
+        return func.count('1')
+
     @property
     def favourite(self):
         if not current_user:
diff --git a/migrations/versions/rev-2021-02-28-20:37:56-cbe8314bce5e_.py b/migrations/versions/rev-2021-02-28-20:37:56-cbe8314bce5e_.py
new file mode 100644
--- /dev/null
+++ b/migrations/versions/rev-2021-02-28-20:37:56-cbe8314bce5e_.py
@@ -0,0 +1,29 @@
+"""empty message
+
+Revision ID: cbe8314bce5e
+Revises: 26f3611683b9
+Create Date: 2021-02-28 20:37:56.792109
+
+"""
+
+from alembic import op
+import sqlalchemy as sa
+import sqlalchemy_utils
+
+
+# revision identifiers, used by Alembic.
+revision = 'cbe8314bce5e'
+down_revision = '26f3611683b9'
+
+
+def upgrade():
+    # ### commands auto generated by Alembic - please adjust! ###
+    op.add_column('sessions', sa.Column('favourite_count', sa.Integer(), server_default='0', nullable=False))
+    op.execute('update sessions set favourite_count = (select count(*) from user_favourite_sessions where session_id = sessions.id)')
+    # ### end Alembic commands ###
+
+
+def downgrade():
+    # ### commands auto generated by Alembic - please adjust! ###
+    op.drop_column('sessions', 'favourite_count')
+    # ### end Alembic commands ###


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

Issue:
Calendar link in calendar not working properly
In the description, "Join using link:  https://eventyay.com/e/fa96ae2c/video/Main Hall/187"

The space is treated as a break, clipping the link at Main"

"Main Hall" should be HTTP encoded to Main%20Hall


Discussion:
I would like to work on this issue. Could you please help me out?
hi @mishari Can I take up this issue
I think we can't address this issue just by adding (%20), as in this scenario we are the one deciding particular string is link or not.
For example: In the description, "Join using the link: https://eventyay.com/e/fa96ae2c/video/Main Hall/187 at 8:00 pm"
our code will end up adding (%20) in place of each space.
What we can do is just remove auto conversion to link, as there is option to covert string in link in editor.
Views @mishari sir @iamareebjamal sir?

Space should be replaced by %20, or `Main Hall` should be converted to `main-hall`

Resolving patch:
diff --git a/app/api/helpers/calendar/ical.py b/app/api/helpers/calendar/ical.py
--- a/app/api/helpers/calendar/ical.py
+++ b/app/api/helpers/calendar/ical.py
@@ -1,3 +1,5 @@
+from urllib.parse import quote
+
 import pytz
 from flask import jsonify
 from flask_jwt_extended import current_user
@@ -57,7 +59,7 @@ def to_ical(event, include_sessions=False, my_schedule=False, user_id=None):
                 " "
                 + event.site_link
                 + '/video/'
-                + session.microlocation.video_stream.name
+                + quote(session.microlocation.video_stream.name)
                 + "/"
                 + str(session.microlocation.video_stream.id)
                 if session.microlocation.video_stream


Test patch: