Skip to content
Snippets Groups Projects
conversion.js 2.11 KiB
Newer Older
import { actions } from 'pubsweet-client'
import { create } from 'pubsweet-client/src/helpers/api'
export const CREATE_DRAFT_REQUEST = 'CREATE_DRAFT_REQUEST'
export const CREATE_DRAFT_SUCCESS = 'CREATE_DRAFT_SUCCESS'

/* action creators */
export const createDraftRequest = () => ({
  type: CREATE_DRAFT_REQUEST,
})

export const createDraftSuccess = draft => ({
  type: CREATE_DRAFT_SUCCESS,
  draft,
})

/* utils */
const generateCustomId = () =>
  moment
    .now()
    .toString()
    .slice(-7)

const addSubmittingAuthor = (user, collectionId) => {
  const author = {
    ...pick(user, ['affiliation', 'email', 'firstName', 'lastName']),
    isSubmitting: true,
    isCorresponding: true,
  }
  create(`/collections/${collectionId}/users`, {
    role: 'author',
    ...author,
  })
}

export const createDraftSubmission = history => (dispatch, getState) => {
  const currentUser = getState().currentUser.user
  return dispatch(
    actions.createCollection({ customId: generateCustomId() }),
  ).then(({ collection }) => {
    if (!collection.id) {
      throw new Error('Failed to create a project')
    }

    // TODO: rethrow errors so they can be caught here
    return dispatch(
      actions.createFragment(collection, {
        created: new Date(), // TODO: set on server
        files: {
          supplementary: [],
        },
        fragmentType: 'version',
        metadata: {},
        version: 1,
      }),
    ).then(({ fragment }) => {
      if (!fragment.id) {
        throw new Error('Failed to create a project')
      }
      const route = `/projects/${collection.id}/versions/${fragment.id}/submit`
      if (!currentUser.admin) {
        addSubmittingAuthor(currentUser, collection.id)
      }

      // redirect after a short delay
      window.setTimeout(() => {
        history.push(route)
const initialState = {
  complete: undefined,
  converting: false,
  error: undefined,
}

export default (state = initialState, action) => {
  switch (action.type) {
    default:
      return state
  }
}