All files / modules/70-pipeline/utils useSaveTemplate.ts

85.42% Statements 82/96
72.46% Branches 100/138
100% Functions 9/9
85.42% Lines 82/96

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              32x 32x 32x 32x 32x 32x             32x 32x 32x 32x 32x   32x 32x 32x   32x                                                                                 32x                     185x 185x 185x     185x 185x 185x 185x 185x 185x   185x         4x                             185x 12x       185x         6x 6x                             4x 4x 4x 2x 2x   4x 4x     4x         2x 2x       2x         185x             12x 12x 6x   6x 6x                       4x 4x 4x     4x 2x 2x   4x 4x 4x   4x         2x 2x       2x           185x           8x   8x               8x             4x         185x             8x     185x         12x 4x             8x             185x   16x 16x     16x 12x                               12x                   12x     4x                               185x        
/*
 * 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 React from 'react'
import { cloneDeep, defaultTo, isEmpty, omit } from 'lodash-es'
import { parse } from 'yaml'
import { useHistory, useParams } from 'react-router-dom'
import { VisualYamlSelectedView as SelectedView } from '@wings-software/uicore'
import {
  createTemplatePromise,
  EntityGitDetails,
  NGTemplateInfoConfig,
  TemplateSummaryResponse,
  updateExistingTemplateLabelPromise
} from 'services/template-ng'
import { AppStoreContext } from 'framework/AppStore/AppStoreContext'
import { useStrings } from 'framework/strings'
import useRBACError from '@rbac/utils/useRBACError/useRBACError'
import { useToaster } from '@common/exports'
import { UseSaveSuccessResponse, useSaveToGitDialog } from '@common/modals/SaveToGitDialog/useSaveToGitDialog'
import type { SaveToGitFormInterface } from '@common/components/SaveToGitForm/SaveToGitForm'
import { DefaultNewTemplateId } from 'framework/Templates/templates'
import { yamlStringify } from '@common/utils/YamlHelperMethods'
import routes from '@common/RouteDefinitions'
import type { GitQueryParams, ModulePathParams, TemplateStudioPathProps } from '@common/interfaces/RouteInterfaces'
import { useQueryParams } from '@common/hooks'
import type { PromiseExtraArgs } from 'framework/Templates/TemplateConfigModal/TemplateConfigModal'
import type { YamlBuilderHandlerBinding } from '@common/interfaces/YAMLBuilderProps'
 
export interface FetchTemplateUnboundProps {
  forceFetch?: boolean
  forceUpdate?: boolean
  signal?: AbortSignal
  repoIdentifier?: string
  branch?: string
}
 
declare global {
  interface WindowEventMap {
    TEMPLATE_SAVED: CustomEvent<TemplateSummaryResponse>
  }
}
 
interface SaveTemplateObj {
  template: NGTemplateInfoConfig
}
 
interface UseSaveTemplateReturnType {
  saveAndPublish: (
    updatedTemplate: NGTemplateInfoConfig,
    extraInfo: PromiseExtraArgs
  ) => Promise<UseSaveSuccessResponse>
}
 
export interface TemplateContextMetadata {
  template: NGTemplateInfoConfig
  yamlHandler?: YamlBuilderHandlerBinding
  gitDetails?: EntityGitDetails
  setLoading?: (loading: boolean) => void
  fetchTemplate?: (args: FetchTemplateUnboundProps) => Promise<void>
  deleteTemplateCache?: (gitDetails?: EntityGitDetails) => Promise<void>
  view?: string
  isPipelineStudio?: boolean
  stableVersion?: string
}
 
export function useSaveTemplate(TemplateContextMetadata: TemplateContextMetadata): UseSaveTemplateReturnType {
  const {
    template,
    yamlHandler,
    gitDetails,
    setLoading,
    fetchTemplate,
    deleteTemplateCache,
    view,
    isPipelineStudio,
    stableVersion
  } = TemplateContextMetadata
  const { isGitSyncEnabled } = React.useContext(AppStoreContext)
  const { templateIdentifier, templateType, projectIdentifier, orgIdentifier, accountId, module } = useParams<
    TemplateStudioPathProps & ModulePathParams
  >()
  const { branch } = useQueryParams<GitQueryParams>()
  const { getString } = useStrings()
  const { showSuccess, showError, clear } = useToaster()
  const { getRBACErrorMessage } = useRBACError()
  const history = useHistory()
  const isYaml = view === SelectedView.YAML
 
  const navigateToLocation = (
    newTemplateId: string,
    versionLabel: string,
    updatedGitDetails?: SaveToGitFormInterface
  ): void => {
    history.replace(
      routes.toTemplateStudio({
        projectIdentifier,
        orgIdentifier,
        accountId,
        module,
        templateType: templateType,
        templateIdentifier: newTemplateId,
        versionLabel: versionLabel,
        repoIdentifier: updatedGitDetails?.repoIdentifier,
        branch: updatedGitDetails?.branch
      })
    )
  }
 
  const stringifyTemplate = React.useCallback(
    (temp: NGTemplateInfoConfig) => yamlStringify(JSON.parse(JSON.stringify({ template: temp })), { version: '1.1' }),
    []
  )
 
  const updateExistingLabel = async (
    comments?: string,
    updatedGitDetails?: SaveToGitFormInterface,
    lastObject?: { lastObjectId?: string }
  ): Promise<UseSaveSuccessResponse> => {
    try {
      const response = await updateExistingTemplateLabelPromise({
        templateIdentifier: template.identifier,
        versionLabel: template.versionLabel,
        body: stringifyTemplate(omit(cloneDeep(template), 'repo', 'branch')),
        queryParams: {
          accountIdentifier: accountId,
          projectIdentifier,
          orgIdentifier,
          comments,
          ...(updatedGitDetails ?? {}),
          ...(lastObject?.lastObjectId ? lastObject : {}),
          ...(updatedGitDetails && updatedGitDetails.isNewBranch ? { baseBranch: branch } : {})
        },
        requestOptions: { headers: { 'Content-Type': 'application/yaml' } }
      })
      setLoading?.(false)
      Eif (response && response.status === 'SUCCESS') {
        if (!isGitSyncEnabled) {
          clear()
          showSuccess(getString('common.template.updateTemplate.templateUpdated'))
        }
        await fetchTemplate?.({ forceFetch: true, forceUpdate: true })
        Iif (updatedGitDetails?.isNewBranch) {
          navigateToLocation(template.identifier, template.versionLabel, updatedGitDetails)
        }
        return { status: response.status }
      } else {
        throw response
      }
    } catch (error) {
      clear()
      Iif (!isGitSyncEnabled) {
        showError(getRBACErrorMessage(error), undefined, 'template.update.template.error')
        return { status: 'FAILURE' }
      } else {
        throw error
      }
    }
  }
 
  const saveAndPublishTemplate = async (
    latestTemplate: NGTemplateInfoConfig,
    comments = '',
    isEdit = false,
    updatedGitDetails?: SaveToGitFormInterface,
    lastObject?: { lastObjectId?: string }
  ): Promise<UseSaveSuccessResponse> => {
    setLoading?.(true)
    if (isEdit) {
      return updateExistingLabel(comments, updatedGitDetails, lastObject)
    } else {
      try {
        const response = await createTemplatePromise({
          body: stringifyTemplate(omit(cloneDeep(latestTemplate), 'repo', 'branch')),
          queryParams: {
            accountIdentifier: accountId,
            projectIdentifier,
            orgIdentifier,
            comments,
            ...(updatedGitDetails ?? {}),
            ...(updatedGitDetails && updatedGitDetails.isNewBranch ? { baseBranch: branch } : {})
          },
          requestOptions: { headers: { 'Content-Type': 'application/yaml' } }
        })
        setLoading?.(false)
        Eif (response && response.status === 'SUCCESS') {
          Iif (response.data?.templateResponseDTO) {
            window.dispatchEvent(new CustomEvent('TEMPLATE_SAVED', { detail: response.data?.templateResponseDTO }))
          }
          if (!isGitSyncEnabled) {
            clear()
            showSuccess(getString('common.template.saveTemplate.publishTemplate'))
          }
          await deleteTemplateCache?.()
          Eif (!isPipelineStudio) {
            navigateToLocation(latestTemplate.identifier, latestTemplate.versionLabel, updatedGitDetails)
          }
          return { status: response.status }
        } else {
          throw response
        }
      } catch (error) {
        clear()
        Iif (!isGitSyncEnabled) {
          showError(getRBACErrorMessage(error), undefined, 'template.save.template.error')
          return { status: 'FAILURE' }
        } else {
          throw error
        }
      }
    }
  }
 
  const saveAngPublishWithGitInfo = async (
    updatedGitDetails: SaveToGitFormInterface,
    payload?: SaveTemplateObj,
    objectId?: string,
    isEdit = false
  ): Promise<UseSaveSuccessResponse> => {
    let latestTemplate: NGTemplateInfoConfig = payload?.template || template
 
    Iif (isYaml && yamlHandler) {
      try {
        latestTemplate = payload?.template || (parse(yamlHandler.getLatestYaml()).pipeline as NGTemplateInfoConfig)
      } /* istanbul ignore next */ catch (err) {
        showError(getRBACErrorMessage(err), undefined, 'template.save.gitinfo.error')
      }
    }
 
    const response = await saveAndPublishTemplate(
      latestTemplate,
      '',
      isEdit,
      omit(updatedGitDetails, 'name', 'identifier'),
      templateIdentifier !== DefaultNewTemplateId ? { lastObjectId: objectId } : {}
    )
    return {
      status: response?.status
    }
  }
 
  const { openSaveToGitDialog } = useSaveToGitDialog<SaveTemplateObj>({
    onSuccess: (
      gitData: SaveToGitFormInterface,
      payload?: SaveTemplateObj,
      objectId?: string,
      isEdit = false
    ): Promise<UseSaveSuccessResponse> =>
      saveAngPublishWithGitInfo(gitData, payload, objectId || gitDetails?.objectId || '', isEdit)
  })
 
  const getUpdatedGitDetails = (
    currGitDetails: EntityGitDetails,
    latestTemplate: NGTemplateInfoConfig,
    isEdit: boolean | undefined = false
  ): EntityGitDetails => {
    if (isEdit) {
      return {
        filePath: `${latestTemplate.identifier}_${latestTemplate.versionLabel
          .toString()
          .replace(/[^a-zA-Z0-9-_]/g, '')}.yaml`,
        ...currGitDetails
      }
    }
    return {
      ...currGitDetails,
      filePath: `${latestTemplate.identifier}_${latestTemplate.versionLabel
        .toString()
        .replace(/[^a-zA-Z0-9-_]/g, '')}.yaml`
    }
  }
  const saveAndPublish = React.useCallback(
    async (updatedTemplate: NGTemplateInfoConfig, extraInfo: PromiseExtraArgs): Promise<UseSaveSuccessResponse> => {
      const { isEdit, comment } = extraInfo
      const latestTemplate: NGTemplateInfoConfig = defaultTo(updatedTemplate, template)
 
      // if Git sync enabled then display modal
      if (isGitSyncEnabled) {
        Iif (isEmpty(gitDetails?.repoIdentifier) || isEmpty(gitDetails?.branch)) {
          clear()
          showError(getString('pipeline.gitExperience.selectRepoBranch'))
          return Promise.reject(getString('pipeline.gitExperience.selectRepoBranch'))
        } else {
          // @TODO - Uncomment below snippet when schema validation is available at BE.
          // When git sync enabled, do not irritate user by taking all git info then at the end showing BE errors related to schema
          // const error = await validateJSONWithSchema({ template: latestTemplate }, templateSchema?.data as any)
          // if (error.size > 0) {
          //   clear()
          //   showError(error)
          //   return
          // }
          // if (isYaml && yamlHandler && !isValidYaml()) {
          //   return
          // }
          openSaveToGitDialog({
            isEditing: defaultTo(isEdit, false),
            resource: {
              type: 'Template',
              name: latestTemplate.name,
              identifier: latestTemplate.identifier,
              gitDetails: gitDetails ? getUpdatedGitDetails(gitDetails, latestTemplate, isEdit) : {}
            },
            payload: { template: omit(latestTemplate, 'repo', 'branch') }
          })
          return Promise.resolve({ status: 'SUCCESS' })
        }
      } else {
        return saveAndPublishTemplate(latestTemplate, comment, isEdit)
      }
    },
    [
      template,
      templateIdentifier,
      gitDetails,
      isGitSyncEnabled,
      isYaml,
      yamlHandler,
      showError,
      showSuccess,
      stableVersion
    ]
  )
 
  return {
    saveAndPublish
  }
}