All files / modules/85-cv/pages/slos CVSLOListingPage.utils.ts

96.13% Statements 149/155
82.56% Branches 71/86
91.67% Functions 44/48
95.76% Lines 113/118

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 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547                  13x   13x   13x                         13x 13x 13x           13x                       13x 13x   13x       13x         21x       21x             21x       21x     13x                                   1x                         13x     15x 15x   15x 13x     2x 1x     1x     13x 10x   10x                 2x                         13x               13x   13x                                                   13x 73x     13x       20x     13x       13x     13x 20x                         13x 20x                         13x       132x 6x       13x       22x 1x       13x       44x     13x               21x                       13x           21x     13x 50x     13x 21x     13x 1x     13x 44x     13x           13x   13x   84x   13x               13x       13x       13x       13x       13x         13x     13x       13x                   13x 13x   13x   1x         4x         1x         1x         3x         1x   1x         1x       13x     21x                 13x       16x 13x     3x                 13x     121x   13x       22x   22x           13x       22x   22x                               13x           22x                                       13x         22x                           13x 22x                 13x       3x               13x 63x     13x     9x   9x    
/*
 * 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 type { Dispatch, SetStateAction } from 'react'
import type QueryString from 'qs'
import moment from 'moment'
import type Highcharts from 'highcharts'
import { Utils, SelectOption } from '@wings-software/uicore'
import type { GetDataError } from 'restful-react'
import { Color } from '@harness/design-system'
import type { UseStringsReturn } from 'framework/strings'
import type { StringsMap } from 'stringTypes'
import type {
  UserJourneyResponse,
  UserJourneyDTO,
  SLODashboardWidget,
  ResponseListMonitoredServiceWithHealthSources,
  GetSLODashboardWidgetsQueryParams,
  RiskCount,
  MonitoredServiceDTO,
  GetAllJourneysQueryParams
} from 'services/cv'
import { getRiskColorValue } from '@cv/utils/CommonUtils'
import { DAYS, HOURS } from '@cv/pages/monitored-service/components/ServiceHealth/ServiceHealth.constants'
import {
  PAGE_SIZE_DASHBOARD_WIDGETS,
  LIST_USER_JOURNEYS_OFFSET,
  LIST_USER_JOURNEYS_PAGESIZE,
  SLOActionTypes
} from './CVSLOsListingPage.constants'
import {
  SLOCardToggleViews,
  GetSLOAndErrorBudgetGraphOptions,
  SLORiskFilter,
  RiskTypes,
  SLITypesParams,
  TargetTypesParams,
  SLOActionPayload,
  SLOFilterAction,
  SLOFilterState,
  SLOTargetChartWithChangeTimelineProps
} from './CVSLOsListingPage.types'
import { getUserJourneyOptions } from './components/CVCreateSLO/CVCreateSLO.utils'
import { getMonitoredServicesOptions } from './components/CVCreateSLO/components/CreateSLOForm/components/SLI/SLI.utils'
 
export const getUserJourneys = (userJourneyResponse?: UserJourneyResponse[]): UserJourneyDTO[] => {
  return userJourneyResponse?.map(response => response.userJourney) ?? []
}
 
export const getSLORiskTypeFilter = (
  getString: (key: keyof StringsMap, vars?: Record<string, any> | undefined) => string,
  riskTypes?: RiskCount[],
  totalCount?: number
): SLORiskFilter[] => {
  Iif (!riskTypes) {
    return []
  }
 
  const totalCountDetail = {
    displayName: getString('cv.slos.totalServices'),
    identifier: getString('all'),
    displayColor: Color.BLACK,
    count: totalCount
  }
 
  const riskTypesCardData = riskTypes.map(riskType => ({
    ...riskType,
    displayColor: getRiskColorValue(riskType.identifier as RiskTypes, false)
  }))
  return [totalCountDetail as SLORiskFilter, ...riskTypesCardData]
}
 
export const getErrorBudgetGaugeOptions = (serviceLevelObjective: SLODashboardWidget): Highcharts.Options => ({
  yAxis: {
    max: serviceLevelObjective.totalErrorBudget,
    tickPositions: [0, serviceLevelObjective.totalErrorBudget],
    minorTickLength: 0,
    tickLength: 0
  },
  series: [
    {
      type: 'solidgauge',
      data: [
        {
          y: serviceLevelObjective.errorBudgetRemaining,
          color: getRiskColorValue(serviceLevelObjective.errorBudgetRisk)
        }
      ],
      dataLabels: {
        formatter: function () {
          return `
            <div style="text-align:center">
              <span style="font-size:25px">
                ${Number(serviceLevelObjective.errorBudgetRemainingPercentage || 0).toFixed(2)}%
              </span>
            </div>
          `
        }
      }
    }
  ]
})
 
export const getDateUnitAndInterval = (
  serviceLevelObjective: SLODashboardWidget
): { unit: string; interval: number } => {
  const MILLISECONDS_PER_SIX_HOURS = 1000 * 60 * 60 * 6
  const timeline = serviceLevelObjective.currentPeriodLengthDays - serviceLevelObjective.timeRemainingDays
 
  /* istanbul ignore else */ if (timeline <= 1) {
    return { unit: 'Do MMM hh:mm A', interval: (MILLISECONDS_PER_SIX_HOURS * 4) / 3 }
  }
 
  /* istanbul ignore else */ if (timeline <= 3) {
    return { unit: 'Do MMM hh:mm A', interval: MILLISECONDS_PER_SIX_HOURS * timeline * 2 }
  }
 
  return { unit: 'Do MMM', interval: MILLISECONDS_PER_SIX_HOURS * timeline }
}
 
