All files / modules/75-cf/components/FlagActivation FlagPrerequisites.tsx

47.29% Statements 61/129
28.42% Branches 54/190
16.28% Functions 7/43
51.28% Lines 60/117

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 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453              3x 3x 3x 3x 3x                     3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x   3x 3x                 3x   3x 3x 3x 3x 3x 3x 3x   3x                                     3x 7x 7x 7x           7x 7x 7x 7x 7x   7x 6x                             7x           7x 6x     7x   7x                   7x   7x                                 7x 1x               1x                                                                                                                                                     1x     1x             1x         1x                                       2x     2x                                                                                                                                                                                                   7x                               7x         7x                   7x                                                                                       1x 1x                      
/*
 * 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, { useMemo, useState } from 'react'
import { useParams } from 'react-router-dom'
import { flatMap, get, isEqual } from 'lodash-es'
import * as yup from 'yup'
import {
  Button,
  Collapse,
  Container,
  Formik,
  FormikForm as Form,
  FormInput,
  Heading,
  Layout,
  Text
} from '@wings-software/uicore'
import { useModalHook } from '@harness/use-modal'
import { FontVariation } from '@harness/design-system'
import { FieldArray } from 'formik'
import cx from 'classnames'
import { Divider, IconName, Dialog } from '@blueprintjs/core'
import { useToaster } from '@common/exports'
import StringWithTooltip from '@common/components/StringWithTooltip/StringWithTooltip'
import { useStrings } from 'framework/strings'
import RbacButton from '@rbac/components/Button/Button'
import { ResourceType } from '@rbac/interfaces/ResourceType'
import { PermissionIdentifier } from '@rbac/interfaces/PermissionIdentifier'
import type { PermissionsRequest } from '@rbac/hooks/usePermission'
import RbacOptionsMenuButton from '@rbac/components/RbacOptionsMenuButton/RbacOptionsMenuButton'
import {
  Feature,
  GitSyncErrorResponse,
  PatchFeatureQueryParams,
  Prerequisite,
  useGetAllFeatures,
  usePatchFeature,
  Variation
} from 'services/cf'
import { AUTO_COMMIT_MESSAGES } from '@cf/constants/GitSyncConstants'
 
import { GIT_SYNC_ERROR_CODE, UseGitSync } from '@cf/hooks/useGitSync'
import { useGovernance } from '@cf/hooks/useGovernance'
import usePlanEnforcement from '@cf/hooks/usePlanEnforcement'
import { FeatureIdentifier } from 'framework/featureStore/FeatureIdentifier'
import patch from '../../utils/instructions'
import SaveFlagToGitSubForm from '../SaveFlagToGitSubForm/SaveFlagToGitSubForm'
import css from './FlagActivationDetails.module.scss'
 
const editCardCollapsedProps = {
  collapsedIcon: 'main-chevron-right' as IconName,
  expandedIcon: 'main-chevron-down' as IconName,
  isOpen: false,
  isRemovable: false,
  className: 'collapse'
}
 
interface FlagPrerequisitesProps {
  featureFlag: Feature
  gitSync: UseGitSync
  refetchFlag: () => void
}
 
interface PrerequisiteEntry {
  feature: string
  variation: string
}
 
export const FlagPrerequisites: React.FC<FlagPrerequisitesProps> = props => {
  const { featureFlag, refetchFlag, gitSync } = props
  const { showError } = useToaster()
  const { getString } = useStrings()
  const {
    orgIdentifier,
    accountId: accountIdentifier,
    projectIdentifier,
    environmentIdentifier
  } = useParams<Record<string, string>>()
  const [searchTerm, setSearchTerm] = useState<string>()
  const { handleError: handleGovernanceError, isGovernanceError } = useGovernance()
  const gitSyncFormMeta = gitSync?.getGitSyncFormMeta(AUTO_COMMIT_MESSAGES.UPDATES_FLAG_PREREQS)
  const PAGE_SIZE = 500
 
  const queryParams = useMemo(
    () => ({
      environmentIdentifier: environmentIdentifier !== 'undefined' ? environmentIdentifier : '',
      projectIdentifier,
      accountIdentifier,
      orgIdentifier,
      name: searchTerm,
      pageSize: PAGE_SIZE
    }),
    [accountIdentifier, environmentIdentifier, orgIdentifier, projectIdentifier, searchTerm]
  )
  const {
    data: searchedFeatures,
    loading,
    error,
    refetch: fetchFlags
  } = useGetAllFeatures({
    lazy: true,
    queryParams,
    debounce: 500
  })
 
  const featureList = useMemo(() => {
    return searchedFeatures?.features?.filter(_feature => _feature.identifier !== featureFlag.identifier) || []
  }, [featureFlag.identifier, searchedFeatures?.features?.filter])
 
  const [isEditingPrerequisites, setEditingPrerequisites] = useState<boolean>(false)
 
  const { mutate: patchPrerequisites } = usePatchFeature({
    identifier: featureFlag.identifier as string,
    queryParams: {
      projectIdentifier: featureFlag.project as string,
      environmentIdentifier: featureFlag.envProperties?.environment as string,
      accountIdentifier,
      orgIdentifier
    } as PatchFeatureQueryParams
  })
 
  const { isPlanEnforcementEnabled } = usePlanEnforcement()
 
  const handlePrerequisiteInteraction = (action: 'edit' | 'delete', prereq: Prerequisite) => () => {
    if (action === 'delete') {
      patch.feature.addInstruction(patch.creators.removePrerequisite(prereq.feature))
      patch.feature.onPatchAvailable(data => {
        patchPrerequisites(data)
          .then(refetchFlag)
          .catch(err => {
            showError(get(err, 'data.message', err?.message), undefined, 'cf.patch.prereq.error')
          })
          .finally(patch.feature.reset)
      })
    } else {
      setEditingPrerequisites(true)
      openModalPrerequisites()
    }
  }
 
  const [openModalPrerequisites, hideModalPrerequisites] = useModalHook(() => {
    const initialPrereqValues = {
      gitDetails: gitSyncFormMeta?.gitSyncInitialValues.gitDetails,
      autoCommit: gitSyncFormMeta?.gitSyncInitialValues.autoCommit,
      prerequisites: flatMap(featureFlag.prerequisites, ({ feature, variations }) => {
        return variations.map(variation => ({ variation, feature } as PrerequisiteEntry))
      })
    }
 
    const handleAddPrerequisite = (prereqValues: typeof initialPrereqValues): void => {
      const validPreqs = prereqValues.prerequisites
        .reduce((acc, next) => {
          const prIndex = acc.findIndex(p => p.feature === next.feature)
          if (prIndex === -1) {
            acc.push({ feature: next.feature, variations: [next.variation] })
          } else {
            acc[prIndex].variations.push(next.variation)
          }
          return acc
        }, [] as Prerequisite[])
        .filter(({ feature, variations }) => Boolean(feature.length && variations.filter(x => x?.length).length))
      const prerequisites = validPreqs
        .reduce((acc, prereq) => {
          const { feature, variations } = prereq
          const exists = acc.find(p => p.feature === feature)
          if (exists) {
            exists.variations = exists.variations.concat(variations)
            return acc
          } else {
            return [...acc, prereq]
          }
        }, [] as Prerequisite[])
        .map(p => ({ ...p, variations: p.variations.sort() } as Prerequisite))
        .sort((a, b) => a.feature.localeCompare(b.feature))
 
      const initialPrerequisites = featureFlag.prerequisites || []
      const removedPrerequisites = initialPrerequisites.filter(pr => !prerequisites.find(p => pr.feature === p.feature))
      const newPrerequisites = prerequisites.filter(p => !initialPrerequisites.find(pr => pr.feature === p.feature))
      const updatedPrerequisites = prerequisites.filter(p =>
        initialPrerequisites.find(pr => pr.feature === p.feature && !isEqual(pr.variations, p.variations))
      )
 
      const instructions = [
        ...removedPrerequisites.map(p => patch.creators.removePrerequisite(p.feature)),
        ...newPrerequisites.map(patch.creators.addPrerequisite),
        ...updatedPrerequisites.map(patch.creators.updatePrequisite)
      ]
 
      patch.feature.addAllInstructions(instructions)
      patch.feature
        .onPatchAvailable(data => {
          patchPrerequisites(
            gitSync?.isGitSyncEnabled
              ? {
                  ...data,
                  gitDetails: prereqValues.gitDetails
                }
              : data
          )
            .then(async () => {
              if (!gitSync?.isAutoCommitEnabled && prereqValues?.autoCommit) {
                await gitSync?.handleAutoCommit(prereqValues.autoCommit)
              }
 
              hideModalPrerequisites()
              refetchFlag()
            })
            .catch(err => {
              if (err.status === GIT_SYNC_ERROR_CODE) {
                gitSync.handleError(err.data as GitSyncErrorResponse)
              } else {
                if (isGovernanceError(err)) {
                  handleGovernanceError(err.data)
                } else {
                  showError(get(err, 'data.message', err?.message), undefined, 'cf.patch.req.error')
                }
              }
            })
            .finally(() => {
              patch.feature.reset()
            })
        })
        .onEmptyPatch(hideModalPrerequisites)
    }
    const title = isEditingPrerequisites
      ? getString('cf.addPrerequisites.editPrerequisitesHeading')
      : getString('cf.addPrerequisites.addPrerequisitesHeading')
    const updateSelect = (e: React.FormEvent<HTMLInputElement>): void => {
      const _searchTerm = (e?.target as HTMLInputElement)?.value || ''
      if (_searchTerm !== searchTerm) {
        setSearchTerm(_searchTerm)
        fetchFlags({ queryParams: { ...queryParams, name: _searchTerm } })
      }
    }
    const updateSelectFromVariation = (entry: PrerequisiteEntry): void => {
      setSearchTerm(entry.feature)
      fetchFlags({ queryParams: { ...queryParams, name: entry.feature } })
    }
 
    return (
      <Dialog enforceFocus={false} title="" onClose={hideModalPrerequisites} isOpen={true}>
        <Layout.Vertical padding={{ left: 'large', right: 'medium' }} data-testid="flag-prerequisite-modal">
          <Heading level={3} font={{ variation: FontVariation.H3 }} margin={{ bottom: 'xlarge' }}>
            {title}
          </Heading>
          <Text margin={{ top: 'medium', bottom: 'xlarge' }}>
            {getString('cf.addPrerequisites.addPrerequisitesDesc')}
          </Text>
          {!loading && !error && (
            <Formik
              enableReinitialize={true}
              initialValues={initialPrereqValues}
              formName="flagPrerequisite"
              onSubmit={handleAddPrerequisite}
              validationSchema={yup.object().shape({
                gitDetails: gitSyncFormMeta?.gitSyncValidationSchema
              })}
            >
              {formikProps => (
                <Form>
                  <FieldArray name="prerequisites">
                    {arrayHelpers => {
                      return (
                        <>
                          {formikProps.values.prerequisites.map((elem, i) => {
                            return (
                              <Layout.Horizontal flex key={`prereq-${i}`}>
                                <FormInput.Select
                                  name={`prerequisites.${i}.feature`}
                                  placeholder={getString('cf.addPrerequisites.selectFlag')}
                                  items={
                                    featureList?.map((flag: Feature) => ({
                                      label: flag.name,
                                      value: flag.identifier
                                    })) ||
                                    (formikProps?.values?.prerequisites[i]?.feature
                                      ? [
                                          {
                                            label: formikProps.values.prerequisites[i].feature,
                                            value: formikProps.values.prerequisites[i].feature
                                          }
                                        ]
                                      : [])
                                  }
                                  selectProps={{
                                    inputProps: {
                                      onFocus: updateSelect,
                                      onInput: updateSelect
                                    }
                                  }}
                                />
 
                                <FormInput.Select
                                  name={`prerequisites.${i}.variation`}
                                  placeholder={getString('cf.addPrerequisites.selectVariation')}
                                  items={
                                    featureList
                                      ?.find(ff => ff.identifier === elem.feature)
                                      ?.variations?.map((v: Variation) => ({
                                        label: v.name?.length ? v.name : v.identifier,
                                        value: v.identifier
                                      })) ||
                                    (formikProps?.values?.prerequisites[i]?.variation
                                      ? [
                                          {
                                            label: formikProps.values.prerequisites[i].variation,
                                            value: formikProps.values.prerequisites[i].variation
                                          }
                                        ]
                                      : [])
                                  }
                                  selectProps={{
                                    inputProps: {
                                      onFocus: () => updateSelectFromVariation(elem)
                                    }
                                  }}
                                />
                              </Layout.Horizontal>
                            )
                          })}
                          <Button
                            minimal
                            intent="primary"
                            text={getString('cf.shared.prerequisites')}
                            icon="small-plus"
                            onClick={() => {
                              arrayHelpers.push({ feature: '', variations: [''] })
                            }}
                          />
                        </>
                      )
                    }}
                  </FieldArray>
                  {gitSync?.isGitSyncEnabled && !gitSync?.isAutoCommitEnabled && (
                    <>
                      <Container margin={{ top: 'medium', bottom: 'medium' }}>
                        <Divider />
                      </Container>
                      <SaveFlagToGitSubForm subtitle="Commit Changes" hideNameField />
                    </>
                  )}
                  <Layout.Horizontal padding={{ top: 'large', bottom: 'large' }} spacing="small">
                    <Button
                      text={getString('save')}
                      intent="primary"
                      type="submit"
                      data-testid="save-prequisites-button"
                    />
                    <Button text={getString('cancel')} onClick={hideModalPrerequisites} />
                  </Layout.Horizontal>
                </Form>
              )}
            </Formik>
          )}
        </Layout.Vertical>
      </Dialog>
    )
  }, [featureList, isEditingPrerequisites, gitSync.isGitSyncEnabled, gitSync.isAutoCommitEnabled])
 
  const prerequisitesTitle = (
    <Text
      style={{
        fontSize: '14px',
        color: '#22222A',
        fontWeight: 600,
        lineHeight: '20px',
        paddingLeft: 'var(--spacing-small)'
      }}
    >
      <StringWithTooltip stringId="cf.shared.prerequisites" tooltipId="ff_ffPrerequisites_heading" />
      <span style={{ fontSize: '12px', fontWeight: 400, display: 'inline-block', marginLeft: 'var(--spacing-xsmall)' }}>
        {getString('cf.featureFlags.prerequisitesDesc')}
      </span>
    </Text>
  )
 
  const rbacPermission: Omit<PermissionsRequest, 'permissions'> & { permission: PermissionIdentifier } = {
    resource: { resourceType: ResourceType.FEATUREFLAG },
    permission: PermissionIdentifier.EDIT_FF_FEATUREFLAG
  }
 
  const planEnforcementProps = isPlanEnforcementEnabled
    ? {
        featuresProps: {
          featuresRequest: {
            featureNames: [FeatureIdentifier.MAUS]
          }
        }
      }
    : undefined
 
  return (
    <Container className={cx(css.collapseFeatures, css.module)}>
      <Collapse {...editCardCollapsedProps} heading={prerequisitesTitle}>
        {!!featureFlag.prerequisites?.length && (
          <Layout.Horizontal flex margin={{ bottom: 'xsmall' }}>
            <Text width="50%">{getString('flag')}</Text>
            <Text width="50%">{getString('cf.shared.variation')}</Text>
          </Layout.Horizontal>
        )}
        <Layout.Vertical className={css.collapseFeaturesPrerequisites}>
          {Boolean(featureFlag.prerequisites?.length) &&
            featureFlag.prerequisites?.map((elem, i) => (
              <Layout.Horizontal key={i} flex padding="medium">
                <Text>{elem.feature}</Text>
                <Text>{elem.variations[0]}</Text>
                <RbacOptionsMenuButton
                  items={[
                    {
                      icon: 'edit',
                      text: getString('edit'),
                      onClick: handlePrerequisiteInteraction('edit', elem),
                      disabled: featureFlag.archived,
                      permission: rbacPermission,
                      ...planEnforcementProps
                    },
                    {
                      icon: 'cross',
                      text: getString('delete'),
                      onClick: handlePrerequisiteInteraction('delete', elem),
                      disabled: featureFlag.archived,
                      permission: rbacPermission,
                      ...planEnforcementProps
                    }
                  ]}
                />
              </Layout.Horizontal>
            ))}
          <RbacButton
            data-testid="add-prerequisites-button"
            minimal
            intent="primary"
            icon="small-plus"
            text={getString('cf.shared.prerequisites')}
            onClick={() => {
              setEditingPrerequisites(false)
              openModalPrerequisites()
            }}
            disabled={featureFlag.archived}
            permission={rbacPermission}
            {...planEnforcementProps}
          />
        </Layout.Vertical>
      </Collapse>
    </Container>
  )
}