All files / modules/35-connectors/pages/connectors/ConnectorDetailsPage ConnectorDetailsPage.tsx

84.62% Statements 66/78
55% Branches 110/200
64.29% Functions 9/14
84.62% Lines 66/78

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 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283              9x 9x 9x 9x 9x 9x 9x 9x               9x 9x 9x   9x 9x 9x 9x 9x 9x 9x 9x 9x 9x                           9x 5x 4x 4x 4x 4x 4x   4x 4x 4x   4x           4x                     4x           4x 4x   4x 2x 2x 2x       4x 2x                 4x         4x 2x 2x                                 4x 2x 2x                         4x   4x 4x             4x 2x           4x     4x                     4x 4x                                                                                       4x                     4x 4x     4x       4x     4x                   12x                                                           9x  
/*
 * Copyright 2022 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, { useEffect, useMemo } from 'react'
import { Layout, Container, Icon, Text, SelectOption, PageSpinner, PageError } from '@wings-software/uicore'
import { Tag } from '@blueprintjs/core'
import cx from 'classnames'
import { useParams, useHistory } from 'react-router-dom'
import { Color } from '@harness/design-system'
import { Page } from '@common/exports'
import {
  useGetConnector,
  ConnectorResponse,
  EntityGitDetails,
  useGetListOfBranchesWithStatus,
  GitBranchDTO,
  ResponseConnectorResponse
} from 'services/cd-ng'
import { useStrings } from 'framework/strings'
import { NGBreadcrumbs } from '@common/components/NGBreadcrumbs/NGBreadcrumbs'
import { useDocumentTitle } from '@common/hooks/useDocumentTitle'
import type { ProjectPathProps, ConnectorPathProps, PipelineType } from '@common/interfaces/RouteInterfaces'
import { useQueryParams } from '@common/hooks'
import routes from '@common/RouteDefinitions'
import { getScopeFromDTO } from '@common/components/EntityReference/EntityReference'
import { Scope } from '@common/interfaces/SecretsInterface'
import ScopedTitle from '@common/components/Title/ScopedTitle'
import { getIconByType } from '../utils/ConnectorUtils'
import ConnectorPageGitDetails from './ConnectorDetailsPageGitDetails/ConnectorPageGitDetails'
import RenderConnectorDetailsActiveTab from '../views/RenderConnectorDetailsActiveTab/RenderConnectorDetailsActiveTab'
import { ConnectorDetailsView } from '../utils/ConnectorHelper'
import css from './ConnectorDetailsPage.module.scss'
 
interface MockData {
  data: ResponseConnectorResponse
}
 
interface ConnectorDetailsPageProps {
  mockData?: MockData
}
 
interface ConnectorDetailsQueryParams extends EntityGitDetails {
  view: ConnectorDetailsView
}
 
const ConnectorDetailsPage: React.FC<ConnectorDetailsPageProps> = props => {
  const { getString } = useStrings()
  const [data, setData] = React.useState<ConnectorResponse>({})
  const [activeCategory, setActiveCategory] = React.useState(ConnectorDetailsView.overview)
  const [selectedBranch, setSelectedBranch] = React.useState<string>('')
  const [branchSelectOptions, setBranchSelectOptions] = React.useState<SelectOption[]>([])
  const [searchTerm, setSearchTerm] = React.useState<string>('')
  const { connectorId, accountId, orgIdentifier, projectIdentifier, module } =
    useParams<PipelineType<ProjectPathProps & ConnectorPathProps>>()
  const { repoIdentifier, branch, view } = useQueryParams<ConnectorDetailsQueryParams>()
  const history = useHistory()
 
  const defaultQueryParam = {
    accountIdentifier: accountId,
    orgIdentifier: orgIdentifier as string,
    projectIdentifier: projectIdentifier as string
  }
 
  const viewToLabelMap: Record<ConnectorDetailsView, string> = {
    [ConnectorDetailsView.overview]: getString('overview'),
    [ConnectorDetailsView.referencedBy]: getString('refrencedBy'),
    [ConnectorDetailsView.activityHistory]: getString('activityHistoryLabel')
  }
 
  const {
    loading,
    data: connectorData,
    refetch,
    error
  } = useGetConnector({
    identifier: connectorId as string,
    queryParams: { ...defaultQueryParam, repoIdentifier, branch },
    mock: props.mockData
  })
 
  const connectorName = data?.connector?.name
  const gitDetails = data?.gitDetails
 
  useEffect(() => {
    Eif (!loading && connectorData?.data) {
      setData(connectorData.data)
      setSelectedBranch(connectorData?.data?.gitDetails?.branch as string)
    }
  }, [connectorData, loading])
 
  useEffect(() => {
    Iif (view) {
      setActiveCategory(view)
    }
  }, [view])
 
  const {
    data: branchList,
    loading: loadingBranchList,
    refetch: getListOfBranchesWithStatus
  } = useGetListOfBranchesWithStatus({
    lazy: true,
    debounce: 500
  })
 
  useEffect(() => {
    const repoId = connectorData?.data?.gitDetails?.repoIdentifier || data?.gitDetails?.repoIdentifier
    Iif (repoId) {
      getListOfBranchesWithStatus({
        queryParams: {
          accountIdentifier: accountId,
          orgIdentifier,
          projectIdentifier,
          yamlGitConfigIdentifier: repoId,
          page: 0,
          size: 10,
          searchTerm
        }
      })
    }
 
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [loading, searchTerm])
 
  useEffect(() => {
    Eif (!loadingBranchList) {
      setBranchSelectOptions(
        branchList?.data?.branches?.content?.map((item: GitBranchDTO) => {
          return {
            label: item.branchName ?? '',
            value: item.branchName ?? ''
          }
        }) || []
      )
    }
 
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [loadingBranchList])
 
  useDocumentTitle([connectorName || connectorData?.data?.connector?.name || '', getString('connectorsLabel')])
 
  const RenderBreadCrumb: React.FC = () => {
    const breadCrumbs = [
      {
        url: routes.toConnectors({ accountId, orgIdentifier, projectIdentifier, module }),
        label: getString('connectorsLabel')
      }
    ]
 
    if (getScopeFromDTO({ accountId, orgIdentifier, projectIdentifier }) === Scope.ACCOUNT) {
      breadCrumbs.unshift({
        url: routes.toAccountResources({ accountId }),
        label: getString('common.accountResources')
      })
    }
 
    return <NGBreadcrumbs links={breadCrumbs} />
  }
 
  const handleBranchClick = (selected: string): void => {
    if (selected !== selectedBranch) {
      //Avoid any state change or API call if current branh is selected again
      setSelectedBranch(selected)
      refetch({
        queryParams:
          repoIdentifier && selected ? { ...defaultQueryParam, repoIdentifier, branch: selected } : defaultQueryParam
      })
    }
  }
 
  const renderTitle = useMemo(
    () => (
      <Layout.Vertical>
        {RenderBreadCrumb(props)}
        <Layout.Horizontal spacing="small">
          <Icon
            margin={{ right: 'xsmall' }}
            name={getIconByType(connectorData?.data?.connector?.type || data?.connector?.type)}
            size={35}
          ></Icon>
          <Container>
            <ScopedTitle
              title={{
                [Scope.PROJECT]: `${getString('connectorsLabel')}: ${
                  connectorData?.data?.connector?.name || connectorName || ''
                }`,
                [Scope.ORG]: getString('connectors.connectorsTitle'),
                [Scope.ACCOUNT]: getString('connectors.connectorsTitle')
              }}
            />
            <Layout.Horizontal spacing="small">
              <Text color={Color.GREY_400}>
                {connectorData?.data?.connector?.identifier || data?.connector?.identifier}
              </Text>
              {activeCategory === ConnectorDetailsView.overview && gitDetails?.objectId ? (
                <ConnectorPageGitDetails
                  handleBranchClick={handleBranchClick}
                  gitDetails={gitDetails}
                  selectedBranch={selectedBranch}
                  branchSelectOptions={branchSelectOptions}
                  loadingBranchList={loadingBranchList}
                  onQueryChange={(query: string) => {
                    setSearchTerm(query)
                  }}
                />
              ) : null}
            </Layout.Horizontal>
          </Container>
        </Layout.Horizontal>
      </Layout.Vertical>
    ),
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [connectorData, branchSelectOptions, activeCategory, selectedBranch, loadingBranchList]
  )
 
  const refetchhandler = (): Promise<void> =>
    refetch({
      queryParams: selectedBranch
        ? {
            ...defaultQueryParam,
            repoIdentifier: connectorData?.data?.gitDetails?.repoIdentifier,
            branch: selectedBranch
          }
        : defaultQueryParam
    })
 
  const getPageBody = (): React.ReactElement => {
    Iif (loading) {
      return <PageSpinner />
    }
    Iif (error) {
      const errorMessage = (error.data as Error)?.message || error.message
      return <PageError message={errorMessage} onClick={refetchhandler} />
    }
    return <RenderConnectorDetailsActiveTab activeCategory={activeCategory} data={data} refetch={refetchhandler} />
  }
 
  return (
    <>
      <Page.Header
        size="large"
        className={css.header}
        title={renderTitle}
        toolbar={
          <Container>
            <Layout.Horizontal spacing="medium">
              {Object.keys(viewToLabelMap).map((item, index) => {
                return (
                  <Tag
                    className={cx(css.tags, css.small, { [css.active]: activeCategory === item })}
                    onClick={() => {
                      history.push({
                        pathname: routes.toConnectorDetails({
                          accountId,
                          orgIdentifier,
                          projectIdentifier,
                          module,
                          connectorId
                        }),
                        search: `?view=${item}`
                      })
                    }}
                    key={item + index}
                  >
                    {viewToLabelMap[item as ConnectorDetailsView]}
                  </Tag>
                )
              })}
            </Layout.Horizontal>
          </Container>
        }
      />
      <Page.Body>{getPageBody()}</Page.Body>
    </>
  )
}
 
export default ConnectorDetailsPage