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

78.87% Statements 153/194
54.32% Branches 176/324
54.17% Functions 26/48
79.69% Lines 153/192

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 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911              1x   1x 1x                               1x 1x 1x 1x 1x 1x 1x 1x   1x                             1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x                                       50x     50x             50x                         50x 50x             50x                                                     50x 50x             50x                                   50x 50x 50x 50x               50x           50x 50x 50x   50x                       50x               50x             50x 40x                             50x                                                                                                                                                                       50x 50x 50x 50x 50x           50x             50x         50x         50x                                                                     1x 50x 50x             50x     50x 50x 50x                           1x 2x 2x 2x 2x 2x                                                                                         1x                           1x   1x             6x 6x 6x 6x   6x 6x 6x     6x 6x 6x 6x 30x           6x             6x 6x         6x 4x         4x           1x                   6x 6x 6x 6x         6x                                       6x 1x     6x   6x                                                                                                                                                                                                             30x     50x                               1x 17x 16x 16x 16x 16x 16x 16x         16x 16x 16x 16x 16x 16x       16x             16x               16x             16x 1x 1x     16x 8x 8x 8x 7x       16x 8x 6x 6x   8x     16x 3x 3x                                                               16x                 16x 8x                   8x 2x           6x                                                                                                         1x         1x                         1x 1x                               1x  
/*
 * 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, { useEffect, useRef, useState } from 'react'
import type { CellProps } from 'react-table'
import cx from 'classnames'
import {
  Text,
  Layout,
  Container,
  Button,
  Icon,
  Link,
  Popover,
  HarnessDocTooltip,
  Heading,
  PageSpinner,
  Page,
  TableV2,
  ExpandingSearchInput,
  PageHeader
} from '@harness/uicore'
import { FontVariation, Color } from '@harness/design-system'
import { isEmpty as _isEmpty, defaultTo as _defaultTo } from 'lodash-es'
import HighchartsReact from 'highcharts-react-official'
import Highcharts from 'highcharts'
import { useHistory, useLocation, useParams } from 'react-router-dom'
import { Classes, Drawer, Menu, Position } from '@blueprintjs/core'
import routes from '@common/RouteDefinitions'
import { useToaster } from '@common/exports'
import type { AccountPathProps } from '@common/interfaces/RouteInterfaces'
import {
  AllResourcesOfAccountResponse,
  Service,
  ServiceSavings,
  useAllServiceResources,
  useGetServices,
  useHealthOfService,
  useRequestsOfService,
  useSavingsOfService,
  useGetServiceDiagnostics,
  ServiceError,
  useCumulativeServiceSavings,
  useDescribeServiceInContainerServiceCluster,
  useRouteDetails
} from 'services/lw'
import { String, useStrings } from 'framework/strings'
import useDeleteServiceHook from '@ce/common/useDeleteService'
import { useTelemetry } from '@common/hooks/useTelemetry'
import { USER_JOURNEY_EVENTS } from '@ce/TrackingEventsConstants'
import { useFeature } from '@common/hooks/useFeatures'
import RbacButton from '@rbac/components/Button/Button'
import { FeatureIdentifier } from 'framework/featureStore/FeatureIdentifier'
import type { FeatureDetail } from 'framework/featureStore/featureStoreUtil'
import { NGBreadcrumbs } from '@common/components/NGBreadcrumbs/NGBreadcrumbs'
import COGatewayAnalytics from './COGatewayAnalytics'
import COGatewayCumulativeAnalytics from './COGatewayCumulativeAnalytics'
import ComputeType from './components/ComputeType'
import { getInstancesLink, getRelativeTime, getStateTag, getRiskGaugeChartOptions } from './Utils'
import useToggleRuleState from './useToggleRuleState'
import TextWithToolTip, { textWithToolTipStatus } from '../TextWithTooltip/TextWithToolTip'
import landingPageSVG from './images/AutostoppingRuleIllustration.svg'
import refreshIcon from './images/refresh.svg'
import NoDataImage from './images/NoData.svg'
import css from './COGatewayList.module.scss'
 
const textColor: { [key: string]: string } = {
  disable: '#6B6D85'
}
 
interface TableRowMenuProps {
  onStateToggle: (type: 'SUCCESS' | 'FAILURE', data: Service, index?: number) => void
  onDelete: (type: 'SUCCESS' | 'FAILURE', data: Service) => void
  onEdit: (data: Service) => void
}
 
interface SearchParams {
  isActive: boolean
  text: string
}
 
interface EmptyListPageProps {
  featureDetail?: FeatureDetail
}
 
function IconCell(tableProps: CellProps<Service>): JSX.Element {
  return <ComputeType data={tableProps.row.original} />
}
function TimeCell(tableProps: CellProps<Service>): JSX.Element {
  return (
    <Text lineClamp={3} color={tableProps.row.original.disabled ? textColor.disable : Color.GREY_500}>
      {tableProps.value} mins
    </Text>
  )
}
function NameCell(tableProps: CellProps<Service>): JSX.Element {
  return (
    <Text
      lineClamp={3}
      color={Color.BLACK}
      style={{ fontWeight: 600, color: tableProps.row.original.disabled ? textColor.disable : 'inherit' }}
    >
      {/* <Icon name={tableProps.row.original.provider.icon as IconName}></Icon> */}
      {tableProps.value}
    </Text>
  )
}
 