export const getPlotLines = (serviceLevelObjective: SLODashboardWidget): Highcharts.YAxisPlotLinesOptions[] => {
  const labelColor = Utils.getRealCSSColor(Color.PRIMARY_7)
 
  return [
    {
      value: Number((Number(serviceLevelObjective.sloTargetPercentage) || 0).toFixed(2)),
      color: Utils.getRealCSSColor(Color.PRIMARY_7),
      width: 2,
      zIndex: 4,
      label: {
        useHTML: true,
        formatter: function () {
          return `
          <div style="background-color:${labelColor};padding:4px 6px;border-radius:4px" >
            <span style="color:white">
              ${Number((Number(serviceLevelObjective.sloTargetPercentage) || 0).toFixed(2))}%
            </span>
          </div>
        `
        }
      }
    }
  ]
}
 
export const getSLOAndErrorBudgetGraphOptions = ({
  type,
  minXLimit,
  maxXLimit,
  serviceLevelObjective,
  startTime,
  isCardView
}: GetSLOAndErrorBudgetGraphOptions): Highcharts.Options => {
  const { unit, interval } = getDateUnitAndInterval(serviceLevelObjective)
 
  return {
    chart: { height: 200, spacing: [30, 0, 20, 0] },
    xAxis: {
      min: startTime,
      tickInterval: interval,
      tickWidth: isCardView ? 0 : 1,
      labels: {
        enabled: !isCardView,
        formatter: function () {
          return moment(new Date(this.value)).format(unit)
        }
      }
    },
    yAxis: {
      min: minXLimit,
      max: maxXLimit,
      plotLines: type === SLOCardToggleViews.SLO ? getPlotLines(serviceLevelObjective) : undefined
    },
    plotOptions: {
      area: {
        color: type === SLOCardToggleViews.ERROR_BUDGET ? Utils.getRealCSSColor(Color.RED_400) : undefined
      }
    }
  }
}
 
const getAllOption = (getString: UseStringsReturn['getString']): SelectOption => {
  return { label: getString('all'), value: getString('all') }
}
 
export const getUserJourneyOptionsForFilter = (
  userJourneyData: UserJourneyResponse[] | undefined,
  getString: UseStringsReturn['getString']
): SelectOption[] => {
  return [getAllOption(getString), ...getUserJourneyOptions(userJourneyData)]
}
 
