Exemplo n.º 1
0
def load_logged_in_user():
    user_id = session.get('user_id')

    if user_id is None:
        g.user = None
    else:
        g.user = get_db().execute('SELECT * FROM user WHERE id = ?',
                                  (user_id, )).fetchone()
Exemplo n.º 2
0
def register():

    if request.method == 'GET':
        url_doi = request.args.get('doi')
        email = request.args.get('email')
        if email != None and email != '':
            return render_template('auth/register.html', doi = email, search_type = 'email')
        elif url_doi != None and url_doi != '':
            return render_template('auth/register.html', doi = url_doi, search_type = 'doi')

    if request.method == 'POST':
        db = get_db()
        error = None
        doi_val = request.form['doi']
        print('doi_val: '+doi_val)
        doi_val = doi_val.replace('   ', '')
        doi_val = doi_val.replace('  ', '')
        doi_val = doi_val.replace(' ', '')
        doi_val = doi_val.replace('\r\n', '')
        doi_val = doi_val.replace('\n', '')
        doi_val = doi_val.replace('\r', '')
        email_val = ''
        author_val = ''
        query_val = str(doi_val.split(',')).replace('[', '(').replace(']', ')')
        search_type = request.form['search_type']
        if search_type == 'email':
            email_val = doi_val
            query_emails = query_val
            print('query_emails: ' + query_emails)

            emails = pg_query(db, 'fetchall', 'SELECT * FROM email_doi_tables WHERE email IN ' + query_emails,())
            if emails == None or len(emails) == 0:
                error = "No articles found associated to supplied email(s). Please check your search and try again."
                flash(error)
                return render_template('auth/register.html', doi = request.form['doi'], search_type = search_type)
            dois = []
            for email in emails:
                print(email['dois'])
                for doi_tmp in email['dois']:
                    dois.append(doi_tmp)
            query_dois = str(dois).replace('[', '(').replace(']', ')')
            print(query_dois)
        # elif search_type == 'pmid':
        #     query_pmids = '('
        #     for pmid in doi_val.split(','):
        #         if not pmid.isnumeric():
        #             error = "One or more value(s) supplied are not numeric PubMed IDs. Please check your search and try again."
        #             flash(error)
        #             return render_template('auth/register.html', doi = request.form['doi'], search_type = search_type)
        #         query_pmids = query_pmids + pmid + ','
            
        #     query_pmids = query_pmids[:-1] + ')'
        #     print('query_pmids: ' + query_pmids)
        #     pmid_dois = pg_query(db, 'fetchall', 'SELECT * FROM pmid_doi WHERE pmid IN ' + query_pmids,())
        #     if pmid_dois == None or len(pmid_dois) == 0:
        #         error = "No articles found associated to supplied pmid(s). Please check your search and try again."
        #         flash(error)
        #         return render_template('auth/register.html', doi = request.form['doi'], search_type = search_type)
        #     dois = []
        #     for pmid_doi in pmid_dois:
        #         dois.append(pmid_doi['doi'])
        #     query_dois = str(dois).replace('[', '(').replace(']', ')')
        #     print(query_dois)
        elif search_type == 'author':
            author_val = request.form['doi']

            query_authors = query_val
            print('query_authors: ' + query_authors)
        else:
            query_dois = query_val
            if 'doi.org' in doi_val:
                doi_val = doi_val.replace('http://www.', '')
                doi_val = doi_val.replace('https://www.', '')
                doi_val = doi_val.replace('https://', '')
                doi_val = doi_val.replace('http://', '')
                doi_val = doi_val.replace('www.doi.org/', '')
                doi_val = doi_val.replace('doi.org/', '')
                query_dois = str(doi_val.split(',')).replace('[', '(').replace(']', ')')
                print(query_dois)
            pmids = '('
            dois = ''
            for s in doi_val.split(','):
                if s.isnumeric():
                    pmids = pmids + s + ','
                else:
                    dois = dois + s + ','
            if pmids != '(':
                query_pmids = pmids[:-1] + ')'
                pmid_dois = pg_query(db, 'fetchall', 'SELECT * FROM pmid_doi WHERE pmid IN ' + query_pmids,())
                if pmid_dois != None and len(pmid_dois) > 0:
                    for pmid_doi in pmid_dois:
                        dois = dois + pmid_doi['doi'] + ','
            if dois == '':
                error = "No article(s) found with supplied DOI(s)/Pubmed ID(s). Please try searching again."
                flash(error)
                return render_template('auth/register.html', doi = request.form['doi'], search_type = search_type)
            query_dois = str(dois.split(',')).replace('[', '(').replace(']', ')')

        articles = pg_query(db, 'fetchall', 'SELECT * FROM article_info WHERE doi IN ' + query_dois,())
        if articles is None or len(articles) == 0:
            error = "No article(s) found with supplied DOI(s)/Pubmed ID(s). Please try searching again."
            flash(error)
            return render_template('auth/register.html', doi = request.form['doi'], search_type = search_type)
        db.close()
        doi_val = query_dois.replace('(', '').replace(')', '').replace('\'', '').replace(' ', '')
        return redirect(url_for('auth.confirm', doi = doi_val, email = email_val))
    
    return render_template('auth/register.html')
