Newer
Older
import { SubmissionError } from 'redux-form'
import {
set,
get,
omit,
pick,
isEqual,
isEmpty,
debounce,
isBoolean,
} from 'lodash'
export const setInitialValues = ({ version }) => ({
initialValues: {
files: get(version, 'files', {}),
authors: get(version, 'authors', []),
metadata: get(version, 'metadata', {}),
conflicts: get(version, 'conflicts', { hasConflicts: 'no' }),
declarations: get(version, 'declarations', { agree: false }),
},
})
export const validate = (values, props) => {
const errors = {}
if (!get(values, 'declarations.agree')) {
set(errors, 'declarations.agree', 'Required')
}
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.'
}
if (isEmpty(get(values, 'files.coverLetter', []))) {
errors.files = 'Cover letter file is required.'
}
return errors
}
const _onChange = (
values,
dispatch,
{ project, version, autosaveRequest, updateFragment },
) => {
const previousValues = pick(version, [
'files',
'authors',
'metadata',
'conflicts',
'declarations',
])
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 {
showModal({
title:
'By submitting the manuscript you agree to the following statements:',
confirmText: 'AGREE & SUBMIT',
cancelText: 'BACK TO SUBMISSION',
onConfirm: () =>
submitManuscript(collectionId, fragmentId)
.then(r => {
history.push('/confirmation-page', {
customId,
version: fragmentId,
project: collectionId,
})
})
.catch(err => {
if (err.validationErrors) {
throw new SubmissionError()
}
}),
onCancel: hideModal,
})