All files / modules/85-cv/pages/slos CVSLOsListingPage.tsx

87.95% Statements 73/83
88.98% Branches 105/118
87.5% Functions 14/16
89.02% Lines 73/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              10x 10x 10x                           10x 10x 10x 10x 10x 10x 10x 10x   10x 10x                   10x 10x 10x   10x                                 10x 10x 10x 10x   10x 21x 21x 21x 21x   21x 16x     21x 16x 3x     21x   21x 16x     21x 16x                       21x             21x                 21x                     21x             21x   21x       21x 1x 1x 1x     1x   1x 1x           21x         21x                     21x 42x         2x                               21x 2x 2x 2x 1x   1x       21x 16x       21x                                                           3x 2x   3x 2x   3x       3x         33x                                                           36x                 7x                                                             10x  
/*
 * 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, useState, useMemo, useReducer } from 'react'
import { useHistory, useParams } from 'react-router-dom'
import {
  useToaster,
  ButtonVariation,
  CardSelect,
  CardSelectType,
  Card,
  NoDataCard,
  Pagination,
  Layout,
  FlexExpander,
  Container,
  Heading,
  HarnessDocTooltip
} from '@wings-software/uicore'
import { FontVariation } from '@harness/design-system'
import noData from '@cv/assets/noData.svg'
import slosEmptyState from '@cv/assets/slosEmptyState.svg'
import { Page } from '@common/exports'
import routes from '@common/RouteDefinitions'
import { useStrings } from 'framework/strings'
import { ResourceType } from '@rbac/interfaces/ResourceType'
import { PermissionIdentifier } from '@rbac/interfaces/PermissionIdentifier'
import type { ProjectPathProps } from '@common/interfaces/RouteInterfaces'
import { NGBreadcrumbs } from '@common/components/NGBreadcrumbs/NGBreadcrumbs'
import {
  useDeleteSLOData,
  useGetAllJourneys,
  useGetAllMonitoredServicesWithTimeSeriesHealthSources,
  useGetSLODashboardWidgets,
  useGetServiceLevelObjectivesRiskCount,
  RiskCount,
  useResetErrorBudget,
  SLOErrorBudgetResetDTO
} from 'services/cv'
import RbacButton from '@rbac/components/Button/Button'
import { getErrorMessage } from '@cv/utils/CommonUtils'
import SLOCardSelect from './components/SLOCardSelect/SLOCardSelect'
import type { CVSLOsListingPageProps, SLORiskFilter } from './CVSLOsListingPage.types'
import {
  getErrorObject,
  getIsSLODashboardAPIsLoading,
  getSLORiskTypeFilter,
  getIsWidgetDataEmpty,
  getIsDataEmpty,
  getIsSetPreviousPage,
  sloFilterReducer,
  SLODashboardFilterActions,
  getInitialFilterStateLazy,
  getSLODashboardWidgetsParams,
  getServiceLevelObjectivesRiskCountParams,
  getUserJourneyParams,
  getMonitoredServicesInitialState,
  getInitialFilterState,
  getClassNameForMonitoredServicePage
} from './CVSLOListingPage.utils'
import SLODashbordFilters from './components/SLODashbordFilters/SLODashbordFilters'
import SLOCardHeader from './SLOCard/SLOCardHeader'
import SLOCardContent from './SLOCard/SLOCardContent'
import css from './CVSLOsListingPage.module.scss'
 
const CVSLOsListingPage: React.FC<CVSLOsListingPageProps> = ({ monitoredService }) => {
  const history = useHistory()
  const { getString } = useStrings()
  const { showError, showSuccess } = useToaster()
  const { accountId, orgIdentifier, projectIdentifier } = useParams<ProjectPathProps>()
 
  const [filterState, dispatch] = useReducer(sloFilterReducer, getInitialFilterState(getString), passedInitialState =>
    getInitialFilterStateLazy(passedInitialState, monitoredService)
  )
 
  useEffect(() => {
    if (monitoredService?.identifier) {
      dispatch(SLODashboardFilterActions.updateMonitoredServices(getMonitoredServicesInitialState(monitoredService)))
    }
  }, [monitoredService])
  const [pageNumber, setPageNumber] = useState(0)
 
  useEffect(() => {
    setPageNumber(0)
  }, [projectIdentifier])
 
  const pathParams = useMemo(() => {
    return {
      accountId,
      orgIdentifier,
      projectIdentifier
    }
  }, [accountId, orgIdentifier, projectIdentifier])
 
  const {
    data: dashboardWidgetsResponse,
    loading: dashboardWidgetsLoading,
    refetch: refetchDashboardWidgets,
    error: dashboardWidgetsError
  } = useGetSLODashboardWidgets(getSLODashboardWidgetsParams(pathParams, getString, filterState, pageNumber))
 
  const {
    data: riskCountResponse,
    loading: riskCountLoading,
    refetch: refetchRiskCount,
    error: dashboardRiskCountError
  } = useGetServiceLevelObjectivesRiskCount(
    getServiceLevelObjectivesRiskCountParams(pathParams, getString, filterState)
  )
 
  const {
    data: monitoredServicesData,
    loading: monitoredServicesLoading,
    error: monitoredServicesDataError,
    refetch: refetchMonitoredServicesData
  } = useGetAllMonitoredServicesWithTimeSeriesHealthSources({
    queryParams: pathParams
  })
 
  const {
    content,
    totalItems = 0,
    totalPages = 0,
    pageIndex = 0,
    pageItemCount = 0,
    pageSize = 10
  } = dashboardWidgetsResponse?.data ?? {}
 
  const {
    data: userJourneysData,
    loading: userJourneysLoading,
    error: userJourneysError,
    refetch: refetchUserJourneys
  } = useGetAllJourneys(getUserJourneyParams(pathParams))
 
  const { mutate: deleteSLO, loading: deleteSLOLoading } = useDeleteSLOData({
    queryParams: pathParams
  })
 
  const onDelete = async (identifier: string, name: string): Promise<void> => {
    try {
      await deleteSLO(identifier)
      Iif (getIsSetPreviousPage(pageIndex, pageItemCount)) {
        setPageNumber(prevPageNumber => prevPageNumber - 1)
      } else {
        await refetchDashboardWidgets()
      }
      await refetchRiskCount()
      showSuccess(getString('cv.slos.sloDeleted', { name }))
    } catch (e) {
      showError(getErrorMessage(e))
    }
  }
 
  const { mutate: resetErrorBudget, loading: resetErrorBudgetLoading } = useResetErrorBudget({
    identifier: '',
    queryParams: pathParams
  })
 
  const onResetErrorBudget = async (identifier: string, formData: SLOErrorBudgetResetDTO): Promise<void> => {
    try {
      await resetErrorBudget(formData, { pathParams: { identifier } })
      await Promise.all([refetchDashboardWidgets(), refetchRiskCount()])
 
      showSuccess(getString('cv.errorBudgetIsSuccessfullyReset'))
    } catch (e) {
      showError(getErrorMessage(e))
    }
  }
 
  const getAddSLOButton = (): JSX.Element => (
    <RbacButton
      icon="plus"
      text={getString('cv.slos.createSLO')}
      variation={ButtonVariation.PRIMARY}
      onClick={() => {
        history.push({
          pathname: routes.toCVCreateSLOs({ accountId, orgIdentifier, projectIdentifier, module: 'cv' }),
          search: monitoredService?.identifier ? `?monitoredServiceIdentifier=${monitoredService.identifier}` : ''
        })
      }}
      className={getClassNameForMonitoredServicePage(css.createSloInMonitoredService, monitoredService?.identifier)}
      permission={{
        permission: PermissionIdentifier.EDIT_SLO_SERVICE,
        resource: {
          resourceType: ResourceType.SLO,
          resourceIdentifier: projectIdentifier
        }
      }}
    />
  )
 
  const onFilter = (currentRiskFilter: SLORiskFilter): void => {
    setPageNumber(0)
    const { updateSloRiskType } = SLODashboardFilterActions
    if (filterState.sloRiskFilter?.identifier === currentRiskFilter.identifier) {
      dispatch(updateSloRiskType({ sloRiskFilter: null }))
    } else {
      dispatch(updateSloRiskType({ sloRiskFilter: currentRiskFilter }))
    }
  }
 
  const filterItemsData = useMemo(
    () => ({ userJourney: userJourneysData, monitoredServices: monitoredServicesData }),
    [userJourneysData, monitoredServicesData]
  )
 
  return (
    <>
      {!monitoredService?.identifier && !getIsDataEmpty(content?.length, riskCountResponse?.data?.riskCounts) && (
        <>
          <Page.Header
            breadcrumbs={<NGBreadcrumbs />}
            title={
              <Heading level={3} font={{ variation: FontVariation.H4 }}>
                {getString('cv.slos.title')}
                <HarnessDocTooltip tooltipId={'sloDashboardTitle'} useStandAlone />
              </Heading>
            }
          />
          <Page.Header title={getAddSLOButton()} />
        </>
      )}
 
      <Page.Body
        loading={getIsSLODashboardAPIsLoading(
          userJourneysLoading,
          dashboardWidgetsLoading,
          deleteSLOLoading,
          monitoredServicesLoading,
          riskCountLoading,
          resetErrorBudgetLoading
        )}
        error={getErrorMessage(
          getErrorObject(dashboardWidgetsError, userJourneysError, dashboardRiskCountError, monitoredServicesDataError)
        )}
        retryOnError={() => {
          if (dashboardWidgetsError) {
            refetchDashboardWidgets()
          }
          if (userJourneysError) {
            refetchUserJourneys()
          }
          Iif (monitoredServicesDataError) {
            refetchMonitoredServicesData()
          }
 
          Iif (dashboardRiskCountError) {
            refetchRiskCount()
          }
        }}
        noData={{
          when: () => getIsDataEmpty(content?.length, riskCountResponse?.data?.riskCounts),
          messageTitle: getString('cv.slos.noData'),
          message: getString('cv.slos.noSLOsStateMessage'),
          button: getAddSLOButton(),
          image: slosEmptyState
        }}
        className={css.pageBody}
      >
        <Layout.Vertical height="100%" padding={{ top: 'medium', left: 'xlarge', right: 'xlarge', bottom: 'xlarge' }}>
          <Layout.Horizontal className={css.sloFiltersRow1}>
            {monitoredService?.identifier && getAddSLOButton()}
            <Container
              className={getClassNameForMonitoredServicePage(css.sloDropdownFilters, monitoredService?.identifier)}
            >
              <SLODashbordFilters
                filterState={filterState}
                dispatch={dispatch}
                filterItemsData={filterItemsData}
                hideMonitoresServicesFilter={Boolean(monitoredService)}
              />
            </Container>
          </Layout.Horizontal>
          <CardSelect<SLORiskFilter>
            type={CardSelectType.CardView}
            data={getSLORiskTypeFilter(
              getString,
              riskCountResponse?.data?.riskCounts as RiskCount[] | undefined,
              riskCountResponse?.data?.totalCount
            )}
            cardClassName={css.sloRiskFilterCard}
            renderItem={({ ...props }) => <SLOCardSelect key={props.identifier} {...props} />}
            selected={filterState.sloRiskFilter as SLORiskFilter}
            onChange={onFilter}
          />
          <hr />
          {!!content?.length && (
            <>
              <div className={css.sloCardContainer} data-testid="slo-card-container">
                {content.map(serviceLevelObjective => (
                  <Card key={serviceLevelObjective.sloIdentifier} className={css.sloCard}>
                    <SLOCardHeader
                      onDelete={onDelete}
                      onResetErrorBudget={onResetErrorBudget}
                      serviceLevelObjective={serviceLevelObjective}
                      monitoredServiceIdentifier={monitoredService?.identifier}
                    />
                    <SLOCardContent serviceLevelObjective={serviceLevelObjective} />
                  </Card>
                ))}
              </div>
              <FlexExpander />
              <Pagination
                itemCount={totalItems}
                pageCount={totalPages}
                pageIndex={pageIndex}
                pageSize={pageSize}
                gotoPage={setPageNumber}
              />
            </>
          )}
 
          {getIsWidgetDataEmpty(content?.length, dashboardWidgetsLoading) && (
            <NoDataCard image={noData} message={getString('cv.slos.noMatchingData')} />
          )}
        </Layout.Vertical>
      </Page.Body>
    </>
  )
}
 
export default CVSLOsListingPage