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

93.15% Statements 68/73
76.52% Branches 88/115
91.67% Functions 11/12
94.44% Lines 68/72

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              10x 10x 10x 10x 10x 10x 10x 10x 10x 10x               10x 10x 10x 10x 10x 10x 10x 10x   10x 10x 10x 10x 10x   10x   8x 8x   8x 8x 8x 8x 8x 8x 8x                 8x                     8x       8x                 8x             8x 3x 3x     8x 3x     8x   8x 5x     8x 1x 1x     8x 1x 1x 1x 1x                   8x 8x   8x   8x     8x     8x                                                                                                                     10x   10x               1x 1x 1x                                                     1x                               10x       20x                                             10x  
/*
 * Copyright 2022 Harness Inc. All rights reserved.
 * Use of this source code is governed by the PolyForm Free Trial 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/05/PolyForm-Free-Trial-1.0.0.txt.
 */
 
import React, { useEffect, useState } from 'react'
import { Card, Container, Icon, Layout, Text, ButtonVariation, PageError } from '@wings-software/uicore'
import { Color } from '@harness/design-system'
import { useParams } from 'react-router-dom'
import ReactTimeago from 'react-timeago'
import { defaultTo } from 'lodash-es'
import { useStrings } from 'framework/strings'
import { Page, useToaster } from '@common/exports'
import { PageSpinner } from '@common/components'
import {
  Permission,
  Role,
  useGetPermissionList,
  useGetRole,
  usePutRole,
  useGetPermissionResourceTypesList
} from 'services/rbac'
import { NGBreadcrumbs } from '@common/components/NGBreadcrumbs/NGBreadcrumbs'
import PermissionCard from '@rbac/components/PermissionCard/PermissionCard'
import RbacFactory from '@rbac/factories/RbacFactory'
import { ResourceType, ResourceCategory } from '@rbac/interfaces/ResourceType'
import { getPermissionMap, onPermissionChange } from '@rbac/pages/RoleDetails/utils'
import routes from '@common/RouteDefinitions'
import TagsRenderer from '@common/components/TagsRenderer/TagsRenderer'
import { getRoleIcon } from '@rbac/utils/utils'
import type { PipelineType, RolePathProps, ProjectPathProps } from '@common/interfaces/RouteInterfaces'
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 css from './RoleDetails.module.scss'
 
