All files / modules/75-ce/utils perspectiveUtils.ts

80% Statements 84/105
60.2% Branches 59/98
65.38% Functions 17/26
78.89% Lines 71/90

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                  24x     24x                         24x 24x   24x   24x       18x     24x 49x                                   24x 28x         24x 12x             24x 8x                                     24x             24x             24x             24x                   24x                         24x 4x     4x 4x         4x 4x                         4x       4x       24x           24x 4x   4x 4x     4x     24x               24x             24x 24x 24x     24x                         24x                   24x 24x 13x 13x 13x 2x   11x 1x   11x 10x   11x     24x 34x             24x     24x 2x 2x   2x         2x       2x   2x 2x           2x 2x     2x 2x     2x 2x     2x     24x                      
/*
 * 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 type { IconName } from '@wings-software/uicore'
import type Highcharts from 'highcharts'
import { get } from 'lodash-es'
import type { ViewRule, ViewIdCondition, CEView } from 'services/ce'
import type { UseStringsReturn } from 'framework/strings'
import {
  QlceViewTimeFilterOperator,
  ViewFieldIdentifier,
  QlceViewFilterWrapperInput,
  QlceViewFieldInputInput,
  QlceViewGroupByInput,
  QlceViewTimeGroupType,
  QlceViewFilterInput,
  ViewTimeRangeType,
  ViewChartType,
  QlceViewRuleInput
} from 'services/ce/services'
import type { PerspectiveQueryParams } from '@ce/types'
import { CCM_CHART_TYPES } from '@ce/constants'
import { CE_DATE_FORMAT_INTERNAL, DATE_RANGE_SHORTCUTS } from './momentUtils'
 
const startTimeLabel = 'startTime'
 
export const getViewFilterForId: (viewId: string, isPreview?: boolean) => QlceViewFilterWrapperInput = (
  viewId: string,
  isPreview = false
) => {
  return { viewMetadataFilter: { viewId: viewId, isPreview: isPreview } } as QlceViewFilterWrapperInput
}
 
export const getTimeFilters: (from: number, to: number) => QlceViewFilterWrapperInput[] = (from, to) => {
  return [
    {
      timeFilter: {
        field: { fieldId: startTimeLabel, fieldName: startTimeLabel, identifier: ViewFieldIdentifier.Common },
        operator: QlceViewTimeFilterOperator.After,
        value: from
      }
    },
    {
      timeFilter: {
        field: { fieldId: startTimeLabel, fieldName: startTimeLabel, identifier: ViewFieldIdentifier.Common },
        operator: QlceViewTimeFilterOperator.Before,
        value: to
      }
    }
  ] as QlceViewFilterWrapperInput[]
}
 
export const getGroupByFilter: (groupBy: QlceViewFieldInputInput) => QlceViewGroupByInput = groupBy => {
  return {
    entityGroupBy: groupBy
  } as QlceViewGroupByInput
}
 
export const getTimeRangeFilter: (aggregation: QlceViewTimeGroupType) => QlceViewGroupByInput = aggregation => {
  return {
    timeTruncGroupBy: {
      resolution: aggregation
    }
  } as QlceViewGroupByInput
}
 
export const getFilters: (viewConditions: QlceViewFilterInput[]) => QlceViewFilterWrapperInput[] = viewConditions => {
  return viewConditions
    .filter(viewCondition => {
      return viewCondition.values?.length
    })
    .map(viewCondition => {
      return {
        idFilter: {
          values: viewCondition.values,
          operator: viewCondition.operator,
          field: {
            fieldId: viewCondition.field.fieldId,
            fieldName: viewCondition.field.fieldName,
            identifier: viewCondition.field.identifier
          }
        }
      }
    }) as QlceViewFilterWrapperInput[]
}
 
export const DEFAULT_GROUP_BY = {
  fieldId: 'product',
  fieldName: 'Product',
  identifier: ViewFieldIdentifier.Common,
  identifierName: ViewFieldIdentifier.Common
}
 
export const GROUP_BY_CLUSTER_NAME = {
  fieldId: 'clusterName',
  fieldName: 'Cluster Name',
  identifier: ViewFieldIdentifier.Cluster,
  identifierName: ViewFieldIdentifier.Cluster
}
 
export const GROUP_BY_POD = {
  fieldId: 'instanceId',
  fieldName: 'Pod',
  identifier: ViewFieldIdentifier.Cluster,
  identifierName: ViewFieldIdentifier.Cluster
}
 
export const generateId: (length: number) => string = length => {
  let result = ''
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  const charactersLength = characters.length
  for (let i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * charactersLength))
  }
  return result
}
 
export const CREATE_CALL_OBJECT = {
  viewVersion: 'v1',
  viewTimeRange: {
    viewTimeRangeType: ViewTimeRangeType.Last_7
  },
  viewType: 'CUSTOMER',
  viewVisualization: {
    granularity: QlceViewTimeGroupType.Day,
    groupBy: { ...DEFAULT_GROUP_BY },
    chartType: ViewChartType.StackedLineChart
  }
}
 
export const normalizeViewRules: (viewRules: ViewRule[] | undefined) => QlceViewRuleInput[] = viewRules => {
  return viewRules
    ? (viewRules
        .map(rule => {
          Eif (rule) {
            return {
              conditions:
                rule.viewConditions &&
                rule.viewConditions
                  .map(c => {
                    const condition = c as unknown as ViewIdCondition
                    return condition.values && condition.values.length
                      ? {
                          field: {
                            fieldId: condition.viewField?.fieldId,
                            fieldName: condition.viewField?.fieldName,
                            identifier: condition.viewField?.identifier,
                            identifierName: condition.viewField?.identifierName
                          },
                          operator: condition.viewOperator,
                          values: condition.values
                        }
                      : null
                  })
                  .filter(condition => !!condition)
            }
          }
        })
        .filter(rule => rule?.conditions && rule.conditions.length) as QlceViewRuleInput[])
    : []
}
 
export const getRuleFilters: (rules: QlceViewRuleInput[]) => QlceViewFilterWrapperInput[] = rules => {
  return rules.map(rule => ({
    ruleFilter: rule
  })) as QlceViewFilterWrapperInput[]
}
 
export const getIdFiltersFromRules: (rules: QlceViewRuleInput[]) => QlceViewFilterWrapperInput[] = rules => {
  const filters: QlceViewFilterWrapperInput[] = []
 
  rules.map(rule =>
    rule.conditions?.map(condition => filters.push({ idFilter: condition } as QlceViewFilterWrapperInput))
  )
 
  return filters
}
 
export const SOURCE_ICON_MAPPING: Record<string, IconName> = {
  AWS: 'service-aws',
  GCP: 'gcp',
  CLUSTER: 'blue-black-cluster',
  CUSTOM: 'pipeline-custom',
  AZURE: 'service-azure'
}
 
export const perspectiveDefaultTimeRangeMapper: Record<string, moment.Moment[]> = {
  [ViewTimeRangeType.Last_7]: DATE_RANGE_SHORTCUTS.LAST_7_DAYS,
  [ViewTimeRangeType.Last_30]: DATE_RANGE_SHORTCUTS.LAST_30_DAYS,
  [ViewTimeRangeType.LastMonth]: DATE_RANGE_SHORTCUTS.LAST_MONTH,
  [ViewTimeRangeType.CurrentMonth]: DATE_RANGE_SHORTCUTS.CURRENT_MONTH
}
 
export enum ChartState {
  IN_ACTIVE = 'inactive',
  NONE = ''
}
 
export const highlightNode = (chartRef: React.RefObject<Highcharts.Chart | undefined>, id: string) => {
  if (chartRef && chartRef.current) {
    const chart = chartRef.current
    chart.series?.length > 1 &&
      chart.series.forEach(chartItem => {
        const nodeId = (chartItem.options as any).nodeId
        if (nodeId !== id) {
          chartItem.setState(ChartState.IN_ACTIVE)
        }
      })
  }
}
 
export const resetNodeState = (chartRef: React.RefObject<Highcharts.Chart | undefined>) => {
  if (chartRef && chartRef.current) {
    const chart = chartRef.current
    chart.series &&
      chart.series.forEach(chartItem => {
        chartItem.setState(ChartState.NONE)
      })
  }
}
 
export const clusterInfoUtil: (dataSources?: string[]) => { isClusterOnly: boolean; hasClusterAsSource: boolean } =
  dataSources => {
    let isClusterOnly = false
    let hasClusterAsSource = false
    if (!dataSources?.length) {
      return { isClusterOnly, hasClusterAsSource }
    }
    if (dataSources.length === 1 && dataSources[0] === ViewFieldIdentifier.Cluster) {
      isClusterOnly = true
    }
    if (dataSources.includes(ViewFieldIdentifier.Cluster)) {
      hasClusterAsSource = true
    }
    return { isClusterOnly, hasClusterAsSource }
  }
 
export const perspectiveDateLabelToDisplayText: (getString: UseStringsReturn['getString']) => Record<string, string> =
  getString => ({
    [ViewTimeRangeType.Last_7]: getString('ce.perspectives.timeRangeConstants.last7Days'),
    [ViewTimeRangeType.Last_30]: getString('projectsOrgs.landingDashboard.last30Days'),
    [ViewTimeRangeType.LastMonth]: getString('ce.perspectives.timeRangeConstants.lastMonth'),
    [ViewTimeRangeType.CurrentMonth]: getString('ce.perspectives.timeRangeConstants.thisMonth')
  })
 
export const getQueryFiltersFromPerspectiveResponse: (
  perspectiveData: CEView,
  initialValue: Partial<PerspectiveQueryParams>
) => Partial<PerspectiveQueryParams> = (perspectiveData, initialValue) => {
  const resAggregation = get(perspectiveData, 'perspectiveData.granularity', QlceViewTimeGroupType.Day)
  const resGroupBy = get(perspectiveData, 'viewVisualization.groupBy', DEFAULT_GROUP_BY)
  const dateRange =
    (perspectiveData.viewTimeRange?.viewTimeRangeType &&
      perspectiveDefaultTimeRangeMapper[perspectiveData.viewTimeRange?.viewTimeRangeType]) ||
    DATE_RANGE_SHORTCUTS.LAST_7_DAYS
 
  const cType =
    perspectiveData.viewVisualization?.chartType === ViewChartType.StackedTimeSeries
      ? CCM_CHART_TYPES.COLUMN
      : CCM_CHART_TYPES.AREA
 
  const updatedQueryParam: Partial<PerspectiveQueryParams> = {}
 
  Eif (!initialValue.timeRange) {
    updatedQueryParam['timeRange'] = JSON.stringify({
      to: dateRange[1].format(CE_DATE_FORMAT_INTERNAL),
      from: dateRange[0].format(CE_DATE_FORMAT_INTERNAL)
    })
  }
 
  Eif (!initialValue.groupBy) {
    updatedQueryParam['groupBy'] = JSON.stringify(resGroupBy)
  }
 
  Eif (!initialValue.aggregation) {
    updatedQueryParam['aggregation'] = JSON.stringify(resAggregation)
  }
 
  Eif (!initialValue.chartType) {
    updatedQueryParam['chartType'] = JSON.stringify(cType)
  }
 
  return updatedQueryParam
}
 
export const EMPTY_PERSPECTIVE_RULE = {
  type: 'VIEW_ID_CONDITION',
  viewField: {
    fieldId: '',
    fieldName: '',
    identifier: '',
    identifierName: ''
  },
  viewOperator: 'IN',
  values: []
}