All files / modules/75-ce/pages/recommendationList RecommendationList.tsx

86.54% Statements 90/104
68.85% Branches 84/122
63.16% Functions 12/19
87.38% Lines 90/103

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 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500              1x 1x 1x   1x 1x 1x 1x 1x                     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                                 1x             4x 4x 4x   4x 4x 4x           4x 4x             4x               4x 1x                   3x 1x               2x 5x 5x   5x   5x           5x 5x 5x   5x 5x                               5x 5x                               5x 5x                         5x                                                                                                 2x 5x 5x 5x             2x 5x             2x 5x                       2x                                                                                                           1x 5x 4x   4x 4x 4x           4x             4x   4x 4x     4x   4x 4x     4x     4x                         4x                   4x 4x   4x   4x 4x   4x   4x   4x                                                     4x                   4x   4x                                                                                                                                             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, { useEffect, useMemo, useState } from 'react'
import { Card, Text, Layout, Container, Icon, Button, ButtonVariation, TableV2, IconName } from '@wings-software/uicore'
import { useHistory, useParams, Link } from 'react-router-dom'
import type { CellProps, Renderer } from 'react-table'
import qs from 'qs'
import { Color, FontVariation } from '@harness/design-system'
import { defaultTo, get } from 'lodash-es'
import { useStrings } from 'framework/strings'
import {
  RecommendationItemDto,
  useRecommendationsQuery,
  useRecommendationsSummaryQuery,
  K8sRecommendationFilterDtoInput,
  ResourceType,
  useFetchCcmMetaDataQuery,
  CcmMetaData,
  Maybe
} from 'services/ce/services'
 
import routes from '@common/RouteDefinitions'
import { Page } from '@common/exports'
import { useQueryParams } from '@common/hooks'
import formatCost from '@ce/utils/formatCost'
import { getViewFilterForId, GROUP_BY_CLUSTER_NAME } from '@ce/utils/perspectiveUtils'
import EmptyView from '@ce/images/empty-state.svg'
import OverviewAddCluster from '@ce/components/OverviewPage/OverviewAddCluster'
import { PAGE_NAMES, USER_JOURNEY_EVENTS } from '@ce/TrackingEventsConstants'
import { useTelemetry } from '@common/hooks/useTelemetry'
import { NGBreadcrumbs } from '@common/components/NGBreadcrumbs/NGBreadcrumbs'
import { CCM_PAGE_TYPE, CloudProvider } from '@ce/types'
import { calculateSavingsPercentage } from '@ce/utils/recommendationUtils'
import { generateFilters } from '@ce/utils/anomaliesUtils'
import RecommendationSavingsCard from '../../components/RecommendationSavingsCard/RecommendationSavingsCard'
import RecommendationFilters from '../../components/RecommendationFilters'
import css from './RecommendationList.module.scss'
 
type RouteFn = (
  params: {
    recommendation: string
    recommendationName: string
  } & {
    accountId: string
  }
) => string
 
interface RecommendationListProps {
  data: Array<RecommendationItemDto>
  fetching: boolean
  ccmData: Maybe<CcmMetaData> | undefined
  pagination: {
    itemCount: number
    pageSize: number
    pageCount: number
    pageIndex: number
    gotoPage: (pageNumber: number) => void
  }
  onAddClusterSuccess: () => void
}
 
