import { get, head } from 'lodash' import { create, get as apiGet, remove, update, } from 'pubsweet-client/src/helpers/api' // constants const REQUEST = 'authors/REQUEST' const FAILURE = 'authors/FAILURE' const SUCCESS = 'authors/SUCCESS' // actions export const authorRequest = () => ({ type: REQUEST, }) export const authorFailure = error => ({ type: FAILURE, error, }) export const authorSuccess = () => ({ type: SUCCESS, }) export const addAuthor = (author, collectionId) => dispatch => { dispatch(authorRequest()) return create(`/collections/${collectionId}/users`, { email: author.email, role: 'author', ...author, }) } export const deleteAuthor = (collectionId, userId) => dispatch => { dispatch(authorRequest()) return remove(`/collections/${collectionId}/users/${userId}`) } export const editAuthor = (collectionId, userId, body) => update(`/collections/${collectionId}/users/${userId}`, body) export const getAuthors = collectionId => apiGet(`/collections/${collectionId}/users`) 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}`) || [] export const getAuthorFetching = state => state.authors.isFetching export const getAuthorError = state => state.authors.error const initialState = { isFetching: false, error: null } export default (state = initialState, action) => { switch (action.type) { case 'UPDATE_FRAGMENT_REQUEST': case REQUEST: return { ...initialState, isFetching: true, } case 'UPDATE_FRAGMENT_FAILURE': case FAILURE: return { ...initialState, error: get(JSON.parse(get(action.error, 'response') || {}), 'error'), isFetching: false, } case 'UPDATE_FRAGMENT_SUCCESS': case SUCCESS: return initialState default: return state } }