All files / modules/75-ce/components/PerspectiveSummary PerspectiveSummary.tsx

60.29% Statements 41/68
38.13% Branches 53/139
40% Functions 4/10
60.29% Lines 41/68

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              1x 1x                         1x 1x 1x 1x 1x             1x 1x 1x     1x 1x 1x 1x   1x                                                                               1x                 4x                   4x                                                               1x         1x                                                                                                                                                                                           1x 4x           4x   4x   4x           4x   4x                 4x       4x       4x                   4x 4x                                                                                                                                                                                             1x             4x       4x 4x 4x     4x   2x           4x                                                     1x  
/*
 * 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, useState } from 'react'
import {
  Layout,
  Card,
  Text,
  Container,
  FlexExpander,
  Icon,
  Carousel,
  Button,
  Link,
  ButtonSize,
  ButtonVariation
} from '@wings-software/uicore'
import cx from 'classnames'
import { FontVariation, Color } from '@harness/design-system'
import { useHistory, useParams } from 'react-router-dom'
import { useStrings } from 'framework/strings'
import {
  PerspectiveTrendStats,
  Maybe,
  useFetchPerspectiveBudgetQuery,
  BudgetSummary,
  K8sRecommendationFilterDtoInput
} from 'services/ce/services'
import useBudgetModal from '@ce/components/PerspectiveReportsAndBudget/PerspectiveCreateBudget'
import formatCost from '@ce/utils/formatCost'
import { useGetLastMonthCost, useGetForecastCost } from 'services/ce'
 
import type { AccountPathProps } from '@common/interfaces/RouteInterfaces'
import routes from '@common/RouteDefinitions'
import { getViewFilterForId } from '@ce/utils/perspectiveUtils'
import RecommendationSummaryCard from './RecommendationSummaryCard'
import css from './PerspectiveSummary.module.scss'
 
const StatsTrendRenderer: React.FC<{ val: number }> = ({ val }) => {
  if (+val === 0) {
    return null
  }
  if (val < 0) {
    return (
      <Text
        iconProps={{
          color: 'green500'
        }}
        icon="caret-down"
        color="green500"
      >
        {`${val * -1}%`}
      </Text>
    )
  }
  return (
    <Text
      iconProps={{
        color: 'red500'
      }}
      icon="caret-up"
      color="red500"
    >
      {`${val}%`}
    </Text>
  )
}
 
interface CostCardProps {
  fetching: boolean
  statsLabel: string | undefined
  statsValue: string | undefined
  statsTrend: any
  statsDescription: string | undefined
  isEmpty: boolean
  showTrend?: boolean
}
 
const CostCard: (val: CostCardProps) => JSX.Element = ({
  fetching,
  statsLabel,
  statsValue,
  statsTrend,
  statsDescription,
  isEmpty,
  showTrend = true
}) => {
  Iif (fetching) {
    return (
      <Card elevation={1} interactive={false}>
        <Container className={cx(css.mainCard, css.loadingContainer)}>
          <Icon name="spinner" color="blue500" size={30} />
        </Container>
      </Card>
    )
  }
 
  return (
    <Card elevation={1} interactive={false}>
      <Container className={css.mainCard}>
        {!isEmpty ? (
          <>
            <Text color={Color.GREY_500} font="small">
              {statsLabel}
            </Text>
            <Layout.Horizontal
              style={{
                alignItems: 'center'
              }}
              margin={{
                top: 'small',
                bottom: 'small'
              }}
            >
              <Text font={{ variation: FontVariation.H3 }}>{statsValue}</Text>
              <FlexExpander />
              {showTrend && <StatsTrendRenderer val={statsTrend} />}
            </Layout.Horizontal>
 
            <Text color="grey400" font="xsmall">
              {statsDescription}
            </Text>
          </>
        ) : null}
      </Container>
    </Card>
  )
}
 
const BAR_WIDTH = 298
interface BudgetCardProps {
  budgetData: BudgetSummary
}
 
const BudgetCard: (props: BudgetCardProps) => JSX.Element | null = ({ budgetData }) => {
  const { accountId } = useParams<AccountPathProps>()
  const { getString } = useStrings()
  const { actualCost, budgetAmount } = budgetData
  const history = useHistory()
 
  const percentage = Math.round((actualCost * 100) / (budgetAmount || 1))
 
  let width = BAR_WIDTH
 
  if (percentage > 100) {
    width = BAR_WIDTH * (budgetAmount / actualCost)
  }
 
  let intentColor = Color.GREEN_500
  if (percentage > 50) {
    intentColor = Color.ORANGE_500
  }
  if (percentage > 90) {
    intentColor = Color.RED_500
  }
 
  return (
    <Container className={cx(css.budgetCard)}>
      <Layout.Horizontal>
        <Text color={Color.GREY_500} font={FontVariation.SMALL}>
          {getString('ce.perspectives.budgets.budgetMonthlyTxt', { period: budgetData.timeScope })}
        </Text>
        <FlexExpander />
        <Link
          className={css.viewBudgetLink}
          withoutHref
          onClick={() =>
            history.push(
              routes.toCEBudgetDetails({
                budgetId: budgetData.id,
                budgetName: budgetData.name,
                accountId: accountId
              })
            )
          }
          size={ButtonSize.SMALL}
          padding="none"
          margin="none"
          font={FontVariation.SMALL}
          variation={ButtonVariation.LINK}
        >
          {getString('ce.perspectives.budgets.viewText')}
        </Link>
      </Layout.Horizontal>
 
      <Layout.Horizontal
        margin={{
          top: 'small',
          bottom: 'small'
        }}
        spacing="xsmall"
        style={{
          alignItems: 'flex-end'
        }}
      >
        <Text font={{ variation: FontVariation.H3 }}>{formatCost(budgetAmount)}</Text>
        <Text className={css.thisMonthText} color={Color.GREY_400} font={{ variation: FontVariation.TINY }}>
          {getString('ce.perspectives.budgets.thisMonth')}
        </Text>
      </Layout.Horizontal>
      <Layout.Horizontal spacing="xsmall">
        {percentage > 100 ? (
          <>
            <Text className={css.spendText} color={Color.GREY_500} font={{ variation: FontVariation.TINY }}>
              {getString('ce.perspectives.budgets.spendExceededBy')}
            </Text>
            <Text color="red500" font={{ variation: FontVariation.TINY_SEMI }}>
              {formatCost(actualCost - budgetAmount)}
            </Text>
          </>
        ) : (
          <>
            <Text className={css.spendText} color={Color.GREY_500} font={{ variation: FontVariation.TINY }}>
              {getString('ce.perspectives.budgets.monthToDateSpend')}
            </Text>
            <Text color={Color.GREY_500} font={{ variation: FontVariation.TINY_SEMI }}>{`${percentage}%`}</Text>
            <Text color={Color.GREY_500} font={{ variation: FontVariation.TINY }}>
              {getString('ce.perspectives.budgets.budgetSmallTxt')}
            </Text>
          </>
        )}
      </Layout.Horizontal>
      <div className={cx(css.indicatorBar, css.indicatorBarWithPattern)}></div>
      <Container width={width} background={intentColor} className={css.indicatorBar}></Container>
    </Container>
  )
}
 
const BudgetCardsCarousel: () => JSX.Element | null = () => {
  const { perspectiveId, accountId, perspectiveName } = useParams<{
    perspectiveId: string
    accountId: string
    perspectiveName: string
  }>()
 
  const [activeSlide, setActiveSlide] = useState<number>(1)
 
  const { getString } = useStrings()
 
  const [{ data, fetching: budgetFetching }, refetchBudget] = useFetchPerspectiveBudgetQuery({
    variables: {
      perspectiveId: perspectiveId
    }
  })
 
  const budgetData = data?.budgetSummaryList
 
  const { openModal, hideModal } = useBudgetModal({
    onSuccess: () => {
      hideModal()
      refetchBudget({
        requestPolicy: 'cache-and-network'
      })
    }
  })
 
  const { data: lmc } = useGetLastMonthCost({
    queryParams: { accountIdentifier: accountId, perspectiveId }
  })
 
  const { data: fc } = useGetForecastCost({
    queryParams: { accountIdentifier: accountId, perspectiveId }
  })
 
  Iif (budgetFetching) {
    return (
      <Card className={css.cardContainer} elevation={1} interactive={false}>
        <Container className={cx(css.budgetCard, { [css.loadingContainer]: budgetFetching })}>
          <Icon name="spinner" color="blue500" size={30} />
        </Container>
      </Card>
    )
  }
 
  Eif (!budgetData?.length) {
    return (
      <Card className={css.cardContainer} elevation={1} interactive={false}>
        <Container className={cx(css.budgetCard)}>
          <Text color="grey800" font="small">
            {getString('ce.perspectives.budgets.title')}
          </Text>
          <Text
            margin={{
              top: 'small',
              bottom: 'small'
            }}
            color="black"
            font={{ weight: 'semi-bold', size: 'medium' }}
          >
            {'$---'}
          </Text>
          <Text
            className={css.addBudgetText}
            color="primary7"
            font="small"
            onClick={() => {
              openModal({
                isEdit: false,
                perspectiveName: perspectiveName,
                perspective: perspectiveId,
                selectedBudget: {
                  lastMonthCost: lmc?.data,
                  forecastCost: fc?.data
                }
              })
            }}
          >
            {getString('ce.perspectives.budgets.addBudget')}
          </Text>
        </Container>
      </Card>
    )
  }
 
  return (
    <Card className={css.cardContainer} elevation={1} interactive={false}>
      <Carousel
        className={css.carousel}
        onChange={setActiveSlide}
        hideIndicators={true}
        previousElement={
          activeSlide > 1 ? (
            <Button
              intent="primary"
              className={css.prevButtons}
              icon="main-caret-left"
              minimal
              iconProps={{
                size: 8,
                color: Color.PRIMARY_7
              }}
            />
          ) : (
            <span />
          )
        }
        nextElement={
          activeSlide < budgetData.length ? (
            <Button
              intent="primary"
              className={css.nextButton}
              icon="main-caret-right"
              minimal
              iconProps={{
                size: 8,
                color: Color.PRIMARY_7
              }}
            />
          ) : (
            <span />
          )
        }
      >
        {budgetData.map(bData => (
          <BudgetCard key={bData?.id} budgetData={bData as BudgetSummary} />
        ))}
      </Carousel>
    </Card>
  )
}
 
interface PerspectiveSummaryProps {
  fetching: boolean
  data: Maybe<PerspectiveTrendStats> | undefined
  forecastedCostData: Maybe<PerspectiveTrendStats> | undefined
  errors?: any[] | null
  isDefaultPerspective: boolean
  hasClusterAsSource: boolean
}
 
const PerspectiveSummary: React.FC<PerspectiveSummaryProps> = ({
  fetching,
  data,
  forecastedCostData,
  isDefaultPerspective,
  hasClusterAsSource
}) => {
  const { perspectiveId } = useParams<{
    perspectiveId: string
  }>()
 
  let showForecastedCostCard = true
  Eif (!fetching && !forecastedCostData?.cost?.statsValue) {
    showForecastedCostCard = false
  }
 
  const recommendationFilters = useMemo(
    () =>
      ({
        perspectiveFilters: [getViewFilterForId(perspectiveId)]
      } as K8sRecommendationFilterDtoInput),
    [perspectiveId]
  )
 
  return (
    <Layout.Horizontal margin="xlarge" spacing="large">
      <CostCard
        fetching={fetching}
        statsLabel={data?.cost?.statsLabel}
        statsDescription={data?.cost?.statsDescription}
        statsTrend={data?.cost?.statsTrend}
        statsValue={data?.cost?.statsValue}
        isEmpty={!data?.cost}
      />
      {!isDefaultPerspective && <BudgetCardsCarousel />}
      {showForecastedCostCard && (
        <CostCard
          fetching={fetching}
          statsLabel={forecastedCostData?.cost?.statsLabel}
          statsDescription={forecastedCostData?.cost?.statsDescription}
          statsTrend={forecastedCostData?.cost?.statsTrend}
          statsValue={forecastedCostData?.cost?.statsValue}
          isEmpty={!forecastedCostData?.cost}
          showTrend={false}
        />
      )}
      {hasClusterAsSource && <RecommendationSummaryCard filters={recommendationFilters} />}
    </Layout.Horizontal>
  )
}
 
export default PerspectiveSummary