const RoleDetails: React.FC = () => {
  const { accountId, projectIdentifier, orgIdentifier, roleIdentifier, module } =
    useParams<PipelineType<ProjectPathProps & RolePathProps>>()
  const [resource, setResource] = useState<ResourceType>()
  const [resourceCategoryMap, setResourceCategoryMap] =
    useState<Map<ResourceType | ResourceCategory, ResourceType[] | undefined>>()
  const { getString } = useStrings()
  const { showSuccess, showError } = useToaster()
  const [permissions, setPermissions] = useState<string[]>([])
  const [isUpdated, setIsUpdated] = useState<boolean>(false)
  const listRef: Map<ResourceCategory | ResourceType, HTMLDivElement | null> = new Map()
  const { data, loading, error, refetch } = useGetRole({
    identifier: roleIdentifier,
    queryParams: {
      accountIdentifier: accountId,
      orgIdentifier,
      projectIdentifier
    }
  })
 
  const [canEdit] = usePermission(
    {
      resource: {
        resourceType: ResourceType.ROLE,
        resourceIdentifier: roleIdentifier
      },
      permissions: [PermissionIdentifier.UPDATE_ROLE]
    },
    [roleIdentifier]
  )
 
  const { data: resourceGroups, loading: resourceTypeLoading } = useGetPermissionResourceTypesList({
    queryParams: { accountIdentifier: accountId, projectIdentifier, orgIdentifier }
  })
 
  const { mutate: addPermissions } = usePutRole({
    identifier: roleIdentifier,
    queryParams: {
      accountIdentifier: accountId,
      orgIdentifier,
      projectIdentifier
    }
  })
 
  const { data: permissionList, loading: permissionLoading } = useGetPermissionList({
    queryParams: {
      accountIdentifier: accountId,
      orgIdentifier,
      projectIdentifier
    }
  })
  useEffect(() => {
    setPermissions(defaultTo(data?.data?.role.permissions, []))
    setIsUpdated(false)
  }, [data?.data])
 
  useEffect(() => {
    setResourceCategoryMap(RbacFactory.getResourceCategoryList(defaultTo(resourceGroups?.data, []) as ResourceType[]))
  }, [resourceGroups?.data])
 
  const permissionsMap: Map<ResourceType, Permission[]> = getPermissionMap(permissionList?.data)
 
  const isPermissionEnabled = (_permission: string): boolean => {
    return permissions.includes(_permission)
  }
 
  const onChangePermission = (permission: string, isAdd: boolean): void => {
    onPermissionChange(permission, isAdd, permissions, setPermissions)
    setIsUpdated(true)
  }
 
  const submitChanges = async (role: Role): Promise<void> => {
    role['permissions'] = permissions
    try {
      const updated = await addPermissions(role)
      /* istanbul ignore else */ Iif (updated) {
        showSuccess(getString('rbac.roleDetails.permissionUpdatedSuccess'))
        refetch()
      }
    } catch (e) {
      /* istanbul ignore next */
      showError(defaultTo(e.data?.message, e.message))
    }
  }
 
  const role = data?.data?.role
  const disableEdit = data?.data?.harnessManaged || !canEdit
 
  useDocumentTitle([defaultTo(role?.name, ''), getString('roles')])
 
  Iif (error) {
    return <PageError message={defaultTo((error.data as Error)?.message, error.message)} onClick={() => refetch()} />
  }
  Iif (!role) {
    return <></>
  }
  return (
    <>
      {loading && <PageSpinner />}
      <Page.Header
        size="xlarge"
        breadcrumbs={
          <NGBreadcrumbs
            links={[
              {
                url: routes.toRoles({ accountId, orgIdentifier, projectIdentifier, module }),
                label: `${getString('accessControl')}: ${getString('roles')}`
              }
            ]}
          />
        }
        title={
          <Layout.Horizontal flex={{ alignItems: 'center', justifyContent: 'flex-start' }} spacing="medium">
            <Icon name={getRoleIcon(role.identifier)} size={40} />
            <Layout.Vertical padding={{ left: 'medium' }} spacing="xsmall" className={css.details}>
              <Text color={Color.BLACK} font="medium">
                {role.name}
              </Text>
              {role.description && <Text lineClamp={2}>{role.description}</Text>}
              {role.tags && (
                <Layout.Horizontal padding={{ top: 'small' }}>
                  <TagsRenderer tags={role.tags} length={6} />
                </Layout.Horizontal>
              )}
            </Layout.Vertical>
          </Layout.Horizontal>
        }
        toolbar={
          <Layout.Horizontal flex>
            {data?.data?.createdAt && (
              <Layout.Vertical
                padding={{ right: 'small' }}
                border={{ right: true, color: Color.GREY_300 }}
                spacing="xsmall"
              >
                <Text>{getString('created')}</Text>
                <ReactTimeago date={data.data.createdAt} />
              </Layout.Vertical>
            )}
            {data?.data?.lastModifiedAt && (
              <Layout.Vertical spacing="xsmall" padding={{ left: 'small' }}>
                <Text>{getString('lastUpdated')}</Text>
                <ReactTimeago date={data.data.lastModifiedAt} />
              </Layout.Vertical>
            )}
          </Layout.Horizontal>
        }
      />
      <Page.Body loading={permissionLoading || resourceTypeLoading}>
        <Layout.Horizontal className={css.body}>
          <Container className={css.resourceList}>
            <Layout.Vertical flex spacing="small">
              {resourceCategoryMap?.keys() &&
                Array.from(resourceCategoryMap.keys()).map(resourceType => {
                  const resourceHandler =
                    RbacFactory.getResourceCategoryHandler(resourceType as ResourceCategory) ||
                    RbacFactory.getResourceTypeHandler(resourceType as ResourceType)
                  return (
                    resourceHandler && (
                      <Card
                        interactive
                        key={resourceType}
                        data-testid={`resourceCard-${resourceType}`}
                        className={css.card}
                        onClick={() => {
                          setResource(resourceType as ResourceType)
                          const elem = listRef.get(resourceType)
                          elem?.scrollIntoView()
                        }}
                      >
                        <Layout.Horizontal flex spacing="small">
                          <Icon name={resourceHandler.icon} size={20} />
                          <Text color={Color.BLACK}>{getString(resourceHandler.label)} </Text>
                        </Layout.Horizontal>
                      </Card>
                    )
                  )
                })}
            </Layout.Vertical>
          </Container>
          <Container padding="large" className={css.permissionListContainer}>
            <Layout.Vertical>
              <Layout.Horizontal flex padding="medium" spacing="medium">
                <Text color={Color.BLACK} font={{ size: 'medium', weight: 'semi-bold' }} padding={{ left: 'medium' }}>
                  {getString('rbac.roleDetails.updateRolePermissions')}
                </Text>
                <Layout.Horizontal flex={{ justifyContent: 'flex-end' }} spacing="small">
                  {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
                    onClick={() => submitChanges(role)}
                    text={getString('applyChanges')}
                    variation={ButtonVariation.PRIMARY}
                    disabled={data?.data?.harnessManaged || !isUpdated}
                    permission={{
                      resource: {
                        resourceType: ResourceType.ROLE,
                        resourceIdentifier: roleIdentifier
                      },
                      permission: PermissionIdentifier.UPDATE_ROLE
                    }}
                  />
                </Layout.Horizontal>
              </Layout.Horizontal>
              {resourceCategoryMap?.keys() &&
                Array.from(resourceCategoryMap.keys()).map(resourceCategory => {
                  return (
                    <div
                      key={resourceCategory}
                      ref={input => {
                        listRef.set(resourceCategory, input)
                      }}
                    >
                      <PermissionCard
                        resourceTypes={resourceCategoryMap.get(resourceCategory)}
                        selected={resourceCategory === resource}
                        permissionMap={permissionsMap}
                        resourceCategory={resourceCategory}
                        disableEdit={disableEdit}
                        onChangePermission={onChangePermission}
                        isPermissionEnabled={isPermissionEnabled}
                      />
                    </div>
                  )
                })}
            </Layout.Vertical>
          </Container>
        </Layout.Horizontal>
      </Page.Body>
    </>
  )
}
 
export default RoleDetails