From d73b4bf3317cb42d3efce50771428b01fbe7c1bb Mon Sep 17 00:00:00 2001
From: Alexandru Munteanu <alexandru.munt@gmail.com>
Date: Thu, 14 Jun 2018 15:17:17 +0300
Subject: [PATCH] fix(submition-wizard): more fixes on author lists

---
 .../src/components/WizardFormStep.js          | 10 ++--
 .../src/components/WizardStep.js              |  4 +-
 .../component-wizard/src/redux/conversion.js  |  9 ++--
 .../src/components/AuthorList/Author.js       |  1 +
 .../src/components/AuthorList/AuthorAdder.js  |  4 +-
 .../src/components/AuthorList/AuthorList.js   | 53 ++++++++-----------
 .../components-faraday/src/redux/authors.js   | 12 +----
 .../components-faraday/src/redux/utils.js     |  6 ++-
 .../app/config/journal/submit-wizard.js       |  8 +--
 .../app/config/journal/wizard-validators.js   |  2 +-
 packages/xpub-faraday/config/validations.js   |  1 +
 11 files changed, 50 insertions(+), 60 deletions(-)

diff --git a/packages/component-wizard/src/components/WizardFormStep.js b/packages/component-wizard/src/components/WizardFormStep.js
index f28662bbe..e87290a13 100644
--- a/packages/component-wizard/src/components/WizardFormStep.js
+++ b/packages/component-wizard/src/components/WizardFormStep.js
@@ -1,8 +1,8 @@
 import PropTypes from 'prop-types'
 import { connect } from 'react-redux'
-import { debounce, pick, get, isEqual } from 'lodash'
 import { actions } from 'pubsweet-client'
-import { compose, getContext, withProps } from 'recompose'
+import { debounce, pick, get, isEqual } from 'lodash'
+import { compose, getContext, withProps, setDisplayName } from 'recompose'
 import { reduxForm, formValueSelector, SubmissionError } from 'redux-form'
 
 import WizardStep from './WizardStep'