const RecommendationsList: React.FC<RecommendationListProps> = ({
  data,
  pagination,
  fetching,
  ccmData,
  onAddClusterSuccess
}) => {
  const history = useHistory()
  const { trackEvent } = useTelemetry()
  const { accountId } = useParams<{ accountId: string }>()
 
  const { getString } = useStrings()
  const resourceTypeToRoute: Record<ResourceType, RouteFn> = useMemo(() => {
    return {
      [ResourceType.Workload]: routes.toCERecommendationDetails,
      [ResourceType.NodePool]: routes.toCENodeRecommendationDetails
    }
  }, [])
 
  const resourceTypeMap: Record<string, string> = useMemo(
    () => ({
      [ResourceType.Workload]: getString('ce.overview.workload'),
      [ResourceType.NodePool]: getString('ce.overview.nodepool')
    }),
    []
  )
 
  Iif (fetching) {
    return (
      <Card elevation={1} className={css.errorContainer}>
        <Icon color="blue500" name="spinner" size={30} />
      </Card>
    )
  }
 
  if (ccmData && !ccmData.k8sClusterConnectorPresent) {
    return (
      <Card elevation={1} className={css.errorContainer}>
        <OverviewAddCluster
          onAddClusterSuccess={onAddClusterSuccess}
          descriptionText={getString('ce.pageErrorMsg.recommendationDesc')}
        />
      </Card>
    )
  }
 
  if (ccmData && ccmData.k8sClusterConnectorPresent && !ccmData.clusterDataPresent) {
    return (
      <Card elevation={1} className={css.errorContainer}>
        <img src={EmptyView} />
        <Text className={css.errorText}>{getString('ce.pageErrorMsg.recommendationNoData')}</Text>
      </Card>
    )
  }
 
  const NameCell: Renderer<CellProps<RecommendationItemDto>> = cell => {
    const originalRowData = cell.row.original
    const { clusterName, namespace, resourceType } = originalRowData
 
    const provider = get(originalRowData, 'recommendationDetails.recommended.provider', '')
 
    const iconMapping: Record<string, IconName> = {
      google: 'gcp',
      azure: 'service-azure',
      amazon: 'service-aws'
    }
 
    const iconName = provider ? iconMapping[provider] : 'app-kubernetes'
    const perspectiveKey = 'defaultClusterPerspectiveId'
    const cloudProvider = 'CLUSTER'
 
    const clusterLink = useMemo(
      () => ({
        pathname: routes.toPerspectiveDetails({
          accountId: accountId,
          perspectiveId: (defaultTo(ccmData, {}) as CcmMetaData)[perspectiveKey] as string,
          perspectiveName: (defaultTo(ccmData, {}) as CcmMetaData)[perspectiveKey] as string
        }),
        search: `?${qs.stringify({
          filters: JSON.stringify(
            generateFilters({ clusterName } as Record<string, string>, cloudProvider as CloudProvider)
          ),
          groupBy: JSON.stringify(GROUP_BY_CLUSTER_NAME)
        })}`
      }),
      []
    )
 
    const namespaceLink = useMemo(
      () => ({
        pathname: routes.toPerspectiveDetails({
          accountId: accountId,
          perspectiveId: (defaultTo(ccmData, {}) as CcmMetaData)[perspectiveKey] as string,
          perspectiveName: (defaultTo(ccmData, {}) as CcmMetaData)[perspectiveKey] as string
        }),
        search: `?${qs.stringify({
          filters: JSON.stringify(
            generateFilters({ clusterName, namespace } as Record<string, string>, cloudProvider as CloudProvider)
          ),
          groupBy: JSON.stringify(GROUP_BY_CLUSTER_NAME)
        })}`
      }),
      []
    )
 
    const resourceDetailsLink = useMemo(
      () => ({
        pathname: routes.toCEPerspectiveWorkloadDetails({
          accountId,
          clusterName: defaultTo(clusterName, ''),
          namespace: defaultTo(namespace, ''),
          perspectiveId: (defaultTo(ccmData, {}) as CcmMetaData)[perspectiveKey] as string,
          perspectiveName: (defaultTo(ccmData, {}) as CcmMetaData)[perspectiveKey] as string,
          workloadName: cell.value
        })
      }),
      []
    )
 
    return (
      <Layout.Horizontal style={{ alignItems: 'center' }}>
        <Icon name={iconName} size={28} padding={{ right: 'medium' }} />
        <Layout.Vertical>
          <Container>
            <Text inline color={Color.GREY_500} font={{ variation: FontVariation.SMALL }}>
              {`${getString('common.cluster')}: `}
            </Text>
            <Link to={clusterLink} onClick={e => e.stopPropagation()}>
              <Text inline color={Color.PRIMARY_7} font={{ variation: FontVariation.BODY2 }}>
                {clusterName}
              </Text>
            </Link>
          </Container>
          {namespace ? (
            <Container>
              <Text inline color={Color.GREY_500} font={{ variation: FontVariation.SMALL }}>
                {`${getString('ce.recommendation.listPage.filters.namespace')}: `}
              </Text>
              <Link to={namespaceLink} onClick={e => e.stopPropagation()}>
                <Text inline color={Color.PRIMARY_7} font={{ variation: FontVariation.BODY2 }}>
                  {namespace}
                </Text>
              </Link>
            </Container>
          ) : null}
          <Container>
            <Text inline color={Color.GREY_500} font={{ variation: FontVariation.SMALL_BOLD }}>
              {`${getString(
                ResourceType.Workload === resourceType ? 'pipelineSteps.workload' : 'ce.nodeRecommendation.nodepool'
              )}: `}
            </Text>
            {resourceType === ResourceType.Workload ? (
              <Link to={resourceDetailsLink} onClick={e => e.stopPropagation()}>
                <Text inline color={Color.PRIMARY_7} font={{ variation: FontVariation.BODY2 }}>
                  {cell.value}
                </Text>
              </Link>
            ) : (
              <Text inline color={Color.GREY_700} font={{ variation: FontVariation.BODY2 }}>
                {cell.value}
              </Text>
            )}
          </Container>
        </Layout.Vertical>
      </Layout.Horizontal>
    )
  }
 
  const RecommendationTypeCell: Renderer<CellProps<RecommendationItemDto>> = ({ row }) => {
    const rowData = row.original
    const { resourceType } = rowData
    return (
      <Text color={Color.GREY_600} font={{ variation: FontVariation.SMALL }}>
        {resourceTypeMap[resourceType]}
      </Text>
    )
  }
 
  const CostCell: Renderer<CellProps<RecommendationItemDto>> = cell => {
    return cell.value ? (
      <Text color={Color.GREY_600} font={{ variation: FontVariation.H6 }}>
        {formatCost(cell.value)}
      </Text>
    ) : null
  }
 
  const SavingCell: Renderer<CellProps<RecommendationItemDto>> = cell => {
    return !isNaN(cell.value) ? (
      <Container>
        <Text inline color={Color.GREEN_700} font={{ variation: FontVariation.H5 }}>
          {formatCost(cell.value)}
        </Text>
        <Text inline color={Color.GREEN_700} font={{ variation: FontVariation.BODY2 }} margin={{ left: 'small' }}>
          {calculateSavingsPercentage(cell.value, defaultTo(cell.row.original.monthlyCost, 0))}
        </Text>
      </Container>
    ) : null
  }
 
  return data ? (
    <>
      <Layout.Vertical spacing="large">
        {data.length ? (
          <TableV2<RecommendationItemDto>
            onRowClick={({ id, resourceType, resourceName }) => {
              trackEvent(USER_JOURNEY_EVENTS.RECOMMENDATION_CLICK, {})
              history.push(
                resourceTypeToRoute[resourceType]({
                  accountId,
                  recommendation: id,
                  recommendationName: resourceName || id
                })
              )
            }}
            data={data}
            columns={[
              {
                accessor: 'resourceName',
                Header: getString('ce.recommendation.listPage.listTableHeaders.resourceName'),
                Cell: NameCell,
                width: '36%'
              },
              {
                accessor: 'monthlySaving',
                Header: getString('ce.recommendation.listPage.listTableHeaders.monthlySavings'),
                Cell: SavingCell,
                width: '18%'
              },
              {
                accessor: 'monthlyCost',
                Header: getString('ce.recommendation.listPage.listTableHeaders.monthlyCost'),
                Cell: CostCell,
                width: '18%'
              },
              {
                Header: getString('ce.recommendation.listPage.listTableHeaders.recommendationType'),
                Cell: RecommendationTypeCell,
                width: '18%'
              }
            ]}
            pagination={pagination}
          ></TableV2>
        ) : (
          <Container className={css.errorContainer}>
            <img src={EmptyView} />
            <Text className={css.errorText}>{getString('ce.pageErrorMsg.noRecommendations')}</Text>
          </Container>
        )}
      </Layout.Vertical>
    </>
  ) : null
}
 
