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

97.6% Statements 122/125
84.58% Branches 203/240
92.59% Functions 25/27
97.22% Lines 105/108

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              13x   13x   13x                               13x 13x                       13x 66x 66x 66x     66x                             13x       20x         14x 14x 14x 14x   14x                                     6x     13x         30x                                                                                 13x 26x 19x 19x 19x 19x   19x   19x 4x       22x 7x 7x 7x 7x 7x 7x 7x                     7x   7x                   2x       20x     13x         5x   2x 2x     2x   2x 1x   2x     1x             13x 43x 41x                 13x     19x 20x             13x 20x 1x                 13x 28x 22x             13x 28x 2x     26x         13x 13x           13x 3x                               13x                       13x 10x   310x     13x 1x   31x     13x 20x   20x 3x     17x 17x   17x 9x 8x 1x 7x 1x 6x 4x     17x     13x 12x   12x                                                           13x 42x                                     13x 6x   6x   6x                                     13x       3x 3x 3x    
/*
 * 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 { omit, isEqual } from 'lodash-es'
import type { TabId } from '@blueprintjs/core'
import { SelectOption, Utils } from '@wings-software/uicore'
import type { FormikProps } from 'formik'
import { Color } from '@harness/design-system'
import type { UseStringsReturn, StringKeys } from 'framework/strings'
import type {
  ServiceLevelObjectiveDTO,
  ThresholdSLIMetricSpec,
  RatioSLIMetricSpec,
  CalenderSLOTargetSpec,
  MonthlyCalenderSpec,
  WeeklyCalendarSpec,
  RollingSLOTargetSpec,
  UserJourneyResponse,
  MonitoredServiceWithHealthSources,
  MetricDTO,
  ServiceLevelIndicatorDTO,
  MonitoredServiceDTO
} from 'services/cv'
import { initialValuesSLO } from './CVCreateSLO.constants'
import {
  SLIForm,
  SLOForm,
  PeriodTypes,
  PeriodLengthTypes,
  Days,
  CreateSLOTabs,
  SLOFormFields,
  SLIMetricTypes,
  Comparators
} from './CVCreateSLO.types'
 
export const convertServiceLevelIndicatorToSLIFormData = (serviceLevelIndicator: ServiceLevelIndicatorDTO): SLIForm => {
  const { type: SLIType, name, identifier, healthSourceRef, sliMissingDataType, spec } = serviceLevelIndicator
  const { type: SLIMetricType, spec: SLIMetricSpec } = spec
  const { eventType, metric1, metric2, thresholdValue, thresholdType } = SLIMetricSpec as ThresholdSLIMetricSpec &
    RatioSLIMetricSpec
 
  return {
    name,
    identifier,
    healthSourceRef,
    SLIType,
    SLIMetricType,
    eventType,
    validRequestMetric: metric1,
    goodRequestMetric: metric2,
    objectiveValue: thresholdValue,
    objectiveComparator: thresholdType,
    SLIMissingDataType: sliMissingDataType
  }
}
 
export const getSLOInitialFormData = (
  serviceLevelObjective?: ServiceLevelObjectiveDTO,
  monitoredServiceIdentifier?: string
): SLOForm => {
  if (serviceLevelObjective) {
    const {
      serviceLevelIndicators: [serviceLevelIndicator],
      target,
      ...rest
    } = serviceLevelObjective
    const SLIMetricSpec = serviceLevelIndicator?.spec.spec as (ThresholdSLIMetricSpec & RatioSLIMetricSpec) | undefined
    const targetSpec = target.spec as (CalenderSLOTargetSpec & RollingSLOTargetSpec) | undefined
    const periodLengthTypeSpec = targetSpec?.spec as (MonthlyCalenderSpec & WeeklyCalendarSpec) | undefined
 
    return {
      ...omit(rest, ['orgIdentifier', 'projectIdentifier']),
      SLIType: serviceLevelIndicator?.type,
      SLIMetricType: serviceLevelIndicator?.spec.type,
      eventType: SLIMetricSpec?.eventType,
      validRequestMetric: SLIMetricSpec?.metric1 ?? '',
      goodRequestMetric: SLIMetricSpec?.metric2,
      objectiveValue: SLIMetricSpec?.thresholdValue,
      objectiveComparator: SLIMetricSpec?.thresholdType,
      SLIMissingDataType: serviceLevelIndicator?.sliMissingDataType,
      periodType: target.type,
      periodLength: targetSpec?.periodLength,
      periodLengthType: targetSpec?.type,
      dayOfWeek: periodLengthTypeSpec?.dayOfWeek,
      dayOfMonth: periodLengthTypeSpec?.dayOfMonth?.toString(),
      SLOTargetPercentage: target.sloTargetPercentage
    }
  }
 
  return { ...initialValuesSLO, [SLOFormFields.MONITORED_SERVICE_REF]: monitoredServiceIdentifier || '' }
}
 
export const createSLORequestPayload = (
  values: SLOForm,
  orgIdentifier: string,
  projectIdentifier: string
): ServiceLevelObjectiveDTO => {
  return {
    name: values.name,
    identifier: values.identifier,
    description: values.description,
    tags: values.tags,
    userJourneyRef: values.userJourneyRef,
    monitoredServiceRef: values.monitoredServiceRef,
    healthSourceRef: values.healthSourceRef,
    orgIdentifier,
    projectIdentifier,
    serviceLevelIndicators: [
      {
        type: values.SLIType,
        sliMissingDataType: values.SLIMissingDataType,
        spec: {
          type: values.SLIMetricType,
          spec: {
            eventType: values.SLIMetricType === SLIMetricTypes.RATIO ? values.eventType : undefined,
            metric1: values.validRequestMetric,
            metric2: values.SLIMetricType === SLIMetricTypes.RATIO ? values.goodRequestMetric : undefined,
            thresholdValue: values.objectiveValue,
            thresholdType: values.objectiveComparator
          } as ThresholdSLIMetricSpec | RatioSLIMetricSpec
        }
      }
    ],
    target: {
      type: values.periodType,
      sloTargetPercentage: values.SLOTargetPercentage,
      spec: {
        type: values.periodLengthType,
        periodLength: values.periodType === PeriodTypes.ROLLING ? values.periodLength : undefined,
        spec: {
          dayOfWeek: values.periodLengthType === PeriodLengthTypes.WEEKLY ? values.dayOfWeek : undefined,
          dayOfMonth: values.periodLengthType === PeriodLengthTypes.MONTHLY ? values.dayOfMonth : undefined
        } as MonthlyCalenderSpec | WeeklyCalendarSpec
      } as CalenderSLOTargetSpec | RollingSLOTargetSpec
    }
  }
}
 
export const isFormDataValid = (formikProps: FormikProps<SLOForm>, selectedTabId: CreateSLOTabs): boolean => {
  if (selectedTabId === CreateSLOTabs.NAME) {
    formikProps.setFieldTouched(SLOFormFields.NAME)
    formikProps.setFieldTouched(SLOFormFields.IDENTIFIER)
    formikProps.setFieldTouched(SLOFormFields.USER_JOURNEY_REF)
    formikProps.setFieldTouched(SLOFormFields.MONITORED_SERVICE_REF)
 
    const { name, identifier, userJourneyRef } = formikProps.values
 
    if (!name || !identifier || !userJourneyRef) {
      return false
    }
  }
 
  if (selectedTabId === CreateSLOTabs.SLI) {
    formikProps.setFieldTouched(SLOFormFields.HEALTH_SOURCE_REF)
    formikProps.setFieldTouched(SLOFormFields.EVENT_TYPE)
    formikProps.setFieldTouched(SLOFormFields.GOOD_REQUEST_METRIC)
    formikProps.setFieldTouched(SLOFormFields.VALID_REQUEST_METRIC)
    formikProps.setFieldTouched(SLOFormFields.OBJECTIVE_VALUE)
    formikProps.setFieldTouched(SLOFormFields.OBJECTIVE_COMPARATOR)
    formikProps.setFieldTouched(SLOFormFields.SLI_MISSING_DATA_TYPE)
 
    const {
      healthSourceRef,
      monitoredServiceRef,
      eventType,
      goodRequestMetric,
      validRequestMetric,
      objectiveValue,
      objectiveComparator,
      SLIMissingDataType
    } = formikProps.errors
 
    if (
      healthSourceRef ||
      monitoredServiceRef ||
      eventType ||
      goodRequestMetric ||
      validRequestMetric ||
      objectiveValue ||
      objectiveComparator ||
      SLIMissingDataType
    ) {
      return false
    }
  }
 
  return true
}
 
export const handleTabChange = (
  nextTabId: TabId,
  formik: FormikProps<SLOForm>,
  setSelectedTabId: (tabId: CreateSLOTabs) => void
): void => {
  switch (nextTabId) {
    case CreateSLOTabs.SLI: {
      isFormDataValid(formik, CreateSLOTabs.NAME) && setSelectedTabId(CreateSLOTabs.SLI)
      break
    }
    case CreateSLOTabs.SLO_TARGET_BUDGET_POLICY: {
      Iif (isFormDataValid(formik, CreateSLOTabs.NAME) && isFormDataValid(formik, CreateSLOTabs.SLI)) {
        setSelectedTabId(CreateSLOTabs.SLO_TARGET_BUDGET_POLICY)
      } else if (isFormDataValid(formik, CreateSLOTabs.NAME)) {
        setSelectedTabId(CreateSLOTabs.SLI)
      }
      break
    }
    default: {
      setSelectedTabId(CreateSLOTabs.NAME)
    }
  }
}
 
// SLO Name
 
export const getUserJourneyOptions = (userJourneyResponse?: UserJourneyResponse[]): SelectOption[] => {
  return (
    userJourneyResponse?.map(userJourney => ({
      label: userJourney.userJourney.name,
      value: userJourney.userJourney.identifier
    })) ?? []
  )
}
 
// SLI
 
export function getMonitoredServiceOptions(
  monitoredServiceWithHealthSources?: MonitoredServiceWithHealthSources[]
): SelectOption[] {
  return (
    monitoredServiceWithHealthSources?.map(monitoredService => ({
      label: monitoredService.name ?? '',
      value: monitoredService.identifier ?? ''
    })) ?? []
  )
}
 
export function getHealthSourceOptions(monitoredService?: MonitoredServiceDTO): SelectOption[] {
  return (
    monitoredService?.sources?.healthSources?.map(healthSource => ({
      label: healthSource?.name ?? '',
      value: healthSource?.identifier ?? ''
    })) ?? []
  )
}
 
// PickMetric
 
export const getSLOMetricOptions = (SLOMetricList?: MetricDTO[]): SelectOption[] => {
  return (
    SLOMetricList?.map(metric => ({
      label: metric.metricName ?? '',
      value: metric.identifier ?? ''
    })) ?? []
  )
}
 
export const getComparatorSuffixLabelId = (comparator?: ThresholdSLIMetricSpec['thresholdType']): StringKeys => {
  if (comparator === Comparators.LESS_EQUAL || comparator === Comparators.GREATER_EQUAL) {
    return 'cv.toObjectiveValue'
  }
 
  return 'cv.thanObjectiveValue'
}
 
// SLOTargetAndBudgetPolicy
 
export const getPeriodTypeOptions = (getString: UseStringsReturn['getString']): SelectOption[] => {
  return [
    { label: getString('cv.slos.sloTargetAndBudget.periodTypeOptions.rolling'), value: PeriodTypes.ROLLING },
    { label: getString('cv.slos.sloTargetAndBudget.periodTypeOptions.calendar'), value: PeriodTypes.CALENDAR }
  ]
}
 
export const getPeriodLengthOptions = (getString: UseStringsReturn['getString']): SelectOption[] => {
  return [
    {
      label: getString('triggers.schedulePanel.weeklyTabTitle'),
      value: PeriodLengthTypes.WEEKLY
    },
    {
      label: getString('common.monthly'),
      value: PeriodLengthTypes.MONTHLY
    },
    {
      label: getString('cv.quarterly'),
      value: PeriodLengthTypes.QUARTERLY
    }
  ]
}
 
export const getWindowEndOptionsForWeek = (getString: UseStringsReturn['getString']): SelectOption[] => {
  return [
    { label: getString('cv.monday'), value: Days.MONDAY },
    { label: getString('cv.tuesday'), value: Days.TUESDAY },
    { label: getString('cv.wednesday'), value: Days.WEDNESDAY },
    { label: getString('cv.thursday'), value: Days.THURSDAY },
    { label: getString('cv.friday'), value: Days.FRIDAY },
    { label: getString('cv.saturday'), value: Days.SATURDAY },
    { label: getString('cv.sunday'), value: Days.SUNDAY }
  ]
}
 
export const getPeriodLengthOptionsForRolling = (): SelectOption[] => {
  return Array(31)
    .fill(0)
    .map((_, i) => ({ label: `${i + 1}`, value: `${i + 1}d` }))
}
 
export const getWindowEndOptionsForMonth = (): SelectOption[] => {
  return Array(31)
    .fill(0)
    .map((_, i) => ({ label: `${i + 1}`, value: `${i + 1}` }))
}
 
export const getErrorBudget = (values: SLOForm): number => {
  const { periodType, periodLength = '', periodLengthType, SLOTargetPercentage } = values
 
  if (Number.isNaN(SLOTargetPercentage) || SLOTargetPercentage < 0 || SLOTargetPercentage > 100) {
    return 0
  }
 
  const minutesPerDay = 60 * 24
  let totalMinutes = 0
 
  if (periodType === PeriodTypes.ROLLING && Number.parseInt(periodLength)) {
    totalMinutes = Number.parseInt(periodLength) * minutesPerDay
  } else if (periodLengthType === PeriodLengthTypes.WEEKLY) {
    totalMinutes = 7 * minutesPerDay
  } else if (periodLengthType === PeriodLengthTypes.MONTHLY) {
    totalMinutes = 30 * minutesPerDay
  } else if (periodLengthType === PeriodLengthTypes.QUARTERLY) {
    totalMinutes = 90 * minutesPerDay
  }
 
  return Math.round(((100 - SLOTargetPercentage) / 100) * totalMinutes)
}
 
export const getCustomOptionsForSLOTargetChart = (values: SLOForm): Highcharts.Options => {
  const labelColor = Utils.getRealCSSColor(Color.PRIMARY_7)
 
  return {
    chart: { height: 200 },
    yAxis: {
      min: 0,
      max: 100,
      tickInterval: 25,
      plotLines: [
        {
          value: Number((Number(values.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(values.SLOTargetPercentage) || 0).toFixed(2))}%</span>
                </div>
              `
            }
          }
        }
      ]
    }
  }
}
 
//
 
export const convertSLOFormDataToServiceLevelIndicatorDTO = (values: SLOForm): ServiceLevelIndicatorDTO => {
  return {
    name: values.name,
    identifier: values.identifier,
    type: values.SLIType,
    healthSourceRef: values.healthSourceRef,
    sliMissingDataType: values.SLIMissingDataType,
    spec: {
      type: values.SLIMetricType,
      spec: {
        eventType: values.SLIMetricType === SLIMetricTypes.RATIO ? values.eventType : undefined,
        metric2: values.SLIMetricType === SLIMetricTypes.RATIO ? values.goodRequestMetric : undefined,
        metric1: values.validRequestMetric,
        thresholdValue: values.objectiveValue,
        thresholdType: values.objectiveComparator
      } as ThresholdSLIMetricSpec & RatioSLIMetricSpec
    }
  }
}
 
const getVerifyData = (data: ServiceLevelObjectiveDTO): any => {
  const { monitoredServiceRef, healthSourceRef, serviceLevelIndicators, target } = data
 
  const { type: sliType, spec } = serviceLevelIndicators[0]
 
  return {
    monitoredServiceRef,
    healthSourceRef,
    sliType,
    specType: spec.type,
    metric1: spec.spec?.metric1,
    metric2: spec.spec?.metric2,
    eventType: spec.spec?.eventType,
    thresholdValue: spec.spec?.thresholdValue,
    thresholdType: spec.spec?.thresholdType,
    targetType: target.type,
    targetMonthly: target.spec?.type,
    dayOfMonth: target.spec.spec?.dayOfMonth,
    dayOfWeek: target.spec.spec?.dayOfWeek,
    sloTargetPercentage: target.sloTargetPercentage,
    periodLength: target.spec.periodLength
  }
}
 
export const getIsUserUpdatedSLOData = (
  existingData: ServiceLevelObjectiveDTO,
  formData: ServiceLevelObjectiveDTO
): boolean => {
  const existingDataToVerify = getVerifyData(existingData)
  const formDataToVerify = getVerifyData(formData)
  return isEqual(existingDataToVerify, formDataToVerify)
}