All files / modules/75-ce/components/PerspectiveReportsAndBudget/CreateBudgetSteps ConfigureAlerts.tsx

70.83% Statements 51/72
60% Branches 21/35
54.17% Functions 13/24
70.83% Lines 51/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 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              6x 6x 6x                           6x 6x 6x 6x 6x 6x 6x 6x 6x   6x                           6x 2x               6x 4x 4x 4x 4x 4x                   4x   4x       4x       4x 4x     4x                                                                                   4x                                 4x                                                                                                                                     6x 4x 4x 4x 4x   4x 4x                   4x 4x 4x                                     4x 4x                                   4x       4x                                                 6x 4x 4x 4x 2x                       4x     4x                                                               6x  
/*
 * 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, { useMemo, useRef, useState } from 'react'
import { FieldArray, FieldArrayRenderProps, FormikProps } from 'formik'
import {
  Container,
  FormInput,
  StepProps,
  Layout,
  Text,
  Formik,
  Button,
  Icon,
  FormikForm,
  ModalErrorHandlerBinding,
  ModalErrorHandler,
  FlexExpander
} from '@wings-software/uicore'
import * as Yup from 'yup'
import { TagInput } from '@blueprintjs/core'
import { FontVariation } from '@harness/design-system'
import moment from 'moment'
import { useStrings } from 'framework/strings'
import formatCost from '@ce/utils/formatCost'
import { getGMTStartDateTime, CE_DATE_FORMAT_INTERNAL } from '@ce/utils/momentUtils'
import { useCreateBudget, Budget, AlertThreshold, useUpdateBudget } from 'services/ce'
import { EmailSchema } from '@common/utils/Validation'
import type { BudgetStepData } from '../types'
import css from '../PerspectiveCreateBudget.module.scss'
interface Props {
  name: string
  viewId: string
  accountId: string
  onSuccess: () => void
  budget?: Budget
  isEditMode: boolean
}
 
interface ThresholdForm {
  alertThresholds: AlertThreshold[]
}
 
const makeNewThresold = (): AlertThreshold => {
  return {
    percentage: undefined,
    basedOn: 'ACTUAL_COST',
    userGroupIds: [],
    emailAddresses: []
  }
}
 
const ConfigureAlerts: React.FC<StepProps<BudgetStepData> & Props> = props => {
  const { getString } = useStrings()
  const [loading, setLoading] = useState(false)
  const [hasError, setError] = useState(false)
  const [modalErrorHandler, setModalErrorHandler] = useState<ModalErrorHandlerBinding | undefined>()
  const { prevStepData, previousStep, accountId, budget, isEditMode } = props
  const {
    type,
    perspective,
    growthRate,
    period,
    budgetName,
    perspectiveName,
    startTime,
    budgetAmount = 0
  } = (prevStepData || {}) as BudgetStepData
 
  const { mutate: updateBudget } = useUpdateBudget({
    id: budget?.uuid || '',
    queryParams: { accountIdentifier: accountId }
  })
  const { mutate: createBudget } = useCreateBudget({
    queryParams: { accountIdentifier: accountId }
  })
 
  const getInitialValues = () => {
    return { alertThresholds: budget?.alertThresholds || [makeNewThresold()] }
  }
 
  const handleSubmit = async ({ alertThresholds }: ThresholdForm) => {
    setError(false)
    setLoading(true)
 
    const altThresholds = alertThresholds.map(alt => {
      return {
        basedOn: alt.basedOn,
        emailAddresses: alt.emailAddresses,
        percentage: alt.percentage,
        userGroupIds: alt.userGroupIds
      }
    })
 
    /* istanbul ignore next */
    const emptyThresholds = (t: AlertThreshold) => (t.emailAddresses?.length || 0) > 0 && t.percentage
    const payload = {
      name: budgetName,
      alertThresholds: altThresholds.filter(emptyThresholds),
      type: type === 'PREVIOUS_MONTH_SPEND' ? 'PREVIOUS_PERIOD_SPEND' : type,
      period,
      startTime: getGMTStartDateTime(moment(startTime).format(CE_DATE_FORMAT_INTERNAL)),
      growthRate: growthRate,
      budgetAmount: +budgetAmount,
      scope: {
        viewName: perspectiveName,
        type: 'PERSPECTIVE',
        viewId: perspective
      }
    }
 
    try {
      /* istanbul ignore next */
      await (isEditMode ? updateBudget(payload as Budget) : createBudget(payload as Budget))
      props.onSuccess()
    } catch (e) {
      setError(true)
      setLoading(false)
      /* istanbul ignore next */
      modalErrorHandler?.showDanger(e.data.message)
    }
  }
 
  return (
    <Container>
      <Formik<ThresholdForm>
        formName="alertThresholds"
        initialValues={getInitialValues()}
        validationSchema={Yup.object().shape({
          alertThresholds: Yup.array(
            Yup.object({
              emailAddresses: EmailSchema()
            })
          )
        })}
        onSubmit={data => {
          handleSubmit(data)
        }}
      >
        {formikProps => {
          return (
            <FormikForm>
              <Container className={css.selectPerspectiveContainer}>
                <Text
                  font={{ variation: FontVariation.H4 }}
                  tooltipProps={{
                    dataTooltipId: 'createBudgetConfigureAlerts'
                  }}
                >
                  {getString('ce.perspectives.budgets.configureAlerts.title')}
                </Text>
                <ModalErrorHandler bind={setModalErrorHandler} />
                <Text
                  margin={{
                    top: 'xlarge',
                    bottom: 'xlarge'
                  }}
                >
                  {getString('ce.perspectives.budgets.configureAlerts.subTitle')}
                </Text>
                <Container
                  margin={{
                    bottom: 'xlarge'
                  }}
                >
                  <Text inline color="grey800" margin={{ right: 'small' }}>
                    {getString('ce.perspectives.budgets.configureAlerts.budgetAmount')}
                  </Text>
                  <Text inline color="grey800" font={{ weight: 'bold', size: 'medium' }}>
                    {formatCost(+budgetAmount)}
                  </Text>
                </Container>
                <Thresholds formikProps={formikProps} hasError={hasError} />
                <FlexExpander />
                <Layout.Horizontal spacing="medium">
                  <Button
                    text={getString('previous')}
                    icon="chevron-left"
                    onClick={() => previousStep?.(prevStepData)}
                  />
                  <Button
                    intent="primary"
                    rightIcon={'chevron-right'}
                    disabled={loading}
                    onClick={() => {
                      setTimeout(() => {
                        formikProps.submitForm()
                      }, 0)
                    }}
                  >
                    {getString('save')}
                  </Button>
                </Layout.Horizontal>
              </Container>
            </FormikForm>
          )
        }}
      </Formik>
    </Container>
  )
}
 