Exemplo n.º 3
0
def confirm():

    url_doi = request.args.get('doi')
    dois = url_doi.split(',')
    query_val = str(dois).replace('[', '(').replace(']', ')')
    email = request.args.get('email')
    if request.method == 'POST' and 'back' in request.form:
        return redirect(url_for('auth.register', doi = url_doi, email = email))
    email_list = []
    if email != None and email != '':
        email_list = email.split(',')
    db = get_db()

    # cur.execute(
    #     'SELECT * FROM article_info WHERE doi = %s', (doi,)
    # )
    # articles = cur.fetchall()
    articles = pg_query(db, 'fetchall', 'SELECT * FROM article_info WHERE doi IN ' + query_val + ' ORDER BY pub_date DESC', ())
    print(articles)
    print(articles[0])
    print(articles[0]["title"])

    article_infos = []

    all_email_ids = '('

    all_has_emails = False

    for article in articles:
        doi = article['doi']
        doi_child = pg_query(db, 'fetchone', 'SELECT * FROM doi_child_tables WHERE doi = %s', (doi,))

        print(doi_child)

        auth_ids = str(doi_child['author_ids']).replace('[', '(').replace(']', ')')

        email_ids = str(doi_child['email_ids']).replace('[', '(').replace(']', ')')

        email_ids = email_ids.replace('None, ', '').replace('None)', ')')

        # cur.execute(
        #     'SELECT * FROM author_doi WHERE doi = %s', (doi,)
        # )
        # authors = cur.fetchall()
        authors = pg_query(db, 'fetchall', 'SELECT * FROM author_doi WHERE id IN ' + auth_ids + ' ORDER BY author_pos ASC NULLS LAST, affiliation_pos ASC ', ())

        completed_urls = pg_query(db, 'fetchall', 'SELECT * FROM email_url WHERE doi = %s and completed_timestamp IS NOT NULL ORDER BY completed_timestamp DESC LIMIT 1 ', (doi,))
        
        has_path = (completed_urls != None and len(completed_urls) > 0)

        auth_aff_list = []
        affiliation_list = []
        for author in authors:
            if author['author_affiliation'] in affiliation_list:
                aff_num = affiliation_list.index(author['author_affiliation']) + 1
            elif author['author_affiliation'] != None:
                affiliation_list.append(author['author_affiliation'])
                aff_num = len(affiliation_list)
            if len(auth_aff_list) > 0 and auth_aff_list[len(auth_aff_list) - 1].author['author_pos'] == author['author_pos']:
                auth_aff_list[len(auth_aff_list) - 1].affiliation_nums.append(aff_num)
            else:
                if author['author_affiliation'] == None:
                    auth_aff = author_affiliations(author, [])
                else:
                    auth_aff = author_affiliations(author, [aff_num])
                auth_aff_list.append(auth_aff)

        # cur.execute(
        #     'SELECT * FROM email_doi WHERE doi = %s', (doi,)
        # )
        # emails = cur.fetchall()
        emails = None
        if email_ids != '()':
            all_email_ids = all_email_ids + str(doi_child['email_ids']).replace('[', '').replace(']', '') + ',' 
            emails = pg_query(db, 'fetchall', 'SELECT * FROM email_doi WHERE id IN ' + email_ids, ())
        has_emails = True
        if emails == None or len(emails) == 0:
            has_emails = False
        else:
            for email_tmp in emails:
                if not email_tmp['email'] in email_list:
                    email_list.append(email_tmp['email'])
        all_has_emails = (all_has_emails or has_emails)
        article_info_tmp = article_info(article, auth_aff_list, emails, has_emails, affiliation_list, has_path)
        article_infos.append(article_info_tmp)
        email_list.sort()

    error = None
    if request.method == 'POST':
        all_email_ids = all_email_ids[:-1] + ')'
        all_emails = pg_query(db, 'fetchall', 'SELECT * FROM email_doi WHERE id IN ' + all_email_ids, ())

        now = datetime.now().timestamp()
        now = round(now)

        for email in all_emails:
            doi_email_str = email['doi'] + '---' + email['email']
            print(doi_email_str + ' found in form: ' + str(doi_email_str in request.form))
        print('REQUEST: ' + str(request.form))

        # email_urls = list()
        sentEmail = False

        for email in all_emails:
            doi_email_str = email['doi'] + '---' + email['email']
            if doi_email_str in request.form:
                for aTmp in articles:
                    if aTmp['doi'] == email['doi']:
                        article = aTmp
                sentEmail = True
                url_id = str(now) + str(hash(email['email'])) + str(hash(email['doi']))
                revision = 1
                # cur.execute(
                #     'SELECT * FROM email_url WHERE email = %s AND doi = %s ORDER BY revision DESC LIMIT 1', (email['email'], doi,)
                # )
                # emUrl = cur.fetchone()
                emUrl = pg_query(db, 'fetchone', 'SELECT * FROM email_url WHERE email = %s AND doi = %s ORDER BY revision DESC LIMIT 1', (email['email'], email['doi'],))
                if not emUrl is None:
                    revision = int(emUrl['revision']) + 1
                # email_url_tmp = email_url(email = author['email'], url_param_id = url_id, doi = doi, revision = '1', completed_timestamp = '')
                sql = ''' INSERT INTO email_url(email,url_param_id,doi,revision)
                VALUES(%s,%s,%s,%s) '''
                email_url_tmp = (email['email'], url_id, email['doi'], revision)
                # cur = db.cursor()
                # cur.execute(sql, email_url_tmp)
                # db.commit()
                pg_query(db, 'insert', sql, email_url_tmp)
                # error = cur.lastrowid

                url_base = 'http://18.116.73.233:5000'

                message_text = """\
                <html>
                    <body>
                        <p>Hello,<br/> Here is your unique URL to enter the submission path for \"""" + article['title'] + """\":<br/>
                        """ + url_base + """/enter/""" + url_id + """<br/>
                        Thank you in advance!<br/>
                        If you didn't request this email, please let us know at [email protected].</p>
                    </body>
                </html>
                """

                send_email(receiver_email = email['email'], message_text = message_text, subject = ('Submission Path Entry For DOI ' + article['doi']), db = db)

                # email_urls.append(email_url_tmp)
        if sentEmail == True:
            db.close()
            return redirect(url_for('thanks.thanks', thanks_type = 'registration'))
        else:
            error = 'No emails selected, please select at least one email to send url to.'






        flash(error)

    db.close()
    return render_template('auth/confirm.html', article_infos = article_infos, email_list = email_list, all_has_emails = all_has_emails)
