"""
This script can be run to generate a CSV output of publisher accounts which do not have th api role set, along
with some useful account information.

```
python accounts_with_missing_api_role.py -o accounts.csv
```
"""
import csv
import esprit
from portality.core import es_connection
from portality import models

MISSING_API_ROLE = {
    "query": {
        "filtered": {
            "query": {
                "term": {
                    "role.exact": "publisher"
                }
            },
            "filter": {
                "not": {
                    "term": {"role.exact": "api"}
                }
            }
        }
    }
}


def publishers_with_journals():
    """ Get accounts for all publishers with journals in the DOAJ """
    for acc in esprit.tasks.scroll(conn, 'account', q=MISSING_API_ROLE, page_size=100, keepalive='1m'):
        publisher_account = models.Account(**acc)
        journal_ids = publisher_account.journal
        if journal_ids is not None:
            for j in journal_ids:
                journal = models.Journal.pull(j)
                if journal is not None and journal.is_in_doaj():
                    yield publisher_account
                    break


if __name__ == "__main__":

    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument("-o", "--out", help="output file path")
    args = parser.parse_args()

    if not args.out:
        print("Please specify an output file path with the -o option")
        parser.print_help()
        exit()

    conn = es_connection

    with open(args.out, "w", encoding="utf-8") as f:
        writer = csv.writer(f)
        writer.writerow(["ID", "Name", "Email", "Created", "Last Updated"])

        for account in publishers_with_journals():
            writer.writerow([
                account.id,
                account.name,
                account.email,
                account.created_date,
                account.last_updated
            ])

@@ -145,16 +145,87 @@
 rmation.
+ Using the flag -a adds the missing API role and key to those accounts.
 %0A%0A%60%60%60%0Apy
@@ -278,16 +278,21 @@
 unts.csv
+ %5B-a%5D
 %0A%60%60%60%0A%22%22%22
@@ -358,16 +358,54 @@
 nection%0A
+from portality.util import ipt_prefix%0A
 from por
@@ -906,16 +906,27 @@
 l(conn, 
+ipt_prefix(
 'account
@@ -926,16 +926,17 @@
 account'
+)
 , q=MISS
@@ -1043,165 +1043,66 @@
     
-journal_ids = publisher_account.journal%0A        if journal_ids is not None:%0A            for j in journal_ids:%0A                journal = models.Journal.pull(j
+issns = models.Journal.issns_by_owner(publisher_account.id
 )%0A  
@@ -1111,73 +1111,27 @@
     
- 
-       if journal is not None and journal.is_in_doaj():%0A        
+if len(issns) %3E 0:%0A
     
@@ -1166,34 +1166,8 @@
 unt%0A
-                    break%0A
 %0A%0Aif
@@ -1313,16 +1313,120 @@
 le path%22
+, required=True)%0A    parser.add_argument('-a', '--add', help=%22add the missing role%22, action='store_true'
 )%0A    ar
@@ -1462,24 +1462,25 @@
  if not 
+(
 args.out
 :%0A      
@@ -1471,16 +1471,29 @@
 args.out
+ or args.add)
 :%0A      
@@ -1554,16 +1554,48 @@
 o option
+, or optionally add role with -a
 %22)%0A     
@@ -1816,16 +1816,25 @@
 Updated%22
+, %22Roles%22
 %5D)%0A%0A    
@@ -1876,24 +1876,164 @@
 journals():%0A
+            if args.add:%0A                account.add_role('api')%0A                account.generate_api_key()%0A                account.save()%0A%0A
             
@@ -2213,16 +2213,46 @@
 _updated
+,%0A                account.role
 %0A       

Add api key gen to script which previously reported on accounts without api role