const RecommendationList: React.FC = () => {
  const [costFilters, setCostFilters] = useState<Record<string, number>>({})
  const [page, setPage] = useState(0)
 
  const { trackPage } = useTelemetry()
  const history = useHistory()
  const { accountId } = useParams<{ accountId: string }>()
  const {
    perspectiveId,
    perspectiveName,
    filters: filterQuery = {},
    origin
  } = useQueryParams<{
    perspectiveId: string
    perspectiveName: string
    filters: Record<string, any>
    origin: string
  }>()
 
  const [filters, setFilters] = useState<Record<string, string[]>>(filterQuery)
 
  useEffect(() => {
    trackPage(PAGE_NAMES.RECOMMENDATIONS_PAGE, {})
  }, [])
 
  const modifiedCostFilters = costFilters['minSaving'] ? costFilters : { ...costFilters, minSaving: 0 }
 
  const [ccmMetaResult, refetchCCMMetaData] = useFetchCcmMetaDataQuery()
  const { data: ccmData, fetching: fetchingCCMMetaData } = ccmMetaResult
 
  const perspectiveFilters = (
    perspectiveId ? { perspectiveFilters: getViewFilterForId(perspectiveId) } : ({} as any)
  ) as K8sRecommendationFilterDtoInput
 
  const [result] = useRecommendationsQuery({
    variables: {
      filter: {
        ...filters,
        ...perspectiveFilters,
        ...modifiedCostFilters,
        offset: page * 10,
        limit: 10
      } as K8sRecommendationFilterDtoInput
    },
    pause: fetchingCCMMetaData
  })
 
  const [summaryResult] = useRecommendationsSummaryQuery({
    variables: {
      filter: {
        ...filters,
        ...perspectiveFilters,
        ...modifiedCostFilters
      } as unknown as K8sRecommendationFilterDtoInput
    }
  })
 
  const { data, fetching } = result
  const { data: summaryData } = summaryResult
 
  const { getString } = useStrings()
 
  const totalMonthlyCost = summaryData?.recommendationStatsV2?.totalMonthlyCost || 0
  const totalSavings = summaryData?.recommendationStatsV2?.totalMonthlySaving || 0
 
  const recommendationItems = data?.recommendationsV2?.items || []
 
  const gotoPage = (pageNumber: number) => setPage(pageNumber)
 
  const goBackToPerspective: () => void = () => {
    if (origin === CCM_PAGE_TYPE.Workload) {
      const clusterName = filterQuery.clusterNames[0],
        namespace = filterQuery.namespaces[0],
        workloadName = filterQuery.names[0]
 
      history.push(
        routes.toCEPerspectiveWorkloadDetails({
          accountId,
          perspectiveId,
          perspectiveName,
          clusterName,
          namespace,
          workloadName
        })
      )
    } else {
      history.push(
        routes.toPerspectiveDetails({
          perspectiveId,
          perspectiveName,
          accountId
        })
      )
    }
  }
 
  const pagination = {
    itemCount: summaryData?.recommendationStatsV2?.count || 0,
    pageSize: 10,
    pageCount: summaryData?.recommendationStatsV2?.count
      ? Math.ceil(summaryData?.recommendationStatsV2?.count / 10)
      : 0,
    pageIndex: page,
    gotoPage: gotoPage
  }
 
  const isEmptyView = !fetching && !recommendationItems?.length
 
  return (
    <>
      <Page.Header
        title={
          <Text
            color="grey800"
            style={{ fontSize: 20, fontWeight: 'bold' }}
            tooltipProps={{ dataTooltipId: 'ccmRecommendations' }}
          >
            {getString('ce.recommendation.sideNavText')}
          </Text>
        }
        breadcrumbs={<NGBreadcrumbs />}
        toolbar={
          perspectiveId ? (
            <Button
              text={getString('ce.recommendation.listPage.backToPerspectives', {
                name: perspectiveName
              })}
              icon="chevron-left"
              onClick={goBackToPerspective}
              variation={ButtonVariation.PRIMARY}
            />
          ) : null
        }
      />
      <Page.Body loading={fetching || fetchingCCMMetaData}>
        <Card style={{ width: '100%' }}>
          <Layout.Horizontal flex={{ justifyContent: 'flex-end' }}>
            <RecommendationFilters
              costFilters={costFilters}
              setCostFilters={setCostFilters}
              setFilters={setFilters}
              filters={filters}
            />
          </Layout.Horizontal>
        </Card>
        <Container className={css.listContainer}>
          <Layout.Vertical spacing="large">
            <Layout.Horizontal spacing="medium">
              <RecommendationSavingsCard
                title={getString('ce.recommendation.listPage.monthlySavingsText')}
                amount={isEmptyView ? '$-' : formatCost(totalSavings)}
                iconName="money-icon"
                subTitle={getString('ce.recommendation.listPage.recommendationCount', {
                  count: summaryData?.recommendationStatsV2?.count
                })}
              />
              <RecommendationSavingsCard
                title={getString('ce.recommendation.listPage.monthlyPotentialCostText')}
                amount={isEmptyView ? '$-' : formatCost(totalMonthlyCost)}
                amountSubTitle={getString('ce.recommendation.listPage.byEOM')}
                subTitle={getString('ce.recommendation.listPage.forecatedCostSubText')}
              />
            </Layout.Horizontal>
            <RecommendationsList
              onAddClusterSuccess={() => {
                refetchCCMMetaData()
              }}
              ccmData={ccmData?.ccmMetaData}
              pagination={pagination}
              fetching={fetching || fetchingCCMMetaData}
              data={recommendationItems as Array<RecommendationItemDto>}
            />
          </Layout.Vertical>
        </Container>
      </Page.Body>
    </>
  )
}
 
export default RecommendationList