Repository: fossasia/open-event-server

Issue:
Export sessions as CSV
**Is your feature request related to a problem? Please describe.**
Exporting sessions as a CSV file hasn't been implemented yet.

**Describe the solution you'd like**
Use the solution used in version 1

**Describe alternatives you've considered**
\-


Discussion:

Resolving patch:
diff --git a/app/api/exports.py b/app/api/exports.py
--- a/app/api/exports.py
+++ b/app/api/exports.py
@@ -212,3 +212,23 @@ def export_attendees_pdf(event_identifier):
     return jsonify(
         task_url=url_for('tasks.celery_task', task_id=task.id)
     )
+
+
+@export_routes.route('/events/<string:event_identifier>/export/sessions/csv', methods=['GET'])
+@jwt_required()
+def export_sessions_csv(event_identifier):
+    if not event_identifier.isdigit():
+        event = db.session.query(Event).filter_by(identifier=event_identifier).first()
+        event_id = str(event.id)
+    else:
+        event_id = event_identifier
+
+    from .helpers.tasks import export_sessions_csv_task
+
+    task = export_sessions_csv_task.delay(event_id)
+
+    create_export_job(task.id, event_id)
+
+    return jsonify(
+        task_url=url_for('tasks.celery_task', task_id=task.id)
+    )
diff --git a/app/api/helpers/csv_jobs_util.py b/app/api/helpers/csv_jobs_util.py
--- a/app/api/helpers/csv_jobs_util.py
+++ b/app/api/helpers/csv_jobs_util.py
@@ -1,3 +1,6 @@
+from app.models.helpers.versioning import strip_tags
+
+
 def export_orders_csv(orders):
     headers = ['Order#', 'Order Date', 'Status', 'Payment Type', 'Total Amount', 'Quantity',
                'Discount Code', 'First Name', 'Last Name', 'Email']
@@ -40,3 +43,27 @@ def export_attendees_csv(attendees):
         rows.append(column)
 
     return rows
+
+
+def export_sessions_csv(sessions):
+    headers = ['Session Title', 'Session Speakers',
+               'Session Track', 'Session Abstract', 'Created At', 'Email Sent']
+    rows = [headers]
+    for session in sessions:
+        if not session.deleted_at:
+            column = [session.title + ' (' + session.state + ')' if session.title else '']
+            if session.speakers:
+                in_session = ''
+                for speaker in session.speakers:
+                    if speaker.name:
+                        in_session += (speaker.name + '; ')
+                column.append(in_session[:-2])
+            else:
+                column.append('')
+            column.append(session.track.name if session.track and session.track.name else '')
+            column.append(strip_tags(session.short_abstract) if session.short_abstract else '')
+            column.append(session.created_at if session.created_at else '')
+            column.append('Yes' if session.is_mail_sent else 'No')
+            rows.append(column)
+
+    return rows
diff --git a/app/api/helpers/tasks.py b/app/api/helpers/tasks.py
--- a/app/api/helpers/tasks.py
+++ b/app/api/helpers/tasks.py
@@ -7,6 +7,7 @@
 
 from app import make_celery
 from app.api.helpers.utilities import strip_tags
+from app.models.session import Session
 
 """
 Define all API v2 celery tasks here
@@ -318,3 +319,32 @@ def export_attendees_pdf_task(self, event_id):
         result = {'__error': True, 'result': str(e)}
 
     return result
+
+
+@celery.task(base=RequestContextTask, name='export.sessions.csv', bind=True)
+def export_sessions_csv_task(self, event_id):
+    sessions = db.session.query(Session).filter_by(event_id=event_id)
+    try:
+        filedir = os.path.join(current_app.config.get('BASE_DIR'), 'static/uploads/temp/')
+        if not os.path.isdir(filedir):
+            os.makedirs(filedir)
+        filename = "sessions-{}.csv".format(uuid.uuid1().hex)
+        file_path = os.path.join(filedir, filename)
+
+        with open(file_path, "w") as temp_file:
+            writer = csv.writer(temp_file)
+            from app.api.helpers.csv_jobs_util import export_sessions_csv
+            content = export_sessions_csv(sessions)
+            for row in content:
+                writer.writerow(row)
+        sessions_csv_file = UploadedFile(file_path=file_path, filename=filename)
+        sessions_csv_url = upload(sessions_csv_file,
+                                  UPLOAD_PATHS['exports-temp']['csv'].format(event_id=event_id, identifier=''))
+        result = {
+            'download_url': sessions_csv_url
+        }
+    except Exception as e:
+        print(traceback.format_exc())
+        result = {'__error': True, 'result': str(e)}
+
+    return result


Test patch:
diff --git a/tests/hook_main.py b/tests/hook_main.py
--- a/tests/hook_main.py
+++ b/tests/hook_main.py
@@ -3685,6 +3685,19 @@ def event_attendees_export_pdf_get(transaction):
         db.session.add(event)
         db.session.commit()
 
+
+@hooks.before(
+    "Event Export > Start Sessions Export as CSV > Start a Task to Export Sessions of an Event as CSV")
+def event_sessions_export_csv_get(transaction):
+    """
+    :param transaction:
+    :return:
+    """
+    with stash['app'].app_context():
+        event = EventFactoryBasic()
+        db.session.add(event)
+        db.session.commit()
+
 # ------------------------- Import -------------------------
 @hooks.before(
     "Event Import > Start Event Import > Start a Task to Import an Event")