All files / modules/33-auth-settings/pages/subscriptions SubscriptionsPage.tsx

93.15% Statements 68/73
87.25% Branches 89/102
66.67% Functions 6/9
94.37% Lines 67/71

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              1x 1x   1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x           1x 1x 1x   1x                             1x                                           1x 15x 15x 15x 15x 15x 15x   15x   75x   75x   15x 15x   15x 15x   15x 15x   15x 15x   15x 15x                 75x   15x             15x   15x                 15x         15x   15x   15x 15x                 15x   2x         2x           13x             65x 65x   65x                         13x 13x 13x 13x 13x 13x 13x   13x   13x                   13x                           13x                                           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, { useEffect, useState } from 'react'
import cx from 'classnames'
 
import moment from 'moment'
import { useParams, useHistory } from 'react-router-dom'
import { Card, Container, Icon, IconName, Layout, Heading, PageError } from '@wings-software/uicore'
import { Color } from '@harness/design-system'
import { useQueryParams } from '@common/hooks'
import { Page } from '@common/exports'
import routes from '@common/RouteDefinitions'
import type { AccountPathProps, Module } from '@common/interfaces/RouteInterfaces'
import { Editions } from '@common/constants/SubscriptionTypes'
import { ContainerSpinner } from '@common/components/ContainerSpinner/ContainerSpinner'
import { useStrings } from 'framework/strings'
import { ModuleName } from 'framework/types/ModuleName'
import {
  useGetAccountNG,
  useGetModuleLicensesByAccountAndModuleType,
  GetModuleLicensesByAccountAndModuleTypeQueryParams
} from 'services/cd-ng'
 
import { useLicenseStore, handleUpdateLicenseStore, isCDCommunity } from 'framework/LicenseStore/LicenseStoreContext'
import { useFeatureFlags } from '@common/hooks/useFeatureFlag'
import SubscriptionTab from './SubscriptionTab'
 
import css from './SubscriptionsPage.module.scss'
 
export interface TrialInformation {
  days: number
  expiryDate: string
  isExpired: boolean
  expiredDays: number
  edition: Editions
  isFreeOrCommunity: boolean
}
interface ModuleSelectCard {
  icon: IconName
  module: ModuleName
}
 