@@ -14,9 +14,8 @@ const onChange = (
   values,
   dispatch,
   { project, version, wizard: { formSectionKeys }, setLoader },
-  prevValues,
 ) => {
-  const prev = pick(prevValues, formSectionKeys)
+  const prev = pick(version, formSectionKeys)
   const newValues = pick(values, formSectionKeys)
   // TODO: fix this if it sucks down the road
   if (!isEqual(prev, newValues)) {
@@ -100,6 +99,7 @@ const onSubmit = (
 }
 
 export default compose(
+  setDisplayName('SubmitWizard'),
   getContext({
     history: PropTypes.object,
     isFinal: PropTypes.bool,
@@ -112,8 +112,8 @@ export default compose(
     toggleConfirmation: PropTypes.func,
   }),
   withProps(({ version, wizard }) => ({
-    initialValues: pick(version, wizard.formSectionKeys),
     readonly: !!get(version, 'submitted'),
+    initialValues: pick(version, wizard.formSectionKeys),
   })),
   connect((state, { wizard: { formSectionKeys } }) => ({
     formValues: wizardSelector(state, ...formSectionKeys),
diff --git a/packages/component-wizard/src/components/WizardStep.js b/packages/component-wizard/src/components/WizardStep.js
index 6846bee3f..1f8a35281 100644
--- a/packages/component-wizard/src/components/WizardStep.js
+++ b/packages/component-wizard/src/components/WizardStep.js
@@ -39,7 +39,6 @@ export default ({
             validate,
             dependsOn,
             renderComponent: Comp,
-            format,
             parse,
             ...rest
           }) => {
@@ -54,10 +53,9 @@ export default ({
                 <ValidatedField
                   component={input => (
                     <div data-test={fieldId}>
-                      <Comp {...rest} {...input} {...dispatchFns} />{' '}
+                      <Comp {...rest} {...input} {...dispatchFns} />
                     </div>
                   )}
-                  format={format}
                   name={fieldId}
                   parse={parse}
                   validate={validate}
diff --git a/packages/component-wizard/src/redux/conversion.js b/packages/component-wizard/src/redux/conversion.js
index a4043ca5d..6a7a58d26 100644
--- a/packages/component-wizard/src/redux/conversion.js
+++ b/packages/component-wizard/src/redux/conversion.js
@@ -24,13 +24,13 @@ const generateCustomId = () =>
     .toString()
     .slice(-7)
 
-const addSubmittingAuthor = (user, collectionId) => {
+const addSubmittingAuthor = (user, collectionId, fragmentId) => {
   const author = {
-    ...pick(user, ['affiliation', 'email', 'firstName', 'lastName']),
+    ...pick(user, ['id', 'email', 'affiliation', 'firstName', 'lastName']),
     isSubmitting: true,
     isCorresponding: true,
   }
-  create(`/collections/${collectionId}/users`, {
+  create(`/collections/${collectionId}/fragments/${fragmentId}/users`, {
     role: 'author',
     ...author,
   })
@@ -50,6 +50,7 @@ export const createDraftSubmission = history => (dispatch, getState) => {
     return dispatch(
       actions.createFragment(collection, {
         created: new Date(), // TODO: set on server
+        collectionId: collection.id,
         files: {
           supplementary: [],
         },
@@ -63,7 +64,7 @@ export const createDraftSubmission = history => (dispatch, getState) => {
       }
       const route = `/projects/${collection.id}/versions/${fragment.id}/submit`
       if (!currentUser.admin) {
-        addSubmittingAuthor(currentUser, collection.id)
+        addSubmittingAuthor(currentUser, collection.id, fragment.id)
       }
 
       // redirect after a short delay
diff --git a/packages/components-faraday/src/components/AuthorList/Author.js b/packages/components-faraday/src/components/AuthorList/Author.js
index 8bfdf0ac9..d993d10b1 100644
--- a/packages/components-faraday/src/components/AuthorList/Author.js
+++ b/packages/components-faraday/src/components/AuthorList/Author.js
@@ -19,6 +19,7 @@ export default ({
   setAuthorEdit,
   isCorresponding,
   parseAuthorType,
+  ...rest
 }) => (
   <Root isOver={isOver}>
     {!isOver && dragHandle}
diff --git a/packages/components-faraday/src/components/AuthorList/AuthorAdder.js b/packages/components-faraday/src/components/AuthorList/AuthorAdder.js
index 86b022531..8ebff1e86 100644
--- a/packages/components-faraday/src/components/AuthorList/AuthorAdder.js
+++ b/packages/components-faraday/src/components/AuthorList/AuthorAdder.js
@@ -4,8 +4,8 @@ import { connect } from 'react-redux'
 import { reduxForm } from 'redux-form'
 import styled from 'styled-components'
 import { Button, th } from '@pubsweet/ui'
-import { compose, withProps } from 'recompose'
 import { selectCurrentUser } from 'xpub-selectors'
+import { compose, withProps, setDisplayName } from 'recompose'
 
 import { emailValidator } from '../utils'
 import { Spinner } from '../UIComponents/'
@@ -100,6 +100,7 @@ export default compose(
   reduxForm({
     form: 'author',
     enableReinitialize: true,
+    destroyOnUnmount: false,
     onSubmit: (
       values,
       dispatch,
@@ -124,6 +125,7 @@ export default compose(
       })
     },
   }),
+  setDisplayName('AuthorAdder'),
 )(AuthorAdder)
 
 // #region styled-components
diff --git a/packages/components-faraday/src/components/AuthorList/AuthorList.js b/packages/components-faraday/src/components/AuthorList/AuthorList.js
index a67dbc403..fde894862 100644
--- a/packages/components-faraday/src/components/AuthorList/AuthorList.js
+++ b/packages/components-faraday/src/components/AuthorList/AuthorList.js
@@ -1,5 +1,5 @@
 import React from 'react'
-import { get } from 'lodash'
+import { get, isBoolean, isNumber } from 'lodash'
 import { th } from '@pubsweet/ui'
 import PropTypes from 'prop-types'
 import { connect } from 'react-redux'
@@ -11,8 +11,9 @@ import {
   withProps,
   getContext,
   withHandlers,
+  setDisplayName,
 } from 'recompose'
-import { change as changeForm } from 'redux-form'
+import { change as changeForm, formValueSelector } from 'redux-form'
 import { SortableList } from 'pubsweet-component-sortable-list/src/components'
 
 import {
@@ -25,11 +26,14 @@ import {
 import { DragHandle } from './FormItems'
 import { Author, StaticList, AuthorAdder, AuthorEditor, utils } from './'
 
+const wizardSelector = formValueSelector('wizard')
+
 const Authors = ({
   match,
   error,
   authors,
   version,
+  addMode,
   editMode,
   dropItem,
   addAuthor,
@@ -45,16 +49,16 @@ const Authors = ({
       addAuthor={addAuthor}
       authors={authors}
       editAuthor={editAuthor}
-      editMode={editMode}
+      editMode={addMode}
       match={match}
       setEditMode={setEditMode}
       setFormAuthors={setFormAuthors}
     />
-    {editedAuthor > -1 ? (
+    {isNumber(editMode) && editMode > -1 ? (
       <StaticList
         authors={authors}
         editComponent={AuthorEditor}
-        editIndex={editedAuthor}
+        editIndex={editMode}
         setFormAuthors={setFormAuthors}
         version={version}
         {...rest}
@@ -63,8 +67,7 @@ const Authors = ({
       <SortableList
         beginDragProps={['index', 'lastName']}
         dragHandle={DragHandle}
-        dropItem={dropItem}
-        editedAuthor={editedAuthor}
+        editedAuthor={editMode}
         items={authors || []}
         listItem={Author}
         moveItem={moveAuthor}
@@ -80,8 +83,9 @@ export default compose(
   getContext({ version: PropTypes.object, project: PropTypes.object }),
   connect(
     state => ({
-      currentUser: state.currentUser.user,
       error: getAuthorError(state),
+      currentUser: get(state, 'currentUser.user'),
+      authorForm: wizardSelector(state, 'authorForm'),
     }),
     {
       addAuthor,
@@ -91,11 +95,11 @@ export default compose(
     },
   ),
   withState('authors', 'setAuthors', []),
-  withProps(({ version }) => ({
+  withProps(({ version, authorForm }) => ({
     authors: get(version, 'authors') || [],
+    addMode: isBoolean(authorForm) && authorForm,
+    editMode: isNumber(authorForm) ? authorForm : -1,
   })),
-  withState('editMode', 'setEditMode', false),
-  withState('editedAuthor', 'setEditedAuthor', -1),
   withHandlers({
     setFormAuthors: ({ setAuthors, changeForm }) => (authors = []) => {
       const mappedAuthors = authors
@@ -106,36 +110,22 @@ export default compose(
     },
   }),
   withHandlers({
-    setAuthorEdit: ({ setEditedAuthor, changeForm }) => editedAuthor => e => {
+    setAuthorEdit: ({ changeForm }) => authorIndex => e => {
       e && e.preventDefault && e.preventDefault()
-      changeForm('wizard', 'editMode', editedAuthor > -1)
-      setEditedAuthor(prev => editedAuthor)
+      changeForm('wizard', 'authorForm', authorIndex)
     },
-    setEditMode: ({ setEditMode, changeForm }) => mode => e => {
+    setEditMode: ({ changeForm }) => mode => e => {
       e && e.preventDefault()
-      changeForm('wizard', 'editMode', mode)
-      setEditMode(v => mode)
-    },
-    dropItem: ({
-      authors,
-      setFormAuthors,
-      project,
-      version,
-      authorFailure,
-    }) => () => {
-      setFormAuthors(authors)
+      changeForm('wizard', 'authorForm', mode)
     },
     parseAuthorType: () => (isSubmitting, isCorresponding, index) => {
       if (isSubmitting) return `#${index + 1} Submitting author`
       if (isCorresponding) return `#${index + 1} Corresponding author`
       return `#${index + 1} Author`
     },
-    moveAuthor: ({ authors, setAuthors, changeForm }) => (
-      dragIndex,
-      hoverIndex,
-    ) => {
+    moveAuthor: ({ authors, setFormAuthors }) => (dragIndex, hoverIndex) => {
       const newAuthors = SortableList.moveItem(authors, dragIndex, hoverIndex)
-      setAuthors(newAuthors)
+      setFormAuthors(newAuthors)
     },
     removeAuthor: ({
       authors,
@@ -154,6 +144,7 @@ export default compose(
       setFormAuthors(newAuthors)
     },
   }),
+  setDisplayName('AuthorList'),
 )(Authors)
 
 // #region styled-components
diff --git a/packages/components-faraday/src/redux/authors.js b/packages/components-faraday/src/redux/authors.js
index 0df800986..34bfe9ce0 100644
--- a/packages/components-faraday/src/redux/authors.js
+++ b/packages/components-faraday/src/redux/authors.js
@@ -1,9 +1,9 @@
-import { get, head } from 'lodash'
+import { get } from 'lodash'
 import {
   create,
-  get as apiGet,
   remove,
   update,
+  get as apiGet,
 } from 'pubsweet-client/src/helpers/api'
 import { handleError } from './utils'
 
@@ -72,14 +72,6 @@ export const deleteAuthor = (collectionId, fragmentId, userId) => dispatch => {
   ).catch(handleError(authorFailure, dispatch))
 }
 
-export const getAuthorsTeam = collectionId =>
-  apiGet(`/teams?object.id=${collectionId}&group=author`).then(teams =>
-    head(teams),
-  )
-
-export const updateAuthorsTeam = (teamId, body) =>
-  update(`/teams/${teamId}`, body)
-
 // selectors
 export const getFragmentAuthors = (state, fragmentId) =>
   get(state, `authors.${fragmentId}`) || []
diff --git a/packages/components-faraday/src/redux/utils.js b/packages/components-faraday/src/redux/utils.js
index 9b69520a3..a84e7328c 100644
--- a/packages/components-faraday/src/redux/utils.js
+++ b/packages/components-faraday/src/redux/utils.js
@@ -11,6 +11,10 @@ export const orderReviewers = r => {
 }
 
 export const handleError = (fn, dispatch = null) => err => {
-  typeof dispatch === 'function' ? dispatch(fn(err)) : fn(err)
+  if (typeof dispatch === 'function') {
+    dispatch(fn(err))
+  } else {
+    fn(err)
+  }
   throw err
 }
diff --git a/packages/xpub-faraday/app/config/journal/submit-wizard.js b/packages/xpub-faraday/app/config/journal/submit-wizard.js
index 23013b340..234a7102d 100644
--- a/packages/xpub-faraday/app/config/journal/submit-wizard.js
+++ b/packages/xpub-faraday/app/config/journal/submit-wizard.js
@@ -10,10 +10,10 @@ import { declarations } from './'
 import issueTypes from './issues-types'
 import manuscriptTypes from './manuscript-types'
 import {
-  requiredBasedOnType,
-  editModeEnabled,
-  parseEmptyHtml,
   requiredFiles,
+  parseEmptyHtml,
+  editModeEnabled,
+  requiredBasedOnType,
 } from './wizard-validators'
 
 const min3Chars = minChars(3)
@@ -153,7 +153,7 @@ export default {
           validate: [required],
         },
         {
-          fieldId: 'editMode',
+          fieldId: 'authorForm',
           renderComponent: Spacing,
           validate: [editModeEnabled],
         },
diff --git a/packages/xpub-faraday/app/config/journal/wizard-validators.js b/packages/xpub-faraday/app/config/journal/wizard-validators.js
index bec3371d1..25d58d437 100644
--- a/packages/xpub-faraday/app/config/journal/wizard-validators.js
+++ b/packages/xpub-faraday/app/config/journal/wizard-validators.js
@@ -23,7 +23,7 @@ export const requiredBasedOnType = (value, formValues) => {
   return undefined
 }
 
-export const editModeEnabled = value => {
+export const editModeEnabled = (value, allValues) => {
   if (value) {
     return 'You have some unsaved author details.'
   }
diff --git a/packages/xpub-faraday/config/validations.js b/packages/xpub-faraday/config/validations.js
index a91cd4977..2b2c1062d 100644
--- a/packages/xpub-faraday/config/validations.js
+++ b/packages/xpub-faraday/config/validations.js
@@ -16,6 +16,7 @@ module.exports = {
   fragment: [
     {
       fragmentType: Joi.valid('version').required(),
+      collectionId: Joi.string().required(),
       created: Joi.date(),
       version: Joi.number(),
       submitted: Joi.date(),
-- 
GitLab