All files / modules/75-cf/pages/target-group-detail/components/FlagSettingsPanel/AddFlagsToTargetGroupDialog AddFlagsToTargetGroupDialog.tsx

98.41% Statements 62/63
94.44% Branches 34/36
100% Functions 13/13
98.39% Lines 61/62

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              1x 1x 1x 1x                         1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x                                 1x           23x 23x 23x 23x 23x   23x             23x                             23x 21x 1x 20x 2x 18x 3x 15x 3x     12x     23x 2x 2x     23x                   23x   2x 2x   2x     2x               2x 2x 2x 2x         2x           23x   23x   15x   106x   26x                                   23x       2x           53x   53x                                                                 1x                                 184x                         1x  
/*
 * 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, { FC, useCallback, useMemo, useState } from 'react'
import { useParams } from 'react-router-dom'
import { Spinner } from '@blueprintjs/core'
import {
  Button,
  ButtonVariation,
  Container,
  Dialog,
  Formik,
  FormikForm,
  getErrorInfoFromErrorObject,
  Layout,
  Page,
  useToaster
} from '@harness/uicore'
import type { ObjectSchema } from 'yup'
import * as yup from 'yup'
import { useStrings } from 'framework/strings'
import { Features, Segment, useGetAllFeatures, usePatchSegment } from 'services/cf'
import { ContainerSpinner } from '@common/components/ContainerSpinner/ContainerSpinner'
import { CF_DEFAULT_PAGE_SIZE, getErrorMessage } from '@cf/utils/CFUtils'
import { NoData } from '@cf/components/NoData/NoData'
import imageUrl from '@cf/images/Feature_Flags_Teepee.svg'
import { FormValuesProvider } from '@cf/hooks/useFormValues'
import { AddFlagsToTargetGroupDialogStatus as STATUS, FlagSettingsFormRow } from '../../../TargetGroupDetailPage.types'
import usePercentageRolloutValidationSchema from '../../../hooks/usePercentageRolloutValidationSchema'
import { getAddFlagsInstruction } from '../flagSettingsInstructions'
import ListingWithSearchAndPagination from './ListingWithSearchAndPagination'
 
import css from './AddFlagsToTargetGroupDialog.module.scss'
 
export interface AddFlagToTargetGroupFormRow extends FlagSettingsFormRow {
  added?: boolean
}
 
export interface AddFlagsToTargetGroupFormValues {
  flags: Record<string, AddFlagToTargetGroupFormRow>
}
 
export interface AddFlagsToTargetGroupDialogProps {
  hideModal: () => void
  onChange: () => void
  targetGroup: Segment
  existingFlagIds: string[]
}
 
const AddFlagsToTargetGroupDialog: FC<AddFlagsToTargetGroupDialogProps> = ({
  targetGroup,
  hideModal,
  onChange,
  existingFlagIds
}) => {
  const { getString } = useStrings()
  const [searchTerm, setSearchTerm] = useState<string>('')
  const [pageNumber, setPageNumber] = useState<number>(0)
  const [submitting, setSubmitting] = useState<boolean>(false)
  const { showError } = useToaster()
 
  const { accountId: accountIdentifier, orgIdentifier, projectIdentifier } = useParams<Record<string, string>>()
 
  const {
    data: flags,
    loading: loadingFlags,
    error: flagsError,
    refetch: refetchFlags
  } = useGetAllFeatures({
    queryParams: {
      accountIdentifier,
      projectIdentifier,
      orgIdentifier,
      environmentIdentifier: targetGroup.environment,
      sortByField: 'name',
      sortOrder: 'ASCENDING',
      pageNumber,
      pageSize: CF_DEFAULT_PAGE_SIZE,
      excludedFeatures: existingFlagIds.join(','),
      name: searchTerm
    }
  })
 
  const state = useMemo<STATUS>(() => {
    if (flagsError) {
      return STATUS.error
    } else if (submitting) {
      return STATUS.submitting
    } else if (loadingFlags) {
      return !searchTerm && !flags ? STATUS.initialLoading : STATUS.loading
    } else if (flags?.itemCount === 0) {
      return searchTerm ? STATUS.noSearchResults : STATUS.noFlags
    }
 
    return STATUS.ok
  }, [flagsError, submitting, loadingFlags, flags, searchTerm])
 
  const onSearch = useCallback((str: string) => {
    setSearchTerm(str.trim().toLocaleLowerCase())
    setPageNumber(0)
  }, [])
 
  const { mutate: patchTargetGroup } = usePatchSegment({
    identifier: targetGroup.identifier,
    queryParams: {
      environmentIdentifier: targetGroup.environment as string,
      projectIdentifier,
      accountIdentifier,
      orgIdentifier
    }
  })
 
  const onSubmit = useCallback(
    async (values: AddFlagsToTargetGroupFormValues) => {
      Eif (state !== STATUS.submitting) {
        setSubmitting(true)
 
        const instructions = [
          getAddFlagsInstruction(
            // extract identifier/variation pairings from the submitted form values
            Object.entries(values.flags).map(([identifier, { variation, percentageRollout }]) => ({
              identifier,
              variation,
              percentageRollout
            }))
          )
        ]
 
        try {
          await patchTargetGroup({ instructions })
          onChange()
          hideModal()
        } catch (e) {
          showError(getErrorInfoFromErrorObject(e))
        }
 
        setSubmitting(false)
      }
    },
    [state, patchTargetGroup, onChange, hideModal, showError]
  )
 
  const percentageRolloutValidationSchema = usePercentageRolloutValidationSchema()
 
  const validationSchema = useMemo(
    () =>
      yup.object({
        flags: yup.lazy(obj =>
          yup.object(
            Object.keys(obj as AddFlagsToTargetGroupFormValues['flags']).reduce<Record<string, ObjectSchema>>(
              (objShape, key) => ({
                ...objShape,
                [key]: yup.object({
                  variation: yup.string().when('added', {
                    is: true,
                    then: yup.string().required(getString('cf.segmentDetail.variationIsRequired'))
                  }),
                  percentageRollout: percentageRolloutValidationSchema
                })
              }),
              {}
            )
          )
        )
      }),
    []
  )
 
  return (
    <Formik<AddFlagsToTargetGroupFormValues>
      formName="AddFlagsToTargetGroup"
      onSubmit={values => {
        onSubmit(values)
      }}
      initialValues={{ flags: {} }}
      validationSchema={validationSchema}
    >
      {({ submitForm, values, setFieldValue, errors }) => {
        const flagCount = Object.values(values.flags).filter(({ added }) => added).length
 
        return (
          <FormValuesProvider values={values} setField={setFieldValue} errors={errors}>
            <Dialog
              className={css.dialog}
              isOpen
              enforceFocus={false}
              title={getString('cf.segmentDetail.addFlagToTargetGroup')}
              onClose={hideModal}
              footer={
                <Layout.Horizontal spacing="small" flex={{ alignItems: 'center' }}>
                  <Button
                    variation={ButtonVariation.PRIMARY}
                    type="submit"
                    intent="primary"
                    onClick={submitForm}
                    disabled={!flagCount || submitting}
                  >
                    {getString('cf.segmentDetail.addFlags', { flagCount })}
                  </Button>
                  <Button variation={ButtonVariation.SECONDARY} onClick={hideModal}>
                    {getString('cancel')}
                  </Button>
                  {submitting && (
                    <span data-testid="saving-spinner">
                      <Spinner size={24} />
                    </span>
                  )}
                </Layout.Horizontal>
              }
            >
              <FormikForm disabled={submitting}>
                <Layout.Vertical className={css.body} spacing="small">
                  {state === STATUS.error && (
                    <Page.Error message={getErrorMessage(flagsError)} onClick={() => refetchFlags()} />
                  )}
 
                  {state === STATUS.initialLoading && <ContainerSpinner flex={{ align: 'center-center' }} />}
 
                  {state === STATUS.noFlags && (
                    <Container height="100%" flex={{ align: 'center-center' }}>
                      <NoData imageURL={imageUrl} message={getString('cf.segmentDetail.noFlagsAvailable')} />
                    </Container>
                  )}
 
                  {[STATUS.ok, STATUS.loading, STATUS.noSearchResults, STATUS.submitting].includes(state) && (
                    <ListingWithSearchAndPagination
                      state={state}
                      onSearch={onSearch}
                      flags={flags as Features}
                      setPageNumber={setPageNumber}
                      isFlagAdded={identifier => !!values.flags[identifier]?.added}
                    />
                  )}
                </Layout.Vertical>
              </FormikForm>
            </Dialog>
          </FormValuesProvider>
        )
      }}
    </Formik>
  )
}
 
export default AddFlagsToTargetGroupDialog