const MODULE_SELECT_CARDS: ModuleSelectCard[] = [
  {
    icon: 'cd-with-dark-text',
    module: ModuleName.CD
  },
  {
    icon: 'ci-with-dark-text',
    module: ModuleName.CI
  },
  {
    icon: 'ff-with-dark-text',
    module: ModuleName.CF
  },
  {
    icon: 'ccm-with-dark-text',
    module: ModuleName.CE
  },
  {
    icon: 'srm-with-dark-text',
    module: ModuleName.CV
  }
]
const SubscriptionsPage: React.FC = () => {
  const { getString } = useStrings()
  const { accountId } = useParams<AccountPathProps>()
  const { moduleCard } = useQueryParams<{ moduleCard?: ModuleName }>()
  const { CDNG_ENABLED, CVNG_ENABLED, CING_ENABLED, CENG_ENABLED, CFNG_ENABLED } = useFeatureFlags()
  const { licenseInformation, updateLicenseStore } = useLicenseStore()
  const history = useHistory()
 
  const ACTIVE_MODULE_SELECT_CARDS = MODULE_SELECT_CARDS.reduce(
    (accumulator: ModuleSelectCard[], card: ModuleSelectCard) => {
      const { module } = card
 
      switch (module) {
        case ModuleName.CD:
          CDNG_ENABLED && accumulator.push(card)
          return accumulator
        case ModuleName.CV:
          CVNG_ENABLED && accumulator.push(card)
          return accumulator
        case ModuleName.CI:
          CING_ENABLED && accumulator.push(card)
          return accumulator
        case ModuleName.CE:
          CENG_ENABLED && accumulator.push(card)
          return accumulator
        case ModuleName.CF:
          CFNG_ENABLED && accumulator.push(card)
          return accumulator
        default:
          return accumulator
      }
    },
    []
  )
 
  const initialModule =
    ACTIVE_MODULE_SELECT_CARDS.find(card => card.module === moduleCard?.toUpperCase()) || ACTIVE_MODULE_SELECT_CARDS[0]
 
  const [selectedModuleCard, setSelectedModuleCard] = useState<ModuleSelectCard>(initialModule)
 
  const {
    data: accountData,
    error: accountError,
    loading: isGetAccountLoading,
    refetch: refetchGetAccount
  } = useGetAccountNG({ accountIdentifier: accountId, queryParams: { accountIdentifier: accountId } })
 
  const getModuleLicenseQueryParams: GetModuleLicensesByAccountAndModuleTypeQueryParams = {
    moduleType: selectedModuleCard.module as GetModuleLicensesByAccountAndModuleTypeQueryParams['moduleType']
  }
 
  const {
    data: licenseData,
    error: licenseError,
    loading: isGetLicenseLoading,
    refetch: refetchGetLicense
  } = useGetModuleLicensesByAccountAndModuleType({
    queryParams: getModuleLicenseQueryParams,
    accountIdentifier: accountId
  })
 
  const hasLicense = licenseData?.data && licenseData.data.length > 0
 
  const latestModuleLicense = hasLicense ? licenseData?.data?.[licenseData.data.length - 1] : undefined
 
  useEffect(() => {
    handleUpdateLicenseStore(
      { ...licenseInformation },
      updateLicenseStore,
      selectedModuleCard.module.toString() as Module,
      latestModuleLicense
    )
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [licenseData])
 
  if (accountError || licenseError) {
    const message =
      (accountError?.data as Error)?.message ||
      accountError?.message ||
      (licenseError?.data as Error)?.message ||
      licenseError?.message
 
    return (
      <PageError message={message} onClick={accountError ? () => refetchGetAccount() : () => refetchGetLicense()} />
    )
  }
 
  function getModuleSelectElements(): React.ReactElement[] {
    return ACTIVE_MODULE_SELECT_CARDS.map(cardData => {
      function handleCardClick(): void {
        setSelectedModuleCard(cardData)
        // reset default tab
        history.push(routes.toSubscriptions({ accountId, moduleCard: cardData.module.toLowerCase() as Module }))
      }
 
      const isSelected = cardData === selectedModuleCard
      const moduleClassName = isSelected && css[cardData.module.toLowerCase() as keyof typeof css]
 
      return (
        <Card
          className={cx(css.moduleSelectCard, moduleClassName)}
          key={cardData.icon}
          selected={isSelected}
          onClick={handleCardClick}
        >
          <Icon className={css.moduleIcons} name={cardData.icon} />
        </Card>
      )
    })
  }
 
  const expiryTime = latestModuleLicense?.expiryTime
  const time = moment(expiryTime)
  const days = Math.round(time.diff(moment.now(), 'days', true))
  const expiryDate = time.format('DD MMM YYYY')
  const isExpired = expiryTime !== -1 && days < 0
  const expiredDays = Math.abs(days)
  const edition = latestModuleLicense?.edition as Editions
 
  const isFreeOrCommunity = edition === Editions.FREE || isCDCommunity(licenseInformation)
 
  const trialInformation: TrialInformation = {
    days,
    expiryDate,
    isExpired,
    expiredDays,
    edition,
    isFreeOrCommunity: isFreeOrCommunity
  }
 
  const innerContent =
    isGetAccountLoading || isGetLicenseLoading ? (
      <Container>
        <ContainerSpinner />
      </Container>
    ) : (
      <SubscriptionTab
        accountName={accountData?.data?.name}
        trialInfo={trialInformation}
        hasLicense={hasLicense}
        selectedModule={selectedModuleCard.module}
        licenseData={latestModuleLicense}
        refetchGetLicense={refetchGetLicense}
      />
    )
  return (
    <>
      <Page.Header title={getString('common.subscriptions.title')} />
      <Layout.Vertical
        padding={{ left: 'xxxlarge', right: 'xxxlarge', top: 'xlarge', bottom: 'xlarge' }}
        flex={{ align: 'center-center' }}
      >
        <Heading color={Color.BLACK} padding={{ bottom: 'large' }}>
          {isCDCommunity(licenseInformation) ? null : getString('common.plans.title')}
        </Heading>
        <Layout.Horizontal
          className={css.moduleSelectCards}
          flex={{ alignItems: 'center', justifyContent: 'flex-start' }}
        >
          {isCDCommunity(licenseInformation) ? null : getModuleSelectElements()}
        </Layout.Horizontal>
        {innerContent}
      </Layout.Vertical>
    </>
  )
}
 
export default SubscriptionsPage