All files / modules/35-connectors/components/ConnectorYAMLEditor ConnectorYAMLEditor.tsx

73.68% Statements 42/57
48.57% Branches 34/70
58.33% Functions 7/12
73.68% Lines 42/57

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                10x 10x                   10x 10x 10x   10x 10x   10x                   10x   10x 10x 10x           10x                                                                   10x                     1x 1x 1x                                                       10x 9x   10x 1x   10x 10x 10x                       9x 9x 9x 9x   9x                   9x                       9x       9x         1x       9x                             9x       9x           9x 2x 2x                                                                                                 9x                                                 1x                                                       10x  
/*
 * 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.
 */
 
// This is used in ConnectorView for connector details page
import React, { useState } from 'react'
import {
  Button,
  Layout,
  ButtonVariation,
  shouldShowError,
  VisualYamlSelectedView,
  PageSpinner,
  useToaster,
  useConfirmationDialog
} from '@wings-software/uicore'
import { parse } from 'yaml'
import { useParams } from 'react-router-dom'
import { isEmpty, noop, omit } from 'lodash-es'
import type { ToasterProps } from '@wings-software/uicore/dist/hooks/useToaster/useToaster'
import YamlBuilder from '@common/components/YAMLBuilder/YamlBuilder'
import { useStrings } from 'framework/strings'
import type { YamlBuilderHandlerBinding, YamlBuilderProps } from '@common/interfaces/YAMLBuilderProps'
import {
  Connector,
  ConnectorInfoDTO,
  ConnectorResponse,
  CreateConnectorQueryParams,
  EntityGitDetails,
  ResponseJsonNode,
  useGetYamlSchema,
  useUpdateConnector
} from 'services/cd-ng'
import { getScopeFromDTO } from '@common/components/EntityReference/EntityReference'
import type { UseGetMockData } from '@common/utils/testUtils'
import { isSMConnector } from '@connectors/pages/connectors/utils/ConnectorUtils'
import { useAppStore } from 'framework/AppStore/AppStoreContext'
import {
  UseSaveSuccessResponse,
  useSaveToGitDialog,
  UseSaveToGitDialogReturn
} from '@common/modals/SaveToGitDialog/useSaveToGitDialog'
import type { SaveToGitFormInterface } from '@common/components/SaveToGitForm/SaveToGitForm'
import css from './ConnectorYAMLEditor.module.scss'
 
interface ConnectorYAMLEditorProp {
  responsedata: ConnectorResponse
  connector: ConnectorInfoDTO
  setConnector: (object: ConnectorInfoDTO) => void
  yamlBuilderProps: YamlBuilderProps
  enableEdit: boolean
  setEnableEdit: (enableEdit: boolean) => void
  selectedView: VisualYamlSelectedView
  setSelectedView: (view: VisualYamlSelectedView) => void
  setConnectorForYaml: (connectorInfo: ConnectorInfoDTO) => void
  refetchConnector: () => Promise<void>
  mockSchemaData?: UseGetMockData<ResponseJsonNode>
}
 
interface SaveYamlhandlerProps {
  isGitSyncEnabled: boolean
  connector: ConnectorInfoDTO
  openSaveToGitDialog: UseSaveToGitDialogReturn<Connector>['openSaveToGitDialog']
  responsedata: ConnectorResponse
  yamlHandler: YamlBuilderHandlerBinding | undefined
  handleSaveYaml: (
    connectorData?: {
      gitData?: SaveToGitFormInterface
      payload?: Connector
    },
    objectId?: EntityGitDetails['objectId']
  ) => Promise<UseSaveSuccessResponse>
  showSuccess: ToasterProps['showSuccess']
  showError: ToasterProps['showError']
  successText: string
}
 
const saveYamlhandler = (handler: SaveYamlhandlerProps): void => {
  const {
    isGitSyncEnabled,
    connector,
    openSaveToGitDialog,
    responsedata,
    yamlHandler,
    handleSaveYaml,
    showSuccess,
    showError,
    successText
  } = handler
  Eif (isGitSyncEnabled && !isSMConnector(connector.type)) {
    openSaveToGitDialog({
      isEditing: true,
      resource: {
        type: 'Connectors',
        name: responsedata.connector?.name || '',
        identifier: responsedata.connector?.identifier || '',
        gitDetails: responsedata.gitDetails
      },
      payload: parse(yamlHandler?.getLatestYaml?.() || '')
    })
  } else {
    handleSaveYaml()
      .then(res => {
        if (res.status === 'SUCCESS') {
          showSuccess(successText)
          res.nextCallback?.()
        } else {
          /* Todo handle error with API status 200 */
        }
      })
      .catch(e => {
        if (shouldShowError(e)) {
          showError(e.data?.message || e.message)
        }
      })
  }
}
 
const showLoader = (isFetchingSchema: boolean, updating: boolean, isGitSyncEnabled: boolean): boolean =>
  isFetchingSchema || (!isGitSyncEnabled && updating)
 
const getConnectorJSON = (payload: Connector | undefined, latestYaml?: string): Connector =>
  !isEmpty(payload) ? payload : parse(latestYaml || '')
 