Exemplo n.º 4
0
def register():

    if request.method == 'GET':
        url_doi = request.args.get('doi')
        url_author_name = request.args.get('author')
        url_email = request.args.get('email')
        if url_author_name != None and url_author_name != '':
            url_last_name = ''
            url_first_name = ''
            url_middle_name = ''
            url_names = url_author_name.split(' ')
            url_first_name = url_names[0]
            if len(url_names) == 2:
                url_last_name = url_names[1]
            else:
                url_middle_name = url_names[1]
                url_last_name = url_names[2]
            if url_middle_name != None and url_middle_name != '':
                return render_template('author/register.html',
                                       last_name=url_last_name,
                                       first_name=url_first_name,
                                       middle_name=url_middle_name,
                                       search_type='author')
            else:
                return render_template('author/register.html',
                                       last_name=url_last_name,
                                       first_name=url_first_name,
                                       search_type='author')
        elif url_email != None and url_email != '':
            return render_template('author/register.html',
                                   doi=url_email,
                                   search_type='email')
        elif url_doi != None and url_doi != '':
            return render_template('author/register.html',
                                   doi=url_doi,
                                   search_type='doi')

    if request.method == 'POST':
        db = get_db()
        error = None
        doi_val = request.form['doi']
        print('doi_val: ' + doi_val)
        doi_val = doi_val.replace('   ', '')
        doi_val = doi_val.replace('  ', '')
        doi_val = doi_val.replace(' ', '')
        doi_val = doi_val.replace('\r\n', '')
        doi_val = doi_val.replace('\n', '')
        doi_val = doi_val.replace('\r', '')
        email_val = ''
        author_val = ''
        query_val = str(doi_val.split(',')).replace('[', '(').replace(']', ')')
        search_type = request.form['search_type']
        if search_type == 'author':
            last_name = request.form['last_name']
            first_name = request.form['first_name']
            middle_name = request.form['middle_name']
            author_val = author_val.replace('\r\n', ' ')
            author_val = author_val.replace('\n', ' ')
            author_val = author_val.replace('\r', ' ')
            author_val = author_val.replace('     ', ' ')
            author_val = author_val.replace('    ', ' ')
            author_val = author_val.replace('   ', ' ')
            author_val = author_val.replace('  ', ' ')
            author_name_split = [last_name.lower(), first_name.lower()]
            author_val = first_name
            if middle_name != None and middle_name != " " and middle_name != "":
                author_name_split.append(middle_name.lower())
                author_val = author_val + ' ' + middle_name
            author_val = author_val + ' ' + last_name
            author_query_names = []
            author_name_list_list = []
            # author_val will be in format {LN} {FN/FI} {(Optional)MI}
            if len(author_name_split) > 1:
                # FN/FI + % + LN
                if len(author_name_split) == 2:
                    query_name_search = 'SELECT * from author_doi_tables where author_last_name = \'' + author_name_split[
                        0] + '\' and author_fore_name like \'' + author_name_split[
                            1] + '%\';'
                # MI
                else:
                    # FI + % + MI + % + LN
                    if len(author_name_split[1]) == 1:
                        query_name_search = 'SELECT * from author_doi_tables where author_last_name = \'' + author_name_split[
                            0] + '\' and author_fore_name like \'' + author_name_split[
                                1] + '%\' and author_fore_name like \'% ' + author_name_split[
                                    2] + '%\';'
                    # FN + MI + % + LN
                    else:
                        query_name_search = 'SELECT * from author_doi_tables where author_last_name = \'' + author_name_split[
                            0] + '\' and author_fore_name like \'' + author_name_split[
                                1] + ' ' + author_name_split[2] + '%\';'
            else:
                query_name_search = 'SELECT * from author_doi_tables where author_last_name = \'' + author_name_split[
                    0] + '\';'

            print('QUERY: ' + query_name_search)
            author_names = pg_query(db, 'fetchall', query_name_search)
            print(author_names)
            if len(author_names) > 0:
                dois = []
                for author in author_names:
                    dois.extend(author['dois'])
                query_dois = str(dois).replace('[', '(').replace(']', ')')
            else:
                error = "No article(s) found with supplied author name. Please try searching again."
                flash(error)
                return render_template('author/register.html',
                                       last_name=request.form['last_name'],
                                       first_name=request.form['first_name'],
                                       middle_name=request.form['middle_name'],
                                       search_type=search_type)
        elif search_type == 'email':
            email_val = doi_val
            query_emails = query_val
            print('query_emails: ' + query_emails)

            emails = pg_query(
                db, 'fetchall',
                'SELECT * FROM email_doi_tables WHERE email IN ' +
                query_emails, ())
            if emails == None or len(emails) == 0:
                error = "No articles found associated to supplied email(s). Please check your search and try again."
                flash(error)
                return render_template('auth/register.html',
                                       doi=request.form['doi'],
                                       search_type=search_type)
            dois = []
            for email in emails:
                print(email['dois'])
                for doi_tmp in email['dois']:
                    dois.append(doi_tmp)
            query_dois = str(dois).replace('[', '(').replace(']', ')')
            print(query_dois)
        else:
            query_dois = query_val
            if 'doi.org' in doi_val:
                doi_val = doi_val.replace('http://www.', '')
                doi_val = doi_val.replace('https://www.', '')
                doi_val = doi_val.replace('https://', '')
                doi_val = doi_val.replace('http://', '')
                doi_val = doi_val.replace('www.doi.org/', '')
                doi_val = doi_val.replace('doi.org/', '')
                query_dois = str(doi_val.split(',')).replace('[', '(').replace(
                    ']', ')')
                print(query_dois)
            pmids = '('
            dois = ''
            for s in doi_val.split(','):
                if s.isnumeric():
                    pmids = pmids + s + ','
                else:
                    dois = dois + s + ','
            if pmids != '(':
                query_pmids = pmids[:-1] + ')'
                pmid_dois = pg_query(
                    db, 'fetchall',
                    'SELECT * FROM pmid_doi WHERE pmid IN ' + query_pmids, ())
                if pmid_dois != None and len(pmid_dois) > 0:
                    for pmid_doi in pmid_dois:
                        dois = dois + pmid_doi['doi'] + ','
            if dois == '':
                error = "No article(s) found with supplied DOI(s)/Pubmed ID(s). Please try searching again."
                flash(error)
                return render_template('author/register.html',
                                       doi=request.form['doi'],
                                       search_type=search_type)
            query_dois = str(dois.split(',')).replace('[',
                                                      '(').replace(']', ')')

        articles = pg_query(
            db, 'fetchall',
            'SELECT * FROM article_info WHERE doi IN ' + query_dois, ())
        if articles is None or len(articles) == 0:
            error = "No article(s) found with supplied DOI(s)/Pubmed ID(s). Please try searching again."
            flash(error)
            return render_template('author/register.html',
                                   doi=request.form['doi'],
                                   search_type=search_type)
        db.close()
        doi_val = query_dois.replace('(', '').replace(')', '').replace(
            '\'', '').replace(' ', '')
        return redirect(
            url_for('author.confirm',
                    doi=doi_val,
                    email=email_val,
                    author=author_val))

    return render_template('author/register.html')