interface ThresholdsProps {
  formikProps: FormikProps<ThresholdForm>
  hasError: boolean
}
 
const Thresholds = (props: ThresholdsProps): JSX.Element => {
  const { formikProps } = props
  const { alertThresholds: alerts } = formikProps.values
  const endRef = useRef<HTMLDivElement>(null)
  const { getString } = useStrings()
 
  const renderLabels = () => {
    return (
      <div className={css.thresholdLabel}>
        <Text className={css.label}>{getString('ce.perspectives.budgets.configureAlerts.basedOn')}</Text>
        <Text color="grey0">{getString('ce.perspectives.budgets.configureAlerts.exceeds')}</Text>
        <Text className={css.label}>{getString('ce.perspectives.budgets.configureAlerts.percent')}</Text>
        <Text className={css.label}>{getString('ce.perspectives.budgets.configureAlerts.sendAlertTo')}</Text>
      </div>
    )
  }
 
  const renderThresholds = (arrayHelpers: FieldArrayRenderProps) => {
    return alerts.map((at, idx) => {
      return (
        <Threshold
          key={idx}
          index={idx}
          value={at}
          formikProps={formikProps}
          handleEmailChange={values => {
            formikProps.setFieldValue(`alertThresholds.${idx}.emailAddresses`, values)
          }}
          onDelete={() => {
            if (alerts.length > 1) {
              arrayHelpers.remove(idx)
            }
          }}
        />
      )
    })
  }
 
  const renderAddThresholdButton = (arrayHelpers: FieldArrayRenderProps) => {
    return (
      <Container margin="medium">
        <Button
          withoutBoxShadow={true}
          className={css.addNewAlertBtn}
          text={getString('ce.perspectives.budgets.configureAlerts.createAlert')}
          onClick={() => {
            arrayHelpers.push(makeNewThresold())
            const timer = setTimeout(() => {
              endRef.current?.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'nearest' })
              clearTimeout(timer)
            }, 0)
          }}
        />
      </Container>
    )
  }
 
  return (
    <FieldArray
      name="alertThresholds"
      render={arrayHelpers => {
        return (
          <Container>
            <div className={css.thresholds}>
              {renderLabels()}
              <div className={css.threshCtn}>
                {renderThresholds(arrayHelpers)}
                <div ref={endRef} />
              </div>
              {renderAddThresholdButton(arrayHelpers)}
            </div>
          </Container>
        )
      }}
    />
  )
}
 
interface ThresholdProps {
  handleEmailChange: (value: React.ReactNode) => void
  value: AlertThreshold
  onDelete: () => void
  index: number
  formikProps: FormikProps<ThresholdForm>
}
 
const Threshold = (props: ThresholdProps): JSX.Element => {
  const { value, index: idx, onDelete, handleEmailChange, formikProps } = props
  const { getString } = useStrings()
  const BASED_ON_OPTIONS = useMemo(() => {
    return [
      {
        label: getString('ce.perspectives.budgets.configureAlerts.actual'),
        value: 'ACTUAL_COST'
      },
      {
        label: getString('ce.perspectives.budgets.configureAlerts.forecasted'),
        value: 'FORECASTED_COST'
      }
    ]
  }, [])
 
  return (
    <div className={css.threshold}>
      <FormInput.Select
        value={BASED_ON_OPTIONS.find(op => op.value === value.basedOn)}
        items={BASED_ON_OPTIONS}
        name={`alertThresholds.${idx}.basedOn`}
      />
      <Text className={css.pushdown7}>exceeds</Text>
      <FormInput.Text name={`alertThresholds.${idx}.percentage`} inputGroup={{ type: 'number' }} />
      <Container>
        <TagInput
          addOnBlur
          className={css.tagInput}
          tagProps={{ className: css.tag }}
          placeholder={getString('ce.perspectives.reports.emailPlaceholder')}
          onChange={values => handleEmailChange(values)}
          // onAdd={values => {}}
          values={value.emailAddresses || []}
        />
        <Text font={{ variation: FontVariation.FORM_MESSAGE_DANGER }}>
          {(formikProps.errors.alertThresholds || [])[idx]?.emailAddresses}
        </Text>
      </Container>
      <Icon
        color="grey200"
        size={18}
        name="ban-circle"
        className={css.pushdown7}
        onClick={onDelete}
        style={{ cursor: 'pointer' }}
      />
    </div>
  )
}
 
export default ConfigureAlerts