function SavingsCell(tableProps: CellProps<Service>): JSX.Element {
  const { accountId } = useParams<AccountPathProps>()
  const { data, loading: savingsLoading } = useSavingsOfService({
    account_id: accountId,
    rule_id: tableProps.row.original.id as number,
    queryParams: {
      accountIdentifier: accountId
    }
  })
  return (
    <Layout.Horizontal spacing="large">
      <HighchartsReact
        highchart={Highcharts}
        options={
          !savingsLoading && data?.response != null
            ? getRiskGaugeChartOptions(
                (data?.response as ServiceSavings).savings_percentage as number,
                tableProps.row.original.disabled
              )
            : getRiskGaugeChartOptions(0)
        }
      />
      <Text className={css.savingsAmount}>
        {savingsLoading ? (
          <Icon name="spinner" size={12} color="blue500" />
        ) : !_isEmpty(data?.response) ? (
          `$${Math.round(((data?.response as ServiceSavings).actual_savings as number) * 100) / 100}`
        ) : (
          0
        )}
      </Text>
    </Layout.Horizontal>
  )
}
 
function ActivityCell(tableProps: CellProps<Service>): JSX.Element {
  const { accountId } = useParams<AccountPathProps>()
  const { data, loading: activityLoading } = useRequestsOfService({
    account_id: accountId,
    rule_id: tableProps.row.original.id as number,
    queryParams: {
      accountIdentifier: accountId
    }
  })
  return (
    <>
      {activityLoading ? (
        <Icon name="spinner" size={12} color="blue500" />
      ) : !_isEmpty(data?.response) ? (
        <Layout.Horizontal spacing="medium">
          <Icon name="history" />
          <Text lineClamp={3} color={tableProps.row.original.disabled ? textColor.disable : Color.GREY_500}>
            {getRelativeTime(data?.response?.[0].created_at as string, 'YYYY-MM-DDTHH:mm:ssZ')}
          </Text>
        </Layout.Horizontal>
      ) : (
        '-'
      )}
    </>
  )
}
function ResourcesCell(tableProps: CellProps<Service>): JSX.Element {
  const { accountId } = useParams<AccountPathProps>()
  const { getString } = useStrings()
  const isK8sRule = tableProps.row.original.kind === 'k8s'
  const { data, loading: healthLoading } = useHealthOfService({
    account_id: accountId,
    rule_id: tableProps.row.original.id as number,
    queryParams: {
      accountIdentifier: accountId
    }
  })
 
  const { data: resources, loading: resourcesLoading } = useAllServiceResources({
    account_id: accountId,
    rule_id: tableProps.row.original.id as number, // eslint-disable-line
    lazy: isK8sRule
  })
 
  const hasCustomDomains = (tableProps.row.original.custom_domains?.length as number) > 0
  const isSubmittedRule = tableProps.row.original.status === 'submitted'
  const isEcsRule = !_isEmpty(tableProps.row.original.routing?.container_svc)
 
  const { data: serviceDescribeData } = useDescribeServiceInContainerServiceCluster({
    account_id: accountId,
    cluster_name: _defaultTo(tableProps.row.original.routing?.container_svc?.cluster, ''),
    service_name: _defaultTo(tableProps.row.original.routing?.container_svc?.service, ''),
    lazy: !isEcsRule,
    queryParams: {
      accountIdentifier: accountId,
      cloud_account_id: tableProps.row.original.cloud_account_id,
      region: _defaultTo(tableProps.row.original.routing?.container_svc?.region, '')
    }
  })
 
  const getClickableLink = () => {
    return isK8sRule
      ? tableProps.row.original.routing?.k8s?.CustomDomain
      : hasCustomDomains
      ? tableProps.row.original.custom_domains?.[0]
      : tableProps.row.original.host_name
  }
 
  const handleDomainClick = (e: React.MouseEvent<HTMLElement, MouseEvent>) => {
    e.stopPropagation()
    if (isSubmittedRule) return
    const link = getClickableLink()
    window.open(`http://${link}`, '_blank')
  }
 
  const renderLink = (linkStr = '') => {
    return (
      <Layout.Horizontal spacing="small">
        <Text
          className={cx(css.link, {
            [css.disabled]: tableProps.row.original.disabled,
            [css.notAllowed]: isSubmittedRule
          })}
          onClick={handleDomainClick}
        >
          {linkStr}
        </Text>
      </Layout.Horizontal>
    )
  }
 
  return (
    <Container className={css.resourceCell}>
      <Layout.Vertical spacing="medium">
        <Layout.Horizontal spacing="xxxsmall">
          {!isK8sRule && !isEcsRule && (
            <>
              <Text
                style={{
                  alignSelf: 'center',
                  color: tableProps.row.original.disabled ? textColor.disable : 'inherit',
                  marginRight: 5
                }}
              >
                {getString('ce.co.noOfInstances')}
              </Text>
              {!resourcesLoading && resources?.response ? (
                <Link
                  href={getInstancesLink(tableProps.row.original, resources as AllResourcesOfAccountResponse)}
                  target="_blank"
                  style={{
                    textOverflow: 'ellipsis',
                    whiteSpace: 'nowrap',
                    color: tableProps.row.original.disabled ? textColor.disable : 'inherit',
                    marginRight: 5
                  }}
                  onClick={e => {
                    e.stopPropagation()
                  }}
                >
                  {resources?.response?.length}
                </Link>
              ) : (
                <Icon name="spinner" size={12} color="blue500" style={{ marginRight: 5 }} />
              )}
            </>
          )}
          {!tableProps.row.original.disabled && !isEcsRule && (
            <>
              {data?.response?.['state'] != null ? (
                getStateTag(data?.response?.['state'])
              ) : !healthLoading ? (
                getStateTag('down')
              ) : (
                <Icon name="spinner" size={12} color="blue500" />
              )}
            </>
          )}
          {isEcsRule && (
            <>
              <Text
                style={{
                  alignSelf: 'center',
                  color: tableProps.row.original.disabled ? textColor.disable : 'inherit',
                  marginRight: 5
                }}
              >
                {`${getString('ce.co.noOfTasks')} ${_defaultTo(serviceDescribeData?.response?.task_count, 0)}`}
              </Text>
              {getStateTag(serviceDescribeData?.response?.task_count ? 'active' : 'down')}
            </>
          )}
        </Layout.Horizontal>
        {!isK8sRule ? (
          renderLink(
            hasCustomDomains ? tableProps.row.original.custom_domains?.join(',') : tableProps.row.original.host_name
          )
        ) : !_isEmpty(tableProps.row.original.routing?.k8s?.CustomDomain) ? (
          renderLink(tableProps.row.original.routing?.k8s?.CustomDomain)
        ) : (
          <Layout.Horizontal flex={{ justifyContent: 'center' }}>
            <Text>{'-'}</Text>
          </Layout.Horizontal>
        )}
      </Layout.Vertical>
      {/* <Icon name={tableProps.row.original.provider.icon as IconName}></Icon> */}
      {tableProps.value}
    </Container>
  )
}
 