const ConnectorYAMLEditor: React.FC<ConnectorYAMLEditorProp> = props => {
  const { showSuccess, showError } = useToaster()
  const { getString } = useStrings()
  const {
    responsedata,
    connector,
    setConnector,
    yamlBuilderProps,
    enableEdit = false,
    setEnableEdit,
    selectedView,
    setSelectedView,
    setConnectorForYaml,
    refetchConnector
  } = props
  const { isGitSyncEnabled } = useAppStore()
  const [yamlHandler, setYamlHandler] = React.useState<YamlBuilderHandlerBinding | undefined>()
  const [hasConnectorChanged, setHasConnectorChanged] = useState<boolean>(false)
 
  const { accountId, projectIdentifier, orgIdentifier } = useParams<{
    accountId: string
    projectIdentifier: string
    orgIdentifier: string
  }>()
 
  const {
    data: connectorSchema,
    loading: isFetchingSchema,
    refetch
  } = useGetYamlSchema({
    queryParams: {
      entityType: 'Connectors',
      projectIdentifier,
      orgIdentifier,
      accountIdentifier: accountId,
      scope: getScopeFromDTO({ accountIdentifier: accountId, orgIdentifier, projectIdentifier })
    },
    mock: props.mockSchemaData,
    lazy: true
  })
 
  const { mutate: updateConnector, loading: updating } = useUpdateConnector({
    queryParams: { accountIdentifier: accountId }
  })
 
  const { openSaveToGitDialog } = useSaveToGitDialog<Connector>({
    onSuccess: (
      gitDetails: SaveToGitFormInterface,
      payload?: Connector,
      objectId?: string
    ): Promise<UseSaveSuccessResponse> => handleSaveYaml({ gitData: gitDetails, payload }, objectId),
    onClose: noop
  })
 
  const { openDialog } = useConfirmationDialog({
    cancelButtonText: getString('cancel'),
    contentText: getString('continueWithoutSavingText'),
    titleText: getString('continueWithoutSavingTitle'),
    confirmButtonText: getString('confirm'),
    onCloseDialog: isConfirmed => {
      if (isConfirmed) {
        setEnableEdit(false)
        setConnectorForYaml(responsedata.connector || ({} as ConnectorInfoDTO))
        setHasConnectorChanged(false)
        setSelectedView(VisualYamlSelectedView.VISUAL)
      }
    }
  })
 
  const onConnectorChange = (isEditorDirty: boolean): void => {
    setHasConnectorChanged(isEditorDirty)
  }
 
  const resetEditor = (event: React.MouseEvent<Element, MouseEvent>): void => {
    event.preventDefault()
    event.stopPropagation()
    openDialog()
  }
 
  React.useEffect(() => {
    Eif (selectedView === VisualYamlSelectedView.YAML && enableEdit) {
      refetch()
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [enableEdit])
 
  /* excluding below method from coverage since it's called only by YAMLBuilder */
  /* istanbul ignore next */
  const handleSaveYaml = async (
    connectorData?: {
      gitData?: SaveToGitFormInterface
      payload?: Connector
    },
    objectId?: EntityGitDetails['objectId']
  ): Promise<UseSaveSuccessResponse> => {
    const { gitData, payload } = connectorData || {}
    const connectorJSONEq = getConnectorJSON(payload, yamlHandler?.getLatestYaml?.())
    const errorMap = yamlHandler?.getYAMLValidationErrorMap?.()
    if (errorMap && errorMap.size > 0) {
      showError(getString('yamlBuilder.yamlError'))
      return {
        status: 'ERROR'
      }
    } else {
      let queryParams: CreateConnectorQueryParams = {}
      if (gitData) {
        queryParams = {
          accountIdentifier: accountId,
          ...omit(gitData, 'sourceBranch')
        }
      }
      const response = await updateConnector(connectorJSONEq, {
        queryParams: {
          ...queryParams,
          lastObjectId: objectId ?? responsedata.gitDetails?.objectId,
          baseBranch: responsedata.gitDetails?.branch
        }
      })
      if (response.status === 'SUCCESS' && response?.data?.connector) {
        setEnableEdit(false)
        setConnector(response?.data?.connector)
        setConnectorForYaml(response?.data?.connector)
      }
      return {
        status: response.status,
        nextCallback: () => refetchConnector()
      }
    }
  }
 
  return (
    <>
      {showLoader(isFetchingSchema, updating, !!isGitSyncEnabled) ? (
        <PageSpinner
          message={updating ? getString('connectors.updating', { name: connector?.name }) : getString('loading')}
        />
      ) : null}
      <div className={css.fullWidth}>
        <YamlBuilder
          {...yamlBuilderProps}
          // snippets={snippetMetaData?.data?.yamlSnippets}
          // onSnippetCopy={onSnippetCopy}
          // snippetFetchResponse={snippetFetchResponse}
          schema={connectorSchema?.data}
          isReadOnlyMode={false}
          bind={setYamlHandler}
          onChange={onConnectorChange}
          showSnippetSection={false}
        />
        <Layout.Horizontal spacing="small">
          <Button
            id="saveYAMLChanges"
            intent="primary"
            text={getString('saveChanges')}
            onClick={() =>
              saveYamlhandler({
                isGitSyncEnabled: !!isGitSyncEnabled,
                connector,
                openSaveToGitDialog,
                responsedata,
                yamlHandler,
                handleSaveYaml,
                showSuccess,
                showError,
                successText: getString('connectors.updatedSuccessfully')
              })
            }
            margin={{ top: 'large' }}
            disabled={!isGitSyncEnabled && !hasConnectorChanged}
            variation={ButtonVariation.PRIMARY}
          />
          <Button
            text={getString('cancel')}
            margin={{ top: 'large' }}
            onClick={resetEditor}
            variation={ButtonVariation.TERTIARY}
          />
        </Layout.Horizontal>
      </div>
    </>
  )
}
 
export default ConnectorYAMLEditor