Skip to content
Snippets Groups Projects
utils.js 2.75 KiB
Newer Older
import { pick, omit, isBoolean, replace } from 'lodash'
import { handleError } from 'pubsweet-component-faraday-ui'
import { update, create } from 'pubsweet-client/src/helpers/api'

const generatePasswordHash = () =>
  Array.from({ length: 4 }, () =>
    Math.random()
      .toString(36)
      .slice(4),
  ).join('')

export const setAdmin = values => {
  const newValues = { ...values, isActive: true }
  if (newValues.roles && newValues.roles.includes('admin')) {
    newValues.admin = true
  } else {
    newValues.admin = false
  }

  return {
    ...omit(newValues, ['role']),
    isConfirmed: false,
    password: 'defaultpass',
    editorInChief: newValues.role === 'editorInChief',
    handlingEditor: newValues.role === 'handlingEditor',
    notifications: {
      email: {
        system: true,
        user: true,
      },
    },
    accessTokens: {
      passwordReset: generatePasswordHash(),
      unsubscribe: generatePasswordHash(),
    },
}

export const parseUpdateUser = values => {
  const parsedValues = {
    ...values,
    editorInChief: values.editorInChief || false,
    handlingEditor: values.handlingEditor || false,
    admin: values.admin || false,
  }
  const valuesToSave = [
    'admin',
    'firstName',
    'lastName',
    'affiliation',
    'title',
    'roles',
    'handlingEditor',
    'isActive',
    'username',
    'accessTokens',
  return pick(parsedValues, valuesToSave)
const toggleUserStatus = user => {
  const { isActive, username } = user
  let newState = true
  let newUsername = ''

  if (!isBoolean(isActive) || isActive) {
    newState = false
    newUsername = `invalid***${username}`
  } else {
    newUsername = replace(username, 'invalid***', '')
  }

  return {
    ...user,
    isActive: newState,
    username: newUsername,
  }
}

export const updateUserStatus = user => {
  const updatedUser = toggleUserStatus(user)
  return update(`/users/${user.id}`, parseUpdateUser(updatedUser))
}

export const onSubmit = (
  values,
  dispatch,
  { edit, setFetching, getUsers, hideModal, setModalError },
) => {
  setFetching(true)
  if (!edit) {
    const newValues = setAdmin(values)
    return create('/users', newValues)
      .then(r => {
        create(`/emails`, {
          email: r.email,
          type: 'invite',
          role: values.role,
        })
        setFetching(false)
        getUsers()
      })
  }
  return update(`/users/${values.id}`, parseUpdateUser(values))
    .then(() => {
      setFetching(false)
      getUsers()