function RenderColumnMenu(
  tableProps: CellProps<Service>,
  { onEdit, onDelete, onStateToggle }: TableRowMenuProps
): JSX.Element {
  const { accountId } = useParams<AccountPathProps>()
  const row = tableProps.row
  const data = row.original.id
  const [menuOpen, setMenuOpen] = useState(false)
  const { triggerToggle } = useToggleRuleState({
    accountId,
    serviceData: row.original,
    onSuccess: (updatedServiceData: Service) => onStateToggle('SUCCESS', updatedServiceData, row.index),
    onFailure: err => onStateToggle('FAILURE', err)
  })
  const { triggerDelete } = useDeleteServiceHook({
    serviceData: row.original,
    accountId,
    onSuccess: (_data: Service) => onDelete('SUCCESS', _data),
    onFailure: err => onDelete('FAILURE', err)
  })
 
  const handleToggleRuleClick = async (e: React.MouseEvent<HTMLElement, MouseEvent>) => {
    e.stopPropagation()
    triggerToggle()
  }
 
  const handleDeleteRuleClick = async (e: React.MouseEvent<HTMLElement, MouseEvent>) => {
    e.stopPropagation()
    triggerDelete()
  }
 
  return (
    <Layout.Horizontal className={css.layout}>
      <Popover
        isOpen={menuOpen}
        onInteraction={nextOpenState => {
          setMenuOpen(nextOpenState)
        }}
        className={Classes.DARK}
        position={Position.BOTTOM_RIGHT}
      >
        <Button
          minimal
          icon="Options"
          onClick={e => {
            e.stopPropagation()
            setMenuOpen(true)
          }}
          data-testid={`menu-${data}`}
        />
        <Menu style={{ minWidth: 'unset' }}>
          {row.original.disabled ? (
            <Menu.Item icon="play" text="Enable" onClick={handleToggleRuleClick} />
          ) : (
            <Menu.Item icon="disable" text="Disable" onClick={handleToggleRuleClick} />
          )}
          {row.original.status !== 'submitted' && (
            <Menu.Item icon="edit" text="Edit" onClick={() => onEdit(row.original)} />
          )}
          <Menu.Item icon="trash" text="Delete" onClick={handleDeleteRuleClick} />
        </Menu>
      </Popover>
    </Layout.Horizontal>
  )
}
 
