All files / modules/75-ce/components/AnomaliesListView AnomaliesListView.tsx

93.9% Statements 77/82
87.5% Branches 14/16
87.5% Functions 14/16
93.9% Lines 77/82

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              2x   2x 2x 2x 2x 2x 2x 2x 2x 2x 2x   2x 2x   2x   2x 2x 2x 2x   2x 8x   2x     2x     2x     2x                                             2x 12x 12x 12x 12x           12x 12x 12x   12x 1x 1x     1x           12x       2x                   1x 1x                               1x 1x 1x               2x                     9x       9x                   9x                     2x 4x 4x   4x 8x 8x   8x                       4x 8x 8x   8x                               4x             4x 8x 8x       8x 8x     8x   8x   8x                                                                                 4x 8x 8x   8x                       4x 8x     4x 3x                                                                                                                                                 2x                             2x  
/*
 * 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, { Dispatch, SetStateAction, useState } from 'react'
import type { CellProps, Column, Renderer } from 'react-table'
import { Text, Icon, TableV2, Layout, Button } from '@wings-software/uicore'
import { Color, FontVariation } from '@harness/design-system'
import qs from 'qs'
import { Link, useParams } from 'react-router-dom'
import { Classes, IconName, Menu, MenuItem, Popover, Position } from '@blueprintjs/core'
import { useStrings } from 'framework/strings'
import { AnomalyData, useReportAnomalyFeedback } from 'services/ce'
import { ANOMALIES_LIST_FORMAT, getTimePeriodString } from '@ce/utils/momentUtils'
import formatCost from '@ce/utils/formatCost'
import { useToaster } from '@common/components'
import type { AccountPathProps } from '@common/interfaces/RouteInterfaces'
import routes from '@common/RouteDefinitions'
import { CcmMetaData, useFetchCcmMetaDataQuery } from 'services/ce/services'
import type { orderType, sortType, serverSortProps } from '@common/components/Table/react-table-config'
import { generateFilters, generateGroupBy } from '@ce/utils/anomaliesUtils'
import type { CloudProvider, TimeRangeFilterType } from '@ce/types'
import { useFeatureFlag } from '@common/hooks/useFeatureFlag'
import { FeatureFlag } from '@common/featureFlags'
import useRBACError from '@rbac/utils/useRBACError/useRBACError'
import css from '../../pages/anomalies-overview/AnomaliesOverviewPage.module.scss'
 
const getResourceIcon = (cloudProvider: string) => {
  switch (cloudProvider) {
    case 'CLUSTER':
      return 'service-kubernetes'
 
    case 'AWS':
      return 'service-aws'
 
    case 'AZURE':
      return 'service-azure'
 
    case 'GCP':
      return 'gcp'
 
    /* istanbul ignore next */
    default:
      return 'harness'
  }
}
 
interface SortByObjInterface {
  sort?: sortType
  order?: orderType
}
interface ListProps {
  listData: AnomalyData[]
  sortByObj: SortByObjInterface
  setSortByObj: Dispatch<SetStateAction<SortByObjInterface>>
  timeRange: TimeRangeFilterType
}
 
interface AnomaliesMenu {
  anomalyId: string
}
 
const AnomaliesMenu: React.FC<AnomaliesMenu> = ({ anomalyId }) => {
  const { getString } = useStrings()
  const [isOpen, setIsOpen] = useState(false)
  const { accountId } = useParams<AccountPathProps>()
  const { mutate: updateAnomalyFeedback } = useReportAnomalyFeedback({
    queryParams: {
      accountIdentifier: accountId,
      anomalyId: anomalyId
    }
  })
  const { getRBACErrorMessage } = useRBACError()
  const { showError, showSuccess } = useToaster()
  const isDevFeature = useFeatureFlag(FeatureFlag.CCM_DEV_TEST)
 
  const anomalyFeedback = async () => {
    try {
      const response = await updateAnomalyFeedback({
        feedback: 'FALSE_ANOMALY'
      })
      response && showSuccess(getString('ce.anomalyDetection.userFeedbackSuccessMsg'))
    } catch (error) {
      showError(getRBACErrorMessage(error))
    }
  }
 
  return (
    <Popover
      isOpen={isOpen}
      onInteraction={nextOpenState => {
        setIsOpen(nextOpenState)
      }}
      className={Classes.DARK}
      position={Position.RIGHT_TOP}
      usePortal={false}
    >
      <Button
        minimal
        icon="Options"
        onClick={e => {
          e.stopPropagation()
          setIsOpen(true)
        }}
      />
      <Menu>
        {isDevFeature ? (
          <MenuItem
            text={getString('ce.anomalyDetection.tableMenu.whitelistResource')}
            onClick={(e: any) => {
              e.stopPropagation()
              setIsOpen(false)
            }}
          />
        ) : /* istanbul ignore next */ null}
        <MenuItem
          text={getString('ce.anomalyDetection.tableMenu.falseAnomaly')}
          onClick={(e: any) => {
            e.stopPropagation()
            setIsOpen(false)
            anomalyFeedback()
          }}
        />
      </Menu>
    </Popover>
  )
}
 
