import { set, get, omit, pick, isEqual, isEmpty, debounce, isBoolean, } from 'lodash' import { handleError } from 'pubsweet-component-faraday-ui' import { autosaveRequest, autosaveSuccess, autosaveFailure, } from '../redux/autosave' import { SubmissionStatement } from './' export const setInitialValues = ({ fragment }) => ({ initialValues: { files: get(fragment, 'files', {}), authors: get(fragment, 'authors', []), metadata: get(fragment, 'metadata', {}), conflicts: get(fragment, 'conflicts', { hasConflicts: 'no', hasDataAvailability: '', hasFunding: '', }), declarations: get(fragment, 'declarations', { agree: false }), }, }) export const validate = values => { 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.' } return errors } const _onChange = ( values, dispatch, { collection, fragment, updateFragment }, ) => { const previousValues = pick(fragment, [ 'files', 'authors', 'metadata', 'conflicts', 'declarations', ]) const newValues = omit(values, ['agree', 'authorForm']) if (!isEqual(newValues, previousValues)) { dispatch(autosaveRequest()) updateFragment(collection, { ...fragment, ...newValues, }).then( () => dispatch(autosaveSuccess()), () => dispatch(autosaveFailure()), ) } } export const onChange = debounce(_onChange, 1000, { maxWait: 5000 }) export const onSubmit = ( values, dispatch, { step, history, nextStep, showModal, hideModal, isEditMode, setModalError, submitManuscript, fragment: { id: fragmentId }, collection: { id: collectionId, customId }, }, ) => { if (step !== 2) { nextStep() } else if (!isEditMode) { showModal({ title: 'By submitting the manuscript, you agree to the following statements:', content: SubmissionStatement, confirmText: 'AGREE & SUBMIT', cancelText: 'BACK TO SUBMISSION', onConfirm: () => { dispatch(autosaveRequest()) submitManuscript({ collectionId, fragmentId }) .then(r => { hideModal() dispatch(autosaveSuccess()) history.push('/confirmation-page', { customId, fragment: fragmentId, collection: collectionId, }) }) .catch(err => { hideModal() handleError(setModalError)(err) }) }, onCancel: hideModal, }) } else { history.goBack() } }