const StatusCell = ({ row }: CellProps<Service>) => {
  const { accountId } = useParams<AccountPathProps>()
  const { data, loading } = useGetServiceDiagnostics({
    account_id: accountId, // eslint-disable-line
    rule_id: row.original.id as number, // eslint-disable-line
    queryParams: {
      accountIdentifier: accountId
    }
  })
  const diagnosticsErrors = (data?.response || [])
    .filter(item => !item.success)
    .map(item => ({ action: item.name, error: item.message }))
  const hasError: boolean = !_isEmpty(row.original.metadata?.service_errors) || !_isEmpty(diagnosticsErrors)
  const combinedErrors: ServiceError[] = (row.original.metadata?.service_errors || []).concat(diagnosticsErrors)
  return loading ? (
    <Icon name="spinner" size={12} color="blue500" />
  ) : (
    <TextWithToolTip
      messageText={row.original.status}
      errors={hasError ? combinedErrors : []}
      status={
        row.original.status === 'errored' || hasError ? textWithToolTipStatus.ERROR : textWithToolTipStatus.SUCCESS
      }
      indicatorColor={row.original.status === 'submitted' ? Color.YELLOW_500 : undefined}
    />
  )
}
 
const EmptyListPage: React.FC<EmptyListPageProps> = () => {
  const { accountId } = useParams<AccountPathProps>()
  const { getString } = useStrings()
  const history = useHistory()
  const { trackEvent } = useTelemetry()
  return (
    <Container background={Color.WHITE} height="100vh">
      <NGBreadcrumbs
        links={[
          {
            url: routes.toCECORules({ accountId }),
            label: getString('ce.co.breadCrumb.rules')
          }
        ]}
      />
      <Layout.Vertical
        spacing="large"
        style={{
          justifyContent: 'center',
          alignItems: 'center',
          paddingTop: '220px'
        }}
      >
        <img src={landingPageSVG} alt="autostopping-rules" width="500px"></img>
        <Text font="normal" style={{ lineHeight: '24px', textAlign: 'center', width: '760px', marginTop: '20px' }}>
          <String stringID="ce.co.landingPageText" useRichText={true} /> <Link href="/">Learn more</Link>
        </Text>
        <RbacButton
          intent="primary"
          text={getString('ce.co.newAutoStoppingRule')}
          icon="plus"
          featuresProps={{
            featuresRequest: {
              featureNames: [FeatureIdentifier.RESTRICTED_AUTOSTOPPING_RULE_CREATION]
            }
          }}
          onClick={() => {
            history.push(
              routes.toCECOCreateGateway({
                accountId
              })
            )
            trackEvent(USER_JOURNEY_EVENTS.CREATE_NEW_AS_CLICK, {})
          }}
        />
      </Layout.Vertical>
    </Container>
  )
}
 
