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

77.27% Statements 51/66
71.84% Branches 74/103
57.14% Functions 12/21
79.69% Lines 51/64

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 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463              5x 5x 5x                           5x 5x   5x 5x 5x 5x 5x 5x 5x 5x 5x   5x                 5x               5x                                                                                                                                                                                       5x           4x   4x 1x 1x       4x 1x                 4x 1x           4x                                                                               8x                                                                                                                                           5x 2x 1x                 1x   1x   1x       1x         1x   1x                 1x                 1x 1x             1x 1x                     1x     1x 4x     8x                                   1x   1x       1x                           4x                                                                                                                                   5x  
/*
 * 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, { useEffect, useMemo, useState } from 'react'
import { get } from 'lodash-es'
import {
  Text,
  Container,
  StepProps,
  Layout,
  Button,
  FormInput,
  Formik,
  FormikForm,
  FlexExpander,
  DateInput,
  Icon,
  HarnessDocTooltip
} from '@wings-software/uicore'
import moment from 'moment'
import { FontVariation, Color } from '@harness/design-system'
import type { FormikProps } from 'formik'
import Highcharts from 'highcharts/highcharts'
import { useParams } from 'react-router-dom'
import { Position } from '@blueprintjs/core'
import { Budget, useGetLastPeriodCost, useGetForecastCostForPeriod } from 'services/ce'
import formatCost from '@ce/utils/formatCost'
import CEChart from '@ce/components/CEChart/CEChart'
import { todayInUTC } from '@ce/utils/momentUtils'
import { useStrings } from 'framework/strings'
import { BudgetPeriod } from 'services/ce/services'
import type { BudgetStepData } from '../types'
import css from '../PerspectiveCreateBudget.module.scss'
 
interface GrowthRateChartProps {
  growthRateVal: number
  amount: number
  period: string
  startTime: number
}
 
const IncrementStep: Record<string, any> = {
  [BudgetPeriod.Daily]: 'd',
  [BudgetPeriod.Weekly]: 'w',
  [BudgetPeriod.Monthly]: 'M',
  [BudgetPeriod.Quarterly]: 'Q',
  [BudgetPeriod.Yearly]: 'y'
}
 
const GrowthRateChart: (props: GrowthRateChartProps) => JSX.Element = ({
  growthRateVal,
  amount,
  period,
  startTime
}) => {
  const { getString } = useStrings()
 
  const incrementFactor = IncrementStep[period]
 
  return (
    <Container
      background={Color.PRIMARY_1}
      padding="medium"
      margin={{
        top: 'huge'
      }}
    >
      <Text font={{ variation: FontVariation.SMALL_SEMI }} margin={{ left: 'small', bottom: 'medium' }}>
        {getString('ce.perspectives.budgets.setBudgetAmount.chartTitle', { rate: growthRateVal })}
      </Text>
      <CEChart
        options={{
          series: [
            {
              color: 'var(--primary-8)',
              data: [
                [Number(moment.utc(startTime).startOf('d').format('x')), +amount],
                [
                  Number(moment.utc(startTime).startOf('d').add(1, incrementFactor).format('x')),
                  +Number(amount * (1 + growthRateVal / 100)).toFixed(2)
                ],
                [
                  Number(moment.utc(startTime).startOf('d').add(2, incrementFactor).format('x')),
                  +Number(amount * (1 + growthRateVal / 100) * (1 + growthRateVal / 100)).toFixed(2)
                ]
              ],
              name: '',
              type: 'line',
              dashStyle: 'ShortDash',
              marker: {
                enabled: false
              }
            }
          ],
          chart: {
            height: 122,
            backgroundColor: 'transparent'
          },
          yAxis: {
            tickAmount: 3,
            title: {
              text: ''
            },
            labels: {
              step: 2,
              formatter: function () {
                return `$ ${this['value']}`
              }
            }
          },
          xAxis: {
            lineWidth: 0,
            type: 'datetime',
            ordinal: true,
            labels: {
              formatter: function () {
                return Highcharts.dateFormat('%e %b %Y', Number(this.value))
              }
            }
          },
          legend: {
            enabled: false
          }
        }}
      />
    </Container>
  )
}
 
interface SetBudgetFormProps {
  formikProps: FormikProps<Form>
  isEditMode: boolean
  lastMonthCost: number | undefined
  setLastCostPeriodCostVar: React.Dispatch<
    React.SetStateAction<{
      startTime: number
      period: 'MONTHLY' | 'DAILY' | 'WEEKLY' | 'QUARTERLY' | 'YEARLY'
    }>
  >
}
 
const SetBudgetForm: (props: SetBudgetFormProps) => JSX.Element = ({
  formikProps,
  isEditMode,
  lastMonthCost,
  setLastCostPeriodCostVar
}) => {
  const { getString } = useStrings()
 
  useEffect(() => {
    Eif (formikProps.values.type === 'PREVIOUS_PERIOD_SPEND' && !isEditMode) {
      formikProps.setFieldValue('budgetAmount', lastMonthCost || 0)
    }
  }, [lastMonthCost])
 
  const BUDGET_PERIOD = useMemo(() => {
    return [
      { label: getString('ce.perspectives.budgets.setBudgetAmount.budgetPeriods.monthly'), value: 'MONTHLY' },
      { label: 'Daily', value: 'DAILY' },
      { label: 'Weekly', value: 'WEEKLY' },
      { label: 'Quarterly', value: 'QUARTERLY' },
      { label: 'Yearly', value: 'YEARLY' }
    ]
  }, [])
 
  const BUDGET_TYPE = useMemo(() => {
    return [
      { label: getString('ce.perspectives.budgets.setBudgetAmount.specifiedAmount'), value: 'SPECIFIED_AMOUNT' },
      { label: getString('ce.perspectives.budgets.setBudgetAmount.lastMonthSpend'), value: 'PREVIOUS_PERIOD_SPEND' }
    ]
  }, [])
 
  return (
    <Container
      padding={{
        right: 'medium'
      }}
    >
      <FormInput.Select
        disabled={isEditMode}
        items={BUDGET_PERIOD}
        name={'period'}
        label={getString('ce.perspectives.budgets.setBudgetAmount.budgetPeriod')}
        tooltipProps={{
          dataTooltipId: 'budgetPeriod'
        }}
        onChange={val => {
          setLastCostPeriodCostVar(x => ({ ...x, period: val.value as any }))
        }}
      />
      <Text font={{ variation: FontVariation.BODY2 }} color={Color.GREY_600}>
        {getString('ce.perspectives.budgets.setBudgetAmount.monthStartsFrom')}
      </Text>
      <DateInput
        disabled={isEditMode}
        popoverProps={{
          position: Position.BOTTOM,
          disabled: isEditMode
        }}
        value={String(formikProps.values.startTime)}
        onChange={val => {
          const startTime = moment(Number(val)).startOf('day').format('x')
          setLastCostPeriodCostVar(x => ({ ...x, startTime: startTime as any }))
 
          formikProps.setValues({
            ...formikProps.values,
            startTime: Number(startTime)
          })
        }}
      />
      <HarnessDocTooltip tooltipId="budgetStartTime" useStandAlone={true} />
      <FormInput.Select
        value={BUDGET_TYPE.find(op => op.value === formikProps.values.type)}
        items={BUDGET_TYPE}
        name={'type'}
        label={getString('ce.perspectives.budgets.setBudgetAmount.budgetType')}
        onChange={option => {
          if (option.value === 'PREVIOUS_PERIOD_SPEND') {
            formikProps.setFieldValue('budgetAmount', lastMonthCost || 0)
          }
        }}
      />
      <FormInput.Text
        disabled={formikProps.values.type === 'PREVIOUS_PERIOD_SPEND'}
        name={'budgetAmount'}
        inputGroup={{ type: 'number' }}
        label={
          formikProps.values.type === 'PREVIOUS_PERIOD_SPEND'
            ? getString('ce.perspectives.budgets.setBudgetAmount.lastMonthSpend')
            : getString('ce.perspectives.budgets.setBudgetAmount.specifyAmount')
        }
      />
      {formikProps.values.type === 'SPECIFIED_AMOUNT' ? (
        <FormInput.CheckBox
          name="growthRateCheck"
          label={getString('ce.perspectives.budgets.setBudgetAmount.growthRateCheck')}
          tooltipProps={{
            dataTooltipId: 'growthRateCheckbox'
          }}
        />
      ) : null}
      {formikProps.values.growthRateCheck && formikProps.values.type === 'SPECIFIED_AMOUNT' ? (
        <Layout.Horizontal
          margin={{
            top: 'xlarge'
          }}
          spacing="small"
        >
          <FormInput.Text
            name={'growthRate'}
            inputGroup={{ type: 'number' }}
            label={getString('ce.perspectives.budgets.setBudgetAmount.growthRateLabel')}
          />
          <Text
            margin={{
              top: 'xxlarge'
            }}
          >
            %
          </Text>
        </Layout.Horizontal>
      ) : null}
    </Container>
  )
}
 
interface Props {
  name: string
  budget?: Budget
  isEditMode: boolean
  perspective?: string
}
 
interface Form {
  type: 'SPECIFIED_AMOUNT' | 'PREVIOUS_MONTH_SPEND' | 'PREVIOUS_PERIOD_SPEND'
  budgetAmount: number
  period: string
  startTime: number
  growthRate: number
  growthRateCheck: boolean
}
 
const SetBudgetAmount: React.FC<StepProps<BudgetStepData> & Props> = props => {
  const { getString } = useStrings()
  const { accountId } = useParams<{
    accountId: string
  }>()
  const {
    nextStep,
    prevStepData,
    previousStep,
    budget: { budgetAmount = 0, period, startTime, growthRate } = {},
    isEditMode
  } = props
 
  let type = props.budget?.type
 
  Iif (type === 'PREVIOUS_MONTH_SPEND') {
    type = 'PREVIOUS_PERIOD_SPEND'
  }
 
  const [lastPeriodCostVar, setLastCostPeriodCostVar] = useState({
    startTime: startTime || get(prevStepData, 'startTime') || Number(todayInUTC().startOf('month').format('x')),
    period: period || get(prevStepData, 'period') || 'MONTHLY'
  })
 
  const { perspective } = prevStepData || {}
 
  const { data: lpc, loading: lpcLoading } = useGetLastPeriodCost({
    queryParams: {
      accountIdentifier: accountId,
      perspectiveId: perspective as string,
      period: lastPeriodCostVar.period,
      startTime: lastPeriodCostVar.startTime
    }
  })
 
  const { data: fcp, loading: fcpLoading } = useGetForecastCostForPeriod({
    queryParams: {
      accountIdentifier: accountId,
      perspectiveId: perspective as string,
      period: lastPeriodCostVar.period,
      startTime: lastPeriodCostVar.startTime
    }
  })
 
  const COSTS = useMemo(
    () => [
      [getString('ce.perspectives.budgets.setBudgetAmount.lastMonthCost'), lpc?.data],
      [getString('ce.perspectives.budgets.setBudgetAmount.projectedCost'), fcp?.data]
    ],
    [lpc?.data, fcp?.data]
  )
 
  const handleSubmit = (data: Form) => {
    const nextStepData = {
      ...((prevStepData || {}) as Budget & { perspective: string }),
      type: data.type,
      budgetAmount: data.budgetAmount,
      lastMonthCost: lpc?.data,
      forecastCost: fcp?.data,
      period: data.period,
      startTime: data.startTime,
      growthRate: data.growthRate
    } as BudgetStepData
 
    nextStep?.(nextStepData)
  }
 
  const renderCosts = () => {
    return (
      <div className={css.costs}>
        {COSTS.map((cost, idx) => {
          return (
            <>
              <div key={idx}>
                <Text color="grey800" margin={{ bottom: 'small' }} font={{ variation: FontVariation.SMALL }}>
                  {cost[0] || 0}
                </Text>
                <Text color="grey800" font={{ variation: FontVariation.H5 }}>
                  {formatCost((cost[1] as number) || 0)}
                </Text>
              </div>
              {idx === 0 && <div className={css.separator}></div>}
            </>
          )
        })}
      </div>
    )
  }
 
  const formLoading = lpcLoading || fcpLoading ? true : undefined
 
  return (
    <Container>
      <Formik<Form>
        onSubmit={data => {
          handleSubmit(data)
        }}
        formName="selectPerspective"
        enableReinitialize={true}
        initialValues={{
          type: type || get(prevStepData, 'type') || 'PREVIOUS_PERIOD_SPEND',
          budgetAmount: budgetAmount || get(prevStepData, 'budgetAmount') || 0,
          period: period || get(prevStepData, 'period') || 'MONTHLY',
          startTime: startTime || get(prevStepData, 'startTime') || Number(todayInUTC().startOf('month').format('x')),
          growthRate: growthRate || get(prevStepData, 'growthRate') || 0,
          growthRateCheck: !!growthRate || !!get(prevStepData, 'growthRate')
        }}
      >
        {formikProps => {
          return (
            <FormikForm className={css.selectPerspectiveContainer}>
              {formLoading ? (
                <Container className={css.loadingContainer}>
                  <Icon name="spinner" size={26} color={Color.BLUE_500} />
                </Container>
              ) : null}
              <Container className={css.selectPerspectiveContainer}>
                <Text
                  font={{ variation: FontVariation.H4 }}
                  tooltipProps={{
                    dataTooltipId: 'createBudgetSetBudget'
                  }}
                >
                  {getString('ce.perspectives.budgets.setBudgetAmount.title')}
                </Text>
 
                <Container
                  margin={{
                    top: 'xxlarge'
                  }}
                  className={css.setBudgetContainer}
                >
                  <SetBudgetForm
                    formikProps={formikProps}
                    isEditMode={isEditMode}
                    lastMonthCost={lpc?.data}
                    setLastCostPeriodCostVar={setLastCostPeriodCostVar}
                  />
                  <Container
                    padding={{
                      left: 'medium'
                    }}
                  >
                    {renderCosts()}
                    {formikProps.values.growthRateCheck ? (
                      <GrowthRateChart
                        period={formikProps.values.period}
                        growthRateVal={formikProps.values.growthRate}
                        amount={formikProps.values.budgetAmount}
                        startTime={formikProps.values.startTime}
                      />
                    ) : null}
                  </Container>
                </Container>
 
                <FlexExpander />
                <Layout.Horizontal spacing="medium">
                  <Button
                    text={getString('previous')}
                    icon="chevron-left"
                    onClick={() => previousStep?.(prevStepData)}
                  />
                  <Button type="submit" intent="primary" rightIcon={'chevron-right'} disabled={false}>
                    {getString('continue')}
                  </Button>
                </Layout.Horizontal>
              </Container>
            </FormikForm>
          )
        }}
      </Formik>
    </Container>
  )
}
 
export default SetBudgetAmount