Exemplo n.º 5
0
def enter(url_id):

    db = get_db()

    email_url = db.execute('SELECT * FROM email_url WHERE url_param_id = ?',
                           (url_id, )).fetchone()

    article_info = db.execute('SELECT * FROM article_info WHERE doi = ?',
                              (email_url["doi"], )).fetchone()

    journal_opts = db.execute('SELECT * FROM journal', ()).fetchall()

    # The submitted request from the client-side is request with the following variables:
    # method (values = GET or POST) - The request method of either simply navigating to the page without submitting a form (GET) or the request sent once you click a button on the page to submit the form (POST)
    # form - The form you submit. Comes back as a list of key-avalue pairs ex.- ('input1', 'hello'), ('name', 'Josh')

    if request.method == 'GET':
        path_list_tmp = [
            paper_path(idx=0,
                       url_param_id=url_id,
                       step=1,
                       journal='',
                       submit_date='',
                       error='',
                       show_error=False).__dict__
        ]
        path_list_tmp.append(
            paper_path(idx=1,
                       url_param_id=url_id,
                       step=2,
                       journal=article_info["journal_name"],
                       submit_date='',
                       error='',
                       show_error=False).__dict__)
        session["path_list"] = path_list_tmp

    elif request.method == 'POST':
        error = None
        print(request.form)
        print(request.form.getlist('journal'))

        idxs = request.form.getlist('idx')
        steps = request.form.getlist('step')
        journals = request.form.getlist('journal')
        submit_dates = request.form.getlist('submit_date')
        del_item = request.form.getlist('del_item')
        last = len(idxs) - 1

        path_list_tmp = []
        isDel = False
        delMod = 0
        max_date = ''
        is_submit = ('submit' in request.form)
        has_error = False
        for i in range(0, last + 1):
            del_item_name = 'del_item' + str(steps[i])
            if not (del_item_name in request.form):
                path_item_tmp = paper_path(i + delMod, url_id,
                                           (i + 1) + delMod, journals[i],
                                           submit_dates[i], '', is_submit)
                path_item_tmp.validate(max_date)
                if not path_item_tmp.error == '':
                    has_error = True

                if not 'Submission date' in path_item_tmp.error:
                    max_date = path_item_tmp.submit_date
                path_list_tmp.append(path_item_tmp.__dict__)

            else:
                delMod = delMod - 1
        print(path_list_tmp)

        if 'add_item' in request.form:
            final_path = path_list_tmp.pop(len(path_list_tmp) - 1)
            if last == 0:
                path_list_tmp = [
                    paper_path(idx=0,
                               url_param_id=url_id,
                               step=1,
                               journal='',
                               submit_date='',
                               error='',
                               show_error=False).__dict__
                ]
            else:
                newIdx = int(idxs[last])
                newStep = int(steps[last])
                path_list_tmp.append(
                    paper_path(newIdx,
                               url_id,
                               newStep,
                               journal='',
                               submit_date='',
                               error='',
                               show_error=False).__dict__)
            final_path["idx"] = final_path["idx"] + 1
            final_path["step"] = final_path["step"] + 1
            path_list_tmp.append(final_path)
        elif 'submit' in request.form:
            if last == -1:
                error = 'You must have at least one item before submitting.'
            elif has_error == True:
                error = 'Errors in form, please review and fix issues.'
            else:
                for path_item in path_list_tmp:
                    sql = ''' INSERT INTO paper_path(step,submission_date,journal,url_param_id)
                        VALUES(?,?,?,?) '''
                    cur = db.cursor()
                    cur.execute(
                        sql, (path_item["step"], path_item["submit_date"],
                              path_item["journal"], path_item["url_param_id"]))
                    db.commit()
                sql = ''' UPDATE email_url
                    SET completed_timestamp = ?
                    WHERE url_param_id = ? '''
                cur = db.cursor()
                cur.execute(sql, (datetime.now(), url_id))
                db.commit()
                return redirect(
                    url_for('thanks.thanks', thanks_type='submission'))

        if error != None:
            flash(error)

        session["path_list"] = path_list_tmp

    return render_template('enter.html',
                           email_url=email_url,
                           journal_opts=journal_opts)