const TOTAL_ITEMS_PER_PAGE = 5
 
interface RulesTableContainerProps {
  rules: Service[]
  setRules: (services: Service[]) => void
  loading: boolean
  rowMenuProps: TableRowMenuProps
  pageProps: { index: number; setIndex: (index: number) => void }
  onRowClick: (data: Service, index: number) => void
  refetchRules: (value: string, isSearchActive: boolean) => Promise<void>
  onSearchCallback?: (value: string) => void
  searchParams: SearchParams
}
 
const POLL_TIMER = 1000 * 60 * 1
 
const useSubmittedRulesStatusUpdate = ({
  rules,
  onRuleUpdate
}: {
  rules: Service[]
  onRuleUpdate?: (params: { updatedService: Service; index: number }) => void
}) => {
  const { accountId } = useParams<AccountPathProps>()
  const { data, refetch, loading } = useRouteDetails({ account_id: accountId, rule_id: 0, lazy: true })
  const rulesToFetch = useRef<{ index: number; rule: Service }[]>([])
  const timer = useRef<NodeJS.Timer | null>(null)
 
  const clearTimer = () => {
    clearTimeout(timer.current as NodeJS.Timer)
    timer.current = null
  }
 
  useEffect(() => {
    rulesToFetch.current = []
    clearTimer()
    rules.forEach((r, i) => {
      Iif (r.status === 'submitted') {
        rulesToFetch.current.push({ index: i, rule: r })
      }
    })
  }, [rules])
 
  const triggerRuleFetching = () => {
    timer.current = setTimeout(() => {
      refetch({ pathParams: { account_id: accountId, rule_id: rulesToFetch.current[0].rule.id } })
      clearTimer()
    }, POLL_TIMER)
  }
 
  useEffect(() => {
    Iif (!_isEmpty(rulesToFetch.current) && !loading && timer.current === null) {
      triggerRuleFetching()
    }
  }, [rulesToFetch.current, timer.current])
 
  useEffect(() => {
    Iif (!_isEmpty(data?.response) && data?.response?.service?.status !== 'submitted') {
      onRuleUpdate?.({ updatedService: data?.response?.service as Service, index: rulesToFetch.current[0].index })
      rulesToFetch.current.shift()
      clearTimer()
    }
    Iif (timer.current) {
      return () => clearTimeout(timer.current as NodeJS.Timer)
    }
  }, [data?.response])
}
 
