All files / modules/20-rbac/pages/UserGroups/CopyGroupMenuItem CopyGroupForm.tsx

59.09% Statements 26/44
42.59% Branches 23/54
25% Functions 2/8
59.09% Lines 26/44

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              11x 11x                         11x 11x   11x 11x 11x   11x 11x                         11x 2x 2x 2x 2x 2x   2x             2x                       2x     2x   2x 2x       2x                             2x                             2x   2x                                                                                                                                               11x  
/*
 * 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, { useState } from 'react'
import {
  FormInput,
  Layout,
  Button,
  ButtonVariation,
  Container,
  Formik,
  ModalErrorHandlerBinding,
  FormikForm as Form,
  useToaster,
  ModalErrorHandler,
  PageSpinner
} from '@wings-software/uicore'
import { useParams } from 'react-router-dom'
import { useGetOrganizationAggregateDTOList, useCopyUserGroup, useGetProjectAggregateDTOList } from 'services/cd-ng'
import type { ProjectPathProps } from '@common/interfaces/RouteInterfaces'
import { useStrings } from 'framework/strings'
import { generateScopeList } from '@rbac/utils/utils'
import useRBACError from '@rbac/utils/useRBACError/useRBACError'
import type { ProjectSelectOption } from '@audit-trail/components/FilterDrawer/FilterDrawer'
import { getOrgDropdownList, getProjectDropdownList } from '@audit-trail/utils/RequestUtil'
import css from './CopyGroupForm.module.scss'
 
export interface CopyGroupFormType {
  organization: string | undefined
  projects: ProjectSelectOption[]
  copyToProjects: boolean
}
 
interface CopyGroupFormProps {
  closeModal: () => void
  identifier: string
}
 
const CopyGroupForm: React.FC<CopyGroupFormProps> = ({ closeModal, identifier }) => {
  const [projectsQuery, setProjectsQuery] = useState('')
  const { accountId } = useParams<ProjectPathProps>()
  const { getRBACErrorMessage } = useRBACError()
  const [modalErrorHandler, setModalErrorHandler] = useState<ModalErrorHandlerBinding>()
  const { getString } = useStrings()
 
  const { data, loading: loadingOrgs } = useGetOrganizationAggregateDTOList({
    queryParams: {
      pageIndex: 0,
      accountIdentifier: accountId
    }
  })
 
  const { data: projectData, refetch: refetchProjectList } = useGetProjectAggregateDTOList({
    queryParams: {
      accountIdentifier: accountId,
      searchTerm: projectsQuery
    },
    lazy: true,
    queryParamStringifyOptions: {
      arrayFormat: 'repeat'
    },
    debounce: 300
  })
 
  const { mutate: copyUserGroup, loading } = useCopyUserGroup({
    queryParams: { accountIdentifier: accountId, groupIdentifier: identifier }
  })
  const { showSuccess } = useToaster()
 
  const orgList = data?.data?.content ? getOrgDropdownList(data?.data?.content || []) : []
  const projects = projectData?.data?.content
    ? getProjectDropdownList(projectData.data.content.map(project => project.projectResponse))
    : []
 
  const onSave = async (values: CopyGroupFormType): Promise<void> => {
    modalErrorHandler?.hide()
    const { organization: selectedOrg, projects: selectedProjects } = values
    const scopeList = selectedOrg ? generateScopeList(selectedOrg, selectedProjects, accountId) : []
    try {
      const response = await copyUserGroup(scopeList)
      if (response) {
        showSuccess(getString('rbac.copyGroup.success'))
      }
      closeModal()
    } catch (e) {
      modalErrorHandler?.showDanger(getRBACErrorMessage(e))
    }
  }
 
  return (
    <>
      {loadingOrgs ? <PageSpinner /> : undefined}
      <Formik<CopyGroupFormType>
        initialValues={{
          organization: undefined,
          projects: [],
          copyToProjects: false
        }}
        formName="copyGroupForm"
        onSubmit={values => {
          onSave(values)
        }}
      >
        {formik => {
          const selectedOrg = formik.values.organization
 
          return (
            <Form>
              <ModalErrorHandler bind={setModalErrorHandler} />
              <Container className={css.copyGroupForm}>
                <FormInput.Select
                  name="organization"
                  label={getString('orgLabel')}
                  items={orgList}
                  tooltipProps={{ dataTooltipId: 'copyGroupOrganization' }}
                  onChange={org => {
                    if (formik.values.copyToProjects) {
                      refetchProjectList({
                        queryParams: {
                          accountIdentifier: accountId,
                          orgIdentifier: org.value as string,
                          pageIndex: 0
                        }
                      })
                      formik.setFieldValue('projects', [])
                    }
                  }}
                />
                <Container margin={{ top: 'xlarge' }}>
                  <FormInput.CheckBox
                    name="copyToProjects"
                    label={getString('rbac.copyGroup.copyToProjects')}
                    tooltipProps={{ dataTooltipId: 'copyToProjects' }}
                    onChange={e => {
                      if (e.currentTarget.checked && formik.values.organization) {
                        refetchProjectList({
                          queryParams: {
                            accountIdentifier: accountId,
                            orgIdentifier: selectedOrg as string,
                            pageIndex: 0
                          }
                        })
                      } else {
                        formik.setFieldValue('projects', [])
                      }
                    }}
                  />
                </Container>
                <FormInput.MultiSelect
                  label={getString('projectsText')}
                  name="projects"
                  items={projects}
                  disabled={!(formik.values.copyToProjects && selectedOrg)}
                  multiSelectProps={{
                    allowCreatingNewItems: false,
                    onQueryChange: (query: string) => {
                      setProjectsQuery(query)
                    }
                  }}
                />
              </Container>
              <Layout.Horizontal spacing="small">
                <Button
                  disabled={!selectedOrg || loading}
                  type="submit"
                  variation={ButtonVariation.PRIMARY}
                  text={getString('save')}
                />
                <Button variation={ButtonVariation.TERTIARY} onClick={closeModal} text={getString('cancel')} />
              </Layout.Horizontal>
            </Form>
          )
        }}
      </Formik>
    </>
  )
}
 
export default CopyGroupForm