All files / modules/85-cv/components/MetricsDashboardList MetricsDashboardList.tsx

86.3% Statements 63/73
71.43% Branches 60/84
77.78% Functions 14/18
86.3% Lines 63/73

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              23x   23x 23x 23x 23x 23x 23x           23x 23x 23x 23x           23x 23x 23x   23x   23x   23x 23x 21x 21x             21x 21x 21x   21x 21x 21x       21x 21x   21x 6x 1x   5x   24x         21x 7x                       21x 7x         21x 8x               8x         21x                   21x                   2x                         2x 2x 2x 2x 2x       2x               1x                   172x 172x             1x 1x 1x 1x 1x       1x                                                   172x                                   1x     1x         1x   1x                              
/*
 * 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, useContext, useEffect, useState } from 'react'
import type { CellProps } from 'react-table'
import { Classes } from '@blueprintjs/core'
import { Container, NoDataCard, PageError, Text, Utils } from '@wings-software/uicore'
import { Color } from '@harness/design-system'
import { useParams } from 'react-router-dom'
import { useStrings } from 'framework/strings'
import { SetupSourceTabsContext } from '@cv/components/CVSetupSourcesView/SetupSourceTabs/SetupSourceTabs'
import type {
  MetricsDashboardListProps,
  TableDashboardItem,
  TableData
} from '@cv/components/MetricsDashboardList/MetricsDashboardList.type'
import { SetupSourceLayout } from '@cv/components/CVSetupSourcesView/SetupSourceLayout/SetupSourceLayout'
import { TableFilter } from '@cv/components/TableFilter/TableFilter'
import { Table } from '@common/components'
import {
  initializeSelectedDashboards,
  initializeTableData,
  isError,
  isNoData
} from '@cv/components/MetricsDashboardList/MetricsDashboardList.utils'
import { ManualInputQueryModal } from '@cv/pages/health-source/connectors/GCOMetricsHealthSource/components/ManualInputQueryModal/ManualInputQueryModal'
import { getManuallyCreatedQueries } from '@cv/pages/health-source/connectors/GCOMetricsHealthSource/GCOMetricsHealthSource.utils'
import { getErrorMessage } from '@cv/utils/CommonUtils'
import type { ProjectPathProps } from '@common/interfaces/RouteInterfaces'
import css from './MetricsDashboardList.module.scss'
 
const TOTAL_ITEMS_PER_PAGE = 7
 
export default function MetricsDashboardList<T>(props: MetricsDashboardListProps<T>): JSX.Element {
  const { getString } = useStrings()
  const { tableItemMapper, defaultItemIcon, dashboardsRequest, manualQueryInputTitle, noDataMessage } = props
  const [{ filter, pageOffset }, setFilterAndPageOffset] = useState<{
    pageOffset: number
    filter?: string
  }>({
    pageOffset: 0,
    filter: undefined
  })
  const { sourceData } = useContext(SetupSourceTabsContext)
  const { accountId, projectIdentifier, orgIdentifier } = useParams<ProjectPathProps>()
  const { onNext, onPrevious, sourceData: propsData } = useContext(SetupSourceTabsContext)
 
  const [tableData, setTableData] = useState<TableData[]>([])
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [selectedDashboards, setSelectedDashboards] = useState(
    initializeSelectedDashboards(props.selectedDashboardList, tableItemMapper)
  )
 
  const { error, loading, data: dashboardList, refetch: refetchData } = dashboardsRequest
  const { pageIndex = -1, pageItemCount = 0, totalPages = 0, pageSize = 0 } = dashboardList?.data || {}
 
  const dashboardItems: TableDashboardItem[] = useMemo(() => {
    if (!dashboardList?.data?.content) {
      return []
    }
    return (
      dashboardList?.data?.content?.map((dashboard: T) => {
        return tableItemMapper(dashboard)
      }) || []
    )
  }, [dashboardList?.data?.content, tableItemMapper])
 
  const queryParams = useMemo(() => {
    return {
      accountId,
      projectIdentifier,
      orgIdentifier,
      connectorIdentifier: (sourceData?.connectorRef as string) || '',
      pageSize: TOTAL_ITEMS_PER_PAGE,
      offset: pageOffset,
      tracingId: Utils.randomId(),
      filter: filter
    }
  }, [filter, pageOffset, accountId, projectIdentifier, orgIdentifier, sourceData?.connectorRef])
 
  useEffect(() => {
    refetchData({
      queryParams: queryParams
    })
  }, [filter, refetchData, queryParams])
 
  useEffect(() => {
    Iif (loading) {
      const loadingItems = Array<TableData>(TOTAL_ITEMS_PER_PAGE).fill(
        { selected: false, dashboard: { name: getString('loading') } },
        0,
        TOTAL_ITEMS_PER_PAGE
      )
      setTableData(loadingItems)
    } else {
      setTableData(initializeTableData(selectedDashboards, dashboardItems))
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [selectedDashboards, dashboardItems, loading])
 
  Iif (isError(loading, error)) {
    return (
      <PageError
        className={css.loadingErrorNoData}
        message={getErrorMessage(error)}
        onClick={() => refetchData({ queryParams })}
      />
    )
  }
 
  return (
    <SetupSourceLayout
      content={
        <Container className={css.main}>
          {isNoData(loading, error, dashboardItems) ? (
            <NoDataCard
              icon="warning-sign"
              className={css.loadingErrorNoData}
              message={noDataMessage ?? getString('cv.monitoringSources.gco.selectDashboardsPage.noDataText')}
              buttonText={getString('cv.monitoringSources.gco.addManualInputQuery')}
              onClick={() => setIsModalOpen(true)}
            />
          ) : (
            <Container>
              <TableFilter
                appliedFilter={filter}
                className={css.filterStyle}
                placeholder={getString('cv.monitoringSources.gco.searchForDashboardsPlaceholder')}
                onFilter={(filterValue: string) => setFilterAndPageOffset({ pageOffset: 0, filter: filterValue })}
              />
              <Table<TableData>
                data={tableData || []}
                onRowClick={(rowData, index) => {
                  const newTableData = [...tableData]
                  newTableData[index].selected = !rowData.selected
                  setTableData(newTableData)
                  Eif (newTableData[index].selected) {
                    selectedDashboards.set(rowData.dashboard.name || '', rowData.dashboard)
                  } else {
                    selectedDashboards.delete(rowData.dashboard.name || '')
                  }
                  setSelectedDashboards(new Map(selectedDashboards))
                }}
                pagination={{
                  pageSize: pageSize,
                  pageIndex: pageIndex,
                  pageCount: totalPages,
                  itemCount: pageItemCount,
                  gotoPage: newPageIndex => {
                    setFilterAndPageOffset({ pageOffset: newPageIndex, filter: filter })
                  }
                }}
                columns={[
                  {
                    Header: '',
                    accessor: 'selected',
                    width: '10%',
                    disableSortBy: true,
                    Cell: function CheckColumn(tableProps: CellProps<TableData>) {
                      const { original, index } = tableProps.row
                      return loading ? (
                        <Container height={16} width={16} className={Classes.SKELETON} />
                      ) : (
                        <input
                          type="checkbox"
                          checked={tableProps.value}
                          onChange={() => {
                            const newTableData = [...tableData]
                            newTableData[index].selected = !tableProps.value
                            setTableData(newTableData)
                            Eif (newTableData[index].selected) {
                              selectedDashboards.set(original.dashboard.name || '', original.dashboard)
                            } else {
                              selectedDashboards.delete(original.dashboard.name || '')
                            }
                            setSelectedDashboards(new Map(selectedDashboards))
                          }}
                        />
                      )
                    }
                  },
                  {
                    Header: (
                      <Container className={css.columnContainer}>
                        <Text
                          intent="primary"
                          onClick={() => setIsModalOpen(true)}
                          className={css.manualQueryLink}
                          tooltipProps={{ dataTooltipId: 'addManualInputQuery' }}
                        >
                          {getString('cv.monitoringSources.gco.addManualInputQuery')}
                        </Text>
                        <Text color={Color.BLACK} tooltipProps={{ dataTooltipId: 'dashboardTableTitle' }}>
                          {getString(props.tableTitle)}
                        </Text>
                      </Container>
                    ),
                    accessor: 'dashboard',
                    width: '90%',
                    disableSortBy: true,
                    Cell: function DashboardName(cellProps: CellProps<TableData>) {
                      return loading ? (
                        <Container height={16} width="100%" className={Classes.SKELETON} />
                      ) : (
                        <Text icon={defaultItemIcon} color={Color.BLACK}>
                          {cellProps.value.name}
                        </Text>
                      )
                    }
                  }
                ]}
              />
            </Container>
          )}
          {isModalOpen && (
            <ManualInputQueryModal
              title={manualQueryInputTitle}
              manuallyInputQueries={getManuallyCreatedQueries(propsData.selectedMetrics)}
              onSubmit={values => {
                Iif (!propsData.selectedMetrics) {
                  propsData.selectedMetrics = new Map()
                }
                propsData.selectedMetrics.set(values.metricName, {
                  isManualQuery: true,
                  isCustomCreatedMetric: true,
                  metricName: values.metricName
                })
                onNext({ ...propsData, selectedDashboards: Array.from(selectedDashboards.values()) })
              }}
              closeModal={() => setIsModalOpen(false)}
            />
          )}
        </Container>
      }
      footerCTAProps={{
        onNext: () => {
          return onNext({ ...propsData, selectedDashboards: Array.from(selectedDashboards.values()) })
        },
        onPrevious: onPrevious,
        className: css.footer
      }}
    />
  )
}