const RulesTableContainer: React.FC<RulesTableContainerProps> = ({
  rules,
  setRules,
  loading,
  rowMenuProps: { onDelete, onEdit, onStateToggle },
  pageProps,
  onRowClick,
  refetchRules,
  searchParams
}) => {
  const { getString } = useStrings()
  const history = useHistory()
  const location = useLocation()
  const tableData = rules.slice(
    pageProps.index * TOTAL_ITEMS_PER_PAGE,
    pageProps.index * TOTAL_ITEMS_PER_PAGE + TOTAL_ITEMS_PER_PAGE
  )
 
  useSubmittedRulesStatusUpdate({
    rules: tableData,
    onRuleUpdate: ({ updatedService, index }) => {
      const updatedRules = [...rules]
      const updatedIndex = pageProps.index * TOTAL_ITEMS_PER_PAGE + index
      updatedRules.splice(updatedIndex, 1, updatedService)
      setRules(updatedRules)
    }
  })
 
  /* istanbul ignore next */
  const onSearchChange = async (val: string) => {
    val = val.trim()
    const hasSearchText = !_isEmpty(val)
    const params = new URLSearchParams({ search: val })
    history.replace({ pathname: location.pathname, search: hasSearchText ? params.toString() : undefined })
    await refetchRules(val, true)
    pageProps.setIndex(0)
  }
 
  const handleRefreshClick = () => {
    refetchRules(searchParams.text, !_isEmpty(searchParams.text))
  }
 
  const emptySearchResults = _isEmpty(rules)
 
  return (
    <Container padding={'xlarge'}>
      <Layout.Horizontal flex={{ justifyContent: 'space-between' }}>
        <Layout.Horizontal>
          {!emptySearchResults && searchParams.text && !loading ? (
            <Text font={{ variation: FontVariation.H6 }}>
              {getString('ce.co.searchResultsText', {
                count: rules.length,
                text: searchParams.text
              })}
            </Text>
          ) : null}
        </Layout.Horizontal>
        <Layout.Horizontal flex>
          <ExpandingSearchInput
            placeholder={getString('search')}
            onChange={onSearchChange}
            throttle={300}
            alwaysExpanded={true}
            defaultValue={searchParams.text}
          />
        </Layout.Horizontal>
      </Layout.Horizontal>
      <Container margin={{ top: 'medium' }} style={{ position: 'relative' }}>
        {loading ? (
          <Layout.Horizontal style={{ padding: 'var(--spacing-large)', paddingTop: 'var(--spacing-xxxlarge)' }}>
            <PageSpinner />
          </Layout.Horizontal>
        ) : emptySearchResults ? (
          <>
            <Layout.Vertical spacing="large" style={{ alignItems: 'center' }}>
              <img src={NoDataImage} height={150} />
              <Text color="grey800" font="normal" style={{ lineHeight: '25px' }}>
                {getString('ce.co.emptyResultText', { string: searchParams.text })}
              </Text>
            </Layout.Vertical>
          </>
        ) : (
          <>
            <Layout.Horizontal
              className={css.refreshIconContainer}
              onClick={handleRefreshClick}
              data-testid={'refreshIconContainer'}
            >
              <img src={refreshIcon} width={'12px'} height={'12px'} />
              <Text>Refresh</Text>
            </Layout.Horizontal>
            <TableV2<Service>
              data={tableData}
              pagination={{
                pageSize: TOTAL_ITEMS_PER_PAGE,
                pageIndex: pageProps.index,
                pageCount: Math.ceil(rules.length / TOTAL_ITEMS_PER_PAGE) ?? 1,
                itemCount: rules.length,
                gotoPage: newPageIndex => pageProps.setIndex(newPageIndex)
              }}
              onRowClick={onRowClick}
              columns={[
                {
                  accessor: 'name',
                  Header: getString('ce.co.rulesTableHeaders.name'),
                  width: '18%',
                  Cell: NameCell,
                  disableSortBy: true
                },
                {
                  accessor: 'idle_time_mins',
                  Header: getString('ce.co.rulesTableHeaders.idleTime'),
                  width: '8%',
                  Cell: TimeCell,
                  disableSortBy: true
                },
                {
                  accessor: 'fulfilment',
                  Header: getString('ce.co.rulesTableHeaders.fulfilment'),
                  width: '12%',
                  Cell: IconCell,
                  disableSortBy: true
                },
                {
                  Header: getString('ce.co.rulesTableHeaders.mangedResources'),
                  width: '22%',
                  Cell: ResourcesCell
                },
                {
                  Header: getString('ce.co.rulesTableHeaders.savings').toUpperCase(),
                  width: '15%',
                  Cell: SavingsCell,
                  disableSortBy: true
                },
                {
                  Header: getString('ce.co.rulesTableHeaders.lastActivity'),
                  width: '10%',
                  Cell: ActivityCell
                },
                {
                  Header: getString('ce.co.rulesTableHeaders.status'),
                  width: '10%',
                  Cell: StatusCell
                },
                {
                  Header: '',
                  id: 'menu',
                  accessor: row => row.id,
                  width: '5%',
                  Cell: (cellData: CellProps<Service>) =>
                    RenderColumnMenu(cellData, {
                      onDelete,
                      onEdit,
                      onStateToggle
                    }),
                  disableSortBy: true
                }
              ]}
            />
          </>
        )}
      </Container>
    </Container>
  )
}
 
