From b8cc767d91c734ad372ecdfe674606d7fe37b572 Mon Sep 17 00:00:00 2001
From: Mihail Hagiu <mihail.hagiu@thinslices.com>
Date: Wed, 24 Oct 2018 17:54:27 +0300
Subject: [PATCH] fix(ReviewerEditorialComments): Fixed versions, correct fetch
 for fragments

---
 .../component-faraday-selectors/src/index.js  | 32 +++++++++++++++----
 .../manuscriptDetails/ManuscriptDetailsTop.js |  2 ++
 .../manuscriptDetails/ManuscriptVersion.js    | 23 +++----------
 .../src/services/Fragment.js                  |  7 ++--
 .../src/routes/fragments/patch.js             |  5 +--
 .../src/components/ManuscriptLayout.js        |  3 ++
 .../src/components/ManuscriptPage.js          |  2 ++
 .../withHandleRecommendation.js               |  2 +-
 .../xpub-faraday/config/authsome-helpers.js   | 12 +++++--
 packages/xpub-faraday/config/authsome-mode.js | 12 +++++++
 10 files changed, 61 insertions(+), 39 deletions(-)

diff --git a/packages/component-faraday-selectors/src/index.js b/packages/component-faraday-selectors/src/index.js
index 67590e4c1..034488170 100644
--- a/packages/component-faraday-selectors/src/index.js
+++ b/packages/component-faraday-selectors/src/index.js
@@ -115,11 +115,9 @@ export const canEICViewEditorialComments = (state, collection = {}) => {
 }
 
 const canReviewerViewEditorialCommentsStatuses = [
-  'rejected',
-  'accepted',
-  'inQA',
   'underReview',
   'reviewCompleted',
+  'pendingApproval',
   'revisionRequested',
 ]
 export const canReviewerViewEditorialComments = (
@@ -127,14 +125,15 @@ export const canReviewerViewEditorialComments = (
   collection = {},
   fragment = {},
 ) => {
+  const status = get(collection, 'status', 'draft')
   const isReviewer = currentUserIsReviewer(state, get(fragment, 'id', ''))
+  const hasDecision = ['rejected', 'accepted', 'inQA'].includes(status)
   const hasRevision = get(fragment, 'revision', false)
-  const hasRecommendation = get(fragment, 'recommendations', false)
-  const status = get(collection, 'status', 'draft')
   return (
     isReviewer &&
-    (hasRevision || hasRecommendation) &&
-    canReviewerViewEditorialCommentsStatuses.includes(status)
+    (hasDecision ||
+      (hasRevision &&
+        canReviewerViewEditorialCommentsStatuses.includes(status)))
   )
 }
 const cannotAuthorViewEditorialCommentsStatuses = [
@@ -430,3 +429,22 @@ export const canSubmitRevision = (state, fragment = {}) => {
   return get(fragment, 'revision', null) && fragmentAuthors.includes(userId)
 }
 // #endregion
+
+export const getVersionOptions = (state, collection = {}) => {
+  const fragments = get(state, 'fragments', {})
+
+  return chain(collection)
+    .get('fragments', [])
+    .reduce(
+      (acc, el) => [
+        ...acc,
+        {
+          value: el,
+          label: `Version ${get(fragments, `${el}.version`)}`,
+        },
+      ],
+      [],
+    )
+    .reverse()
+    .value()
+}
diff --git a/packages/component-faraday-ui/src/manuscriptDetails/ManuscriptDetailsTop.js b/packages/component-faraday-ui/src/manuscriptDetails/ManuscriptDetailsTop.js
index 2564bf721..6a4c5dfb3 100644
--- a/packages/component-faraday-ui/src/manuscriptDetails/ManuscriptDetailsTop.js
+++ b/packages/component-faraday-ui/src/manuscriptDetails/ManuscriptDetailsTop.js
@@ -16,6 +16,7 @@ import {
 
 const ManuscriptDetailsTop = ({
   history,
+  versions,
   goToEdit,
   getSignedUrl,
   goToTechnicalCheck,
@@ -78,6 +79,7 @@ const ManuscriptDetailsTop = ({
         collection={collection}
         fragment={fragment}
         history={history}
+        versions={versions}
       />
     </Item>
   </Row>
diff --git a/packages/component-faraday-ui/src/manuscriptDetails/ManuscriptVersion.js b/packages/component-faraday-ui/src/manuscriptDetails/ManuscriptVersion.js
index 765541622..2f7473750 100644
--- a/packages/component-faraday-ui/src/manuscriptDetails/ManuscriptVersion.js
+++ b/packages/component-faraday-ui/src/manuscriptDetails/ManuscriptVersion.js
@@ -1,38 +1,23 @@
 import React from 'react'
 import { get } from 'lodash'
 import { Menu } from '@pubsweet/ui'
-import { compose, withHandlers, withProps } from 'recompose'
 
 const ManuscriptVersion = ({
   history,
-  fragments,
+  versions,
   fragment = {},
   collection = {},
-  parseVersionOptions,
 }) =>
-  !!fragments.length && (
+  versions.length > 0 && (
     <Menu
       inline
       onChange={v =>
         history.push(`/projects/${collection.id}/versions/${v}/details`)
       }
-      options={parseVersionOptions(fragments)}
+      options={versions}
       placeholder="Please select"
       value={get(fragment, 'id')}
     />
   )
 
-export default compose(
-  withProps(({ collection = {} }) => ({
-    fragments: get(collection, 'fragments', []),
-  })),
-  withHandlers({
-    parseVersionOptions: ({ fragments }) => () =>
-      fragments
-        .map((f, index) => ({
-          value: f,
-          label: `Version ${index + 1}`,
-        }))
-        .reverse(),
-  }),
-)(ManuscriptVersion)
+export default ManuscriptVersion
diff --git a/packages/component-helper-service/src/services/Fragment.js b/packages/component-helper-service/src/services/Fragment.js
index db1ae899e..174067efd 100644
--- a/packages/component-helper-service/src/services/Fragment.js
+++ b/packages/component-helper-service/src/services/Fragment.js
@@ -94,12 +94,9 @@ class Fragment {
     const { fragment: { invitations = [], recommendations = [] } } = this
     let filteredInvitations = isAccepted
       ? invitations.filter(
-          inv =>
-            inv.role === role &&
-            inv.hasAnswer === true &&
-            inv.isAccepted === true,
+          inv => inv.role === role && inv.hasAnswer && inv.isAccepted,
         )
-      : invitations.filter(inv => inv.role === role && inv.hasAnswer === false)
+      : invitations.filter(inv => inv.role === role && !inv.hasAnswer)
 
     if (type === 'submitted') {
       filteredInvitations = filteredInvitations.filter(inv =>
diff --git a/packages/component-manuscript-manager/src/routes/fragments/patch.js b/packages/component-manuscript-manager/src/routes/fragments/patch.js
index 09e3dbc8f..f28b8cc08 100644
--- a/packages/component-manuscript-manager/src/routes/fragments/patch.js
+++ b/packages/component-manuscript-manager/src/routes/fragments/patch.js
@@ -70,10 +70,7 @@ module.exports = models => async (req, res) => {
     fragment.save()
 
     if (heRecommendation.recommendation === 'major') {
-      const reviewerIds = newFragment.invitations.map(inv => {
-        const { userId } = inv
-        return userId
-      })
+      const reviewerIds = newFragment.invitations.map(inv => inv.userId)
 
       teamHelper.createTeam({
         role: 'reviewer',
diff --git a/packages/component-manuscript/src/components/ManuscriptLayout.js b/packages/component-manuscript/src/components/ManuscriptLayout.js
index 81d2be237..c3e868330 100644
--- a/packages/component-manuscript/src/components/ManuscriptLayout.js
+++ b/packages/component-manuscript/src/components/ManuscriptLayout.js
@@ -64,6 +64,7 @@ const ManuscriptLayout = ({
   inviteReviewer,
   recommendationHandler,
   inviteHandlingEditor,
+  versions,
 }) => (
   <Root pb={30}>
     {!isEmpty(collection) && !isEmpty(fragment) ? (
@@ -74,6 +75,7 @@ const ManuscriptLayout = ({
           fragment={fragment}
           getSignedUrl={getSignedUrl}
           history={history}
+          versions={versions}
         />
         <ManuscriptHeader
           collection={collection}
@@ -86,6 +88,7 @@ const ManuscriptLayout = ({
           journal={journal}
           resendInvitation={inviteHandlingEditor.assignHE}
           revokeInvitation={inviteHandlingEditor.revokeHE}
+          versions={versions}
         />
 
         <ManuscriptMetadata
diff --git a/packages/component-manuscript/src/components/ManuscriptPage.js b/packages/component-manuscript/src/components/ManuscriptPage.js
index b5cf99de5..0b77b64cd 100644
--- a/packages/component-manuscript/src/components/ManuscriptPage.js
+++ b/packages/component-manuscript/src/components/ManuscriptPage.js
@@ -54,6 +54,7 @@ import {
   canAuthorViewEditorialComments,
   getFragmentReviewerRecommendations,
   getInvitationsWithReviewersForFragment,
+  getVersionOptions,
 } from 'pubsweet-component-faraday-selectors'
 import {
   handleError,
@@ -205,6 +206,7 @@ export default compose(
         state,
         get(fragment, 'id', ''),
       ),
+      versions: getVersionOptions(state, collection),
     }),
   ),
   ConnectPage(({ currentUser }) => {
diff --git a/packages/component-manuscript/src/handleRecommendation/withHandleRecommendation.js b/packages/component-manuscript/src/handleRecommendation/withHandleRecommendation.js
index 020d7e45d..19fb97c4d 100644
--- a/packages/component-manuscript/src/handleRecommendation/withHandleRecommendation.js
+++ b/packages/component-manuscript/src/handleRecommendation/withHandleRecommendation.js
@@ -52,7 +52,7 @@ export default compose(
     },
   }),
   withProps(props => ({
-    recommendationHandle: {
+    recommendationHandler: {
       ...pick(props, ['createRecommendation', 'onEditorialRecommendation']),
     },
   })),
diff --git a/packages/xpub-faraday/config/authsome-helpers.js b/packages/xpub-faraday/config/authsome-helpers.js
index 1f885f1b2..c92571ecc 100644
--- a/packages/xpub-faraday/config/authsome-helpers.js
+++ b/packages/xpub-faraday/config/authsome-helpers.js
@@ -247,7 +247,10 @@ const getCollections = async ({ user, models }) => {
         })
       }
 
-      return { ...collection, visibleStatus }
+      return {
+        ...collection,
+        visibleStatus,
+      }
     }),
   )).filter(Boolean)
 }
@@ -259,7 +262,9 @@ async function updateReviewerVisibleStatusByInvitation({
 }) {
   const fragmentId = last(collection.fragments)
   const fragment = await FragmentModel.find(fragmentId)
-  const invitation = fragment.invitations.find(inv => inv.userId === user.id)
+  const invitation = get(fragment, 'invitations', []).find(
+    inv => inv.userId === user.id,
+  )
   const recommendationDone =
     fragment.recommendations &&
     fragment.recommendations.some(
@@ -273,7 +278,8 @@ async function updateReviewerVisibleStatusByInvitation({
     return get(statuses, `${collection.status}.reviewer.label`)
   }
 
-  return invitation.hasAnswer && invitation.isAccepted
+  return get(invitation, 'hasAnswer', false) &&
+    get(invitation, 'isAccepted', false)
     ? get(statuses, `underReview.reviewer.label`)
     : get(statuses, `reviewersInvited.reviewer.label`)
 }
diff --git a/packages/xpub-faraday/config/authsome-mode.js b/packages/xpub-faraday/config/authsome-mode.js
index 7b269f385..2bb207ebd 100644
--- a/packages/xpub-faraday/config/authsome-mode.js
+++ b/packages/xpub-faraday/config/authsome-mode.js
@@ -73,6 +73,12 @@ async function applyAuthenticatedUserPolicy(user, operation, object, context) {
             Team: context.models.Team,
           })
 
+          const fragmentPermissions = userPermissions
+            .filter(
+              up => up.objectType === 'fragment' && up.role === 'reviewer',
+            )
+            .map(up => up.objectId)
+
           // if (collection.owners.map(o => o.id).includes(user.id)) {
           //   return collection
           // }
@@ -98,6 +104,12 @@ async function applyAuthenticatedUserPolicy(user, operation, object, context) {
 
           return {
             ...collection,
+            fragments:
+              role !== 'reviewer'
+                ? collection.fragments
+                : collection.fragments.filter(fragId =>
+                    fragmentPermissions.includes(fragId),
+                  ),
             visibleStatus,
           }
         },
-- 
GitLab