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

90.75% Statements 157/173
53.71% Branches 94/175
80% Functions 40/50
90.59% Lines 154/170

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 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749              2x 2x 2x 2x   2x                         2x 2x 2x 2x 2x 2x                       2x 2x   2x 2x 2x 2x 2x 2x 2x 2x                                                                 2x 1x 1x     1x 1x     1x 1x     1x 1x 1x 1x   1x                   1x                                                                                           2x 5x       5x     2x 5x 5x 5x 5x 5x 5x   1x 1x     5x   5x 1x 1x           1x 1x         1x             5x 3x                           35x 35x           35x   1x               5x 1x 1x     5x                                                                                         2x 2x     2x     2x 2x 2x 2x 2x 2x 2x           2x   2x 1x 1x           1x 1x         1x             2x 2x                             2x 2x             2x 2x   2x                                   2x 2x   2x                                             1x                 2x                   2x                                                           2x                                                     2x 13x 13x 13x 13x 13x       13x 13x                 13x             13x             13x 13x 2x 2x       13x 6x 2x       13x 13x   13x 1x 1x         1x 1x           13x 2x           13x 4x               39x 39x             13x                                       1x                       1x 1x                                 2x 20x   20x               20x                                       20x                                   2x 35x 35x     2x 2x 2x 2x 2x             2x     2x 76x 76x   76x                           53x                             2x 50x 50x                                                         2x 2x 2x     2x  
/*
 * 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, useMemo, ReactNode, useEffect } from 'react'
import cronstrue from 'cronstrue'
import { isEmpty } from 'lodash-es'
import { useHistory, useParams } from 'react-router-dom'
import type { Column, CellProps, Renderer } from 'react-table'
import {
  Button,
  Container,
  Text,
  Layout,
  Icon,
  FlexExpander,
  useToaster,
  ButtonSize,
  ButtonVariation,
  Link,
  getErrorInfoFromErrorObject
} from '@wings-software/uicore'
import { FontVariation, Color } from '@harness/design-system'
import { Popover, Position, Classes, PopoverInteractionKind } from '@blueprintjs/core'
import { DEFAULT_GROUP_BY } from '@ce/utils/perspectiveUtils'
import routes from '@common/RouteDefinitions'
import { QlceViewFieldInputInput, ViewChartType, AlertThreshold } from 'services/ce/services'
import {
  CEView,
  CEReportSchedule,
  useGetReportSetting,
  useListBudgetsForPerspective,
  useDeleteBudget,
  useDeleteReportSetting,
  Budget,
  useGetNotificationSettings,
  CCMNotificationChannel,
  useDeleteNotificationSettings
} from 'services/ce'
import { useStrings } from 'framework/strings'
import formatCost from '@ce/utils/formatCost'
 
import { useTelemetry } from '@common/hooks/useTelemetry'
import { USER_JOURNEY_EVENTS } from '@ce/TrackingEventsConstants'
import Table from './Table'
import PerspectiveBuilderPreview from '../PerspectiveBuilderPreview/PerspectiveBuilderPreview'
import useCreateReportModal from './PerspectiveCreateReport'
import useBudgetModal from './PerspectiveCreateBudget'
import useAnomaliesAlertDialog from '../AnomaliesAlert/AnomaliesAlertDialog'
import css from './PerspectiveReportsAndBudgets.module.scss'
 
interface ListProps {
  grid: ReactNode
  buttonText: string
  hasData: boolean
  loading: boolean
  meta?: ReactNode
  showCreateButton?: boolean
  onButtonClick: () => void
}
 
interface TableActionsProps {
  onClickEdit: () => void
  onClickDelete: () => void
  className?: string
}
 
interface ReportsAndBudgetsProps {
  values?: CEView
  onPrevButtonClick: () => void
}
 
interface SelectedAlertType {
  perspectiveId: string
  channels: CCMNotificationChannel[]
}
 
export interface UrlParams {
  perspectiveId: string
  accountId: string
}
 
const ReportsAndBudgets: React.FC<ReportsAndBudgetsProps> = ({ values, onPrevButtonClick }) => {
  const [groupBy, setGroupBy] = useState<QlceViewFieldInputInput>(() => {
    return (values?.viewVisualization?.groupBy as QlceViewFieldInputInput) || DEFAULT_GROUP_BY
  })
 
  useEffect(() => {
    values?.viewVisualization?.groupBy && setGroupBy(values?.viewVisualization?.groupBy as QlceViewFieldInputInput)
  }, [values?.viewVisualization?.groupBy])
 
  const [chartType, setChartType] = useState<ViewChartType>(() => {
    return (values?.viewVisualization?.chartType as ViewChartType) || ViewChartType.StackedLineChart
  })
 
  const history = useHistory()
  const { trackEvent } = useTelemetry()
  const { getString } = useStrings()
  const { perspectiveId, accountId } = useParams<UrlParams>()
 
  const savePerspective = (): void => {
    history.push(
      routes.toPerspectiveDetails({
        accountId,
        perspectiveId,
        perspectiveName: perspectiveId
      })
    )
  }
 
  return (
    <Container className={css.mainContainer}>
      <Container className={css.innerContainer}>
        <Layout.Vertical
          spacing="xxlarge"
          height="100%"
          padding={{
            left: 'large',
            right: 'xxlarge',
            bottom: 'xxlarge',
            top: 'xxlarge'
          }}
          style={{ overflowY: 'auto' }}
        >
          <ScheduledReports />
          <Budgets perspectiveName={values?.name || ''} />
          <AnomalyAlerts />
          <FlexExpander />
          <Layout.Horizontal padding={{ top: 'medium' }} spacing="large">
            <Button icon="chevron-left" text={getString('previous')} onClick={onPrevButtonClick} />
            <Button
              intent="primary"
              text={getString('ce.perspectives.save')}
              onClick={() => {
                trackEvent(USER_JOURNEY_EVENTS.SAVE_PERSPECTIVE, {})
                savePerspective()
              }}
            />
          </Layout.Horizontal>
        </Layout.Vertical>
        {values && (
          <PerspectiveBuilderPreview
            setGroupBy={(gBy: QlceViewFieldInputInput) => setGroupBy(gBy)}
            groupBy={groupBy}
            chartType={chartType}
            setChartType={(type: ViewChartType) => {
              setChartType(type)
            }}
            formValues={values}
          />
        )}
      </Container>
    </Container>
  )
}
 
const useFetchReports = (accountId: string, perspectiveId: string) => {
  const { data, loading, refetch } = useGetReportSetting({
    accountIdentifier: accountId,
    queryParams: { perspectiveId }
  })
  return { reports: data?.data || [], loading, refetch }
}
 
export const ScheduledReports: React.FC = () => {
  const { getString } = useStrings()
  const { accountId, perspectiveId } = useParams<UrlParams>()
  const { trackEvent } = useTelemetry()
  const { reports, loading, refetch } = useFetchReports(accountId, perspectiveId)
  const { mutate: deleteReport } = useDeleteReportSetting({})
  const { openModal, hideModal } = useCreateReportModal({
    onSuccess: () => {
      hideModal()
      refetch()
    }
  })
  const { showSuccess, showError } = useToaster()
 
  const handleDelete = async (report: CEReportSchedule) => {
    try {
      const deleted = await deleteReport(accountId, {
        queryParams: { reportId: report?.uuid },
        headers: {
          'content-type': 'application/json'
        }
      })
      Eif (deleted) {
        showSuccess(
          getString('ce.perspectives.reports.reportDeletedTxt', {
            name: report.name
          })
        )
        refetch()
      }
    } catch (err) {
      showError(err?.data?.message || err?.message)
    }
  }
 
  const columns: Column<CEReportSchedule>[] = useMemo(
    () => [
      {
        Header: getString('ce.perspectives.reports.reportName'),
        accessor: 'name'
      },
      {
        Header: getString('ce.perspectives.reports.frequency'),
        accessor: 'userCron',
        Cell: RenderReportFrequency
      },
      {
        Header: getString('ce.perspectives.reports.recipients'),
        accessor: 'recipients',
        Cell: ({ row }: CellProps<CEReportSchedule>) => {
          const recipients = [...(row.original.recipients || [])]
          return <RenderEmailAddresses emailAddresses={recipients} />
        }
      },
      {
        id: 'edit-delete-action-column',
        Cell: ({ row }: CellProps<CEReportSchedule>) => (
          <RenderEditDeleteActions
            onClickEdit={() => openModal({ isEdit: true, selectedReport: row.original })}
            onClickDelete={() => handleDelete(row.original)}
          />
        )
      }
    ],
    []
  )
 
  const openCreateReportModal = () => {
    trackEvent(USER_JOURNEY_EVENTS.CREATE_PERSPECTIVE_ADD_NEW_REPORT, {})
    openModal()
  }
 
  return (
    <Container>
      <Layout.Horizontal>
        <Container>
          <Text color={Color.GREY_800} font={{ variation: FontVariation.H4 }}>
            {getString('ce.perspectives.reports.title', {
              count: reports.length || 0
            })}
          </Text>
        </Container>
        <FlexExpander />
        {reports.length ? (
          <Link
            onClick={openCreateReportModal}
            size={ButtonSize.SMALL}
            padding="none"
            margin="none"
            font={FontVariation.SMALL}
            variation={ButtonVariation.LINK}
            icon="plus"
            iconProps={{
              size: 10
            }}
          >
            {getString('ce.perspectives.reports.addReportSchedule')}
          </Link>
        ) : null}
      </Layout.Horizontal>
      <Text padding={{ top: 'large', bottom: 'large' }} color={Color.GREY_800} className={css.subtext}>
        {`${getString('ce.perspectives.reports.desc')} ${
          !reports.length ? getString('ce.perspectives.reports.msg') : ''
        }`}
      </Text>
      <List
        buttonText={getString('ce.perspectives.reports.createNew')}
        onButtonClick={openCreateReportModal}
        showCreateButton={!reports.length}
        hasData={!!reports.length}
        loading={loading}
        grid={<Table<CEReportSchedule> data={reports} columns={columns} />}
      />
    </Container>
  )
}
 
const useFetchBudget = (accountId: string, perspectiveId: string) => {
  const { data, loading, refetch } = useListBudgetsForPerspective({
    queryParams: { accountIdentifier: accountId, perspectiveId: perspectiveId }
  })
  return { budgets: data?.data || [], loading, refetch }
}
 
export const Budgets = ({ perspectiveName }: { perspectiveName: string }): JSX.Element => {
  const { getString } = useStrings()
  const { accountId, perspectiveId } = useParams<UrlParams>()
  const { mutate: deleteBudget } = useDeleteBudget({ queryParams: { accountIdentifier: accountId } })
  const { budgets, loading, refetch } = useFetchBudget(accountId, perspectiveId)
  const { trackEvent } = useTelemetry()
  const { openModal, hideModal } = useBudgetModal({
    onSuccess: () => {
      hideModal()
      refetch()
    }
  })
  const { showSuccess, showError } = useToaster()
 
  const handleDeleteBudget: (budget: Budget) => void = async budget => {
    try {
      const deleted = await (budget?.uuid &&
        deleteBudget(budget.uuid, {
          headers: {
            'content-type': 'application/json'
          }
        }))
      Eif (deleted) {
        showSuccess(
          getString('ce.budgets.budgetDeletedTxt', {
            name: budget.name
          })
        )
        refetch()
      }
    } catch (err) {
      showError(err?.data?.message || err?.message)
    }
  }
 
  const columns: Column<AlertThreshold>[] = useMemo(
    () => [
      {
        Header: getString('ce.perspectives.budgets.configureAlerts.basedOn'),
        accessor: 'basedOn',
        Cell: RenderBasedOn
      },
      {
        Header: getString('ce.perspectives.budgets.configureAlerts.percent'),
        accessor: 'percentage',
        Cell: RenderAlertThresholds
      },
      {
        Header: getString('ce.perspectives.reports.recipientLabel'),
        accessor: 'emailAddresses',
        Cell: ({ row }: CellProps<AlertThreshold>) => {
          const emailAddresses = [...(row.original.emailAddresses || [])] as string[]
          return <RenderEmailAddresses emailAddresses={emailAddresses} />
        }
      }
    ],
    []
  )
 
  const renderMeta: (budget: Budget, index: number) => JSX.Element = (budget, index) => {
    const { budgetAmount = 0, growthRate } = budget
 
    return (
      <Container>
        <Text font={{ variation: FontVariation.H6 }}>
          {growthRate
            ? getString('ce.perspectives.budgets.budgetTextWithGrowthRate', {
                index: index + 1,
                amount: formatCost(budgetAmount),
                growth: growthRate
              })
            : getString('ce.perspectives.budgets.budgetText', {
                index: index + 1,
                amount: formatCost(budgetAmount)
              })}
        </Text>
      </Container>
    )
  }
 
  const renderGrid: (budget: Budget) => JSX.Element = budget => {
    const { alertThresholds = [] } = budget
 
    return (
      <Container>
        <Layout.Horizontal
          margin={{ top: 'large', bottom: 'medium' }}
          spacing="small"
          style={{
            justifyContent: 'space-between',
            alignItems: 'center'
          }}
        >
          <Text font="small" color={Color.GREY_800}>
            {getString('ce.perspectives.budgets.sendAlerts')}
          </Text>
          <Container margin={{ right: 'large' }}>
            <RenderEditDeleteActions
              onClickEdit={() =>
                openModal({
                  perspectiveName: perspectiveName,
                  perspective: perspectiveId,
                  isEdit: true,
                  selectedBudget: budget
                })
              }
              onClickDelete={() => handleDeleteBudget(budget)}
            />
          </Container>
        </Layout.Horizontal>
        <Table<AlertThreshold> columns={columns} data={(alertThresholds || []) as any} />
      </Container>
    )
  }
 
  const openCreateNewBudgetModal = (): void => {
    trackEvent(USER_JOURNEY_EVENTS.CREATE_PERSPECTIVE_ADD_NEW_BUDGET, {})
    openModal({
      isEdit: false,
      perspectiveName: perspectiveName,
      perspective: perspectiveId,
      selectedBudget: {}
    })
  }
 
  return (
    <Container>
      <Layout.Horizontal>
        <Text color={Color.GREY_800} font={{ variation: FontVariation.H4 }}>
          {getString('ce.perspectives.budgets.perspectiveCreateBudgetTitle', {
            count: budgets.length || 0
          })}
        </Text>
        <FlexExpander />
        {budgets.length ? (
          <Link
            size={ButtonSize.SMALL}
            padding="none"
            margin="none"
            font={FontVariation.SMALL}
            variation={ButtonVariation.LINK}
            icon="plus"
            iconProps={{
              size: 10
            }}
            onClick={openCreateNewBudgetModal}
          >
            {getString('ce.budgets.addNewBudget')}
          </Link>
        ) : null}
      </Layout.Horizontal>
      <Text padding={{ top: 'large', bottom: 'large' }} color={Color.GREY_800} className={css.subtext}>
        {getString('ce.perspectives.budgets.desc')}
      </Text>
      {budgets.map((budget, idx) => {
        return (
          <List
            key={budget.uuid}
            buttonText={getString('ce.perspectives.budgets.createNew')}
            onButtonClick={openCreateNewBudgetModal}
            hasData={!isEmpty(budget)}
            loading={loading}
            showCreateButton={isEmpty(budget)}
            meta={renderMeta(budget, idx)}
            grid={renderGrid(budget)}
          />
        )
      })}
      {!budgets.length ? (
        <List
          grid={null}
          loading={loading}
          onButtonClick={openCreateNewBudgetModal}
          buttonText={getString('ce.perspectives.budgets.createNew')}
          hasData={false}
          showCreateButton={true}
        />
      ) : null}
    </Container>
  )
}
 
export const AnomalyAlerts = () => {
  const { getString } = useStrings()
  const { showError, showSuccess } = useToaster()
  const { perspectiveId, accountId } = useParams<UrlParams>()
  const [isRefetching, setRefetchingState] = useState(false)
  const selectedAlertInitState: SelectedAlertType = {
    perspectiveId: perspectiveId,
    channels: []
  }
  const [selectedAlert, setSelectedAlert] = useState(selectedAlertInitState)
  const { openAnomaliesAlertModal } = useAnomaliesAlertDialog({
    setRefetchingState: setRefetchingState,
    selectedAlert: selectedAlert
  })
 
  const {
    data: notificationsList,
    loading,
    refetch: fetchNotificationList
  } = useGetNotificationSettings({
    perspectiveId,
    queryParams: {
      accountIdentifier: accountId
    }
  })
 
  const { mutate: deleteNotificationAlert } = useDeleteNotificationSettings({
    queryParams: {
      accountIdentifier: accountId,
      perspectiveId: perspectiveId
    }
  })
 
  useEffect(() => {
    if (isRefetching) {
      fetchNotificationList()
      setRefetchingState(false)
    }
  }, [fetchNotificationList, isRefetching])
 
  useEffect(() => {
    if (selectedAlert && selectedAlert.channels.length) {
      openAnomaliesAlertModal()
    }
  }, [openAnomaliesAlertModal, selectedAlert])
 
  const alertList = notificationsList?.data
  const channelsList = alertList?.channels || []
 
  const deleteNotification = async () => {
    try {
      const response = await deleteNotificationAlert(void 0, {
        headers: {
          'content-type': 'application/json'
        }
      })
      setRefetchingState(true)
      response && showSuccess(getString('ce.anomalyDetection.notificationAlerts.deleteAlertSuccessMsg'))
    } catch (error) {
      showError(getErrorInfoFromErrorObject(error))
    }
  }
 
  const onEdit = () => {
    setSelectedAlert({
      perspectiveId: perspectiveId,
      channels: channelsList || []
    })
  }
 
  const columns: Column<CCMNotificationChannel>[] = useMemo(
    () => [
      {
        Header: getString('ce.anomalyDetection.alertType'),
        accessor: 'notificationChannelType'
      },
      {
        Header: getString('ce.anomalyDetection.alertReciepients'),
        Cell: ({ row }: CellProps<CCMNotificationChannel>) => {
          const recipients = [...(row.original.channelUrls || [])]
          return <RenderEmailAddresses emailAddresses={recipients} />
        }
      }
    ],
    []
  )
 
  return (
    <Container>
      <Layout.Horizontal>
        <Text color={Color.GREY_800} font={{ variation: FontVariation.H4 }}>
          {getString('ce.anomalyDetection.perspectiveCreateAnomalyAlertTitle', {
            count: channelsList.length || 0
          })}
        </Text>
        <FlexExpander />
        {channelsList.length ? (
          <Link
            size={ButtonSize.SMALL}
            padding="none"
            margin="none"
            font={FontVariation.SMALL}
            variation={ButtonVariation.LINK}
            icon="plus"
            iconProps={{
              size: 10
            }}
            onClick={() => onEdit()}
          >
            {getString('ce.anomalyDetection.addNewAnomalyAlert')}
          </Link>
        ) : null}
      </Layout.Horizontal>
      <Text padding={{ top: 'large', bottom: 'large' }} color={Color.GREY_800} className={css.subtext}>
        {getString('ce.anomalyDetection.addAnoamlyAlertDesc')}
      </Text>
      <Container className={css.anomalyAlertsWrapper}>
        {channelsList.length ? (
          <RenderEditDeleteActions
            onClickEdit={() => onEdit()}
            onClickDelete={() => deleteNotification()}
            className={css.anomalyAlertsActionBtn}
          />
        ) : null}
        <List
          buttonText={getString('ce.anomalyDetection.createNewAnomalyAlert')}
          onButtonClick={openAnomaliesAlertModal}
          showCreateButton={!channelsList.length}
          hasData={!!channelsList.length}
          loading={loading}
          grid={<Table<CCMNotificationChannel> data={channelsList} columns={columns} />}
        />
      </Container>
    </Container>
  )
}
 
const List = (props: ListProps): JSX.Element => {
  const { grid, buttonText, hasData, onButtonClick, loading, meta, showCreateButton } = props
 
  const renderLoader = (): JSX.Element => {
    return (
      <Container className={css.loader}>
        <Icon name="spinner" color={Color.BLUE_500} size={30} />
      </Container>
    )
  }
 
  const renderCreateNewButton = () => {
    return (
      <Layout.Horizontal
        spacing="small"
        style={{
          justifyContent: hasData ? 'flex-end' : 'center',
          alignItems: 'center'
        }}
      >
        <Button
          type="submit"
          withoutBoxShadow={true}
          className={css.createBtn}
          text={buttonText}
          onClick={onButtonClick}
        />
      </Layout.Horizontal>
    )
  }
 
  return (
    <Container
      margin={{
        bottom: 'xlarge'
      }}
    >
      {loading && renderLoader()}
      {!loading && hasData && (
        <>
          {meta}
          {grid}
        </>
      )}
      {!loading && showCreateButton && renderCreateNewButton()}
    </Container>
  )
}
 
const RenderReportFrequency: Renderer<CellProps<CEReportSchedule>> = ({ row }) => {
  const cron = row.original.userCron || ''
  return <span>{cronstrue.toString(cron)}</span>
}
 
const RenderBasedOn: Renderer<CellProps<AlertThreshold>> = ({ row }) => {
  const { getString } = useStrings()
  const basedOn = row.original.basedOn!
  const map: Record<string, string> = useMemo(
    () => ({
      ACTUAL_COST: getString('ce.perspectives.budgets.actualSpend'),
      FORECASTED_COST: getString('ce.perspectives.budgets.forecastedCost')
    }),
    []
  )
 
  return <span>{map[basedOn]}</span>
}
 
const RenderEmailAddresses = ({ emailAddresses = [] }: { emailAddresses: string[] }) => {
  const email = emailAddresses.shift()
  const remainingEmailsCount = emailAddresses.length ? `(+${emailAddresses.length})` : ''
 
  return (
    <Layout.Horizontal spacing="xsmall">
      <Text color={Color.GREY_700} font="small">
        {email}
      </Text>
      {emailAddresses.length ? (
        <Popover
          popoverClassName={Classes.DARK}
          position={Position.BOTTOM}
          interactionKind={PopoverInteractionKind.HOVER}
          content={
            <div className={css.popoverContent}>
              <ul>
                {emailAddresses.map((em, idx) => (
                  <li key={idx}>{em}</li>
                ))}
              </ul>
            </div>
          }
        >
          <Text color="primary7" font="small">
            {remainingEmailsCount}
          </Text>
        </Popover>
      ) : null}
    </Layout.Horizontal>
  )
}
 
const RenderEditDeleteActions = (props: TableActionsProps): JSX.Element => {
  const { onClickEdit, onClickDelete, className } = props
  return (
    <Layout.Horizontal
      spacing="medium"
      style={{
        justifyContent: 'center',
        alignItems: 'center'
      }}
      className={className}
    >
      <Icon
        size={14}
        name={'Edit'}
        color={Color.PRIMARY_7}
        onClick={onClickEdit}
        className={css.icon}
        data-testid="editIcon"
      />
      <Icon
        size={14}
        name={'trash'}
        color={Color.PRIMARY_7}
        onClick={onClickDelete}
        className={css.icon}
        data-testid="deleteIcon"
      />
    </Layout.Horizontal>
  )
}
 
const RenderAlertThresholds: Renderer<CellProps<AlertThreshold>> = ({ row }) => {
  const percentage = row.original.percentage
  return <span>{percentage}%</span>
}
 
export default ReportsAndBudgets