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

Issue:
expire pending tickets after one day
Parent Issue : fossasia/open-event-frontend#2852

Point to work on : Expiring the pending tickets after 1 day using a scheduled task.


Discussion:

Resolving patch:
diff --git a/app/__init__.py b/app/__init__.py
--- a/app/__init__.py
+++ b/app/__init__.py
@@ -29,7 +29,7 @@
 from app.views import BlueprintsManager
 from app.api.helpers.auth import AuthManager
 from app.api.helpers.scheduled_jobs import send_after_event_mail, send_event_fee_notification, \
-    send_event_fee_notification_followup, change_session_state_on_event_completion
+    send_event_fee_notification_followup, change_session_state_on_event_completion, expire_pending_tickets_after_one_day
 from app.models.event import Event
 from app.models.role_invite import RoleInvite
 from app.views.healthcheck import health_check_celery, health_check_db, health_check_migrations, check_migrations
@@ -243,6 +243,7 @@ def update_sent_state(sender=None, body=None, **kwargs):
 scheduler.add_job(send_event_fee_notification, 'cron', day=1)
 scheduler.add_job(send_event_fee_notification_followup, 'cron', day=15)
 scheduler.add_job(change_session_state_on_event_completion, 'cron', hour=5, minute=30)
+scheduler.add_job(expire_pending_tickets_after_one_day, 'cron', hour=5)
 scheduler.start()
 
 
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
@@ -140,3 +140,12 @@ def send_event_fee_notification_followup():
                                                         app_name,
                                                         link,
                                                         incomplete_invoice.event.id)
+
+
+def expire_pending_tickets_after_one_day():
+    from app import current_app as app
+    with app.app_context():
+        db.session.query(Order).filter(Order.status == 'pending',
+                                       (datetime.datetime.today() - Order.created_at).days > 1).\
+                                       update({'status': 'expired'})
+        db.session.commit()


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

Issue:
Tickets endpoint results in too many redirects in production.
```python
            try:
                response = make_response(send_file(file_path))
                response.headers['Content-Disposition'] = 'attachment; filename=ticket-%s.pdf' % order_identifier
                return response
            except FileNotFoundError:
                create_pdf_tickets_for_holder(order)
                return redirect(url_for('ticket_blueprint.ticket_attendee_authorized', order_identifier=order_identifier))
```

The redirect call seems to be the problem, removing it and manually sending the response seems to fix it.



Discussion:
should we just replace it with a simple error message?
@mrsaicharan1 I was thinking, that you handle a `fileNotFoundError` by then creating the tickets, and recalling the endpoint. 
if you just replace this portion with:
```python
def return_file():
     response = make_response(send_file(file_path))
                response.headers['Content-Disposition'] = 'attachment; filename=ticket-%s.pdf' % 
     order_identifier
     return response

try:
    return_file()
except FileNotFoundError:
                create_pdf_tickets_for_holder(order)
                return_file()
```
Then there is no need for redirecting in that case.
                     





I guess you're right. I'll send a PR with the changes. This would totally eliminate the redirections.

Resolving patch:
diff --git a/app/api/auth.py b/app/api/auth.py
--- a/app/api/auth.py
+++ b/app/api/auth.py
@@ -281,6 +281,11 @@ def change_password():
     })
 
 
+def return_tickets(file_path, order_identifier):
+    response = make_response(send_file(file_path))
+    response.headers['Content-Disposition'] = 'attachment; filename=ticket-%s.pdf' % order_identifier
+    return response
+
 @ticket_blueprint.route('/tickets/<string:order_identifier>')
 @jwt_required()
 def ticket_attendee_authorized(order_identifier):
@@ -294,12 +299,10 @@ def ticket_attendee_authorized(order_identifier):
             key = UPLOAD_PATHS['pdf']['ticket_attendee'].format(identifier=order_identifier)
             file_path = '../generated/tickets/{}/{}/'.format(key, generate_hash(key)) + order_identifier + '.pdf'
             try:
-                response = make_response(send_file(file_path))
-                response.headers['Content-Disposition'] = 'attachment; filename=ticket-%s.zip' % order_identifier
-                return response
+                return return_tickets(file_path, order_identifier)
             except FileNotFoundError:
                 create_pdf_tickets_for_holder(order)
-                return redirect(url_for('ticket_blueprint.ticket_attendee_authorized', order_identifier=order_identifier))
+                return return_tickets(file_path, order_identifier)
         else:
             return ForbiddenError({'source': ''}, 'Unauthorized Access').respond()
     else:


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

Issue:
Depenendency Upgrades
The following dependencies have to be upgraded