const COGatewayList: React.FC = () => {
  const { getString } = useStrings()
  const history = useHistory()
  const location = useLocation()
  const { trackEvent } = useTelemetry()
  const { accountId } = useParams<AccountPathProps>()
  const { showSuccess, showError } = useToaster()
  const { featureDetail } = useFeature({
    featureRequest: {
      featureName: FeatureIdentifier.RESTRICTED_AUTOSTOPPING_RULE_CREATION
    }
  })
  const [selectedService, setSelectedService] = useState<{ data: Service; index: number } | null>()
  const [isDrawerOpen, setIsDrawerOpen] = useState<boolean>(false)
  const [tableData, setTableData] = useState<Service[]>([])
  const [pageIndex, setPageIndex] = useState<number>(0)
  const searchQueryText = useRef(new URLSearchParams(location.search).get('search'))
  const [searchParams, setSearchParams] = useState<SearchParams>({
    isActive: !_isEmpty(searchQueryText.current),
    text: _defaultTo(searchQueryText.current, '')
  })
  const [isLoadingPage, setIsLoadingPage] = useState(true) // track initial loading of page
 
  const {
    data: servicesData,
    error,
    loading,
    refetch: refetchServices
  } = useGetServices({
    account_id: accountId,
    queryParams: {
      accountIdentifier: accountId,
      value: _defaultTo(searchParams.text, '')
    }
  })
 
  const { data: graphData, loading: graphLoading } = useCumulativeServiceSavings({
    account_id: accountId,
    queryParams: {
      accountIdentifier: accountId
    }
  })
 
  const triggerServiceFetch = async (value: string, isSearchActive: boolean) => {
    await refetchServices({ queryParams: { accountIdentifier: accountId, value } })
    setSearchParams({ isActive: isSearchActive, text: value })
  }
 
  const trackLandingPage = () => {
    const hasData = !_isEmpty(servicesData?.response)
    const eventName = hasData ? USER_JOURNEY_EVENTS.LOAD_AS_SUMMARY_PAGE : USER_JOURNEY_EVENTS.LOAD_AS_LANDING_PAGE
    if (!loading) {
      trackEvent(eventName, {})
    }
  }
 
  useEffect(() => {
    if (servicesData) {
      setTableData(_defaultTo(servicesData?.response, []))
      setIsLoadingPage(false) // to stop initial loading of page
    }
    trackLandingPage()
  }, [servicesData?.response])
 
  if (error) {
    const errMessage = _defaultTo((error.data as any)?.errors?.join(', '), error.message)
    showError(errMessage, undefined, 'ce.get.svc.error')
  }
 
  /* istanbul ignore next */
  const onServiceStateToggle = (type: 'SUCCESS' | 'FAILURE', data: Service | any, index?: number) => {
    if (type === 'SUCCESS') {
      const currTableData: Service[] = [...tableData]
      currTableData.splice(index as number, 1, data)
      setTableData(currTableData)
      if (!_isEmpty(selectedService)) {
        setSelectedService({ data, index: index as number })
      }
      showSuccess(`Rule ${data.name} ${!data.disabled ? 'enabled' : 'disabled'}`)
    } else {
      showError(data, undefined, 'ce.svc.stage.toggle.error')
    }
  }
 
  /* istanbul ignore next */
  const onServiceDeletion = (type: 'SUCCESS' | 'FAILURE', data: Service | any) => {
    if (type === 'SUCCESS') {
      showSuccess(`Rule ${data.name} deleted successfully`)
      if (isDrawerOpen) {
        setIsDrawerOpen(false)
        setSelectedService(null)
      }
      refetchServices()
    } else {
      showError(data, undefined, 'ce.svc.delete.error')
    }
  }
 
  const handleServiceEdit = (_service: Service) =>
    history.push(
      routes.toCECOEditGateway({
        accountId: _service.account_identifier as string,
        gatewayIdentifier: _service.id?.toString() as string
      })
    )
 
  // Render page loader for initial loading of the page
  if (isLoadingPage) {
    return (
      <div style={{ position: 'relative', height: 'calc(100vh - 128px)' }}>
        <PageSpinner />
      </div>
    )
  }
 
  // Render empty page component when:
  // no data is available
  // search is not active
  if (!isLoadingPage && _isEmpty(tableData) && !searchParams.isActive) {
    return <EmptyListPage featureDetail={featureDetail} />
  }
 
  // Render summary and table when:
  // without search - data is available
  // with search - data is available or unavailable
  return (
    <Container background={Color.WHITE} height="100vh">
      <PageHeader
        title={
          <Layout.Horizontal flex={{ alignItems: 'center' }}>
            <Heading data-tooltip-id="autostoppingRule" level={2} color={Color.GREY_800} font={{ weight: 'bold' }}>
              {getString('ce.co.breadCrumb.rules')}
            </Heading>
            <HarnessDocTooltip tooltipId="autostoppingRule" useStandAlone={true} />
          </Layout.Horizontal>
        }
        breadcrumbs={<NGBreadcrumbs />}
      />
 
      <Drawer
        autoFocus={true}
        enforceFocus={true}
        hasBackdrop={true}
        usePortal={true}
        canOutsideClickClose={true}
        canEscapeKeyClose={true}
        isOpen={isDrawerOpen}
        onClose={() => {
          setIsDrawerOpen(false)
          setSelectedService(null)
        }}
        size="656px"
        style={{
          boxShadow: '0px 2px 8px rgba(40, 41, 61, 0.04), 0px 16px 24px rgba(96, 97, 112, 0.16)',
          borderRadius: '8px',
          overflowY: 'scroll'
        }}
      >
        <COGatewayAnalytics
          service={selectedService}
          handleServiceToggle={onServiceStateToggle}
          handleServiceDeletion={onServiceDeletion}
          handleServiceEdit={handleServiceEdit}
        />
      </Drawer>
      <>
        <Layout.Horizontal padding="large">
          <Layout.Horizontal width="55%">
            <RbacButton
              intent="primary"
              text={getString('ce.co.newAutoStoppingRule')}
              icon="plus"
              featuresProps={{
                featuresRequest: {
                  featureNames: [FeatureIdentifier.RESTRICTED_AUTOSTOPPING_RULE_CREATION]
                }
              }}
              onClick={() => {
                history.push(
                  routes.toCECOCreateGateway({
                    accountId
                  })
                )
                trackEvent('StartedMakingAutoStoppingRule', {})
              }}
            />
          </Layout.Horizontal>
        </Layout.Horizontal>
      </>
      <Page.Body className={css.pageContainer}>
        <COGatewayCumulativeAnalytics data={graphData?.response} loadingData={graphLoading} />
        <RulesTableContainer
          rules={tableData}
          setRules={setTableData}
          loading={loading}
          onRowClick={(e, index) => {
            setSelectedService({ data: e, index })
            setIsDrawerOpen(true)
          }}
          pageProps={{ index: pageIndex, setIndex: setPageIndex }}
          refetchRules={triggerServiceFetch}
          rowMenuProps={{
            onDelete: onServiceDeletion,
            onEdit: handleServiceEdit,
            onStateToggle: onServiceStateToggle
          }}
          searchParams={searchParams}
        />
      </Page.Body>
    </Container>
  )
}
 
export default COGatewayList