All files / modules/45-projects-orgs/modals/ProjectModal/views Collaborators.tsx

81.4% Statements 70/86
54.89% Branches 73/133
66.67% Functions 14/21
80.95% Lines 68/84

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 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412              18x 18x                                       18x 18x 18x 18x 18x 18x 18x 18x   18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x                               18x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x                         27x               27x               27x                 27x 11x 11x       27x   162x               27x       27x   81x                 27x                                                               27x                                       27x                                                                                     1x                                   2x           312x                                         81x                                                                           18x           5x   5x   5x 2x           5x                       1x     1x               1x     1x 1x                 18x           1x 1x                                                     18x  
/*
 * 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 {
  Formik,
  FormikForm as Form,
  FormInput,
  Button,
  Text,
  Layout,
  StepProps,
  Container,
  SelectOption,
  TextInput,
  MultiSelectOption,
  Icon,
  ModalErrorHandlerBinding,
  ModalErrorHandler,
  ButtonVariation,
  Label,
  DropDown,
  Heading
} from '@wings-software/uicore'
import cx from 'classnames'
import * as Yup from 'yup'
import { FontVariation, Color } from '@harness/design-system'
import { useHistory, useParams } from 'react-router-dom'
import { defaultTo } from 'lodash-es'
import { Project, useGetInvites, Organization, useAddUsers, AddUsers, useGetUsers } from 'services/cd-ng'
import { useStrings } from 'framework/strings'
import { useGetRoleList } from 'services/rbac'
import type { AccountPathProps } from '@common/interfaces/RouteInterfaces'
import { useToaster } from '@common/exports'
import { CopyText } from '@common/components/CopyText/CopyText'
import routes from '@common/RouteDefinitions'
import { InvitationStatus, handleInvitationResponse } from '@rbac/utils/utils'
import { getDefaultRole, getDetailsUrl } from '@projects-orgs/utils/utils'
import { isCDCommunity, useLicenseStore } from 'framework/LicenseStore/LicenseStoreContext'
import { useMutateAsGet } from '@common/hooks'
import UserItemRenderer from '@audit-trail/components/UserItemRenderer/UserItemRenderer'
import UserTagRenderer from '@audit-trail/components/UserTagRenderer/UserTagRenderer'
import { useTelemetry } from '@common/hooks/useTelemetry'
import { Category, ProjectActions } from '@common/constants/TrackingConstants'
import InviteListRenderer from './InviteListRenderer'
import css from './Steps.module.scss'
 
interface CollaboratorModalData {
  projectIdentifier?: string
  orgIdentifier?: string
  showManage?: boolean
  defaultRole?: SelectOption
}
 
interface RoleOption extends SelectOption {
  managed: boolean
}
interface CollaboratorsData {
  collaborators: MultiSelectOption[]
}
 
const Collaborators: React.FC<CollaboratorModalData> = props => {
  const { projectIdentifier, orgIdentifier, showManage = true } = props
  const { accountId } = useParams<AccountPathProps>()
  const { getString } = useStrings()
  const { licenseInformation } = useLicenseStore()
  const isCommunity = isCDCommunity(licenseInformation)
  const { showSuccess } = useToaster()
  const history = useHistory()
  const [search, setSearch] = useState<string>()
  const [modalErrorHandler, setModalErrorHandler] = useState<ModalErrorHandlerBinding>()
  const initialValues: CollaboratorsData = { collaborators: [] }
  const { data: userData } = useMutateAsGet(useGetUsers, {
    queryParams: { accountIdentifier: accountId, orgIdentifier, projectIdentifier },
    body: {
      searchTerm: search,
      parentFilter: 'STRICTLY_PARENT_SCOPES'
    },
    debounce: 300
  })
 
  const {
    data: inviteData,
    loading: inviteLoading,
    refetch: reloadInvites
  } = useGetInvites({
    queryParams: {
      accountIdentifier: accountId,
      orgIdentifier,
      projectIdentifier
    }
  })
 
  const { mutate: sendInvite, loading } = useAddUsers({
    queryParams: {
      accountIdentifier: accountId,
      orgIdentifier,
      projectIdentifier
    }
  })
 
  const { data: roleData, refetch: fetchRoleData } = useGetRoleList({
    queryParams: {
      accountIdentifier: accountId,
      orgIdentifier,
      projectIdentifier
    },
    lazy: true
  })
 
  useEffect(() => {
    Eif (!isCommunity) {
      fetchRoleData()
    }
  }, [])
 
  const users: SelectOption[] = defaultTo(
    userData?.data?.content?.map(user => {
      return {
        label: defaultTo(user.name, user.email),
        value: user.email
      }
    }),
    []
  )
 
  const [role, setRole] = useState<RoleOption>(
    getDefaultRole({ accountIdentifier: accountId, orgIdentifier, projectIdentifier }, getString)
  )
 
  const roles: RoleOption[] = defaultTo(
    roleData?.data?.content?.map(roleOption => {
      return {
        label: roleOption.role.name,
        value: roleOption.role.identifier,
        managed: defaultTo(roleOption.harnessManaged, false)
      }
    }),
    []
  )
 
  const SendInvitation = async (values: MultiSelectOption[]): Promise<void> => {
    const usersToSubmit = values?.map(collaborator => {
      return collaborator.value.toString()
    })
 
    const dataToSubmit: AddUsers = {
      emails: usersToSubmit,
      roleBindings: isCommunity
        ? []
        : [
            {
              roleIdentifier: role.value.toString(),
              roleName: role.label,
              managedRole: role.managed
            }
          ]
    }
 
    try {
      const response = await sendInvite(dataToSubmit)
      handleInvitationResponse({
        responseType: Object.values(defaultTo(response.data?.addUserResponseMap, {}))?.[0] as InvitationStatus,
        getString,
        showSuccess,
        modalErrorHandler,
        onSubmit: reloadInvites
      })
    } catch (e) {
      modalErrorHandler?.showDanger(defaultTo(e.data?.message, e.message))
    }
  }
 
  return (
    <Formik<CollaboratorsData>
      initialValues={initialValues}
      validationSchema={Yup.object().shape({
        collaborators: Yup.array().of(
          Yup.object().shape({
            value: Yup.string().email().required()
          })
        )
      })}
      formName="collaboratorsForm"
      onSubmit={(values, { resetForm }) => {
        modalErrorHandler?.hide()
        SendInvitation(values.collaborators)
        setRole(getDefaultRole({ accountIdentifier: accountId, orgIdentifier, projectIdentifier }, getString))
        resetForm({ collaborators: [] })
      }}
      enableReinitialize={true}
    >
      {formik => {
        return (
          <Form>
            <ModalErrorHandler bind={setModalErrorHandler} />
            <Container className={css.collaboratorForm}>
              <Heading level={3} font={{ variation: FontVariation.H3 }} padding={{ bottom: 'xxlarge' }}>
                {getString('projectsOrgs.invite')}
              </Heading>
              <Label>
                {projectIdentifier
                  ? getString('projectsOrgs.urlMessageProject')
                  : getString('projectsOrgs.urlMessageOrg')}
              </Label>
              <TextInput
                placeholder={getDetailsUrl({ accountId, orgIdentifier, projectIdentifier })}
                disabled
                rightElement={
                  (
                    <CopyText
                      className={css.copy}
                      iconName="duplicate"
                      textToCopy={getDetailsUrl({ accountId, orgIdentifier, projectIdentifier })}
                      iconAlwaysVisible
                    />
                  ) as any
                }
              />
              <Layout.Horizontal padding={{ top: 'medium' }} className={cx(css.align, css.input)} flex>
                <Layout.Horizontal width="50%">
                  <Label>{getString('projectsOrgs.inviteCollab')}</Label>
                </Layout.Horizontal>
                {!isCommunity && (
                  <Layout.Horizontal
                    width="50%"
                    flex={{ alignItems: 'center', justifyContent: 'flex-end' }}
                    padding={{ right: 'medium' }}
                  >
                    <Label>
                      <Layout.Horizontal flex spacing="xsmall">
                        {getString('projectsOrgs.roleLabel')}
                        <DropDown
                          items={roles}
                          value={role.value.toString()}
                          onChange={item => {
                            setRole(item as RoleOption)
                          }}
                          isLabel={true}
                          filterable={false}
                          width={160}
                        />
                      </Layout.Horizontal>
                    </Label>
                  </Layout.Horizontal>
                )}
              </Layout.Horizontal>
              <Layout.Horizontal spacing="small">
                <FormInput.MultiSelect
                  name={getString('projectsOrgs.collaborator')}
                  items={users}
                  multiSelectProps={{
                    allowCreatingNewItems: true,
                    onQueryChange: (query: string) => {
                      setSearch(query)
                    },
                    tagRenderer: (item: MultiSelectOption) => (
                      <UserTagRenderer key={item.value.toString()} item={item} />
                    ),
                    itemRender: (item, { handleClick }) => (
                      <UserItemRenderer key={item.value.toString()} item={item} handleClick={handleClick} />
                    )
                  }}
                  className={css.input}
                />
                <Button
                  text={getString('add')}
                  variation={ButtonVariation.PRIMARY}
                  inline
                  disabled={role.value === 'none' || formik.values.collaborators.length === 0 ? true : false}
                  type="submit"
                  loading={loading}
                />
              </Layout.Horizontal>
              {inviteData?.data?.content?.length ? (
                <Layout.Vertical padding={{ top: 'medium', bottom: 'xxxlarge' }}>
                  <Text padding={{ bottom: 'small' }}>
                    {getString('projectsOrgs.pendingUsers', { name: inviteData?.data?.content?.length.toString() })}
                  </Text>
                  <Container className={css.pendingList}>
                    {inviteData?.data?.content.slice(0, 15).map(user => (
                      <InviteListRenderer
                        key={user.name}
                        user={user}
                        reload={reloadInvites}
                        roles={roles}
                        isCommunity={isCommunity}
                      />
                    ))}
                  </Container>
                </Layout.Vertical>
              ) : inviteLoading ? (
                <Layout.Vertical padding={{ top: 'xxxlarge', bottom: 'xxxlarge' }}>
                  <Icon name="steps-spinner" size={32} color={Color.GREY_600} flex={{ align: 'center-center' }} />
                </Layout.Vertical>
              ) : null}
            </Container>
 
            {showManage ? (
              <Layout.Horizontal>
                <Button
                  variation={ButtonVariation.LINK}
                  text={
                    projectIdentifier ? getString('projectsOrgs.manageProject') : getString('projectsOrgs.manageOrg')
                  }
                  onClick={() => {
                    history.push(routes.toUsers({ accountId, orgIdentifier, projectIdentifier }))
                  }}
                  className={css.manageUsers}
                />
              </Layout.Horizontal>
            ) : null}
          </Form>
        )
      }}
    </Formik>
  )
}
 
export const ProjectCollaboratorsStep: React.FC<StepProps<Project> & CollaboratorModalData> = ({
  prevStepData,
  previousStep,
  nextStep,
  ...rest
}) => {
  const { getString } = useStrings()
 
  const { trackEvent } = useTelemetry()
 
  useEffect(() => {
    trackEvent(ProjectActions.LoadInviteCollaborators, {
      category: Category.PROJECT
    })
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])
 
  return (
    <Layout.Vertical padding="xxxlarge">
      <Collaborators
        projectIdentifier={prevStepData?.identifier}
        orgIdentifier={prevStepData?.orgIdentifier}
        showManage={false}
        {...rest}
      />
      <Layout.Horizontal spacing="small">
        <Button
          variation={ButtonVariation.SECONDARY}
          onClick={() => {
            trackEvent(ProjectActions.ClickBackToProject, {
              category: Category.PROJECT
            })
            previousStep?.(prevStepData)
          }}
          text={getString('back')}
        />
        <Button
          variation={ButtonVariation.PRIMARY}
          text={getString('saveAndContinue')}
          onClick={() => {
            trackEvent(ProjectActions.SaveInviteCollaborators, {
              category: Category.PROJECT
            })
            /* istanbul ignore else */ if (prevStepData) {
              nextStep?.({ ...prevStepData })
            }
          }}
        />
      </Layout.Horizontal>
    </Layout.Vertical>
  )
}
 
export const OrgCollaboratorsStep: React.FC<StepProps<Organization> & CollaboratorModalData> = ({
  prevStepData,
  previousStep,
  nextStep,
  ...rest
}) => {
  const { getString } = useStrings()
  return (
    <Layout.Vertical padding="xxxlarge">
      <Collaborators orgIdentifier={prevStepData?.identifier} showManage={false} {...rest} />
      {prevStepData ? (
        <Layout.Horizontal spacing="small">
          <Button onClick={() => previousStep?.(prevStepData)} text={getString('back')} />
          <Button
            variation={ButtonVariation.PRIMARY}
            text={getString('finish')}
            onClick={() => {
              /* istanbul ignore else */ Iif (prevStepData) {
                nextStep?.({ ...prevStepData })
              }
            }}
          />
        </Layout.Horizontal>
      ) : (
        <Layout.Horizontal>
          <Button inline minimal disabled tooltip={getString('projectsOrgs.notAvailableForBeta')}>
            {getString('projectsOrgs.manageProject')}
          </Button>
        </Layout.Horizontal>
      )}
    </Layout.Vertical>
  )
}
 
export default Collaborators