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

Issue:
Remove elasticsearch initialization
elasticsearch is neither working nor supported. It causes confusion and incompatibilities for beginners. Hence, it's integration should be removed. For now, remove any iniitalization but keep the integration code.

However, in future as well, we should not use a service which requires 64 GB of RAM to run (sarcasm)


Discussion:

Resolving patch:
diff --git a/app/instance.py b/app/instance.py
--- a/app/instance.py
+++ b/app/instance.py
@@ -195,17 +195,6 @@ def create_app():
     shell.init_app(app)
     limiter.init_app(app)
 
-    # elasticsearch
-    if app.config['ENABLE_ELASTICSEARCH']:
-        from app.views.elastic_cron_helpers import cron_rebuild_events_elasticsearch
-        client.init_app(app)
-        connections.add_connection('default', client.elasticsearch)
-        with app.app_context():
-            try:
-                cron_rebuild_events_elasticsearch.delay()
-            except Exception:
-                pass
-
     app_created = True
     return app
 
@@ -251,11 +240,6 @@ def update_sent_state(sender=None, headers=None, **kwargs):
 scheduler = BackgroundScheduler(timezone=utc)
 # scheduler.add_job(send_mail_to_expired_orders, 'interval', hours=5)
 # scheduler.add_job(empty_trash, 'cron', hour=5, minute=30)
-if app.config['ENABLE_ELASTICSEARCH']:
-    from app.views.elastic_cron_helpers import sync_events_elasticsearch, cron_rebuild_events_elasticsearch
-    scheduler.add_job(sync_events_elasticsearch, 'interval', minutes=60)
-    scheduler.add_job(cron_rebuild_events_elasticsearch, 'cron', day=7)
-
 scheduler.add_job(send_after_event_mail, 'cron', hour=5, minute=30)
 scheduler.add_job(send_event_fee_notification, 'cron', day=1)
 scheduler.add_job(send_event_fee_notification_followup, 'cron', day=1, month='1-12')


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

Issue:
Remove event-orga endpoint
It is not being used and redundant. Create proper sales stats API if needed


Discussion:

Resolving patch:
diff --git a/app/api/order_statistics/events.py b/app/api/order_statistics/events.py
--- a/app/api/order_statistics/events.py
+++ b/app/api/order_statistics/events.py
@@ -9,6 +9,7 @@
 from app.api.helpers.utilities import dasherize
 from app.models import db
 from app.models.event import Event
+from app.models.ticket import Ticket
 from app.models.order import Order, OrderTicket
 
 
@@ -32,6 +33,7 @@ class Meta:
     orders = fields.Method("orders_count")
     sales = fields.Method("sales_count")
 
+
     def tickets_count(self, obj):
         obj_id = obj.id
         total = db.session.query(func.sum(OrderTicket.quantity.label('sum'))).join(Order.order_tickets).filter(
@@ -48,6 +50,8 @@ def tickets_count(self, obj):
             Order.event_id == obj_id, Order.status == 'placed').scalar()
         completed = db.session.query(func.sum(OrderTicket.quantity.label('sum'))).join(Order.order_tickets).filter(
             Order.event_id == obj_id, Order.status == 'completed').scalar()
+        max = db.session.query(func.sum(Ticket.quantity.label('sum'))).filter(Ticket.event_id == obj_id,
+                                                                              Ticket.deleted_at == None).scalar()
         result = {
             'total': total or 0,
             'draft': draft or 0,
@@ -55,7 +59,8 @@ def tickets_count(self, obj):
             'pending': pending or 0,
             'expired': expired or 0,
             'placed': placed or 0,
-            'completed': completed or 0
+            'completed': completed or 0,
+            'max': max or 0
         }
         return result
 


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

Issue:
Speaker Model: Instagram field is present in custom form but not in speaker model
Add Instagram field to the speaker as it is present in form mixin.
```js
      this.store.createRecord('custom-form', {
        fieldIdentifier : 'instagram',
        form            : 'speaker',
        type            : 'text',
        isRequired      : false,
        isIncluded      : false,
        event           : parent
      })
```



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
@@ -42,6 +42,7 @@ class Meta:
     facebook = fields.Url(allow_none=True)
     github = fields.Url(allow_none=True)
     linkedin = fields.Url(allow_none=True)
+    instagram = fields.Url(allow_none=True)
     organisation = fields.Str(allow_none=True)
     is_featured = fields.Boolean(default=False)
     is_email_overridden = fields.Boolean(default=False)
