All files / modules/75-ce/components/PerspectiveReportsAndBudget PerspectiveCreateReport.tsx

92.59% Statements 50/54
77.08% Branches 37/48
86.67% Functions 13/15
92.59% Lines 50/54

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              2x 2x 2x 2x 2x 2x                     2x   2x 2x 2x 2x 2x 2x                                     2x 7x 7x 7x 7x 7x 7x 7x 7x                 7x 2x 2x       2x       2x 2x 2x             7x 2x               8x     4x 4x         7x 2x   2x 1x               1x               7x   2x       2x               16x                             2x                                                     7x     2x 2x 2x 2x         2x  
/*
 * Copyright 2021 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 cx from 'classnames'
import * as Yup from 'yup'
import { useParams } from 'react-router-dom'
import { Classes, Dialog, IDialogProps } from '@blueprintjs/core'
import {
  Container,
  Layout,
  Label,
  Button,
  Formik,
  FormInput,
  FormikForm,
  useToaster,
  getErrorInfoFromErrorObject
} from '@wings-software/uicore'
import { useModalHook } from '@harness/use-modal'
 
import { CEReportSchedule, useCreateReportSetting, useUpdateReportSetting } from 'services/ce'
import { useStrings } from 'framework/strings'
import { regexEmail } from '@common/utils/StringUtils'
import TimezoneSelector from '@ce/common/TimeZoneSelector/TimeZoneSelector'
import Cron from './Cron'
import css from './PerspectiveCreateReport.module.scss'
 
export interface ReportDetailsForm {
  name: string
  recipients: string
  cron: string
  userCronTimeZone: string
}
 
interface OpenModalArgs {
  isEdit?: boolean
  selectedReport?: CEReportSchedule
}
 
interface CreateReportModalProps {
  onSuccess?: () => void
  onError?: () => void
}
 
const useCreateReportModal = ({ onSuccess, onError }: CreateReportModalProps) => {
  const { getString } = useStrings()
  const { showError } = useToaster()
  const [isEditMode, setIsEditMode] = useState(false)
  const [report, setReport] = useState<CEReportSchedule>()
  const { perspectiveId, accountId } = useParams<{ perspectiveId: string; accountId: string }>()
  const { mutate: createReport } = useCreateReportSetting({ accountIdentifier: accountId })
  const { mutate: updateReport } = useUpdateReportSetting({ accountIdentifier: accountId })
  const modalPropsLight: IDialogProps = {
    isOpen: true,
    usePortal: true,
    autoFocus: true,
    canOutsideClickClose: false,
    enforceFocus: false,
    className: cx(Classes.DIALOG, css.mainCtn)
  }
 
  const handleSubmit = async (data: ReportDetailsForm): Promise<void> => {
    const { cron, recipients, name } = data
    const payload = {
      viewsId: [perspectiveId],
      name: name,
      userCron: `0 ${cron}`,
      recipients: recipients.split(',').map((s: string) => s.trim()),
      userCronTimeZone: data.userCronTimeZone
    }
 
    try {
      await (isEditMode ? updateReport({ ...report, ...payload }) : createReport(payload))
      onSuccess?.()
    } catch (e) {
      showError(getErrorInfoFromErrorObject(e))
      onError?.()
    }
  }
 
  const getSchemaValidations = () => {
    return Yup.object().shape({
      name: Yup.string().required(getString('ce.perspectives.validations.reportNameRequired')),
      recipients: Yup.string()
        .required(getString('ce.perspectives.validations.emailRequired'))
        .test(
          'emails',
          getString('ce.perspectives.validations.invalidEmails'),
          value =>
            value &&
            value
              .split(',')
              .map((s: string) => s.trim())
              .every((v: string) => regexEmail.test(v))
        )
    })
  }
 
  const getInitialValues = (): ReportDetailsForm => {
    const userTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone
 
    if (!isEditMode) {
      return {
        name: '',
        recipients: '',
        cron: '',
        userCronTimeZone: userTimezone
      }
    }
 
    return {
      name: report?.name || '',
      cron: report?.userCron?.split(' ').slice(1).join(' ') || '',
      recipients: report?.recipients?.join(', ') || '',
      userCronTimeZone: report?.userCronTimeZone || userTimezone
    }
  }
 
  const [openModal, hideModal] = useModalHook(
    () => (
      <Dialog onClose={hideModal} {...modalPropsLight}>
        <Container padding="xlarge">
          <Formik<ReportDetailsForm>
            onSubmit={data => {
              handleSubmit(data)
            }}
            formName="createReportScheduleForm"
            enableReinitialize={true}
            initialValues={getInitialValues()}
            validationSchema={getSchemaValidations()}
          >
            {formikProps => {
              return (
                <FormikForm>
                  <Layout.Vertical spacing="xlarge">
                    <Container style={{ minHeight: 300 }}>
                      <FormInput.Text name={'name'} label={getString('name')} />
                      <Container margin={{ top: 'xlarge', bottom: 'xlarge' }}>
                        <Layout.Horizontal style={{ justifyContent: 'space-between' }} margin={{ bottom: 'small' }}>
                          <Label className={css.cronLabel}>{getString('ce.perspectives.reports.cronLabel')}</Label>
                          <TimezoneSelector
                            timezone={formikProps.values.userCronTimeZone}
                            onTimezoneSelect={tz => formikProps.setFieldValue('userCronTimeZone', tz)}
                          />
                        </Layout.Horizontal>
                        <Cron
                          cron={formikProps.values.cron}
                          onChange={cron => formikProps.setFieldValue('cron', cron)}
                        />
                      </Container>
                      <FormInput.TextArea
                        placeholder={getString('ce.perspectives.reports.emailPlaceholder')}
                        className={css.recipients}
                        name={'recipients'}
                        label={getString('ce.perspectives.reports.recipientLabel')}
                      />
                    </Container>
                    <Layout.Horizontal spacing="medium">
                      <Button type="submit" intent="primary" disabled={false}>
                        {getString('save')}
                      </Button>
                      <Button onClick={() => hideModal()} text={getString('cancel')}></Button>
                    </Layout.Horizontal>
                  </Layout.Vertical>
                </FormikForm>
              )
            }}
          </Formik>
        </Container>
      </Dialog>
    ),
    [isEditMode, report]
  )
 
  return {
    hideModal,
    openModal: (args?: OpenModalArgs) => {
      const { isEdit, selectedReport } = args || {}
      setIsEditMode(!!isEdit)
      setReport(selectedReport)
      openModal()
    }
  }
}
 
export default useCreateReportModal