const getServerSortProps = ({
  enableServerSort,
  accessor,
  sortByObj,
  setSortByObj
}: {
  enableServerSort: boolean
  accessor: string
  sortByObj: SortByObjInterface
  setSortByObj: Dispatch<SetStateAction<SortByObjInterface>>
}): serverSortProps => {
  Iif (!enableServerSort) {
    return { enableServerSort: false }
  } else {
    let newOrder: orderType | undefined
    const sortName = accessor
 
    /* istanbul ignore next */
    if (sortName === sortByObj.sort && sortByObj.order) {
      newOrder = sortByObj.order === 'DESC' ? 'ASC' : 'DESC'
    } else {
      // no saved state for sortBy of the same sort type
      newOrder = 'ASC'
    }
 
    return {
      enableServerSort: true,
      isServerSorted: sortByObj.sort === accessor,
      isServerSortedDesc: sortByObj.order === 'DESC',
      getSortedColumn: ({ sort }: { sort?: sortType }) => {
        setSortByObj({ sort, order: newOrder })
      }
    }
  }
}
 
const AnomaliesListGridView: React.FC<ListProps> = ({ listData, sortByObj, setSortByObj, timeRange }) => {
  const { getString } = useStrings()
  const { accountId } = useParams<AccountPathProps>()
 
  const DateCell: Renderer<CellProps<AnomalyData>> = ({ row }) => {
    const timestamp = row.original.time as number
    const relativeTime = row.original.anomalyRelativeTime
 
    return (
      <Layout.Vertical spacing="small">
        <Text color={Color.BLACK} font={{ variation: FontVariation.BODY2 }}>
          {getTimePeriodString(timestamp, ANOMALIES_LIST_FORMAT)}
        </Text>
        <Text color={Color.GREY_600} font={{ variation: FontVariation.SMALL }}>
          {relativeTime}
        </Text>
      </Layout.Vertical>
    )
  }
 
  const CostCell: Renderer<CellProps<AnomalyData>> = ({ row }) => {
    const actualAmount = row.original.anomalousSpend as number
    const trend = row.original.anomalousSpendPercentage
 
    return (
      <Layout.Horizontal style={{ alignItems: 'baseline' }} spacing="small">
        <Text font={{ variation: FontVariation.BODY2 }} color={Color.BLACK}>
          {formatCost(actualAmount)}
        </Text>
        {trend ? (
          <Text font={{ variation: FontVariation.TINY }} color={Color.RED_600}>
            {getString('ce.anomalyDetection.trend', {
              trend: trend
            })}
          </Text>
        ) : /* istanbul ignore next */ null}
      </Layout.Horizontal>
    )
  }
 
  const map: Record<string, string> = {
    AZURE: 'defaultAzurePerspectiveId',
    AWS: 'defaultAwsPerspectiveId',
    GCP: 'defaultGcpPerspectiveId',
    CLUSTER: 'defaultClusterPerspectiveId'
  }
 
  const ResourceCell: Renderer<CellProps<AnomalyData>> = ({ row }) => {
    const resourceName = row.original.resourceName
    const resourceInfo = row.original.resourceInfo
    /* istanbul ignore next */
    const cloudProvider = row.original.cloudProvider || ''
 
    const [ccmMetaResult] = useFetchCcmMetaDataQuery()
    const { data: ccmData } = ccmMetaResult
    /* istanbul ignore next */
    const ccmMetaData = (ccmData?.ccmMetaData || {}) as CcmMetaData
    const mapping = map[cloudProvider]
 
    const entity = row.original.entity
 
    return (
      <Layout.Horizontal style={{ alignItems: 'center' }}>
        <Icon name={getResourceIcon(cloudProvider) as IconName} size={24} />
        <Layout.Vertical spacing="small">
          <Link
            to={{
              pathname: routes.toPerspectiveDetails({
                accountId: accountId,
                perspectiveId: ccmMetaData[mapping as keyof CcmMetaData] as string,
                perspectiveName: ccmMetaData[mapping as keyof CcmMetaData] as string
              }),
              search: `?${qs.stringify({
                filters: entity
                  ? JSON.stringify(generateFilters(entity as Record<string, string>, cloudProvider as CloudProvider))
                  : /* istanbul ignore next */
                    [],
                groupBy: JSON.stringify(
                  /* istanbul ignore next */ generateGroupBy((entity as any)?.field, cloudProvider as CloudProvider)
                ),
                timeRange: JSON.stringify(timeRange)
              })}`
            }}
          >
            <Text
              font={{ variation: FontVariation.SMALL }}
              inline
              color={Color.PRIMARY_7}
              lineClamp={1}
              style={{ maxWidth: 200 }}
            >
              {resourceName}
            </Text>
          </Link>
          <Text font={{ variation: FontVariation.SMALL }} color={Color.GREY_600}>
            {resourceInfo}
          </Text>
        </Layout.Vertical>
      </Layout.Horizontal>
    )
  }
 
  const StatusCell: Renderer<CellProps<AnomalyData>> = ({ row }) => {
    const status = row.original.status
    const stausRelativeTime = row.original.statusRelativeTime
 
    return (
      <Layout.Vertical spacing="small">
        <Text font={{ variation: FontVariation.BODY }} color={Color.ORANGE_700}>
          {status}
        </Text>
        <Text font={{ variation: FontVariation.SMALL }} color={Color.GREY_600}>
          {stausRelativeTime}
        </Text>
      </Layout.Vertical>
    )
  }
 
  const MenuCell: Renderer<CellProps<AnomalyData>> = ({ row }) => {
    return <AnomaliesMenu anomalyId={row.original.id || /* istanbul ignore next */ ''} />
  }
 
  const columns: Column<AnomalyData>[] = React.useMemo(
    () => [
      {
        Header: (
          <Text font={{ variation: FontVariation.TABLE_HEADERS }}>
            {getString('ce.anomalyDetection.tableHeaders.date')}
          </Text>
        ),
        accessor: 'time',
        Cell: DateCell,
        width: '20%',
        serverSortProps: getServerSortProps({
          enableServerSort: true,
          accessor: 'TIME',
          sortByObj,
          setSortByObj
        })
      },
      {
        Header: (
          <Text font={{ variation: FontVariation.TABLE_HEADERS }}>
            {getString('ce.anomalyDetection.tableHeaders.anomalousSpend')}
          </Text>
        ),
        accessor: 'actualAmount',
        Cell: CostCell,
        width: '20%',
        serverSortProps: getServerSortProps({
          enableServerSort: true,
          accessor: 'ACTUAL_COST',
          sortByObj,
          setSortByObj
        })
      },
      {
        Header: (
          <Text font={{ variation: FontVariation.TABLE_HEADERS }}>
            {getString('ce.anomalyDetection.tableHeaders.resource')}
          </Text>
        ),
        accessor: 'resourceName',
        Cell: ResourceCell,
        width: '35%'
      },
      {
        Header: (
          <Text font={{ variation: FontVariation.TABLE_HEADERS }}>
            {getString('ce.anomalyDetection.tableHeaders.status')}
          </Text>
        ),
        accessor: 'status',
        Cell: StatusCell,
        width: '20%',
        serverSortProps: getServerSortProps({
          enableServerSort: true,
          accessor: 'STATUS',
          sortByObj,
          setSortByObj
        })
      },
      {
        Header: ' ',
        width: '5%',
        Cell: MenuCell
      }
    ],
    [timeRange.to, timeRange.from]
  )
 
  /* istanbul ignore next */
  if (!listData.length) {
    return null
  }
 
  return (
    <TableV2
      className={css.tableView}
      columns={columns}
      data={listData}
      pagination={{
        itemCount: listData.length,
        pageCount: 0,
        pageIndex: 0,
        pageSize: 10
      }}
    />
  )
}
 
export default AnomaliesListGridView