Exemplo n.º 6
0
def enter(url_id):

    db = get_db()

    allow_enter = True
    # cur.execute(
    #     'SELECT * FROM email_url WHERE url_param_id = %s', (url_id,)
    # )
    # email_url = cur.fetchone()
    email_url = pg_query(db, 'fetchone',
                         'SELECT * FROM email_url WHERE url_param_id = %s',
                         (url_id, ))
    print('email_url debug start')
    print(email_url)
    print(email_url['completed_timestamp'])
    print(email_url['completed_timestamp'] != '')
    print(email_url['completed_timestamp'] is not None)
    print('email_url debug end')

    if email_url['completed_timestamp'] is not None:
        error = 'Path already entered for this unique URL, please re-register if you wish to enter a new publication path!'
        allow_enter = False

    # cur.execute(
    #     'SELECT * from paper_path WHERE url_param_id = (SELECT url_param_id from email_url WHERE completed_timestamp IS NOT NULL and doi = %s ORDER BY completed_timestamp DESC LIMIT 1) ORDER BY step ASC;', (email_url['doi'],)
    # )
    # completed_paths = cur.fetchall()
    completed_paths = pg_query(
        db, 'fetchall',
        'SELECT * from paper_path WHERE url_param_id = (SELECT url_param_id from email_url WHERE completed_timestamp IS NOT NULL and doi = %s ORDER BY completed_timestamp DESC LIMIT 1) ORDER BY step ASC;',
        (email_url['doi'], ))

    # cur.execute(
    #     'SELECT * FROM author_doi WHERE doi = %s', (email_url['doi'],)
    # )
    # author_doi = cur.fetchall()
    doi_child = pg_query(db, 'fetchone',
                         'SELECT * FROM doi_child_tables WHERE doi = %s',
                         (email_url["doi"], ))
    print(doi_child)
    auth_ids = str(doi_child['author_ids']).replace('[', '(').replace(']', ')')
    authors = pg_query(
        db, 'fetchall', 'SELECT * FROM author_doi WHERE id IN ' + auth_ids +
        ' ORDER BY author_pos ASC NULLS LAST, affiliation_pos ASC ', ())

    auth_aff_list = []
    affiliation_list = []
    for author in authors:
        if author['author_affiliation'] in affiliation_list:
            aff_num = affiliation_list.index(author['author_affiliation']) + 1
        else:
            affiliation_list.append(author['author_affiliation'])
            aff_num = len(affiliation_list)
        if len(auth_aff_list) > 0 and auth_aff_list[
                len(auth_aff_list) -
                1].author['author_pos'] == author['author_pos']:
            auth_aff_list[len(auth_aff_list) -
                          1].affiliation_nums.append(aff_num)
        else:
            auth_aff = author_affiliations(author, [aff_num])
            auth_aff_list.append(auth_aff)

    # cur.execute(
    #     'SELECT * FROM article_info WHERE doi = %s', (email_url["doi"],)
    # )
    # article_info = cur.fetchone()
    article_info = pg_query(db, 'fetchone',
                            'SELECT * FROM article_info WHERE doi = %s',
                            (email_url["doi"], ))

    # cur.execute(
    #     'SELECT * FROM journal_name', ()
    # )
    # journal_opts = cur.fetchall()
    journal_opts = pg_query(
        db, 'fetchall', 'SELECT * FROM journal_name ORDER BY journal_name ASC',
        ())

    confirm = False

    if request.method == 'GET' and allow_enter == True:
        path_list_tmp = [
            paper_path(idx=0,
                       url_param_id=url_id,
                       step=1,
                       journal='',
                       peer_review='',
                       submit_date='',
                       error='',
                       show_error=False).__dict__
        ]
        path_list_tmp.append(
            paper_path(idx=1,
                       url_param_id=url_id,
                       step=2,
                       journal=article_info["journal_name"],
                       peer_review='Yes',
                       submit_date='',
                       error='',
                       show_error=False).__dict__)
        session["path_list"] = path_list_tmp

    elif request.method == 'POST' and allow_enter == True:
        error = None
        print(request.form)
        print(request.form.getlist('journal'))

        idxs = request.form.getlist('idx')
        steps = request.form.getlist('step')
        journals = request.form.getlist('journal')
        submit_dates = request.form.getlist('submit_date')
        peer_reviews = []
        for step in steps:
            peer_reviews.append(request.form.get('peer_review' + step))
        del_item = request.form.getlist('del_item')
        last = len(idxs) - 1

        path_list_tmp = []
        isDel = False
        delMod = 0
        addMod = 0
        prior_date = ''
        max_date = article_info['pub_date']
        prev_journal = ''
        is_submit = ('submit' in request.form)
        has_error = False
        up_idx = None
        down_idx = None
        for i in range(0, last + 1):
            del_item_name = 'del_item' + str(steps[i])
            add_item_name = 'add_item' + str(steps[i])
            up_item_name = 'up_item' + str(steps[i])
            down_item_name = 'down_item' + str(steps[i])
            if not (del_item_name in request.form):
                if up_item_name in request.form:
                    up_idx = i
                if down_item_name in request.form:
                    down_idx = i
                if add_item_name in request.form:
                    path_list_tmp.append(
                        paper_path(i + delMod + addMod, url_id,
                                   (i + 1) + delMod + addMod, '', '', '', '',
                                   is_submit).__dict__)
                    addMod = addMod + 1
                path_item_tmp = paper_path(i + delMod + addMod, url_id,
                                           (i + 1) + delMod + addMod,
                                           journals[i], peer_reviews[i],
                                           submit_dates[i], '', is_submit)
                path_item_tmp.validate(prior_date, max_date, prev_journal)
                prev_journal = path_item_tmp.journal
                if not path_item_tmp.error == '':
                    has_error = True

                if not 'Submission date' in path_item_tmp.error and path_item_tmp.submit_date is not None and path_item_tmp.submit_date != '':
                    prior_date = path_item_tmp.submit_date
                path_list_tmp.append(path_item_tmp.__dict__)

            else:
                delMod = delMod - 1
        if up_idx != None:
            print(up_idx)
            up_path_tmp = path_list_tmp.pop(up_idx)
            up_path_tmp["step"] = up_path_tmp["step"] - 1
            up_path_tmp["idx"] = up_path_tmp["idx"] - 1
            prev_path_tmp = path_list_tmp.pop(up_idx - 1)
            prev_path_tmp["step"] = prev_path_tmp["step"] + 1
            prev_path_tmp["idx"] = prev_path_tmp["idx"] + 1
            path_list_tmp.insert(up_idx - 1, up_path_tmp)
            path_list_tmp.insert(up_idx, prev_path_tmp)
        if down_idx != None:
            print(down_idx)
            next_path_tmp = path_list_tmp.pop(down_idx + 1)
            next_path_tmp["step"] = next_path_tmp["step"] - 1
            next_path_tmp["idx"] = next_path_tmp["idx"] - 1
            down_path_tmp = path_list_tmp.pop(down_idx)
            down_path_tmp["step"] = down_path_tmp["step"] + 1
            down_path_tmp["idx"] = down_path_tmp["idx"] + 1
            path_list_tmp.insert(down_idx, next_path_tmp)
            path_list_tmp.insert(down_idx + 1, down_path_tmp)
        print(path_list_tmp)

        if 'add_item' in request.form:
            final_path = path_list_tmp.pop(len(path_list_tmp) - 1)
            if last == 0:
                path_list_tmp = [
                    paper_path(idx=0,
                               url_param_id=url_id,
                               step=1,
                               journal='',
                               peer_review='',
                               submit_date='',
                               error='',
                               show_error=False).__dict__
                ]
            else:
                newIdx = int(idxs[last])
                newStep = int(steps[last])
                path_list_tmp.append(
                    paper_path(newIdx,
                               url_id,
                               newStep,
                               journal='',
                               peer_review='',
                               submit_date='',
                               error='',
                               show_error=False).__dict__)
            final_path["idx"] = final_path["idx"] + 1
            final_path["step"] = final_path["step"] + 1
            path_list_tmp.append(final_path)
        elif 'submit' in request.form:
            if last == -1:
                error = 'You must have at least one item before submitting.'
            elif has_error == True:
                error = 'Errors in form, please review and fix issues.'
            else:
                confirm = True
        elif 'confirm' in request.form:
            for path_item in path_list_tmp:
                sql = ''' INSERT INTO paper_path(step,submission_date,journal,peer_review,url_param_id)
                    VALUES(%s,%s,%s,%s,%s) '''
                cur = db.cursor()
                if path_item["submit_date"] != '':
                    cur.execute(
                        sql, (path_item["step"], path_item["submit_date"],
                              path_item["journal"], path_item["peer_review"],
                              path_item["url_param_id"]))
                else:
                    sql = ''' INSERT INTO paper_path(step,journal,peer_review,url_param_id)
                    VALUES(%s,%s,%s,%s) '''
                    cur.execute(
                        sql,
                        (path_item["step"], path_item["journal"],
                         path_item["peer_review"], path_item["url_param_id"]))
                db.commit()
                cur.close()
            sql = ''' UPDATE email_url
                SET completed_timestamp = %s
                WHERE url_param_id = %s '''
            cur = db.cursor()
            cur.execute(sql, (datetime.now(), url_id))
            db.commit()
            cur.close()
            db.close()
            return redirect(url_for('thanks.thanks', thanks_type='submission'))

        if error != None:
            flash(error)

        session["path_list"] = path_list_tmp
    elif allow_enter == False:
        cur = db.cursor()
        cur.execute('SELECT * FROM paper_path WHERE url_param_id = %s',
                    (url_id, ))
        path_list_entered = cur.fetchall()
        cur.close()
        path_list_tmp = []
        for path_list_item in path_list_entered:
            path_list_tmp.append(
                paper_path(idx=(path_list_item['step'] - 1),
                           url_param_id=url_id,
                           step=path_list_item['step'],
                           journal=path_list_item['journal'],
                           submit_date=path_list_item['submission_date'],
                           error='',
                           show_error=False).__dict__)

    db.close()
    return render_template('enter.html',
                           email_url=email_url,
                           journal_opts=journal_opts,
                           article_info=article_info,
                           author_doi=auth_aff_list,
                           affiliation_list=affiliation_list,
                           confirm=confirm,
                           allow_enter=allow_enter,
                           completed_paths=completed_paths,
                           has_completed=(len(completed_paths) > 0))