Skip to content
Snippets Groups Projects
utils.js 1.67 KiB
Newer Older
import { SubmissionError } from 'redux-form'
import { get, isBoolean, isEmpty, debounce, isEqual, pick, omit } from 'lodash'

export const validate = (values, props) => {
  const errors = {}

  if (isEmpty(get(values, 'authors', []))) {
    errors.authors = 'Authors are required.'
  }

  if (!isBoolean(values.authorForm) && values.authorForm > -1) {
    errors.authors = 'You have an unsaved author.'
  }

  if (isBoolean(values.authorForm) && values.authorForm) {
    errors.authors = 'Finish or cancel adding a new author.'
  }

  if (isEmpty(get(values, 'files.manuscripts', []))) {
    errors.files = 'At least one manuscript file is required.'
  }

  return errors
}

const _onChange = (
  values,
  dispatch,
  { project, version, autosaveRequest, updateFragment },
) => {
  const previousValues = pick(version, ['metadata', 'authors', 'files'])
  const newValues = omit(values, ['agree', 'authorForm'])
  if (!isEqual(newValues, previousValues)) {
    autosaveRequest()
    updateFragment(project, {
      ...version,
      ...newValues,
    })
  }
}

export const onChange = debounce(_onChange, 1000, { maxWait: 5000 })

export const onSubmit = (
  values,
  dispatch,
  {
    step,
    history,
    nextStep,
    submitManuscript,
    version: { id: fragmentId },
    project: { id: collectionId, customId },
  },
) => {
  if (step !== 2) {
    nextStep()
  } else {
    submitManuscript(collectionId, fragmentId)
      .then(r => {
        history.push('/confirmation-page', {
          customId,
          version: fragmentId,
          project: collectionId,
        })
      })
      .catch(err => {
        if (err.validationErrors) {
          throw new SubmissionError()
        }
      })
  }
}