export const getMonitoredServicesOptionsForFilter = (
  monitoredServiceData: ResponseListMonitoredServiceWithHealthSources | null,
  getString: UseStringsReturn['getString']
): SelectOption[] => {
  return [getAllOption(getString), ...getMonitoredServicesOptions(monitoredServiceData)]
}
 
export const getSliTypeOptionsForFilter = (getString: UseStringsReturn['getString']): SelectOption[] => {
  return [
    getAllOption(getString),
    {
      label: 'Availability',
      value: 'Availability'
    },
    {
      label: 'Latency',
      value: 'Latency'
    }
  ]
}
 
export const getPeriodTypeOptionsForFilter = (getString: UseStringsReturn['getString']): SelectOption[] => {
  return [
    getAllOption(getString),
    {
      label: 'Rolling',
      value: 'Rolling'
    },
    {
      label: 'Calender',
      value: 'Calender'
    }
  ]
}
 
export function getFilterValueForSLODashboardParams(
  getString: (key: keyof StringsMap, vars?: Record<string, any> | undefined) => string,
  selectedValue: SelectOption
): string[] | undefined {
  if (selectedValue.value !== getString('all')) {
    return [selectedValue.value as string]
  }
}
 
export function getRiskFilterForSLODashboardParams(
  getString: (key: keyof StringsMap, vars?: Record<string, any> | undefined) => string,
  selectedValue: string | null
): string[] | undefined {
  if (selectedValue && selectedValue !== getString('all')) {
    return [selectedValue as string]
  }
}
 
export function getMonitoredServiceSLODashboardParams(
  getString: (key: keyof StringsMap, vars?: Record<string, any> | undefined) => string,
  monitoredService: SelectOption
): string | undefined {
  return monitoredService.value !== getString('all') ? (monitoredService.value as string) : undefined
}
 
export function getIsSLODashboardAPIsLoading(
  userJourneysLoading: boolean,
  dashboardWidgetsLoading: boolean,
  deleteSLOLoading: boolean,
  monitoredServicesLoading: boolean,
  riskCountLoading: boolean,
  resetErrorBudgetLoading: boolean
): boolean {
  return (
    userJourneysLoading ||
    dashboardWidgetsLoading ||
    deleteSLOLoading ||
    monitoredServicesLoading ||
    riskCountLoading ||
    resetErrorBudgetLoading
  )
}
 
type ErrorType = GetDataError<unknown> | null
// Sonar recommendation
export const getErrorObject = (
  dashboardWidgetsError: ErrorType,
  userJourneysError: ErrorType,
  dashboardRiskCountError: ErrorType,
  monitoredServicesDataError: ErrorType
): ErrorType => {
  return dashboardWidgetsError || userJourneysError || dashboardRiskCountError || monitoredServicesDataError
}
 
export const getIsDataEmpty = (contentLength?: number, riskCounts?: RiskCount[]): boolean => {
  return !contentLength && isRiskCountEmptyForEveryCategory(riskCounts)
}
 
export const getIsWidgetDataEmpty = (contentLength?: number, dashboardWidgetsLoading?: boolean): boolean => {
  return !contentLength && !dashboardWidgetsLoading
}
 
export const getIsSetPreviousPage = (pageIndex: number, pageItemCount: number): boolean => {
  return Boolean(pageIndex) && pageItemCount === 1
}
 
export function isRiskCountEmptyForEveryCategory(riskCounts?: RiskCount[]): boolean {
  return !!riskCounts?.every((el: RiskCount) => el.count === 0)
}
 
export function setFilterValue<T>(callback: Dispatch<SetStateAction<T>>, value: T): void {
  if (value) {
    callback(value)
  }
}
 
const defaultAllOption: SelectOption = { label: 'All', value: 'All' }
 
const getDefaultAllOption = (
  getString: (key: keyof StringsMap, vars?: Record<string, any> | undefined) => string
): SelectOption => ({ label: getString('all'), value: getString('all') })
 