diff --git a/app/models/speaker.py b/app/models/speaker.py
--- a/app/models/speaker.py
+++ b/app/models/speaker.py
@@ -22,6 +22,7 @@ class Speaker(SoftDeletionModel):
     facebook = db.Column(db.String)
     github = db.Column(db.String)
     linkedin = db.Column(db.String)
+    instagram = db.Column(db.String)
     organisation = db.Column(db.String)
     is_featured = db.Column(db.Boolean, default=False)
     is_email_overridden = db.Column(db.Boolean, default=False)
@@ -51,6 +52,7 @@ def __init__(self,
                  facebook=None,
                  github=None,
                  linkedin=None,
+                 instagram=None,
                  organisation=None,
                  is_featured=False,
                  is_email_overridden=False,
@@ -79,6 +81,7 @@ def __init__(self,
         self.facebook = facebook
         self.github = github
         self.linkedin = linkedin
+        self.instagram = instagram
         self.is_featured = is_featured
         self.is_email_overridden = is_email_overridden
         self.organisation = organisation
diff --git a/migrations/versions/rev-2020-01-13-22:43:30-eef7c9bc83a0_.py b/migrations/versions/rev-2020-01-13-22:43:30-eef7c9bc83a0_.py
new file mode 100644
--- /dev/null
+++ b/migrations/versions/rev-2020-01-13-22:43:30-eef7c9bc83a0_.py
@@ -0,0 +1,28 @@
+"""empty message
+
+Revision ID: eef7c9bc83a0
+Revises: dee1ad7bee53
+Create Date: 2020-01-13 22:43:30.603812
+
+"""
+
+from alembic import op
+import sqlalchemy as sa
+import sqlalchemy_utils
+
+
+# revision identifiers, used by Alembic.
+revision = 'eef7c9bc83a0'
+down_revision = 'dee1ad7bee53'
+
+
+def upgrade():
+    # ### commands auto generated by Alembic - please adjust! ###
+    op.add_column('speaker', sa.Column('instagram', sa.String(), nullable=True))
+    # ### end Alembic commands ###
+
+
+def downgrade():
+    # ### commands auto generated by Alembic - please adjust! ###
+    op.drop_column('speaker', 'instagram')
+    # ### end Alembic commands ###


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

Issue:
Remove version model
**Describe the bug**
The version model is not used currently and should be removed

https://github.com/fossasia/open-event-server/blob/development/app/models/version.py


**Additional context**
@iamareebjamal Taking this



Discussion:

Resolving patch:
diff --git a/app/models/version.py b/app/models/version.py
deleted file mode 100644
--- a/app/models/version.py
+++ /dev/null
@@ -1,56 +0,0 @@
-from sqlalchemy.orm import backref
-
-from app.models import db
-
-
-class Version(db.Model):
-    """Version model class"""
-    __tablename__ = 'versions'
-    id = db.Column(db.Integer, primary_key=True)
-    event_id = db.Column(db.Integer, db.ForeignKey('events.id', ondelete='CASCADE'))
-    events = db.relationship("Event", backref=backref('version', uselist=False))
-
-    event_ver = db.Column(db.Integer, nullable=False, default=0)
-    sessions_ver = db.Column(db.Integer, nullable=False, default=0)
-    speakers_ver = db.Column(db.Integer, nullable=False, default=0)
-    tracks_ver = db.Column(db.Integer, nullable=False, default=0)
-    sponsors_ver = db.Column(db.Integer, nullable=False, default=0)
-    microlocations_ver = db.Column(db.Integer, nullable=False, default=0)
-
-    def __init__(self,
-                 event_id=None,
-                 event_ver=None,
-                 sessions_ver=None,
-                 speakers_ver=None,
-                 tracks_ver=None,
-                 sponsors_ver=None,
-                 microlocations_ver=None):
-        self.event_id = event_id
-        self.event_ver = event_ver
-        self.sessions_ver = sessions_ver
-        self.speakers_ver = speakers_ver
-        self.tracks_ver = tracks_ver
-        self.sponsors_ver = sponsors_ver
-        self.microlocations_ver = microlocations_ver
-
-    def __repr__(self):
-        return '<Version %r>' % self.id
-
-    def __str__(self):
-        return self.__repr__()
-
-    @property
-    def serialize(self):
-        """Return object data in easily serializable format"""
-        return {
-            'version': [
-                {'id': self.id,
-                 'event_id': self.event_id,
-                 'event_ver': self.event_ver,
-                 'sessions_ver': self.sessions_ver,
-                 'speakers_ver': self.speakers_ver,
-                 'tracks_ver': self.tracks_ver,
-                 'sponsors_ver': self.sponsors_ver,
-                 'microlocations_ver': self.microlocations_ver}
-            ]
-        }


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

Issue:
Missing link attributes in mail templates
**Describe the bug**
Due to the messy HTML being sent over mails, it's difficult for people to confirm their emails/view their session links over a mobile device

**Additional context**
Working on it.


Discussion:

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
@@ -73,7 +73,7 @@
         'message': (
             u"Hi {email},<br/>" +
             u"The event <strong>{event_name}</strong> has received a new session proposal. " +
-            u"<br/> Visit this link to view the session: {link}"
+            u"<br/> Visit this link to view the session: <a href='{link}' target='_blank'>{link}</a>"
         )
     },
     USER_REGISTER: {
@@ -97,7 +97,7 @@
         'subject': u'Email Confirmation to Create Account for Open-Event',
         'message': (
             u"Hi {email},<br/>" +
-            u"Please visit this link to confirm your email: {link}"
+            u"Please visit this link to confirm your email:  <a href='{link}' target='_blank'>{link}</a>"
         )
     },
     USER_CHANGE_EMAIL: {
@@ -179,7 +179,7 @@
             u"Hi, {buyer_email} just bought tickets for the event {event_name}"
             u"<br/>The order has been processed successfully." +
             u"<br/> <a href='{order_url}'>Click here</a> to view/download the invoice."
-            u"<br/>Login to manage the orders at {frontend_url} </em>"
+            u"<br/>Login to manage the orders at <a href='{frontend_url}' target='_blank'>{frontend_url}</a> </em>"
         )
     },
     TICKET_CANCELLED: {
@@ -190,7 +190,8 @@
             u"<br/>your order for {event_name} has been cancelled by the organizer."
             u"<br/>Please contact the organizer for more info." +
             u"{cancel_msg}"
-            u"<br/>To manage orders please login to {frontend_url} and visit \"My Tickets\"."
+            u"<br/>To manage orders please login to <a href='{frontend_url}' target='_blank'>{frontend_url}</a>"
+            u"and visit \"My Tickets\"."
             u"<br/>Best regards,"
             u"<br/>{app_name} Team"
         )


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

