All files / modules/20-rbac/pages/ResourceGroupDetails ResourceGroupDetails.tsx

85.57% Statements 83/97
73.04% Branches 84/115
71.43% Functions 10/14
86.17% Lines 81/94

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              10x 10x                       10x   10x 10x 10x   10x 10x 10x               10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x                             10x   10x 11x     10x 10x 10x 10x 10x 10x 10x 10x 10x   10x 10x   10x                               10x                 10x               10x 4x     4x 4x 4x 4x     10x 4x 4x 4x 4x     10x                 10x 2x 2x 1x   2x 1x 1x   1x             1x 1x 1x 1x 1x             10x 10x     10x 2x 2x     10x               10x         10x 10x 10x   10x   10x 10x           10x     10x                                                                                                                                                       2x                                                                                                                                           10x  
/*
 * 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, { useEffect, useState } from 'react'
import {
  Text,
  Layout,
  Container,
  Icon,
  ButtonVariation,
  useToaster,
  Page,
  Card,
  Button,
  DropDown
} from '@wings-software/uicore'
import { Color, FontVariation } from '@harness/design-system'
 
import { useParams } from 'react-router-dom'
import ReactTimeago from 'react-timeago'
import { defaultTo } from 'lodash-es'
import type { ModulePathParams, ResourceGroupDetailsPathProps } from '@common/interfaces/RouteInterfaces'
import { useStrings } from 'framework/strings'
import ResourceTypeList from '@rbac/components/ResourceTypeList/ResourceTypeList'
import {
  useUpdateResourceGroupV2,
  ResourceGroupV2,
  useGetResourceTypes,
  ScopeSelector,
  useGetResourceGroupV2,
  ResourceGroupV2Request
} from 'services/resourcegroups'
import { ResourceType, ResourceCategory } from '@rbac/interfaces/ResourceType'
import { NGBreadcrumbs } from '@common/components/NGBreadcrumbs/NGBreadcrumbs'
import routes from '@common/RouteDefinitions'
import RbacFactory from '@rbac/factories/RbacFactory'
import { useDocumentTitle } from '@common/hooks/useDocumentTitle'
import RbacButton from '@rbac/components/Button/Button'
import { PermissionIdentifier } from '@rbac/interfaces/PermissionIdentifier'
import { usePermission } from '@rbac/hooks/usePermission'
import { SelectionType } from '@rbac/utils/utils'
import useRBACError from '@rbac/utils/useRBACError/useRBACError'
import { getScopeFromDTO } from '@common/components/EntityReference/EntityReference'
import ResourcesCardList from '@rbac/components/ResourcesCardList/ResourcesCardList'
import {
  cleanUpResourcesMap,
  computeResourceMapOnChange,
  computeResourceMapOnMultiChange,
  getFilteredResourceTypes,
  getFormattedDataForApi,
  getIncludedScopes,
  getResourceSelectorsfromMap,
  getScopeDropDownItems,
  getScopeType,
  getSelectedResourcesMap,
  getSelectionType,
  SelectorScope,
  validateResourceSelectors
} from './utils'
import css from './ResourceGroupDetails.module.scss'
 
const ResourceGroupDetails: React.FC = () => {
  const { accountId, projectIdentifier, orgIdentifier, resourceGroupIdentifier, module } = useParams<
    ResourceGroupDetailsPathProps & ModulePathParams
  >()
  const { getString } = useStrings()
  const { showError, showSuccess } = useToaster()
  const { getRBACErrorMessage } = useRBACError()
  const [isUpdated, setIsUpdated] = useState<boolean>(false)
  const [includedScopes, setIncludedScopes] = useState<ScopeSelector[]>([])
  const [selectedScope, setSelectedScope] = useState<SelectorScope>(SelectorScope.CURRENT)
  const [selectionType, setSelectionType] = useState<SelectionType>(SelectionType.SPECIFIED)
  const [selectedResourcesMap, setSelectedResourceMap] = useState<Map<ResourceType, string[] | string>>(new Map())
  const [resourceTypes, setResourceTypes] = useState<ResourceType[]>([])
  const [resourceCategoryMap, setResourceCategoryMap] =
    useState<Map<ResourceType | ResourceCategory, ResourceType[] | undefined>>()
  const scope = getScopeFromDTO({ accountIdentifier: accountId, orgIdentifier, projectIdentifier })
 
  const [canEdit] = usePermission(
    {
      resource: {
        resourceType: ResourceType.RESOURCEGROUP,
        resourceIdentifier: resourceGroupIdentifier
      },
      permissions: [PermissionIdentifier.UPDATE_RESOURCEGROUP]
    },
    [resourceGroupIdentifier]
  )
 
  const {
    data: resourceGroupDetails,
    error: errorInGettingResourceGroup,
    loading,
    refetch
  } = useGetResourceGroupV2({
    identifier: resourceGroupIdentifier,
    queryParams: {
      accountIdentifier: accountId,
      projectIdentifier,
      orgIdentifier
    }
  })
 
  const { data: resourceTypeData } = useGetResourceTypes({
    queryParams: {
      accountIdentifier: accountId,
      projectIdentifier,
      orgIdentifier
    }
  })
 
  useEffect(() => {
    setSelectedResourceMap(
      getSelectedResourcesMap(resourceTypes, resourceGroupDetails?.data?.resourceGroup.resourceFilter)
    )
    setIsUpdated(false)
    setIncludedScopes(defaultTo(resourceGroupDetails?.data?.resourceGroup.includedScopes, []))
    setSelectionType(getSelectionType(resourceGroupDetails?.data?.resourceGroup))
    setSelectedScope(getScopeType(resourceGroupDetails?.data?.resourceGroup))
  }, [resourceGroupDetails?.data?.resourceGroup])
 
  useEffect(() => {
    const types = getFilteredResourceTypes(resourceTypeData, selectedScope)
    setResourceTypes(types)
    setResourceCategoryMap(_map => RbacFactory.getResourceCategoryList(types))
    setSelectedResourceMap(_selectedResourcesMap => cleanUpResourcesMap(types, _selectedResourcesMap, selectionType))
  }, [selectedScope, resourceTypeData])
 
  const { mutate: updateResourceGroup, loading: updating } = useUpdateResourceGroupV2({
    identifier: defaultTo(resourceGroupIdentifier, ''),
    queryParams: {
      accountIdentifier: accountId,
      orgIdentifier,
      projectIdentifier
    }
  })
 
  const updateResourceGroupData = async (data: ResourceGroupV2): Promise<void> => {
    const resourceSelectors = getResourceSelectorsfromMap(selectedResourcesMap)
    const invalidResources = validateResourceSelectors(resourceSelectors)?.map(val =>
      getString(defaultTo(RbacFactory.getResourceTypeLabelKey(val), 'string'))
    )
    if (invalidResources.length > 0) {
      showError(getString('rbac.resourceSelectorErrorMessage', { resources: invalidResources.toString() }))
      return
    }
    const dataToSubmit: ResourceGroupV2Request = getFormattedDataForApi(
      data,
      selectionType,
      includedScopes,
      resourceSelectors
    )
 
    try {
      const updated = await updateResourceGroup(dataToSubmit)
      Eif (updated) {
        showSuccess(getString('rbac.resourceGroup.updateSuccess'))
        refetch()
      }
    } /* istanbul ignore next */ catch (err) {
      showError(getRBACErrorMessage(err))
    }
  }
 
  const disableSelection = (): boolean => {
    return selectionType === SelectionType.ALL || selectedScope === SelectorScope.INCLUDE_CHILD_SCOPES
  }
 
  const onResourceSelectionChange = (resourceType: ResourceType, isAdd: boolean, identifiers?: string[]): void => {
    setIsUpdated(true)
    computeResourceMapOnChange(setSelectedResourceMap, selectedResourcesMap, resourceType, isAdd, identifiers)
  }
 
  const onSelectionTypeChange = (type: SelectionType): void => {
    setSelectionType(type)
    setIsUpdated(true)
    if (type === SelectionType.ALL) {
      computeResourceMapOnMultiChange(setSelectedResourceMap, selectedResourcesMap, resourceTypes, true)
    }
  }
 
  const onResourceCategorySelect = (types: ResourceType[], isAdd: boolean): void => {
    setIsUpdated(true)
    computeResourceMapOnMultiChange(setSelectedResourceMap, selectedResourcesMap, types, isAdd)
  }
 
  const resourceGroup = resourceGroupDetails?.data?.resourceGroup
  const isHarnessManaged = resourceGroupDetails?.data?.harnessManaged
  const disableAddingResources = isHarnessManaged || !canEdit || selectionType === SelectionType.ALL
 
  useDocumentTitle([defaultTo(resourceGroup?.name, ''), getString('resourceGroups')])
 
  Iif (loading) return <Page.Spinner />
  Iif (errorInGettingResourceGroup)
    return (
      <Page.Error
        message={defaultTo((errorInGettingResourceGroup.data as Error)?.message, errorInGettingResourceGroup.message)}
      />
    )
  Iif (!resourceGroup)
    return <Page.NoDataCard icon="resources-icon" message={getString('rbac.resourceGroup.noResourceGroupFound')} />
 
  return (
    <>
      <Page.Header
        size="xlarge"
        breadcrumbs={
          <NGBreadcrumbs
            links={[
              {
                url: routes.toResourceGroups({ accountId, orgIdentifier, projectIdentifier, module }),
                label: `${getString('accessControl')}: ${getString('resourceGroups')}`
              }
            ]}
          />
        }
        title={
          <Layout.Horizontal spacing="medium" flex={{ justifyContent: 'flex-start', alignItems: 'center' }}>
            <div style={{ backgroundColor: resourceGroup.color }} className={css.colorDiv}></div>
            <Layout.Vertical padding={{ left: 'small' }} spacing="xsmall">
              <Text font="medium" lineClamp={1} color={Color.BLACK} width={700}>
                {resourceGroup.name}
              </Text>
              {resourceGroup.description && (
                <Text lineClamp={1} color={Color.GREY_400} width={700}>
                  {resourceGroup.description}
                </Text>
              )}
            </Layout.Vertical>
          </Layout.Horizontal>
        }
        toolbar={
          <Layout.Horizontal margin={{ top: 'huge' }}>
            <Layout.Horizontal
              padding={{ right: 'small' }}
              border={{ right: true, color: Color.GREY_300 }}
              spacing="xsmall"
            >
              <Text font="small">{getString('created').toUpperCase()}:</Text>
              <Text lineClamp={1} color={Color.BLACK} font="small">
                {isHarnessManaged ? (
                  <Text lineClamp={1} color={Color.BLACK}>
                    {getString('rbac.resourceGroup.builtInResourceGroup')}
                  </Text>
                ) : (
                  <ReactTimeago date={defaultTo(resourceGroupDetails?.data?.createdAt, '')} />
                )}
              </Text>
            </Layout.Horizontal>
            <Layout.Horizontal spacing="xsmall" padding={{ left: 'small' }}>
              <Text font="small">{getString('lastUpdated').toUpperCase()}:</Text>
              <Text lineClamp={1} color={Color.BLACK} font="small">
                {isHarnessManaged ? (
                  <Text lineClamp={1} color={Color.BLACK}>
                    {getString('rbac.resourceGroup.builtInResourceGroup')}
                  </Text>
                ) : (
                  <ReactTimeago date={defaultTo(resourceGroupDetails?.data?.lastModifiedAt, '')} />
                )}
              </Text>
            </Layout.Horizontal>
          </Layout.Horizontal>
        }
      />
      <Page.Body loading={updating || loading} className={css.resourceGroupDetails}>
        {!isHarnessManaged && (
          <Card className={css.subHeader}>
            <Layout.Horizontal flex={{ justifyContent: 'space-between' }} width="100%">
              <Text color={Color.BLACK}>{getString('rbac.resourceGroup.selectionHeading')}</Text>
              <Layout.Horizontal flex={{ justifyContent: 'flex-end' }} spacing="medium">
                {isUpdated && (
                  <Layout.Horizontal spacing="xsmall" flex>
                    <Icon name="dot" color={Color.ORANGE_600} size={20} />
                    <Text color={Color.ORANGE_600}>{getString('unsavedChanges')}</Text>
                  </Layout.Horizontal>
                )}
                <RbacButton
                  text={getString('applyChanges')}
                  onClick={() => updateResourceGroupData(resourceGroup)}
                  disabled={updating || !isUpdated}
                  variation={ButtonVariation.PRIMARY}
                  permission={{
                    resource: {
                      resourceType: ResourceType.RESOURCEGROUP,
                      resourceIdentifier: resourceGroupIdentifier
                    },
                    permission: PermissionIdentifier.UPDATE_RESOURCEGROUP
                  }}
                />
                <Button
                  text={getString('common.discard')}
                  onClick={() => refetch()}
                  disabled={!isUpdated}
                  variation={ButtonVariation.TERTIARY}
                />
              </Layout.Horizontal>
            </Layout.Horizontal>
          </Card>
        )}
        <Container className={css.pageContainer}>
          <Container padding="xlarge" className={css.resourceTypeListContainer}>
            <ResourceTypeList
              selectionType={selectionType}
              resourceCategoryMap={resourceCategoryMap}
              onResourceSelectionChange={onResourceSelectionChange}
              onResourceCategorySelect={onResourceCategorySelect}
              preSelectedResourceList={Array.from(selectedResourcesMap.keys())}
              disableAddingResources={disableAddingResources}
              onSelectionTypeChange={onSelectionTypeChange}
            />
          </Container>
          <Layout.Vertical spacing="small">
            <Layout.Horizontal
              spacing="small"
              flex={{ justifyContent: 'flex-start' }}
              padding={{ top: 'xlarge', left: 'xlarge', bottom: 'small' }}
            >
              <Text font={{ variation: FontVariation.H6 }} color={Color.GREY_800}>
                {getString('common.scope')}
              </Text>
              <DropDown
                items={getScopeDropDownItems(scope, getString)}
                icon="settings"
                value={selectedScope}
                onChange={item => {
                  setIsUpdated(true)
                  setSelectedScope(item.value as SelectorScope)
                  setIncludedScopes(getIncludedScopes(item.value as SelectorScope, resourceGroup))
                }}
                width={300}
                filterable={false}
              />
            </Layout.Horizontal>
            <ResourcesCardList
              selectedResourcesMap={selectedResourcesMap}
              resourceCategoryMap={resourceCategoryMap}
              onResourceSelectionChange={onResourceSelectionChange}
              onResourceCategorySelect={onResourceCategorySelect}
              disableAddingResources={isHarnessManaged}
              disableSelection={disableSelection()}
            />
          </Layout.Vertical>
        </Container>
      </Page.Body>
    </>
  )
}
 
export default ResourceGroupDetails