export const initialState: SLOFilterState = {
  userJourney: defaultAllOption,
  monitoredService: defaultAllOption,
  sliTypes: defaultAllOption,
  targetTypes: defaultAllOption,
  sloRiskFilter: null
}
 
const updateUserJourney = (payload: SLOActionPayload): SLOFilterAction => ({
  type: SLOActionTypes.userJourney,
  payload
})
const updateMonitoredServices = (payload: SLOActionPayload): SLOFilterAction => ({
  type: SLOActionTypes.monitoredService,
  payload
})
const updateSliType = (payload: SLOActionPayload): SLOFilterAction => ({
  type: SLOActionTypes.sliTypes,
  payload
})
const updateTargetType = (payload: SLOActionPayload): SLOFilterAction => ({
  type: SLOActionTypes.targetTypes,
  payload
})
const updateSloRiskType = (payload: SLOActionPayload): SLOFilterAction => ({
  type: SLOActionTypes.sloRiskFilterAction,
  payload
})
 
const resetFilters = (): SLOFilterAction => ({
  type: SLOActionTypes.reset
})
const resetFiltersInMonitoredServicePageAction = (): SLOFilterAction => ({
  type: SLOActionTypes.resetFiltersInMonitoredServicePage
})
 
export const SLODashboardFilterActions = {
  updateUserJourney,
  updateMonitoredServices,
  updateSliType,
  updateTargetType,
  updateSloRiskType,
  resetFilters,
  resetFiltersInMonitoredServicePageAction
}
 
export const sloFilterReducer = (state = initialState, data: SLOFilterAction): SLOFilterState => {
  const { payload = {} } = data
 
  switch (data.type) {
    case SLOActionTypes.userJourney:
      return {
        ...state,
        userJourney: payload.userJourney as SelectOption
      }
    case SLOActionTypes.monitoredService:
      return {
        ...state,
        monitoredService: payload.monitoredService as SelectOption
      }
    case SLOActionTypes.sliTypes:
      return {
        ...state,
        sliTypes: payload.sliTypes as SelectOption
      }
    case SLOActionTypes.targetTypes:
      return {
        ...state,
        targetTypes: payload.targetTypes as SelectOption
      }
    case SLOActionTypes.sloRiskFilterAction:
      return {
        ...state,
        sloRiskFilter: payload.sloRiskFilter as SLORiskFilter | null
      }
    case SLOActionTypes.reset:
      return initialState
    case SLOActionTypes.resetFiltersInMonitoredServicePage:
      return {
        ...initialState,
        monitoredService: state.monitoredService
      }
    default:
      return initialState
  }
}
 
export const getInitialFilterState = (
  getString: (key: keyof StringsMap, vars?: Record<string, any> | undefined) => string
): SLOFilterState => {
  return {
    userJourney: getDefaultAllOption(getString),
    monitoredService: getDefaultAllOption(getString),
    sliTypes: getDefaultAllOption(getString),
    targetTypes: getDefaultAllOption(getString),
    sloRiskFilter: null
  }
}
 
export const getInitialFilterStateLazy = (
  defaultInitialState: SLOFilterState,
  monitoredServiceData?: Pick<MonitoredServiceDTO, 'name' | 'identifier'>
): SLOFilterState => {
  if (!monitoredServiceData) {
    return defaultInitialState
  }
 
  return {
    ...defaultInitialState,
    monitoredService: {
      label: monitoredServiceData.name,
      value: monitoredServiceData.identifier
    }
  }
}
 
const getIsFiltersUnchanged = (
  filters: (string | number | symbol)[],
  getString: (key: keyof StringsMap, vars?: Record<string, any> | undefined) => string
): boolean => filters.every(value => value === getString('all'))
 
export const getIsClearFilterDisabled = (
  filterState: SLOFilterState,
  getString: (key: keyof StringsMap, vars?: Record<string, any> | undefined) => string
): boolean => {
  const { monitoredService, sliTypes, sloRiskFilter, targetTypes, userJourney } = filterState
 
  return (
    getIsFiltersUnchanged([monitoredService.value, sliTypes.value, targetTypes.value, userJourney.value], getString) &&
    sloRiskFilter === null
  )
}
 