Issue:
Error in migrations
**Describe the bug**
Due to recent merging of PRs https://github.com/fossasia/open-event-server/pull/6744/ https://github.com/fossasia/open-event-server/pull/6748

The PR https://github.com/fossasia/open-event-server/pull/6744 has an invalid migration to remove the 'secret' column from the db which was unrelated to PR. Hence now we have two migration for  the same column `secret` from `settings` which
 drops column on upgrade and creates  on downgrade


**Additional context**
@iamareebjamal - Please chck



Discussion:
#6744 has wrong migration. Not #6748

Remove it from migration 

Resolving patch:
diff --git a/migrations/versions/rev-2020-01-17-18:09:31-6ebafb385765_.py b/migrations/versions/rev-2020-01-17-18:09:31-6ebafb385765_.py
--- a/migrations/versions/rev-2020-01-17-18:09:31-6ebafb385765_.py
+++ b/migrations/versions/rev-2020-01-17-18:09:31-6ebafb385765_.py
@@ -18,7 +18,6 @@
 
 def upgrade():
     # ### commands auto generated by Alembic - please adjust! ###
-    op.drop_column('settings', 'secret')
     op.add_column('ticket_holders', sa.Column('age_group', sa.String(), nullable=True))
     # ### end Alembic commands ###
 
@@ -26,5 +25,4 @@ def upgrade():
 def downgrade():
     # ### commands auto generated by Alembic - please adjust! ###
     op.drop_column('ticket_holders', 'age_group')
-    op.add_column('settings', sa.Column('secret', sa.VARCHAR(), autoincrement=False, nullable=True))
     # ### end Alembic commands ###


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

Issue:
Unable to like/dislike some events
**Describe the bug**
Unable to like/dislike some events in the open event attendee app.

**Expected behavior**
The user should be able to like/dislike the events without any error.

**Additional context**
URL: https://open-event-api-dev.herokuapp.com/v1/user-favourite-events 
Response: 
```
{"errors": [{"status": 409, "source": {"pointer": "/data/relationships/event"}, "title": "Conflict", "detail": "Event already favourited"}], "jsonapi": {"version": "1.0"}}
```

URL: https://open-event-api-dev.herokuapp.com/v1/user-favourite-events/16
Response: 
```
{"errors": [{"status": 404, "source": {"pointer": ""}, "title": "Object not found", "detail": "Object Not Found"}], "jsonapi": {"version": "1.0"}}
```

