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

100% Statements 50/50
82.86% Branches 58/70
100% Functions 14/14
100% Lines 48/48

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              1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x           1x 7x 7x   7x             7x                   7x 6x                           7x           7x 12x       7x 6x 3x                   7x 6x 3x     3x       30x   9x   12x       30x               7x 1x 1x     7x 1x 1x     7x           7x 1x     1x         6x 1x     5x 1x                       4x                   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, useEffect, useMemo } from 'react'
import { useParams } from 'react-router-dom'
import { Container, PageError, useToaster } from '@harness/uicore'
import { useStrings } from 'framework/strings'
import { Feature, GetAllFeaturesQueryParams, Segment, useGetAllFeatures, useGetSegmentFlags } from 'services/cf'
import { ContainerSpinner } from '@common/components/ContainerSpinner/ContainerSpinner'
import { getErrorMessage } from '@cf/utils/CFUtils'
import { NoData } from '@cf/components/NoData/NoData'
import imageUrl from '@cf/images/Feature_Flags_Teepee.svg'
import type { TargetGroupFlagsMap } from '../../TargetGroupDetailPage.types'
import useAddFlagsToTargetGroupDialog from '../../hooks/useAddFlagsToTargetGroupDialog'
import FlagSettingsForm from './FlagSettingsForm'
 
export interface FlagSettingsPanelProps {
  targetGroup: Segment
}
 
const FlagSettingsPanel: FC<FlagSettingsPanelProps> = ({ targetGroup }) => {
  const { getString } = useStrings()
  const { showSuccess } = useToaster()
 
  const { accountId: accountIdentifier, orgIdentifier, projectIdentifier } = useParams<Record<string, string>>()
 
  const {
    data: targetGroupFlags,
    loading: loadingTargetGroupFlags,
    error: targetGroupFlagsError,
    refetch: refetchTargetGroupFlags
  } = useGetSegmentFlags({
    identifier: targetGroup.identifier,
    queryParams: {
      accountIdentifier,
      orgIdentifier,
      projectIdentifier,
      environmentIdentifier: targetGroup.environment as string
    }
  })
 
  const flagsQueryParams = useMemo<GetAllFeaturesQueryParams>(
    () => ({
      accountIdentifier,
      orgIdentifier,
      projectIdentifier,
      environmentIdentifier: targetGroup.environment as string
    }),
    [accountIdentifier, orgIdentifier, projectIdentifier, targetGroup.environment]
  )
 
  const {
    data: flags,
    loading: loadingFlags,
    error: flagsError,
    refetch: refetchFlags
  } = useGetAllFeatures({
    lazy: true,
    debounce: 200,
    queryParams: flagsQueryParams
  })
 
  const targetGroupFlagIds = useMemo<string[]>(
    () => (targetGroupFlags || []).map(({ identifier }) => identifier),
    [targetGroupFlags]
  )
 
  useEffect(() => {
    if (targetGroupFlagIds.length) {
      refetchFlags({
        queryParams: {
          ...flagsQueryParams,
          pageSize: targetGroupFlagIds.length,
          featureIdentifiers: targetGroupFlagIds.join(',')
        }
      })
    }
  }, [flagsQueryParams, refetchFlags, targetGroupFlagIds])
 
  const targetGroupFlagsMap = useMemo<TargetGroupFlagsMap>(() => {
    if (!targetGroupFlags?.length || !flags?.features?.length) {
      return {}
    }
 
    return (
      targetGroupFlags
        // filter out flags that are present in the target group, but not in the features response
        .filter(({ identifier: targetGroupFlagId }) =>
          (flags.features ?? []).some(({ identifier: flagId }) => targetGroupFlagId === flagId)
        )
        .sort(({ name: n1 }, { name: n2 }) => (n1.toLocaleLowerCase() > n2.toLocaleLowerCase() ? 1 : -1))
        .reduce<TargetGroupFlagsMap>(
          (map, targetGroupFlag) => ({
            ...map,
            [targetGroupFlag.identifier]: {
              ...targetGroupFlag,
              flag: flags?.features?.find(({ identifier }) => identifier === targetGroupFlag.identifier) as Feature
            }
          }),
          {}
        )
    )
  }, [targetGroupFlags, flags?.features])
 
  const onFlagsAdded = useCallback(() => {
    showSuccess(getString('cf.segmentDetail.flagsAddedSuccessfully'))
    refetchTargetGroupFlags()
  }, [refetchTargetGroupFlags, showSuccess])
 
  const onFlagsUpdated = useCallback(() => {
    showSuccess(getString('cf.segmentDetail.updateSuccessful'))
    refetchTargetGroupFlags()
  }, [refetchTargetGroupFlags, showSuccess])
 
  const [openAddFlagsToTargetGroupDialog] = useAddFlagsToTargetGroupDialog(
    targetGroup,
    onFlagsAdded,
    targetGroupFlagIds
  )
 
  if (targetGroupFlagsError || flagsError) {
    return (
      <PageError
        message={getErrorMessage(targetGroupFlagsError || flagsError)}
        onClick={async () => await refetchTargetGroupFlags()}
      />
    )
  }
 
  if (loadingTargetGroupFlags || loadingFlags || (targetGroupFlags?.length && !flags)) {
    return <ContainerSpinner flex={{ align: 'center-center' }} />
  }
 
  if (!targetGroupFlags?.length || !flags?.features?.length) {
    return (
      <Container width="100%" height="100%" flex={{ align: 'center-center' }}>
        <NoData
          imageURL={imageUrl}
          message={getString('cf.segmentDetail.noFlags')}
          onClick={openAddFlagsToTargetGroupDialog}
          buttonText={getString('cf.segmentDetail.addFlagToTargetGroup')}
        />
      </Container>
    )
  }
 
  return (
    <FlagSettingsForm
      targetGroup={targetGroup}
      targetGroupFlagsMap={targetGroupFlagsMap}
      onChange={onFlagsUpdated}
      openAddFlagDialog={openAddFlagsToTargetGroupDialog}
    />
  )
}
 
export default FlagSettingsPanel