All files / modules/40-gitsync/pages/errors/GitSyncErrorsPanel GitSyncErrorsPanel.tsx

77.46% Statements 55/71
55.3% Branches 73/132
52.38% Functions 11/21
77.27% Lines 51/66

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 284 285 286 287 288 289 290 291 292 293              1x 1x 1x 1x 1x                     1x 1x 1x         1x                 1x 1x 1x 1x   1x 1x                 1x 14x                       1x       1x                                                     1x 2x                   1x                                 1x 9x 9x 9x 8x                         1x       8x           1x     1x 10x 9x 9x 9x   9x 9x   9x   9x                       9x       9x   9x               9x                                                                                                                           9x         9x 10x     10x       10x           10x       17x               9x              
/*
 * 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, { Dispatch, SetStateAction, useContext, useState } from 'react'
import { useParams } from 'react-router-dom'
import { defaultTo } from 'lodash-es'
import { Drawer, Position } from '@blueprintjs/core'
import {
  Layout,
  Pagination,
  PaginationProps,
  PageError,
  Button,
  PillToggle,
  PillToggleProps,
  Text,
  Icon
} from '@wings-software/uicore'
import { useModalHook } from '@harness/use-modal'
import { Color, FontVariation } from '@harness/design-system'
import {
  GitErrorExperienceSubTab,
  GitErrorExperienceTab,
  GitSyncErrorState
} from '@gitsync/pages/errors/GitSyncErrorContext'
import {
  ListGitToHarnessErrorsCommitsQueryParams,
  useListGitToHarnessErrorsCommits,
  GitSyncErrorAggregateByCommitDTO,
  useListGitSyncErrors,
  GitSyncErrorDTO,
  GetYamlSchemaQueryParams
} from 'services/cd-ng'
import type { ProjectPathProps } from '@common/interfaces/RouteInterfaces'
import YAMLBuilder from '@common/components/YAMLBuilder/YamlBuilder'
import { PageSpinner } from '@common/components'
import { downloadYamlAsFile } from '@common/utils/downloadYamlUtils'
import { useStrings } from 'framework/strings'
import type { GitSyncErrorMessageProps } from '@gitsync/components/GitSyncErrorMessage/GitSyncErrorMessageItem'
import { GitSyncErrorMessage, parseCommitItems } from '@gitsync/components/GitSyncErrorMessage/GitSyncErrorMessage'
import styles from '@gitsync/pages/errors/GitSyncErrorsPanel/GitSyncErrorsPanel.module.scss'
 
interface SelectedFile {
  fileName: string
  filePath: string
  type: string
  content: string
}
 
const parseDataForCommitView = (data: GitSyncErrorAggregateByCommitDTO[] = []): GitSyncErrorMessageProps[] => {
  return data.map(item => ({
    mode: 'COMMIT',
    title: item.commitMessage || '',
    count: item.failedCount,
    repo: item.repoId,
    branch: item.branchName,
    commitId: item.gitCommitId,
    timestamp: item.createdAt,
    items: parseCommitItems(defaultTo(item.errorsForSummaryView, []))
  }))
}
 
const parseDataForFileView = (
  data: GitSyncErrorDTO[],
  onShowDetails: (fileData: SelectedFile) => void
): GitSyncErrorMessageProps[] => {
  return data.map(item => ({
    mode: 'FILE',
    title: item.completeFilePath || '',
    repo: item.repoId,
    branch: item.branchName,
    timestamp: item.createdAt,
    commitId: defaultTo(item.additionalErrorDetails?.gitCommitId, ''),
    items: [
      {
        reason: item.failureReason || '',
        ...(item.additionalErrorDetails?.yamlContent
          ? {
              showDetails: () => {
                onShowDetails({
                  fileName: defaultTo((item.completeFilePath || '').split('/').pop(), ''),
                  filePath: item.additionalErrorDetails?.entityUrl,
                  type: defaultTo(item.entityType, ''),
                  content: item.additionalErrorDetails?.yamlContent
                })
              }
            }
          : {})
      }
    ]
  }))
}
 
const parseDataForConnectivityView = (data: GitSyncErrorDTO[] = []): GitSyncErrorMessageProps[] => {
  return data.map(item => ({
    mode: 'CONNECTIVITY',
    title: item.failureReason || '',
    repo: item.repoId,
    branch: item.branchName,
    timestamp: item.createdAt,
    items: []
  }))
}
 
const drawerProps = {
  autoFocus: true,
  canEscapeKeyClose: true,
  canOutsideClickClose: true,
  enforceFocus: true,
  isOpen: true,
  hasBackdrop: true,
  position: Position.RIGHT,
  usePortal: true,
  size: '40%',
  isCloseButtonShown: true
}
 
const GitErrorExperienceToggle: React.FC<{
  selectedTab: GitErrorExperienceTab
  selectedView: GitErrorExperienceSubTab | null
  setView: Dispatch<SetStateAction<GitErrorExperienceSubTab | null>>
}> = props => {
  const { getString } = useStrings()
  const { selectedTab, setView, selectedView } = props
  if (selectedTab === GitErrorExperienceTab.ALL_ERRORS) {
    const toggleProps: PillToggleProps<GitErrorExperienceSubTab> = {
      selectedView: selectedView ?? GitErrorExperienceSubTab.ALL_ERRORS_COMMIT_VIEW,
      options: [
        {
          label: getString('commits'),
          value: GitErrorExperienceSubTab.ALL_ERRORS_COMMIT_VIEW
        },
        {
          label: getString('common.files'),
          value: GitErrorExperienceSubTab.ALL_ERRORS_FILE_VIEW
        }
      ],
      onChange: view => {
        setView(view)
      },
      className: styles.toggle
    }
    return (
      <Layout.Horizontal flex={{ justifyContent: 'center' }}>
        <PillToggle {...toggleProps} />
      </Layout.Horizontal>
    )
  }
  return <></>
}
 
export const GitSyncErrorsPanel: React.FC = () => {
  const { accountId, orgIdentifier, projectIdentifier } = useParams<ProjectPathProps>()
  const { selectedTab, view, setView, searchTerm, branch, repoIdentifier, reloadAction } = useContext(GitSyncErrorState)
  const isCommitView = view === GitErrorExperienceSubTab.ALL_ERRORS_COMMIT_VIEW
  const isFileView = view === GitErrorExperienceSubTab.ALL_ERRORS_FILE_VIEW
 
  const [pageIndex, setPageIndex] = useState(0)
  const [selectedFile, setSelectedFile] = useState<SelectedFile>()
 
  const { getString } = useStrings()
 
  const queryParams: ListGitToHarnessErrorsCommitsQueryParams = {
    accountIdentifier: accountId,
    orgIdentifier,
    projectIdentifier,
    searchTerm,
    branch,
    repoIdentifier,
    pageIndex,
    pageSize: 10,
    ...(isCommitView ? {} : { gitToHarness: isFileView })
  }
 
  const { data, loading, error, refetch } = (isCommitView ? useListGitToHarnessErrorsCommits : useListGitSyncErrors)({
    queryParams
  })
 
  reloadAction.current = refetch
 
  const paginationProps: PaginationProps = {
    itemCount: data?.data?.totalItems || 0,
    pageSize: data?.data?.pageSize || 0,
    pageCount: data?.data?.totalPages || 0,
    pageIndex: data?.data?.pageIndex || 0,
    gotoPage: pageNumber => setPageIndex(pageNumber)
  }
 
  const [showModal, hideDrawer] = useModalHook(() => {
    const download = (): void => {
      downloadYamlAsFile(selectedFile?.content, defaultTo(selectedFile?.fileName, ''))
    }
 
    const openFile = (): void => {
      window.open(selectedFile?.filePath, '_blank')
    }
 
    const renderCustomHeader = (): JSX.Element => (
      <Layout.Horizontal
        flex={{ justifyContent: 'space-between' }}
        padding={{ left: 'xlarge', right: 'xlarge', top: 'large', bottom: 'large' }}
      >
        <Layout.Horizontal flex={{ alignItems: 'center' }}>
          <Icon name="main-applications" size={20} color={Color.GREY_400} margin={{ right: 'large' }} />
          <Text font={{ variation: FontVariation.H5 }}>{getString('gitsync.fileContent')}</Text>
        </Layout.Horizontal>
        <Layout.Horizontal flex={{ alignItems: 'center' }}>
          <Icon
            name="command-install"
            size={18}
            color={Color.GREY_400}
            margin={{ right: 'xlarge' }}
            onClick={download}
            className={styles.hover}
          />
          <Icon name="main-share" size={18} color={Color.GREY_400} onClick={openFile} className={styles.hover} />
        </Layout.Horizontal>
      </Layout.Horizontal>
    )
 
    return (
      <Drawer
        onClose={() => {
          hideDrawer()
        }}
        className={styles.drawer}
        {...drawerProps}
      >
        <Button
          minimal
          className={styles.almostFullScreenCloseBtn}
          icon="cross"
          withoutBoxShadow
          onClick={() => {
            hideDrawer()
          }}
        />
        <YAMLBuilder
          entityType={selectedFile?.type as GetYamlSchemaQueryParams['entityType']}
          fileName={getString('gitsync.fileContent')}
          isReadOnlyMode
          isEditModeSupported={false}
          existingYaml={selectedFile?.content}
          showSnippetSection={false}
          renderCustomHeader={renderCustomHeader}
        />
      </Drawer>
    )
  }, [selectedFile])
 
  const onShowDetails = (fileData: SelectedFile): void => {
    setSelectedFile(fileData)
    showModal()
  }
 
  const Component = (): React.ReactElement => {
    Iif (loading) {
      return <PageSpinner />
    }
    Iif (error) {
      return <PageError onClick={() => refetch()} />
    }
 
    const parsedData = isCommitView
      ? parseDataForCommitView(data?.data?.content)
      : isFileView
      ? parseDataForFileView(defaultTo(data?.data?.content, []), onShowDetails)
      : parseDataForConnectivityView(data?.data?.content)
 
    return (
      <Layout.Vertical height="calc(100% - 16px)">
        <Layout.Vertical className={styles.gitSyncErrorsPanel}>
          {parsedData.map(item => (
            <GitSyncErrorMessage key={item.commitId} {...item} />
          ))}
        </Layout.Vertical>
        <Pagination {...paginationProps} />
      </Layout.Vertical>
    )
  }
 
  return (
    <Layout.Vertical padding={{ left: 'large', right: 'large' }}>
      <GitErrorExperienceToggle selectedTab={selectedTab} setView={setView} selectedView={view} />
      <Component />
    </Layout.Vertical>
  )
}