All files / modules/85-cv/pages/monitored-service/components/Configurations Configurations.tsx

70.09% Statements 75/107
49.17% Branches 59/120
61.9% Functions 13/21
70.75% Lines 75/106

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              15x 15x 15x 15x 15x   15x 15x 15x 15x 15x   15x 15x               15x   15x 15x 15x 15x 15x 15x 15x   15x 15x             15x 12x 12x 12x 12x     12x           12x 12x 12x 12x 12x 12x           12x                                   12x                 12x     12x         12x 8x                       12x 11x   1x     1x 1x 1x   1x 1x 1x                           12x 8x     8x         12x 9x                   12x   12x           12x       12x 8x 7x 3x         12x 4x 4x                 12x         12x   2x 2x                                                                             2x 2x           12x                                                         12x   12x                 12x                                                     2x                                                                                              
/*
 * 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 React, { useEffect, useMemo, useState, useCallback } from 'react'
import { Container, Tab, Tabs, PageError, Views } from '@wings-software/uicore'
import { useHistory, useParams, matchPath } from 'react-router-dom'
import { isEqual, omit } from 'lodash-es'
import { parse } from 'yaml'
import type { FormikProps } from 'formik'
import { useQueryParams } from '@common/hooks'
import { getCVMonitoringServicesSearchParam, getErrorMessage, getSearchString } from '@cv/utils/CommonUtils'
import { accountPathProps, projectPathProps, modulePathProps } from '@common/utils/routeUtils'
import routes from '@common/RouteDefinitions'
import { editParams } from '@cv/utils/routeUtils'
import type { ProjectPathProps } from '@common/interfaces/RouteInterfaces'
import { useIndexedDBHook, CVObjectStoreNames } from '@cv/hooks/IndexedDBHook/IndexedDBHook'
import {
  ChangeSourceDTO,
  MonitoredServiceDTO,
  useGetMonitoredService,
  useGetMonitoredServiceYamlTemplate,
  useSaveMonitoredService,
  useUpdateMonitoredService
} from 'services/cv'
import { PageSpinner, useToaster, NavigationCheck } from '@common/components'
import type { NGTemplateInfoConfigWithMonitoredService } from '@templates-library/components/Templates/MonitoredServiceTemplate/MonitoredServiceTemplate'
import { MonitoredServiceEnum } from '@cv/pages/monitored-service/MonitoredServicePage.constants'
import { ChangeSourceCategoryName } from '@cv/pages/ChangeSource/ChangeSourceDrawer/ChangeSourceDrawer.constants'
import { useStrings } from 'framework/strings'
import { SLODetailsPageTabIds } from '@cv/pages/slos/CVSLODetailsPage/CVSLODetailsPage.types'
import Service from './components/Service/Service'
import Dependency from './components/Dependency/Dependency'
import { getInitFormData } from './components/Service/Service.utils'
import type { MonitoredServiceForm } from './components/Service/Service.types'
import { determineUnSaveState, onTabChange, onSubmit } from './Configurations.utils'
import css from './Configurations.module.scss'
 
interface ConfigurationsInterface {
  isTemplate?: boolean
  updateTemplate?: (template: NGTemplateInfoConfigWithMonitoredService) => Promise<void>
}
 
export default function Configurations({ isTemplate, updateTemplate }: ConfigurationsInterface): JSX.Element {
  const { getString } = useStrings()
  const { showWarning, showError, showSuccess } = useToaster()
  const history = useHistory()
  const { orgIdentifier, projectIdentifier, accountId, identifier } = useParams<
    ProjectPathProps & { identifier: string }
  >()
  const { view, redirectToSLO, sloIdentifier, monitoredServiceIdentifier } = useQueryParams<{
    view?: Views.GRID
    redirectToSLO?: boolean
    sloIdentifier?: string
    monitoredServiceIdentifier?: string
  }>()
  const [cachedInitialValues, setCachedInitialValue] = useState<MonitoredServiceForm | null>(null)
  const [selectedTabID, setselectedTabID] = useState(getString('service'))
  const serviceTabformRef: React.MutableRefObject<FormikProps<MonitoredServiceForm> | null> = React.useRef(null)
  const dependencyTabformRef: React.MutableRefObject<FormikProps<MonitoredServiceForm> | null> = React.useRef(null)
  const [overrideBlockNavigation, setOverrideBlockNavigation] = useState<boolean>(false)
  const [defaultMonitoredService, setDefaultMonitoredService] = useState<MonitoredServiceDTO>()
  const {
    data: dataMonitoredServiceById,
    error: errorFetchMonitoredService,
    refetch: fetchMonitoredService,
    loading: loadingGetMonitoredService
  } = useGetMonitoredService({
    identifier,
    pathParams: {
      identifier
    },
    queryParams: {
      accountId,
      orgIdentifier,
      projectIdentifier
    },
    lazy: true
  })
 
  const {
    data: yamlMonitoredService,
    error: errorFetchMonitoredServiceYAML,
    loading: loadingFetchMonitoredServiceYAML,
    refetch: fetchMonitoredServiceYAML
  } = useGetMonitoredServiceYamlTemplate({
    queryParams: {
      orgIdentifier,
      projectIdentifier,
      accountId
    },
    lazy: true
  })
 
  const { mutate: saveMonitoredService } = useSaveMonitoredService({
    queryParams: { accountId }
  })
  const { mutate: updateMonitoredService, loading: loadingUpdateMonitoredService } = useUpdateMonitoredService({
    identifier,
    queryParams: { accountId }
  })
 
  useEffect(() => {
    Iif (overrideBlockNavigation && !redirectToSLO) {
      history.push({
        pathname: routes.toCVMonitoringServices({
          orgIdentifier,
          projectIdentifier,
          accountId
        }),
        search: getCVMonitoringServicesSearchParam({ view })
      })
    }
  }, [overrideBlockNavigation, redirectToSLO])
 
  useEffect(() => {
    if (yamlMonitoredService && yamlMonitoredService?.resource) {
      // This only executed on creating new Monitored Service
      const { monitoredService }: { monitoredService: MonitoredServiceDTO } = parse(yamlMonitoredService?.resource)
      // Category is not present in default changeSource object
      // hence adding here
      monitoredService.sources?.changeSources?.forEach(changeSource => {
        changeSource['category'] = ChangeSourceCategoryName.DEPLOYMENT as ChangeSourceDTO['category']
        changeSource['spec'] = {}
      })
      setDefaultMonitoredService(prevService => {
        Eif (!prevService) {
          return monitoredService
        }
        const currSources = prevService.sources?.changeSources || []
        return {
          ...prevService,
          sources: {
            changeSources: currSources.concat(monitoredService.sources?.changeSources || []),
            healthSources: prevService.sources?.healthSources || []
          }
        }
      })
    }
  }, [yamlMonitoredService])
 
  useEffect(() => {
    Iif (identifier) {
      fetchMonitoredService()
    } else {
      fetchMonitoredServiceYAML()
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [identifier])
 
  const initialValues: MonitoredServiceForm = useMemo(
    () => getInitFormData(dataMonitoredServiceById?.data?.monitoredService, defaultMonitoredService, !!identifier),
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [
      dataMonitoredServiceById?.data?.monitoredService.name,
      identifier,
      loadingGetMonitoredService,
      defaultMonitoredService
    ]
  )
 
  useEffect(() => {
    // In case user refereshes page with saved changes
    Iif (isEqual(cachedInitialValues, initialValues)) {
      dbInstance?.clear(CVObjectStoreNames.MONITORED_SERVICE)
      setCachedInitialValue(null)
    }
  }, [cachedInitialValues, initialValues])
 
  const { isInitializingDB, dbInstance } = useIndexedDBHook({
    clearStroreList: [CVObjectStoreNames.MONITORED_SERVICE]
  })
 
  useEffect(() => {
    if (!isInitializingDB && dbInstance) {
      dbInstance.get(CVObjectStoreNames.MONITORED_SERVICE, 'monitoredService')?.then(data => {
        setCachedInitialValue(data?.currentData)
      })
    }
  }, [isInitializingDB, dbInstance])
 
  const setDBData = async (data: MonitoredServiceForm) => {
    try {
      await dbInstance?.put(CVObjectStoreNames.MONITORED_SERVICE, {
        monitoredService: 'monitoredService',
        currentData: data
      })
    } catch (e) {
      showWarning(e)
    }
  }
 
  const onDiscard = useCallback(() => {
    dbInstance?.clear(CVObjectStoreNames.MONITORED_SERVICE)
    setCachedInitialValue(initialValues)
  }, [initialValues])
 
  const onSuccess = useCallback(
    async (payload, tabId) => {
      try {
        await onSubmit({
          formikValues: payload,
          identifier,
          orgIdentifier,
          projectIdentifier,
          cachedInitialValues,
          updateMonitoredService,
          saveMonitoredService,
          fetchMonitoredService,
          setOverrideBlockNavigation
        })
        setCachedInitialValue(null)
        if (!identifier) {
          setselectedTabID(tabId)
        }
        showSuccess(
          getString(
            identifier ? 'cv.monitoredServices.monitoredServiceUpdated' : 'cv.monitoredServices.monitoredServiceCreated'
          )
        )
 
        if (redirectToSLO && sloIdentifier) {
          history.push({
            pathname: routes.toCVSLODetailsPage({
              accountId,
              orgIdentifier,
              projectIdentifier,
              identifier: sloIdentifier,
              module: 'cv'
            }),
            search: getSearchString({ tab: SLODetailsPageTabIds.Configurations, monitoredServiceIdentifier })
          })
        } else if (redirectToSLO) {
          history.push({
            pathname: routes.toCVCreateSLOs({ accountId, orgIdentifier, projectIdentifier, module: 'cv' }),
            search: monitoredServiceIdentifier ? `?monitoredServiceIdentifier=${monitoredServiceIdentifier}` : ''
          })
        }
      } catch (e) {
        showError(getErrorMessage(e))
        return e
      }
    },
    [identifier, redirectToSLO, sloIdentifier, history, monitoredServiceIdentifier]
  )
 
  const onNavigationChange = useCallback(
    nextLocation => {
      const currentPath = nextLocation.pathname
      const createPath = routes.toCVAddMonitoringServicesSetup({ ...accountPathProps, ...projectPathProps })
      const editPath = `${routes.toCVAddMonitoringServicesEdit({
        ...accountPathProps,
        ...projectPathProps,
        ...modulePathProps,
        ...editParams,
        module: 'cv'
      })}${getCVMonitoringServicesSearchParam({ tab: MonitoredServiceEnum.Configurations })}`
      const matchDefault = matchPath(currentPath, {
        path: identifier ? editPath : createPath,
        exact: true
      })
      return determineUnSaveState({
        cachedInitialValues,
        initialValues,
        overrideBlockNavigation,
        isExactPath: !!matchDefault?.isExact,
        selectedTabID,
        serviceTabformRef,
        dependencyTabformRef,
        getString
      })
    },
    [identifier, cachedInitialValues, initialValues, overrideBlockNavigation, selectedTabID]
  )
 
  Iif (identifier && errorFetchMonitoredService) {
    return <PageError message={getErrorMessage(errorFetchMonitoredService)} onClick={() => fetchMonitoredService()} />
  } else Iif (!identifier && errorFetchMonitoredService) {
    return (
      <PageError
        message={getErrorMessage(errorFetchMonitoredServiceYAML)}
        onClick={() => fetchMonitoredServiceYAML()}
      />
    )
  }
 
  return (
    <Container className={css.configurationTabs}>
      {(loadingGetMonitoredService || loadingFetchMonitoredServiceYAML || loadingUpdateMonitoredService) && (
        <PageSpinner />
      )}
      <Tabs
        id="configurationTabs"
        selectedTabId={selectedTabID}
        onChange={async nextTab =>
          onTabChange({
            nextTab,
            getString,
            selectedTabID,
            dbInstance,
            serviceTabformRef,
            dependencyTabformRef,
            setselectedTabID,
            setCachedInitialValue
          })
        }
      >
        <Tab
          id={getString('service')}
          title={getString('service')}
          panel={
            <Service
              value={initialValues}
              onSuccess={async payload => onSuccess(payload, getString('service'))}
              serviceTabformRef={serviceTabformRef}
              cachedInitialValues={!isTemplate ? cachedInitialValues : undefined}
              setDBData={setDBData}
              onDiscard={onDiscard}
              isTemplate={isTemplate}
              updateTemplate={updateTemplate}
              onChangeMonitoredServiceType={updatedDTO => {
                setDefaultMonitoredService(omit(updatedDTO, ['isEdit']) as MonitoredServiceDTO)
                setCachedInitialValue(updatedDTO)
                fetchMonitoredServiceYAML({
                  queryParams: {
                    orgIdentifier,
                    projectIdentifier,
                    accountId,
                    type: updatedDTO.type
                  }
                })
              }}
            />
          }
        />
        <Tab
          id={getString('pipelines-studio.dependenciesGroupTitle')}
          title={getString('pipelines-studio.dependenciesGroupTitle')}
          panel={
            <Dependency
              value={initialValues}
              dependencyTabformRef={dependencyTabformRef}
              onSuccess={async payload => onSuccess(payload, getString('pipelines-studio.dependenciesGroupTitle'))}
              cachedInitialValues={cachedInitialValues}
              setDBData={setDBData}
              onDiscard={onDiscard}
            />
          }
        />
      </Tabs>
      <NavigationCheck
        when={true}
        shouldBlockNavigation={onNavigationChange}
        navigate={newPath => {
          history.push(newPath)
        }}
      />
    </Container>
  )
}