**Would you like to work on the issue?**
<!-- Please let us know if you can work on it or the issue should be assigned to someone else. -->
- [ ] Yes
- [x] No
- Other: 



Discussion:
@rob729 Thankyou for opening an issue, We also mention the client-side issue which was created for reference.

https://github.com/fossasia/open-event-attendee-android/issues/2553



Resolving patch:
diff --git a/app/api/user_favourite_events.py b/app/api/user_favourite_events.py
--- a/app/api/user_favourite_events.py
+++ b/app/api/user_favourite_events.py
@@ -35,8 +35,7 @@ def before_post(self, args, kwargs, data):
             raise ForbiddenException({'source': ''}, 'Only Authorized Users can favourite an event')
 
         data['user'] = current_user.id
-        user_favourite_event = UserFavouriteEvent.query.filter_by(
-                                   user=current_user, event_id=int(data['event'])).first()
+        user_favourite_event = find_user_favourite_event_by_id(event_id=data['event'])
         if user_favourite_event:
             raise ConflictException({'pointer': '/data/relationships/event'}, "Event already favourited")
 
@@ -86,8 +85,7 @@ def before_get_object(self, view_kwargs):
 
         if view_kwargs.get('id') is not None:
             try:
-                user_favourite_event = UserFavouriteEvent.query.filter_by(
-                    user=current_user, event_id=view_kwargs['id']).first()
+                user_favourite_event = find_user_favourite_event_by_id(event_id=view_kwargs['id'])
             except NoResultFound:
                 raise ObjectNotFound({'source': '/data/relationships/event'}, "Object: not found")
             else:
@@ -113,3 +111,9 @@ class UserFavouriteEventRelationship(ResourceRelationship):
     methods = ['GET']
     data_layer = {'session': db.session,
                   'model': UserFavouriteEvent}
+
+
+def find_user_favourite_event_by_id(event_id):
+    return UserFavouriteEvent.query.filter_by(deleted_at=None,
+                                              user=current_user,
+                                              event_id=event_id).first()


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

Issue:
Task send_event_fee_notification failing
```
raised unexpected: AttributeError("'Ticket' object has no attribute 'ticket_id'")
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/celery/app/trace.py", line 385, in trace_task
    R = retval = fun(*args, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/flask_celeryext/app.py", line 101, in __call__
    res = Task.__call__(self, *args, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/celery/app/trace.py", line 650, in __protected_call__
    return self.run(*args, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/sentry_sdk/integrations/celery.py", line 161, in _inner
    reraise(*exc_info)
  File "/usr/local/lib/python3.7/site-packages/sentry_sdk/_compat.py", line 57, in reraise
    raise value
  File "/usr/local/lib/python3.7/site-packages/sentry_sdk/integrations/celery.py", line 156, in _inner
    return f(*args, **kwargs)
  File "/data/app/app/api/helpers/scheduled_jobs.py", line 90, in send_event_fee_notification
    ticket = safe_query(db, Ticket, 'id', order_ticket.ticket_id, 'ticket_id')
AttributeError: 'Ticket' object has no attribute 'ticket_id'

```


Discussion:

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
@@ -86,8 +86,7 @@ def send_event_fee_notification():
 
             fee_total = 0
             for order in orders:
-                for order_ticket in order.tickets:
-                    ticket = safe_query(db, Ticket, 'id', order_ticket.ticket_id, 'ticket_id')
+                for ticket in order.tickets:
                     if order.paid_via != 'free' and order.amount > 0 and ticket.price > 0:
                         fee = ticket.price * (get_fee(event.payment_country, order.event.payment_currency) / 100.0)
                         fee_total += fee


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

Issue:
Event fee notification task is triggered every minute
Should be triggered once per day

Please fix @codedsun 


Discussion:

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
@@ -226,7 +226,7 @@ def send_monthly_event_invoice():
 def setup_scheduled_task(sender, **kwargs):
     from celery.schedules import crontab
     sender.add_periodic_task(crontab(hour='*/5', minute=30), send_after_event_mail)
-    sender.add_periodic_task(crontab(day_of_week='0-6'), send_event_fee_notification)
+    sender.add_periodic_task(crontab(minute=0, hour=0), send_event_fee_notification)
     sender.add_periodic_task(crontab(minute=0, hour=0, day_of_month=1), send_event_fee_notification_followup)
     sender.add_periodic_task(crontab(hour='*/5', minute=30), change_session_state_on_event_completion)
     sender.add_periodic_task(crontab(minute='*/45'), expire_pending_tickets)


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

