All files / modules/75-ce/components/COGatewayDetails COGatewayDetails.tsx

68.22% Statements 73/107
32.58% Branches 29/89
47.62% Functions 10/21
67.96% Lines 70/103

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              3x 3x 3x 3x 3x 3x 3x 3x   3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x                 3x 18x         17x 17x 17x 17x 17x   17x 17x 17x 17x 17x 17x   17x   17x             17x       17x             17x               17x         17x                                     17x                       17x                             17x                 17x                       17x                                           17x 2x 2x     2x 2x     17x 2x 1x 1x         17x       17x 23x 17x             17x       1x 1x 1x 1x 1x     17x                                                                                                                                           1x               2x                 2x                             3x  
/*
 * 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, { useState } from 'react'
import { defaultTo as _defaultTo } from 'lodash-es'
import { Layout, Tabs, Tab, Button, Container, Icon } from '@wings-software/uicore'
import { useParams, useHistory } from 'react-router-dom'
import { useToaster } from '@common/exports'
import COGatewayConfig from '@ce/components/COGatewayConfig/COGatewayConfig'
import COGatewayAccess from '@ce/components/COGatewayAccess/COGatewayAccess'
import COGatewayReview from '@ce/components/COGatewayReview/COGatewayReview'
import type { FixedScheduleClient, GatewayDetails } from '@ce/components/COCreateGateway/models'
import routes from '@common/RouteDefinitions'
import { Utils } from '@ce/common/Utils'
import { useTelemetry } from '@common/hooks/useTelemetry'
import { useStrings } from 'framework/strings'
import { useSaveService, Service, useGetServices, useCreateStaticSchedules, useDeleteStaticSchedule } from 'services/lw'
import { Breadcrumbs } from '@common/components/Breadcrumbs/Breadcrumbs'
import { ASRuleTabs } from '@ce/constants'
import { GatewayContextProvider } from '@ce/context/GatewayContext'
import { useAppStore } from 'framework/AppStore/AppStoreContext'
import { USER_JOURNEY_EVENTS } from '@ce/TrackingEventsConstants'
import { ConfigTabTitle, ReviewTabTitle, SetupAccessTabTitle } from './TabTitles'
import { getServiceObjectFromgatewayDetails, isPrimaryBtnDisable, trackPrimaryBtnClick } from './helper'
import css from './COGatewayDetails.module.scss'
 
interface COGatewayDetailsProps {
  previousTab: () => void
  gatewayDetails: GatewayDetails
  setGatewayDetails: (gwDetails: GatewayDetails) => void
  activeTab?: ASRuleTabs
  isEditFlow: boolean
}
const COGatewayDetails: React.FC<COGatewayDetailsProps> = props => {
  const { accountId, orgIdentifier, projectIdentifier } = useParams<{
    accountId: string
    orgIdentifier: string
    projectIdentifier: string
  }>()
  const history = useHistory()
  const { getString } = useStrings()
  const { showError, showSuccess } = useToaster()
  const { trackEvent } = useTelemetry()
  const { currentUserInfo } = useAppStore()
 
  const [selectedTabId, setSelectedTabId] = useState<string>(props.activeTab ?? ASRuleTabs.CONFIGURATION)
  const [validConfig, setValidConfig] = useState<boolean>(false)
  const [validAccessSetup, setValidAccessSetup] = useState<boolean>(false)
  const [saveInProgress, setSaveInProgress] = useState<boolean>(false)
  const [activeConfigStep, setActiveConfigStep] = useState<{ count?: number; tabId?: string } | null>(null)
  const [serverNames, setServerNames] = useState<string[]>([])
 
  const tabs = [ASRuleTabs.CONFIGURATION, ASRuleTabs.SETUP_ACCESS, ASRuleTabs.REVIEW]
 
  const { data: servicesData, error } = useGetServices({
    account_id: accountId,
    queryParams: {
      accountIdentifier: accountId
    },
    debounce: 300
  })
  Iif (error) {
    showError('Faield to fetch services', undefined, 'ce.svc.fetch.error')
  }
 
  const { mutate: saveGateway } = useSaveService({
    account_id: accountId,
    queryParams: {
      accountIdentifier: accountId
    }
  })
 
  const { mutate: createStaticSchesules } = useCreateStaticSchedules({
    account_id: accountId,
    queryParams: {
      accountIdentifier: accountId,
      cloud_account_id: props.gatewayDetails.cloudAccount.id
    }
  })
 
  const { mutate: deleteSchedule } = useDeleteStaticSchedule({
    account_id: accountId,
    queryParams: { accountIdentifier: accountId }
  })
 
  const saveStaticSchedules = async (ruleId: number) => {
    const schedules = _defaultTo(
      props.gatewayDetails.schedules
        ?.filter(s => !s.isDeleted)
        ?.map(s =>
          Utils.convertScheduleClientToSchedule(s, {
            accountId,
            ruleId,
            userId: _defaultTo(currentUserInfo.uuid, '')
          })
        ),
      []
    )
    for (const sch of schedules) {
      /* eslint-disable-next-line no-await-in-loop */
      await saveSchedule(sch)
    }
  }
 
  const saveSchedule = async (data: FixedScheduleClient) => {
    try {
      await createStaticSchesules({ schedule: data })
    } catch (e) {
      showError(
        getString('ce.co.autoStoppingRule.configuration.step4.tabs.schedules.unsuccessfulDeletionMessage', {
          error: e.data?.errors?.join('\n') || e.data?.message
        })
      )
    }
  }
 
  const deleteStaticSchedules = async () => {
    const deletedSchedules = Utils.getConditionalResult(
      props.isEditFlow,
      _defaultTo(
        props.gatewayDetails.schedules?.filter(s => s.isDeleted),
        []
      ),
      []
    )
    for (const delSch of deletedSchedules) {
      /* eslint-disable-next-line no-await-in-loop */
      await triggerDeleteSchedule(delSch)
    }
  }
 
  const triggerDeleteSchedule = async (data: FixedScheduleClient) => {
    await deleteSchedule(data.id as number)
    showSuccess(
      getString('ce.co.autoStoppingRule.configuration.step4.tabs.schedules.successfullyDeletedSchedule', {
        name: data.name
      })
    )
  }
 
  const handlePostRuleSave = async (response?: Service) => {
    if (response) {
      await deleteStaticSchedules()
      await saveStaticSchedules(response?.id as number)
      history.push(
        routes.toCECORules({
          accountId
        })
      )
    }
  }
 
  const onSave = async (): Promise<void> => {
    try {
      setSaveInProgress(true)
      const gateway = getServiceObjectFromgatewayDetails(
        props.gatewayDetails,
        orgIdentifier,
        projectIdentifier,
        accountId,
        serverNames
      )
      const result = await saveGateway({ service: gateway, deps: props.gatewayDetails.deps, apply_now: false }) // eslint-disable-line
      // Rule creation is halted until the access point creation takes place successfully.
      // Informing the user regarding the same
      if (props.gatewayDetails.accessPointData?.status === 'submitted') {
        showSuccess('Rule will take effect once the load balancer creation is successful!!')
      }
      await handlePostRuleSave(result.response)
    } catch (e) {
      setSaveInProgress(false)
      showError(e.data?.errors?.join('\n') || e.data?.message || e.message, undefined, 'ce.savegw.error')
    }
  }
  const nextTab = (): void => {
    const tabIndex = tabs.findIndex(t => t == selectedTabId)
    Iif (tabIndex == tabs.length - 1) {
      trackEvent(USER_JOURNEY_EVENTS.SAVE_RULE_CLICK, {})
      onSave()
    } else Eif (tabIndex < tabs.length - 1) {
      setSelectedTabId(tabs[tabIndex + 1])
    }
  }
  const previousTab = (): void => {
    const tabIndex = tabs.findIndex(t => t == selectedTabId)
    Eif (tabIndex > 0) {
      setSelectedTabId(tabs[tabIndex - 1])
    } else {
      props.previousTab()
    }
  }
  const selectTab = (tabId: string) => {
    const tabIndex = tabs.findIndex(t => t == tabId)
    setSelectedTabId(tabs[tabIndex])
  }
  const getNextButtonText = (): string => {
    const tabIndex = tabs.findIndex(t => t == selectedTabId)
    return Utils.getConditionalResult(
      tabIndex === tabs.length - 1,
      getString('ce.co.autoStoppingRule.save'),
      getString('next')
    )
  }
 
  const handleReviewDetailsEdit = (tabDetails: {
    id: string
    metaData?: { activeStepCount?: number; activeStepTabId?: string }
  }) => {
    setSelectedTabId(tabDetails.id)
    const activeStepDetails: { count?: number; tabId?: string } = {}
    activeStepDetails['count'] = tabDetails.metaData?.activeStepCount
    activeStepDetails['tabId'] = tabDetails.metaData?.activeStepTabId
    setActiveConfigStep(activeStepDetails)
  }
 
  return (
    <Container style={{ overflow: 'scroll', maxHeight: '100vh', backgroundColor: 'var(--white)' }}>
      <Breadcrumbs
        className={css.breadCrumb}
        links={[
          {
            url: routes.toCECORules({ accountId }),
            label: getString('ce.co.breadCrumb.rules')
          },
          {
            url: '',
            label: props.gatewayDetails.name
          }
        ]}
      />
      <GatewayContextProvider isEditFlow={props.isEditFlow}>
        <Container className={css.detailsTab}>
          <Tabs id="tabsId1" selectedTabId={selectedTabId} onChange={selectTab}>
            <Tab
              id="configuration"
              disabled
              title={<ConfigTabTitle isValidConfig={validConfig} />}
              panel={
                <COGatewayConfig
                  gatewayDetails={props.gatewayDetails}
                  setGatewayDetails={props.setGatewayDetails}
                  valid={validConfig}
                  setValidity={setValidConfig}
                  activeStepDetails={activeConfigStep}
                  allServices={servicesData?.response as Service[]}
                />
              }
            />
            <Tab
              id="setupAccess"
              disabled
              title={<SetupAccessTabTitle isValidAccessSetup={validAccessSetup} />}
              panel={
                <COGatewayAccess
                  valid={validAccessSetup}
                  setValidity={setValidAccessSetup}
                  gatewayDetails={props.gatewayDetails}
                  setGatewayDetails={props.setGatewayDetails}
                  activeStepDetails={activeConfigStep}
                  allServices={servicesData?.response as Service[]}
                  serverNames={serverNames}
                  setServerNames={setServerNames}
                />
              }
            />
            <Tab
              id="review"
              disabled
              title={<ReviewTabTitle isValidConfig={validConfig} isValidAccessSetup={validAccessSetup} />}
              panel={
                <COGatewayReview
                  gatewayDetails={props.gatewayDetails}
                  onEdit={handleReviewDetailsEdit}
                  allServices={servicesData?.response as Service[]}
                  serverNames={serverNames}
                />
              }
            />
          </Tabs>
        </Container>
      </GatewayContextProvider>
      <Layout.Horizontal className={css.footer} spacing="medium">
        <Button
          text="Previous"
          icon="chevron-left"
          onClick={() => previousTab()}
          disabled={selectedTabId == tabs[0] && (props.gatewayDetails.id as number) != undefined}
        />
        <Button
          intent="primary"
          text={getNextButtonText()}
          icon="chevron-right"
          onClick={() => {
            trackPrimaryBtnClick(
              selectedTabId,
              {
                [ASRuleTabs.CONFIGURATION]: {},
                [ASRuleTabs.REVIEW]: {},
                [ASRuleTabs.SETUP_ACCESS]: props.gatewayDetails.opts.access_details
              },
              trackEvent
            )
            nextTab()
          }}
          disabled={isPrimaryBtnDisable(
            selectedTabId,
            { config: validConfig, setupAccess: validAccessSetup },
            saveInProgress
          )}
          loading={saveInProgress}
        />
        {saveInProgress ? <Icon name="spinner" size={24} color="blue500" style={{ alignSelf: 'center' }} /> : null}
      </Layout.Horizontal>
    </Container>
  )
}
 
export default COGatewayDetails