- urllib3 = ">=1.24.2"
- SQLAlchemy = ">=1.3.0"
- Jinja2 = ">=2.10.1"
- marshmallow = ">=2.15.1"


Discussion:
@iamareebjamal May I work on it?
Go ahead

Resolving patch:
diff --git a/app/api/admin_sales/locations.py b/app/api/admin_sales/locations.py
--- a/app/api/admin_sales/locations.py
+++ b/app/api/admin_sales/locations.py
@@ -15,8 +15,8 @@ def sales_per_location_by_status(status):
         Event.location_name.label('location'),
         func.sum(Order.amount).label(status + '_sales'),
         func.sum(OrderTicket.quantity).label(status + '_tickets')) \
-                     .outerjoin(Order) \
-                     .outerjoin(OrderTicket) \
+                     .outerjoin(Order, Order.event_id == Event.id) \
+                     .outerjoin(OrderTicket, OrderTicket.order_id == Order.id) \
                      .filter(Event.id == Order.event_id) \
                      .filter(Order.status == status) \
                      .group_by(Event.location_name, Order.status) \


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

Issue:
Ticket Sales are coming in with invalid date
The ticket sales for the Open Tech Summit Europe are showing "invalid date".

![Screenshot from 2019-05-17 12-49-01](https://user-images.githubusercontent.com/1583873/57923308-3b833380-78a2-11e9-9e8f-aa687539a359.png)



Discussion:

Resolving patch:
diff --git a/app/api/orders.py b/app/api/orders.py
--- a/app/api/orders.py
+++ b/app/api/orders.py
@@ -139,6 +139,8 @@ def after_create_object(self, order, data, view_kwargs):
 
         # send e-mail and notifications if the order status is completed
         if order.status == 'completed':
+            if order.payment_mode in ['free', 'bank', 'cheque', 'onsite']:
+                order.completed_at = datetime.utcnow()
             send_email_to_attendees(order, current_user.id)
             send_notif_to_attendees(order, current_user.id)
 
@@ -308,6 +310,8 @@ def after_update_object(self, order, data, view_kwargs):
             delete_related_attendees_for_order(order)
 
         elif order.status == 'completed':
+            if order.payment_mode in ['free', 'bank', 'cheque', 'onsite']:
+                order.completed_at = datetime.utcnow()
             send_email_to_attendees(order, current_user.id)
             send_notif_to_attendees(order, current_user.id)
 


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

Issue:
Add new field for attendee form activation
Server issue of  fossasia/open-event-frontend#2963
- Add new model field for an event, "is_ticket_form_enabled"


Discussion:

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
@@ -98,6 +98,7 @@ def validate_timezone(self, data, original_data):
     schedule_published_on = fields.DateTime(allow_none=True)
     is_ticketing_enabled = fields.Bool(default=False)
     is_featured = fields.Bool(default=False)
+    is_ticket_form_enabled = fields.Bool(default=True)
     payment_country = fields.Str(allow_none=True)
     payment_currency = fields.Str(allow_none=True)
     tickets_available = fields.Float(dump_only=True)
diff --git a/app/models/event.py b/app/models/event.py
--- a/app/models/event.py
+++ b/app/models/event.py
@@ -91,6 +91,7 @@ class Event(SoftDeletionModel):
     schedule_published_on = db.Column(db.DateTime(timezone=True))
     is_ticketing_enabled = db.Column(db.Boolean, default=False)
     is_donation_enabled = db.Column(db.Boolean, default=False)
+    is_ticket_form_enabled = db.Column(db.Boolean, default=True, nullable=False)
     payment_country = db.Column(db.String)
     payment_currency = db.Column(db.String)
     paypal_email = db.Column(db.String)
@@ -195,6 +196,7 @@ def __init__(self,
                  code_of_conduct=None,
                  schedule_published_on=None,
                  is_sessions_speakers_enabled=False,
+                 is_ticket_form_enabled=True,
                  is_donation_enabled=False,
                  is_map_shown=False,
                  has_organizer_info=False,
@@ -275,6 +277,7 @@ def __init__(self,
         self.can_pay_by_omise = can_pay_by_omise
         self.is_donation_enabled = is_donation_enabled
         self.is_featured = is_featured
+        self.is_ticket_form_enabled = is_ticket_form_enabled
         self.identifier = get_new_event_identifier()
         self.cheque_details = cheque_details
         self.bank_details = bank_details
diff --git a/migrations/versions/0e80c49a6e28_.py b/migrations/versions/0e80c49a6e28_.py
new file mode 100644
--- /dev/null
+++ b/migrations/versions/0e80c49a6e28_.py
@@ -0,0 +1,29 @@
+"""empty message
+
+Revision ID: 0e80c49a6e28
+Revises: 6f7b6fad3f54
+Create Date: 2019-05-20 21:56:44.770504
+
+"""
+
+from alembic import op
+import sqlalchemy as sa
+
+
+# revision identifiers, used by Alembic.
+revision = '0e80c49a6e28'
+down_revision = '6f7b6fad3f54'
+
+
+def upgrade():
+    # ### commands auto generated by Alembic - please adjust! ###
+    op.add_column('events', sa.Column('is_ticket_form_enabled', sa.Boolean(), server_default='True', nullable=False))
+    op.add_column('events_version', sa.Column('is_ticket_form_enabled', sa.Boolean(), server_default='True', nullable=False))
+    # ### end Alembic commands ###
+
+
+def downgrade():
+    # ### commands auto generated by Alembic - please adjust! ###
+    op.drop_column('events_version', 'is_ticket_form_enabled')
+    op.drop_column('events', 'is_ticket_form_enabled')
+    # ### end Alembic commands ###


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

Issue:
Call for Speakers Not working - Fields description disappeared in Wizard and Public Form
Call for Speakers Not working - Fields description disappeared in Wizard and Public Form

![Screenshot from 2019-05-20 14-35-19](https://user-images.githubusercontent.com/1583873/58021960-ab94f200-7b0c-11e9-9780-dccfd87d343a.png)



Discussion:

Resolving patch:
diff --git a/migrations/versions/6f7b6fad3f55_refactor_customform_identifiers.py b/migrations/versions/6f7b6fad3f55_refactor_customform_identifiers.py
new file mode 100644
--- /dev/null
+++ b/migrations/versions/6f7b6fad3f55_refactor_customform_identifiers.py
@@ -0,0 +1,45 @@
+"""Refactor custom form identifiers
+Revision ID: 6f7b6fad3f55
+Revises: 6f7b6fad3f54
+Create Date: 2019-05-21 01:48:12.345
+"""
+
+from alembic import op
+
+# revision identifiers, used by Alembic.
+revision = '6f7b6fad3f55'
+down_revision = '6f7b6fad3f54'
+
+
+def upgrade():
+    op.execute("UPDATE custom_forms SET type = 'select' where field_identifier = 'track';",
+               execution_options=None)
+    op.execute("UPDATE custom_forms SET type = 'select' where field_identifier = 'sessionType';",
+               execution_options=None)
+    op.execute("UPDATE custom_forms SET type = 'image' where field_identifier = 'photoUrl';",
+               execution_options=None)
+    op.execute("UPDATE custom_forms SET field_identifier = 'slidesUrl' where field_identifier = 'slides';",
+               execution_options=None)
+    op.execute("UPDATE custom_forms SET field_identifier = 'audioUrl' where field_identifier = 'audio';",
+               execution_options=None)
+    op.execute("UPDATE custom_forms SET field_identifier = 'videoUrl' where field_identifier = 'video';",
+               execution_options=None)
+    op.execute("UPDATE custom_forms SET field_identifier = 'photoUrl' where field_identifier = 'photo';",
+               execution_options=None)
+
+
+def downgrade():
+    op.execute("UPDATE custom_forms SET type = 'text' where field_identifier = 'track';",
+               execution_options=None)
+    op.execute("UPDATE custom_forms SET type = 'text' where field_identifier = 'sessionType';",
+               execution_options=None)
+    op.execute("UPDATE custom_forms SET type = 'text' where field_identifier = 'photoUrl';",
+               execution_options=None)
+    op.execute("UPDATE custom_forms SET field_identifier = 'slides' where field_identifier = 'slidesUrl';",
+               execution_options=None)
+    op.execute("UPDATE custom_forms SET field_identifier = 'audio' where field_identifier = 'audioUrl';",
+               execution_options=None)
+    op.execute("UPDATE custom_forms SET field_identifier = 'video' where field_identifier = 'videoUrl';",
+               execution_options=None)
+    op.execute("UPDATE custom_forms SET field_identifier = 'photo' where field_identifier = 'photoUrl';",
+               execution_options=None)


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

Issue:
Timestamp saved in Database is not correct
**Describe the bug**
Timestamp saved in `created_at` column of users field is not correct.

![Screenshot from 2019-05-21 20-40-02](https://user-images.githubusercontent.com/31065687/58108228-13306780-7c09-11e9-8494-7f8cfffbfaed.png)

Here, all five users were created at different times.


**Expected behavior**
Timestamp should be correct.

**Additional context**
Working on it.



Discussion:
@iamareebjamal I noticed that same time saves in case of subsequent requests. Any idea why? Though the package used for saving default time shows the correct time when printing the value in some other file in the same request. 
Time is saved in UTC. What is wrong?
It saves the same time even when they are created at different times.
How much separation was there between the requests
@iamareebjamal Around 10-15 seconds. 
Debug why
@iamareebjamal On it. 

Resolving patch:
diff --git a/app/models/session.py b/app/models/session.py
--- a/app/models/session.py
+++ b/app/models/session.py
@@ -2,6 +2,7 @@
 
 import pytz
 from sqlalchemy import event, func
+from sqlalchemy.sql import func as sql_func
 
 from app.models import db
 from app.models.base import SoftDeletionModel
@@ -46,7 +47,7 @@ class Session(SoftDeletionModel):
     event_id = db.Column(db.Integer, db.ForeignKey('events.id', ondelete='CASCADE'))
     creator_id = db.Column(db.Integer, db.ForeignKey('users.id', ondelete='CASCADE'))
     state = db.Column(db.String, default="pending")
-    created_at = db.Column(db.DateTime(timezone=True), default=datetime.datetime.utcnow)
+    created_at = db.Column(db.DateTime(timezone=True), default=sql_func.now())
     submitted_at = db.Column(db.DateTime(timezone=True))
     submission_modifier = db.Column(db.String)
     is_mail_sent = db.Column(db.Boolean, default=False)
diff --git a/app/models/user.py b/app/models/user.py
--- a/app/models/user.py
+++ b/app/models/user.py
@@ -7,6 +7,7 @@
 from flask_scrypt import generate_password_hash, generate_random_salt
 from sqlalchemy import event, desc
 from sqlalchemy.ext.hybrid import hybrid_property
+from sqlalchemy.sql import func
 from sqlalchemy.orm.exc import MultipleResultsFound, NoResultFound
 
 from app.api.helpers.db import get_count
@@ -77,7 +78,7 @@ class User(SoftDeletionModel):
     is_verified = db.Column(db.Boolean, default=False)
     was_registered_with_order = db.Column(db.Boolean, default=False)
     last_accessed_at = db.Column(db.DateTime(timezone=True))
-    created_at = db.Column(db.DateTime(timezone=True), default=datetime.now(pytz.utc))
+    created_at = db.Column(db.DateTime(timezone=True), default=func.now())
     speaker = db.relationship('Speaker', backref="user")
     favourite_events = db.relationship('UserFavouriteEvent', backref="user")
     session = db.relationship('Session', backref="user")


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

Issue:
Make Order Invoice similar to EventBrite
**Describe the bug**
Parent Issue:
https://github.com/fossasia/open-event-server/issues/5878

**Expected behavior**
The current order invoice needs to be generated as a proper PDF with the details specified here:
https://github.com/fossasia/open-event-server/pull/5886#issuecomment-492976538

_**While calculating the tax, the percentage and the amount must be shown**_

**Additional context**
Will work on this as soon as https://github.com/fossasia/open-event-server/pulls/5886 is merged.


Discussion:

Resolving patch:
diff --git a/app/api/helpers/order.py b/app/api/helpers/order.py
--- a/app/api/helpers/order.py
+++ b/app/api/helpers/order.py
@@ -11,6 +11,7 @@
 from app.models import db
 from app.models.ticket import Ticket
 from app.models.ticket_holder import TicketHolder
+from app.models.order import OrderTicket
 
 
 def delete_related_attendees_for_order(order):
@@ -70,7 +71,9 @@ def create_pdf_tickets_for_holder(order):
             save_to_db(holder)
 
         # create order invoices pdf
-        create_save_pdf(render_template('pdf/order_invoice.html', order=order, event=order.event),
+        order_ticket_info = OrderTicket.query.filter_by(order_id=order.id).one()
+        create_save_pdf(render_template('pdf/order_invoice.html', order=order, event=order.event,
+                        tax=order.event.tax, tickets=order.tickets, order_tickets_info=order_ticket_info),
                         UPLOAD_PATHS['pdf']['order'], dir_path='/static/uploads/pdf/tickets/',
                         identifier=order.identifier, upload_dir='generated/invoices/')
         save_to_db(order)


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

Issue:
'werkzeug.contrib.profiler' has moved to 'werkzeug.middleware.profiler'
**Describe the bug**
This import has been deprecated as of version 0.15 and will be removed in version 1.0.

**Additional context**
Working on it.


Discussion:

Resolving patch:
diff --git a/app/__init__.py b/app/__init__.py
--- a/app/__init__.py
+++ b/app/__init__.py
@@ -27,7 +27,7 @@
 from app.models import db
 from app.api.helpers.jwt import jwt_authenticate, jwt_identity
 from app.api.helpers.cache import cache
-from werkzeug.contrib.profiler import ProfilerMiddleware
+from werkzeug.middleware.profiler import ProfilerMiddleware
 from app.views import BlueprintsManager
 from app.api.helpers.auth import AuthManager
 from app.api.helpers.scheduled_jobs import send_after_event_mail, send_event_fee_notification, \


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

Issue:
Update API docs for Omise payment Gateway fields
New fields have been introduced in the event and settings models. API docs need to be updated to reflect those changes

Parent issue: #5823 


Discussion:
@CosmicCoder96 Can i take it ?
@kushthedude yes please proceed. 
@CosmicCoder96 Taking this one due to inactivity


Resolving patch:
diff --git a/app/factories/setting.py b/app/factories/setting.py
--- a/app/factories/setting.py
+++ b/app/factories/setting.py
@@ -67,6 +67,12 @@ class Meta:
     paypal_secret = common.string_
     paypal_sandbox_client = common.string_
     paypal_sandbox_secret = common.string_
+    # Omise Credentials
+    omise_mode = 'development'
+    omise_test_public = common.string_
+    omise_test_secret = common.string_
+    omise_live_public = common.string_
+    omise_live_secret = common.string_
     #
     # EMAIL
     #


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

Issue:
multiple db heads present
**Describe the bug**
<!-- A clear and concise description of what the bug is. -->

Multiple db heads present after recent merge, will push a fix making them sequential:

```
b3bfa7949acf (head)
0e80c49a6e28 (head)
Sentry is attempting to send 0 pending error messages
Waiting up to 2.0 seconds
```


Discussion:

Resolving patch:
diff --git a/migrations/versions/0e80c49a6e28_.py b/migrations/versions/0e80c49a6e28_.py
--- a/migrations/versions/0e80c49a6e28_.py
+++ b/migrations/versions/0e80c49a6e28_.py
@@ -1,7 +1,7 @@
 """empty message
 
 Revision ID: 0e80c49a6e28
-Revises: 6f7b6fad3f54
+Revises: b3bfa7949acf
 Create Date: 2019-05-20 21:56:44.770504
 
 """
@@ -12,7 +12,7 @@
 
 # revision identifiers, used by Alembic.
 revision = '0e80c49a6e28'
-down_revision = '6f7b6fad3f54'
+down_revision = 'b3bfa7949acf'
 
 
 def upgrade():


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

Issue:
Typo in the mail being sent after event ends
**Describe the bug**
Typo in the mail being sent after the event ends.

![Screenshot from 2019-06-03 02-29-20](https://user-images.githubusercontent.com/31065687/58767363-a5d8eb00-85a7-11e9-8742-94bca64884f9.png)

**Additional context**
Free for anyone to take up.



Discussion:
@iamareebjamal We should label it Good First Issue
I am taking up this issue

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
@@ -61,8 +61,8 @@
         'message': (
             u"Hi {email},<br/>" +
             u"Thank You for participating in our event. We hope you enjoyed it. "
-            u"Please check the list of more upcoming events" +
-            u"Here are the upcoming events: {upcoming_events} .Get ready!! "
+            u"Please check the list of more upcoming events. <br />" +
+            u"Here are the upcoming events: {upcoming_events}. Get ready!! "
         ),
         'sent_at': '1 day after the event'
     },


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

Issue:
No attribute 'days' error in expiring pending tickets after 3 days function
**Describe the bug**
After 3 days of a pending order, when trying to expire it throws error.

**Expected behavior**
Should not throw any error.

**Error Screenshot**
![Screenshot from 2019-06-04 10-34-19](https://user-images.githubusercontent.com/31065687/58903442-13f5ed00-8723-11e9-80ff-d3b14450ba6b.png)

**Additional context**
Working on it.


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
@@ -12,9 +12,9 @@
 from app.api.helpers.utilities import monthdelta
 from app.models import db
 from app.models.event import Event
-from app.models.session import Session
 from app.models.event_invoice import EventInvoice
 from app.models.order import Order
+from app.models.session import Session
 from app.models.ticket import Ticket
 from app.models.ticket_fee import get_fee
 from app.settings import get_settings
@@ -146,6 +146,6 @@ def expire_pending_tickets_after_three_days():
     from app import current_app as app
     with app.app_context():
         db.session.query(Order).filter(Order.status == 'pending',
-                                       (datetime.datetime.today() - Order.created_at).days > 3).\
+                                       (Order.created_at + datetime.timedelta(days=3)) <= datetime.datetime.now()).\
                                        update({'status': 'expired'})
         db.session.commit()


Test patch: