All files / modules/75-cf/pages/feature-flags-detail/targeting-rules-tab TargetingRulesTab.tsx

100% Statements 64/64
92% Branches 23/25
100% Functions 17/17
100% Lines 64/64

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              3x 3x 3x 3x 3x 3x 3x               3x 3x   3x 3x   3x 3x 3x 3x 3x 3x 3x             3x         21x 21x   21x   21x                       21x                 21x         21x 21x   21x 21x 21x             21x 21x   21x 12x         21x 12x         21x         2x 2x                   2x     21x         1x 1x       1x     21x         2x 2x                             4x         2x     21x         1x   1x       1x     21x             8x   1x     70x                           4x                       70x                   2x     1x     2x     1x                                                                   3x  
/*
 * 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 { Card, Container, Formik, FormikForm, Layout } from '@harness/uicore'
import React, { ReactElement } from 'react'
import { useParams } from 'react-router-dom'
import { v4 as uuid } from 'uuid'
import { FieldArray, FieldArrayRenderProps } from 'formik'
import FlagToggleSwitch from '@cf/components/EditFlagTabs/FlagToggleSwitch'
import {
  Feature,
  GetAllSegmentsQueryParams,
  GetAllTargetsQueryParams,
  useGetAllSegments,
  useGetAllTargets,
  Variation
} from 'services/cf'
import { FeatureFlagActivationStatus } from '@cf/utils/CFUtils'
import useActiveEnvironment from '@cf/hooks/useActiveEnvironment'
 
import usePatchFeatureFlag from './hooks/usePatchFeatureFlag'
import TargetingRulesTabFooter from './components/tab-targeting-footer/TargetingRulesTabFooter'
 
import FlagEnabledRulesCard from './components/flag-enabled-rules-card/FlagEnabledRulesCard'
import { FormVariationMap, VariationPercentageRollout, TargetingRuleItemType, TargetingRuleItemStatus } from './types'
import useFeatureEnabled from './hooks/useFeatureEnabled'
import DefaultRules from './components/default-rules/DefaultRules'
import useTargetingRulesFormValidation from './hooks/useTargetingRulesFormValidation'
import useTargetingRulesFormData from './hooks/useTargetingRulesFormData'
import css from './TargetingRulesTab.module.scss'
export interface TargetingRulesTabProps {
  featureFlagData: Feature
  refetchFlag: () => Promise<unknown>
  refetchFlagLoading: boolean
}
 
const TargetingRulesTab = ({
  featureFlagData,
  refetchFlag,
  refetchFlagLoading
}: TargetingRulesTabProps): ReactElement => {
  const { orgIdentifier, accountId: accountIdentifier, projectIdentifier } = useParams<Record<string, string>>()
  const { activeEnvironment: environmentIdentifier } = useActiveEnvironment()
 
  const debounce = 500
 
  const queryParams = {
    environmentIdentifier,
    projectIdentifier,
    accountIdentifier,
    orgIdentifier,
    pageSize: 100
  }
 
  const {
    data: targetsData,
    loading: targetsLoading,
    refetch: refetchTargets
  } = useGetAllTargets({
    queryParams: queryParams as GetAllTargetsQueryParams,
    debounce
  })
 
  const {
    data: segmentsData,
    loading: segmentsLoading,
    refetch: refetchSegments
  } = useGetAllSegments({
    queryParams: queryParams as GetAllSegmentsQueryParams,
    debounce
  })
 
  const segments = segmentsData?.segments || []
  const targets = targetsData?.targets || []
 
  const { initialValues, getNextPriority, variationColorMap } = useTargetingRulesFormData({ featureFlagData, segments })
  const { validate } = useTargetingRulesFormValidation()
  const { saveChanges, loading: patchFeatureLoading } = usePatchFeatureFlag({
    initialValues,
    variations: featureFlagData.variations,
    featureFlagIdentifier: featureFlagData.identifier,
    refetchFlag
  })
 
  const { featureEnabled } = useFeatureEnabled()
  const disabled = patchFeatureLoading || refetchFlagLoading || targetsLoading || segmentsLoading || !featureEnabled
 
  const handleRefetchSegments = async (searchTerm: string): Promise<void> =>
    await refetchSegments({
      queryParams: { ...queryParams, identifier: searchTerm, name: searchTerm },
      debounce
    })
 
  const handleRefetchTargets = async (searchTerm: string): Promise<void> =>
    await refetchTargets({
      queryParams: { ...queryParams, targetIdentifier: searchTerm, targetName: searchTerm },
      debounce
    })
 
  const handleAddVariation = (
    newVariation: Variation,
    targetingRuleItems: (FormVariationMap | VariationPercentageRollout)[],
    arrayHelpers: FieldArrayRenderProps
  ): void => {
    const priority = getNextPriority(targetingRuleItems)
    const variation: FormVariationMap = {
      status: TargetingRuleItemStatus.ADDED,
      priority: priority,
      type: TargetingRuleItemType.VARIATION,
      variationIdentifier: newVariation.identifier,
      variationName: newVariation.name as string,
      targets: [],
      targetGroups: []
    }
 
    arrayHelpers.push(variation)
  }
 
  const handleRemoveVariation = (
    removedVariationIndex: number,
    targetingRuleItems: (FormVariationMap | VariationPercentageRollout)[],
    arrayHelpers: FieldArrayRenderProps
  ): void => {
    const item = targetingRuleItems[removedVariationIndex] as FormVariationMap
    const variation: FormVariationMap = {
      ...item,
      status: TargetingRuleItemStatus.DELETED
    }
    arrayHelpers.replace(removedVariationIndex, variation)
  }
 
  const handleAddPercentageRollout = (
    targetingRuleItems: (FormVariationMap | VariationPercentageRollout)[],
    arrayHelpers: FieldArrayRenderProps
  ): void => {
    // need to add with empty fields so the validation messages appear correctly
    const priority = getNextPriority(targetingRuleItems)
    const newPercentageRollout: VariationPercentageRollout = {
      status: TargetingRuleItemStatus.ADDED,
      ruleId: uuid(),
      priority: priority,
      type: TargetingRuleItemType.PERCENTAGE_ROLLOUT,
      bucketBy: 'identifier',
      clauses: [
        {
          attribute: '',
          id: '',
          negate: false,
          op: '',
          values: ['']
        }
      ],
      variations: featureFlagData.variations.map(variation => ({
        variation: variation.identifier,
        weight: 0
      }))
    }
    arrayHelpers.push(newPercentageRollout)
  }
 
  const handleRemovePercentageRollout = (
    removedPercentageRolloutIndex: number,
    targetingRuleItems: (FormVariationMap | VariationPercentageRollout)[],
    arrayHelpers: FieldArrayRenderProps
  ): void => {
    const item = targetingRuleItems[removedPercentageRolloutIndex] as VariationPercentageRollout
 
    const variation: VariationPercentageRollout = {
      ...item,
      status: TargetingRuleItemStatus.DELETED
    }
    arrayHelpers.replace(removedPercentageRolloutIndex, variation)
  }
 
  return (
    <Formik
      enableReinitialize={true}
      validateOnChange={false}
      validateOnBlur={false}
      formName="targeting-rules-form"
      initialValues={initialValues}
      validate={values => validate(values)}
      onSubmit={values => {
        saveChanges(values)
      }}
    >
      {formikProps => (
        <FormikForm data-testid="targeting-rules-tab-form" disabled={disabled}>
          <Container className={css.tabContainer}>
            <Layout.Vertical
              spacing="small"
              padding={{ left: 'xlarge', right: 'xlarge', bottom: 'xlarge' }}
              className={css.flagRulesSection}
            >
              <Card elevation={0}>
                <FlagToggleSwitch
                  disabled={disabled}
                  currentState={formikProps.values.state}
                  currentEnvironmentState={featureFlagData.envProperties?.state}
                  handleToggle={() =>
                    formikProps.setFieldValue(
                      'state',
                      formikProps.values.state === FeatureFlagActivationStatus.OFF
                        ? FeatureFlagActivationStatus.ON
                        : FeatureFlagActivationStatus.OFF
                    )
                  }
                />
              </Card>
              <FieldArray
                name="targetingRuleItems"
                render={arrayHelpers => (
                  <FlagEnabledRulesCard
                    variationColorMap={variationColorMap}
                    targetingRuleItems={formikProps.values.targetingRuleItems}
                    targets={targets}
                    segments={segments}
                    featureFlagVariations={featureFlagData.variations}
                    disabled={disabled}
                    refetchSegments={handleRefetchSegments}
                    refetchTargets={handleRefetchTargets}
                    addVariation={newVariation =>
                      handleAddVariation(newVariation, formikProps.values.targetingRuleItems, arrayHelpers)
                    }
                    removeVariation={removedVariationIndex =>
                      handleRemoveVariation(removedVariationIndex, formikProps.values.targetingRuleItems, arrayHelpers)
                    }
                    addPercentageRollout={() =>
                      handleAddPercentageRollout(formikProps.values.targetingRuleItems, arrayHelpers)
                    }
                    removePercentageRollout={removedPercentageRolloutIndex =>
                      handleRemovePercentageRollout(
                        removedPercentageRolloutIndex,
                        formikProps.values.targetingRuleItems,
                        arrayHelpers
                      )
                    }
                  />
                )}
              />
 
              <Card>
                <DefaultRules
                  hideSubheading
                  featureFlagVariations={featureFlagData.variations}
                  titleStringId="cf.featureFlags.rules.whenFlagDisabled"
                  inputName="offVariation"
                />
              </Card>
            </Layout.Vertical>
 
            {formikProps.dirty && (
              <TargetingRulesTabFooter
                isLoading={disabled}
                handleSubmit={formikProps.handleSubmit}
                handleCancel={formikProps.handleReset}
              />
            )}
          </Container>
        </FormikForm>
      )}
    </Formik>
  )
}
 
export default TargetingRulesTab