Skip to content
Snippets Groups Projects
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
MyManuscripts.jsx 9.91 KiB
import React from 'react'
import { Query } from 'react-apollo'
import styled from 'styled-components'
import { H2 as HTwo, Link } from '@pubsweet/ui'
import { th } from '@pubsweet/ui-toolkit'
import { pageSize, states } from 'config'
import URLSearchParams from 'url-search-params'
import { createBrowserHistory } from 'history'
import { Loading, LoadingIcon, Notification, Toggle, Pagination } from '../ui'
import {
  USER_MANUSCRIPTS,
  MANUSCRIPTS_BY_STATUS,
  COUNT_MANUSCRIPTS,
} from './operations'
import DashboardList from './DashboardList'
import SearchBoxes from './SearchBoxes'

const H2 = styled(HTwo)`
  font-size: ${th('fontSizeHeading4')};
  line-height: ${th('lineHeightHeading4')};
`
const H3 = styled(HTwo)`
  font-size: ${th('fontSizeHeading3')};
  line-height: ${th('lineHeightHeading3')};
  margin-top: 0;
`
const ToggleBar = styled(Toggle)`
  float: left;
  @media screen and (max-width: 880px) {
    float: none;
  }
`
const PaginationPane = styled.div`
  display: flex;
  justify-content: flex-end;
`

const MyManuscripts = ({ currentUser, errors, history }) => (
  <Query fetchPolicy="cache-and-network" query={COUNT_MANUSCRIPTS}>
    {({ data, loading }) => {
      if (loading) {
        return (
          <Loading>
            <LoadingIcon />
          </Loading>
        )
      }
      if (!data) {
        createBrowserHistory({ forceRefresh: true }).push('/login')
        return null
      }
      // get the total number of manuscripts to decide whether the toggles are required
      const { countByStatus } = data
      const done = states.indexOf('xml-complete')
      const highlight = [
        'INITIAL',
        'READY',
        'submission-error',
        'in-review',
        'xml-review',
      ]
      const totalCount = countByStatus.reduce(
        (sum, status) => sum + parseInt(status.count, 10),
        0,
      )
      const totalAttention = countByStatus
        .filter(s => highlight.includes(s.type))
        .reduce((sum, status) => sum + parseInt(status.count, 10), 0)
      const totalComplete = countByStatus
        .filter(s => states.slice(done).includes(s.type))
        .reduce((sum, status) => sum + parseInt(status.count, 10), 0)
      const totalProcess = countByStatus
        .filter(s =>
          states
            .slice(done)
            .filter(s => !highlight.includes(s))
            .includes(s.type),
        )
        .reduce((sum, status) => sum + parseInt(status.count, 10), 0)
      const params = new URLSearchParams(history.location.search)
      const togglesRequired = totalCount > pageSize
      const query = togglesRequired ? MANUSCRIPTS_BY_STATUS : USER_MANUSCRIPTS
      const showStates = params.get('status')
      const variables = {}
      if (togglesRequired) {
        variables.page = params.get('page') ? params.get('page') - 1 : 0
        variables.pageSize = pageSize
        variables.query =
          (showStates === 'completed' && states.slice(done).join(',')) ||
          (showStates === 'processing' &&
            states
              .slice(done)
              .filter(s => !highlight.includes(s))
              .join(',')) ||
          highlight.join(',')
      }
      const searchTitle =
        (showStates === 'completed' && 'Submission complete') ||
        (showStates === 'processing' && 'In process at Europe PMC') ||
        'Needs attention'
      const onPageEntered = p => {
        history.push(
          `/dashboard?page=${p}${showStates ? `&status=${showStates}` : ''}`,
        )
      }
      return (
        <Query
          fetchPolicy="cache-and-network"
          query={query}
          variables={variables}
        >
          {({ data, loading, errors: dErrors }) => {
            if (loading) {
              return (
                <Loading>
                  <LoadingIcon />
                </Loading>
              )
            }
            if (dErrors) {
              return dErrors.map(e => (
                <Notification type="error">{e.message}</Notification>
              ))
            }
            const manuscripts = togglesRequired
              ? data.findByStatus.manuscripts
              : data.manuscripts
            const total = togglesRequired
              ? data.findByStatus.total
              : data.manuscripts.length

            const toggles = togglesRequired && (
              <React.Fragment>
                <ToggleBar>
                  <Link
                    className={!showStates ? 'current' : ''}
                    to="/dashboard"
                  >
                    Attention {showStates && `(${totalAttention})`}
                  </Link>
                  <Link
                    className={showStates === 'processing' ? 'current' : ''}
                    to="/dashboard?status=processing"
                  >
                    In process{' '}
                    {showStates !== 'processing' && `(${totalProcess})`}
                  </Link>
                  <Link
                    className={
                      showStates === 'completed' ? `current (${total})` : ''
                    }
                    to="/dashboard?status=completed"
                  >
                    Completed{' '}
                    {showStates !== 'completed' && `(${totalComplete})`}
                  </Link>
                </ToggleBar>
                <SearchBoxes reviewer />
              </React.Fragment>
            )

            if (togglesRequired) {
              const currentPage = params.get('page')
                ? parseInt(params.get('page'), 10)
                : 1

              const PageNavigation = () => (
                <Pagination
                  currentPage={currentPage}
                  onPageEntered={onPageEntered}
                  pageSize={pageSize}
                  totalSize={total}
                />
              )
              return (
                <React.Fragment>
                  {toggles}
                  <PaginationPane
                    style={{
                      justifyContent: 'space-between',
                      alignItems: 'baseline',
                    }}
                  >
                    <H3>
                      {searchTitle} ({total})
                    </H3>
                    {total > 0 && <PageNavigation />}
                  </PaginationPane>
                  <DashboardList
                    currentUser={currentUser}
                    listData={manuscripts}
                  />
                  {total > 0 && (
                    <PaginationPane>
                      <PageNavigation />
                    </PaginationPane>
                  )}
                </React.Fragment>
              )
            }

            const attention = []
            const warning = []
            const processing = []
            const complete = []
            manuscripts.forEach(m => {
              const reviewer = m.teams.find(t => t.role === 'reviewer')
              const submitter = m.teams.find(t => t.role === 'submitter')
              if (highlight.includes(m.status)) {
                if (
                  reviewer &&
                  reviewer.teamMembers[0].user.id === currentUser.id &&
                  highlight.slice(-2).includes(m.status)
                ) {
                  attention.push(m)
                } else if (
                  submitter.teamMembers[0].user.id === currentUser.id &&
                  highlight.slice(0, 3).includes(m.status)
                ) {
                  attention.push(m)
                } else {
                  warning.push(m)
                }
              } else if (
                !togglesRequired &&
                states.slice(done).includes(m.status)
              ) {
                complete.push(m)
              } else {
                processing.push(m)
              }
            })
            return (
              <React.Fragment>
                {toggles}
                {manuscripts.length === 0 && (
                  <Notification type="info">
                    There are currently no manuscripts connected to this
                    account.
                  </Notification>
                )}
                {errors.map(e => (
                  <Notification
                    key="message"
                    type={e.type ? e.type : 'warning'}
                  >
                    {e.message}
                  </Notification>
                ))}
                {attention.length > 0 && (
                  <React.Fragment>
                    <H2>Needs my attention ({attention.length})</H2>
                    <DashboardList
                      currentUser={currentUser}
                      listData={attention}
                      sectionColor="error"
                    />
                  </React.Fragment>
                )}
                {warning.length > 0 && (
                  <React.Fragment>
                    <H2>
                      Waiting for action by another user ({warning.length})
                    </H2>
                    <DashboardList
                      currentUser={currentUser}
                      listData={warning}
                      sectionColor="warning"
                    />
                  </React.Fragment>
                )}
                {processing.length > 0 && (
                  <React.Fragment>
                    <H2>In process at Europe PMC ({processing.length})</H2>
                    <DashboardList
                      currentUser={currentUser}
                      listData={processing}
                    />
                  </React.Fragment>
                )}
                {complete.length > 0 && (
                  <React.Fragment>
                    <H2>Submission complete ({complete.length})</H2>
                    <DashboardList
                      currentUser={currentUser}
                      listData={complete}
                    />
                  </React.Fragment>
                )}
              </React.Fragment>
            )
          }}
        </Query>
      )
    }}
  </Query>
)

export default MyManuscripts