Issue:
Session export celery task status endpoint failing
celery task endpoint was failing due to old celery import remaining to be refactored


Discussion:

Resolving patch:
diff --git a/app/api/celery_tasks.py b/app/api/celery_tasks.py
--- a/app/api/celery_tasks.py
+++ b/app/api/celery_tasks.py
@@ -20,7 +20,7 @@ def celery_task(task_id):
         state = TASK_RESULTS[task_id]['state']
         info = TASK_RESULTS[task_id]['result']
     else:
-        from app.views.celery_ import celery
+        from app.api.helpers.tasks import celery
         result = AsyncResult(id=task_id, app=celery)
         state = result.state
         info = result.info


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

Issue:
user is able to save event without selecting payment method for donation ticket.
**Describe the bug**
Related Frontend issue - [#3850](https://github.com/fossasia/open-event-frontend/issues/3850)

Right now user is able to save event with `donation ticket` without selecting a `payment method`.

**Expected behavior**
Server should throw an error like `Donation ticket must have a payment method` as it throws in case of `Paid Tickets`

**Additional context**
<!-- Add any other context about the problem here. -->
I will work on this issue.


Discussion:

Resolving patch:
diff --git a/app/api/tickets.py b/app/api/tickets.py
--- a/app/api/tickets.py
+++ b/app/api/tickets.py
@@ -70,7 +70,7 @@ def before_create_object(self, data, view_kwargs):
                     {'event_id': data['event']}, "Event does not exist"
                 )
 
-            if data.get('type') == 'paid':
+            if data.get('type') == 'paid' or data.get('type') == 'donation':
                 if not event.is_payment_enabled():
                     raise UnprocessableEntity(
                         {'event_id': data['event']},
@@ -231,7 +231,7 @@ def before_update_object(self, ticket, data, view_kwargs):
         :param view_kwargs:
         :return:
         """
-        if ticket.type == 'paid':
+        if ticket.type == 'paid' or ticket.type == 'donation':
             try:
                 event = (
                     db.session.query(Event)


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

Issue:
Error in deleting marketer role user
User with marketer role are not getting deleted


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
@@ -353,7 +353,7 @@ def before_update_object(self, user, data, view_kwargs):
 
         if (
             has_access('is_admin')
-            and ('us_marketer' in data)
+            and ('is_marketer' in data)
             and data.get('is_marketer') != user.is_marketer
         ):
             user.is_marketer = not user.is_marketer


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

Issue:
After Event Mail: Mails are getting sent in every 5 hours.
The scheduled job for the after event mail is misbehaving. I have been getting 3 emails periodically every 5 hours once my event was over.



Discussion:
Will fix this .

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
@@ -302,17 +302,27 @@ def send_monthly_event_invoice():
 def setup_scheduled_task(sender, **kwargs):
     from celery.schedules import crontab
 
-    sender.add_periodic_task(crontab(hour='*/5', minute=30), send_after_event_mail)
-    sender.add_periodic_task(crontab(minute=0, hour=0), send_event_fee_notification)
+    # Every day at 5:30
+    sender.add_periodic_task(crontab(hour=5, minute=30), send_after_event_mail)
+    # Every 1st day of month at 0:00
+    sender.add_periodic_task(
+        crontab(minute=0, hour=0, day_of_month=1), send_event_fee_notification
+    )
+    # Every 1st day of month at 0:00
     sender.add_periodic_task(
         crontab(minute=0, hour=0, day_of_month=1), send_event_fee_notification_followup
     )
+    # Every day at 5:30
     sender.add_periodic_task(
-        crontab(hour='*/5', minute=30), change_session_state_on_event_completion
+        crontab(hour=5, minute=30), change_session_state_on_event_completion
     )
+    # Every 45 minutes
     sender.add_periodic_task(crontab(minute='*/45'), expire_pending_tickets)
+    # Every 1st day of month at 0:00
     sender.add_periodic_task(
         crontab(minute=0, hour=0, day_of_month=1), send_monthly_event_invoice
     )
-    sender.add_periodic_task(crontab(minute=0, hour='*/5'), event_invoices_mark_due)
+    # Every day at 5:00
+    sender.add_periodic_task(crontab(minute=0, hour=5), event_invoices_mark_due)
+    # Every 5 minutes
     sender.add_periodic_task(crontab(minute='*/5'), delete_ticket_holders_no_order_id)


Test patch: