All files / modules/10-common/modals/SwitchAccount SwitchAccount.tsx

90% Statements 63/70
75% Branches 48/64
94.44% Functions 17/18
90% Lines 63/70

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236              4x 4x                       4x 4x 4x 4x             4x   4x 4x   4x 4x 4x                         4x 20x 20x     4x 20x 20x     4x 7x 7x             4x 7x 7x 7x 7x 7x 7x     7x 7x       7x 20x   20x 1x 1x 1x             1x 1x   1x                 20x                       7x 22x   22x 1x     1x 1x           22x             1x 1x           22x                         7x 3x       7x   6x     15x           7x 6x     15x             15x             15x             15x               7x                                               4x  
/*
 * Copyright 2021 Harness Inc. All rights reserved.
 * Use of this source code is governed by the PolyForm Shield 1.0.0 license
 * that can be found in the licenses directory at the root of this repository, also available at
 * https://polyformproject.org/wp-content/uploads/2020/06/PolyForm-Shield-1.0.0.txt.
 */
 
import React, { useMemo, useState, useEffect } from 'react'
import {
  Container,
  Text,
  Button,
  ButtonVariation,
  PageError,
  TableV2,
  useConfirmationDialog,
  useToaster,
  NoDataCard
} from '@wings-software/uicore'
import type { Column, Renderer, CellProps } from 'react-table'
import { useParams, useHistory } from 'react-router-dom'
import { get, defaultTo } from 'lodash-es'
import { Intent } from '@blueprintjs/core'
import {
  useGetUser,
  useSetDefaultAccountForCurrentUser,
  RestResponseUser,
  useRestrictedSwitchAccount
} from 'services/portal'
import type { User, Account } from 'services/portal'
import { PageSpinner } from '@common/components'
import type { AccountPathProps } from '@common/interfaces/RouteInterfaces'
import { useStrings } from 'framework/strings'
import routes from '@common/RouteDefinitions'
import type { UseGetMockData } from '@common/utils/testUtils'
import { getLoginPageURL } from 'framework/utils/SessionUtils'
import AppStorage from 'framework/utils/AppStorage'
import css from './SwitchAccount.module.scss'
 
interface SwitchAccountProps {
  hideModal: () => void
  searchString?: string
  mock?: UseGetMockData<RestResponseUser>
}
 
interface ReAuthenticationNoteProps {
  accounts: Account[]
  accountId: string
}
 
const RenderColumnCompanyName: Renderer<CellProps<Account>> = ({ row }) => {
  const name = row.original.companyName
  return <Text lineClamp={1}>{name}</Text>
}
 
const RenderColumnAccountEdition: Renderer<CellProps<Account>> = ({ row }) => {
  const name = row.original.licenseInfo?.accountType
  return <Text>{name}</Text>
}
 
const ReAuthenticationNote: React.FC<ReAuthenticationNoteProps> = ({ accounts, accountId }) => {
  const { getString } = useStrings()
  return accounts.length > 1 || (accounts[0] && accounts[0].uuid !== accountId) ? (
    <Text intent="warning" padding={{ left: 'large', right: 'large', top: 'small' }}>
      {getString('common.noteAccountSwitch')}
    </Text>
  ) : null
}
 
const SwitchAccount: React.FC<SwitchAccountProps> = ({ searchString = '', mock }) => {
  const { accountId } = useParams<AccountPathProps>()
  const [user, setUser] = useState<User>()
  const { showError } = useToaster()
  const history = useHistory()
  const { getString } = useStrings()
  const { data, loading, error, refetch } = useGetUser({
    mock
  })
  const { mutate: setDefaultAccount, loading: settingDefault } = useSetDefaultAccountForCurrentUser({ accountId })
  const { mutate: switchAccount, loading: switchAccountLoading } = useRestrictedSwitchAccount({
    // requestOptions: { headers: { 'content-type': 'application/json' } }
  })
 
  const RenderColumnAccountName: Renderer<CellProps<Account>> = ({ row }) => {
    const account = row.original
 
    const handleSwitchAccount = async (): Promise<void> => {
      try {
        const response = await switchAccount({ accountId: account.uuid })
        Iif (response.resource?.requiresReAuthentication) {
          const baseUrl = window.location.href.split('#')[0]
          const returnUrl = `${baseUrl}#${routes.toHome({ accountId: account.uuid })}`
          history.push({
            pathname: routes.toRedirect(),
            search: `?returnUrl=${encodeURIComponent(getLoginPageURL({ returnUrl }))}`
          })
        } else Eif (response.resource) {
          AppStorage.set('acctId', account.uuid)
          // this needs to be a server-redirect to support cluster isolation
          window.location.href = window.location.pathname
        } else {
          showError(getString('common.switchAccountError'))
        }
      } catch (err) {
        showError(getString('common.switchAccountError'))
      }
    }
 
    return (
      <Button
        onClick={handleSwitchAccount}
        text={account.accountName}
        loading={switchAccountLoading}
        disabled={account.uuid === accountId}
        minimal={account.uuid === accountId}
        variation={ButtonVariation.LINK}
      />
    )
  }
 
  const RenderColumnDefaultAccount: Renderer<CellProps<Account>> = ({ row }) => {
    const account = row.original
 
    const handleSetDefault = async (): Promise<void> => {
      const { resource, responseMessages } = await setDefaultAccount(undefined, {
        pathParams: { accountId: account.uuid }
      })
      Eif (resource === true) {
        refetch()
      } else {
        showError(get(responseMessages, '[0].message', getString('somethingWentWrong')))
      }
    }
 
    const { openDialog } = useConfirmationDialog({
      cancelButtonText: getString('cancel'),
      confirmButtonText: getString('continue'),
      titleText: getString('common.changeDefaultAccountTitle'),
      contentText: getString('common.changeDefaultAccountMessage', { name: account.accountName }),
      intent: Intent.WARNING,
      onCloseDialog: isConfirmed => {
        Eif (isConfirmed) {
          handleSetDefault()
        }
      }
    })
 
    // default account should not be actionable
    return account.uuid === user?.defaultAccountId ? (
      <Text flex={{ align: 'center-center' }}>Default</Text>
    ) : (
      <Button
        small
        variation={ButtonVariation.TERTIARY}
        text={getString('common.setAsDefault')}
        onClick={openDialog}
        data-testid={`set-default-account-${account.accountName}`}
      />
    )
  }
 
  useEffect(() => {
    setUser(data?.resource)
  }, [data])
 
  // eslint-disable-next-line react-hooks/exhaustive-deps
  const accounts = useMemo(
    () =>
      defaultTo(
        user?.accounts
          ?.concat(defaultTo(user.supportAccounts, []))
          ?.filter(account => account.accountName.toLowerCase().includes(searchString.toLowerCase())),
        []
      ),
    [user, searchString]
  )
 
  const columns: Column<Account>[] = useMemo(
    () => [
      {
        Header: getString('common.headerAccountName'),
        accessor: row => row.accountName,
        id: 'name',
        width: '30%',
        Cell: RenderColumnAccountName
      },
      {
        Header: getString('common.headerCompanyName'),
        accessor: row => row.companyName,
        id: 'companyName',
        width: '30%',
        Cell: RenderColumnCompanyName
      },
      {
        Header: getString('common.headerAccountEdition'),
        accessor: row => row.licenseInfo?.accountType,
        id: 'accountType',
        width: '20%',
        Cell: RenderColumnAccountEdition
      },
      {
        Header: getString('common.headerDefaultAccount'),
        accessor: row => row.defaults,
        id: 'defaultAccount',
        width: '20%',
        Cell: RenderColumnDefaultAccount
      }
    ],
    [accounts]
  )
  return (
    <>
      <ReAuthenticationNote accounts={accounts} accountId={accountId} />
      <Container padding={{ left: 'large', right: 'large' }} className={css.container}>
        {loading || settingDefault ? <PageSpinner /> : null}
        {error ? (
          <PageError message={error.message || getString('somethingWentWrong')} onClick={() => refetch()} />
        ) : null}
        {!loading && !settingDefault && !error && accounts ? (
          accounts.length ? (
            <TableV2 columns={columns} data={accounts} sortable={false} />
          ) : (
            <NoDataCard
              message={getString('noData')}
              className={css.noDataCard}
              containerClassName={css.noDataCardContainer}
            />
          )
        ) : null}
      </Container>
    </>
  )
}
 
export default SwitchAccount