From 0b5b29f6e834c19f8aa818b222b0cd992aff14f9 Mon Sep 17 00:00:00 2001
From: Jorran de Wit <jorrandewit@outlook.com>
Date: Tue, 18 Apr 2017 22:07:36 +0200
Subject: [PATCH] Add export Contributors command

---
 scipost/constants.py                          |  4 +-
 .../commands/export_contributors.py           | 50 +++++++++++++++++++
 scipost/views.py                              |  5 --
 3 files changed, 52 insertions(+), 7 deletions(-)
 create mode 100644 scipost/management/commands/export_contributors.py

diff --git a/scipost/constants.py b/scipost/constants.py
index 2956972ce..790f06d66 100644
--- a/scipost/constants.py
+++ b/scipost/constants.py
@@ -125,7 +125,7 @@ subject_areas_dict = {}
 for k in subject_areas_raw_dict.keys():
     subject_areas_dict.update(dict(subject_areas_raw_dict[k]))
 
-
+CONTRIBUTOR_NORMAL = 1
 CONTRIBUTOR_STATUS = (
     # status determine the type of Contributor:
     # 0: newly registered (unverified; not allowed to submit, comment or vote)
@@ -137,7 +137,7 @@ CONTRIBUTOR_STATUS = (
     # -3: barred from SciPost (abusive behaviour)
     # -4: disabled account (deceased)
     (0, 'newly registered'),
-    (1, 'normal user'),
+    (CONTRIBUTOR_NORMAL, 'normal user'),
     (-1, 'not a professional scientist'),
     (-2, 'other account already exists'),
     (-3, 'barred from SciPost'),
diff --git a/scipost/management/commands/export_contributors.py b/scipost/management/commands/export_contributors.py
new file mode 100644
index 000000000..889698b31
--- /dev/null
+++ b/scipost/management/commands/export_contributors.py
@@ -0,0 +1,50 @@
+import csv
+from datetime import datetime
+
+from django.core.management.base import BaseCommand
+
+from ...constants import CONTRIBUTOR_NORMAL
+from ...models import Contributor
+
+
+class Command(BaseCommand):
+    """
+    Use this command to export the Contributor table. One could filter the export
+    by simply using the --group argument.
+
+    For example, one could run:
+    $ ./manage.py export_contributors --group 'Registered Contributors'
+    """
+    def add_arguments(self, parser):
+        parser.add_argument(
+            '--group',
+            dest='group',
+            default=False,
+            type=str,
+            help='Filter the contributors by their group name'
+        )
+
+    def handle(self, *args, **kwargs):
+        # File variables
+        filename = 'export_%s_contributors_%s.csv' % (datetime.now().strftime('%Y_%m_%d_%H_%M'),
+                                                      kwargs.get('group', ''))
+        filename = filename.replace(' ', '_')
+        fieldnames = ['first_name', 'last_name', 'email_address']
+
+        # Query
+        queryset = Contributor.objects.filter(user__is_active=True, status=CONTRIBUTOR_NORMAL)
+        if kwargs['group']:
+            queryset = queryset.filter(user__groups__name=kwargs['group'])
+
+        # Open + write the file
+        with open(filename, 'w', newline='') as _file:
+            writer = csv.writer(_file, quotechar='|', quoting=csv.QUOTE_MINIMAL)
+            writer.writerow(fieldnames)
+            n = 0
+            for contributor in queryset:
+                user = contributor.user
+                writer.writerow([user.first_name, user.last_name, user.email])
+                n += 1
+        self.stdout.write(self.style.SUCCESS('Successfully wrote %i Contributors to file %s.' % (
+            n, filename
+        )))
diff --git a/scipost/views.py b/scipost/views.py
index 44d609e97..974b32abf 100644
--- a/scipost/views.py
+++ b/scipost/views.py
@@ -1,8 +1,4 @@
-import datetime
-import hashlib
-import random
 import re
-import string
 
 from django.utils import timezone
 from django.shortcuts import get_object_or_404, render
@@ -17,7 +13,6 @@ from django.core.mail import EmailMessage, EmailMultiAlternatives
 from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
 from django.core.urlresolvers import reverse
 from django.db.models import Q
-from django.http import HttpResponseRedirect
 from django.shortcuts import redirect
 from django.template import Context, Template
 from django.utils.http import is_safe_url
-- 
GitLab