export const getIsMonitoresServicePageClearFilterDisabled = (
  filterState: SLOFilterState,
  getString: (key: keyof StringsMap, vars?: Record<string, any> | undefined) => string
): boolean => {
  const { sliTypes, sloRiskFilter, targetTypes, userJourney } = filterState
 
  return (
    getIsFiltersUnchanged([sliTypes.value, targetTypes.value, userJourney.value], getString) && sloRiskFilter === null
  )
}
 
interface SLODashboardWidgetsParams {
  queryParams: GetSLODashboardWidgetsQueryParams
  queryParamStringifyOptions: QueryString.IStringifyOptions
}
 
interface PathParams {
  accountId: string
  orgIdentifier: string
  projectIdentifier: string
}
 
export const getSLODashboardWidgetsParams = (
  pathParams: PathParams,
  getString: (key: keyof StringsMap, vars?: Record<string, any> | undefined) => string,
  filterState: SLOFilterState,
  pageNumber?: number
): SLODashboardWidgetsParams => {
  return {
    queryParams: {
      ...pathParams,
      monitoredServiceIdentifier: getMonitoredServiceSLODashboardParams(getString, filterState.monitoredService),
      pageNumber,
      pageSize: PAGE_SIZE_DASHBOARD_WIDGETS,
      userJourneyIdentifiers: getFilterValueForSLODashboardParams(getString, filterState.userJourney),
      targetTypes: getFilterValueForSLODashboardParams(getString, filterState.targetTypes) as TargetTypesParams[],
      sliTypes: getFilterValueForSLODashboardParams(getString, filterState.sliTypes) as SLITypesParams[],
      errorBudgetRisks: getRiskFilterForSLODashboardParams(
        getString,
        filterState.sloRiskFilter?.identifier as string | null
      ) as RiskTypes[]
    },
    queryParamStringifyOptions: {
      arrayFormat: 'repeat'
    }
  }
}
 
export const getServiceLevelObjectivesRiskCountParams = (
  pathParams: PathParams,
  getString: (key: keyof StringsMap, vars?: Record<string, any> | undefined) => string,
  filterState: SLOFilterState
): SLODashboardWidgetsParams => {
  return {
    queryParams: {
      ...pathParams,
      monitoredServiceIdentifier: getMonitoredServiceSLODashboardParams(getString, filterState.monitoredService),
      userJourneyIdentifiers: getFilterValueForSLODashboardParams(getString, filterState.userJourney),
      targetTypes: getFilterValueForSLODashboardParams(getString, filterState.targetTypes) as TargetTypesParams[],
      sliTypes: getFilterValueForSLODashboardParams(getString, filterState.sliTypes) as SLITypesParams[]
    },
    queryParamStringifyOptions: {
      arrayFormat: 'repeat'
    }
  }
}
 
export const getUserJourneyParams = (pathParams: PathParams): { queryParams: GetAllJourneysQueryParams } => {
  return {
    queryParams: {
      ...pathParams,
      offset: LIST_USER_JOURNEYS_OFFSET,
      pageSize: LIST_USER_JOURNEYS_PAGESIZE
    }
  }
}
 
export const getMonitoredServicesInitialState = (monitoredService: {
  name: string
  identifier: string
}): { monitoredService: SelectOption } => {
  return {
    monitoredService: {
      label: monitoredService.name,
      value: monitoredService.identifier
    }
  }
}
 
export const getClassNameForMonitoredServicePage = (className: string, isMonitoredServicePage?: string): string => {
  return isMonitoredServicePage ? className : ''
}
 
export const getTimeFormatForAnomaliesCard = (
  sliderTimeRange: SLOTargetChartWithChangeTimelineProps['sliderTimeRange']
): string => {
  const diff = moment(sliderTimeRange?.endTime).diff(moment(sliderTimeRange?.startTime), 'days')
 
  return diff < 2 ? HOURS : DAYS
}