All files / modules/10-common/layouts TrialLicenseBanner.tsx

77.11% Statements 64/83
55.91% Branches 52/93
33.33% Functions 3/9
77.78% Lines 63/81

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              13x 13x 13x 13x 13x 13x 13x 13x   13x   13x 13x 13x 13x 13x               13x   13x         13x 13x 13x 13x   13x   13x 11x 11x 11x 11x 11x 11x 11x                   11x           11x 11x             11x 11x 11x       11x 11x 11x 11x   11x             11x   11x             11x   11x           11x   11x                                                     11x           11x                                         11x                           11x   11x                                     11x   11x 3x 1x                     2x 1x   1x               11x                   11x 8x     3x       3x                                  
/*
 * 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 } from 'react'
import moment from 'moment'
import cx from 'classnames'
import { capitalize, pick } from 'lodash-es'
import { useParams } from 'react-router-dom'
import { Text, Layout, Button, PageSpinner, ButtonVariation, ButtonSize } from '@wings-software/uicore'
import { Color, FontVariation } from '@harness/design-system'
import { useStrings } from 'framework/strings'
import type { StringsMap } from 'stringTypes'
import { useToaster } from '@common/components'
import type { Module } from 'framework/types/ModuleName'
import { useModuleInfo } from '@common/hooks/useModuleInfo'
import { useLocalStorage } from '@common/hooks/useLocalStorage'
import { useContactSalesMktoModal } from '@common/modals/ContactSales/useContactSalesMktoModal'
import { useAppStore } from 'framework/AppStore/AppStoreContext'
import {
  useExtendTrialLicense,
  StartTrialDTO,
  useSaveFeedback,
  FeedbackFormDTO,
  useGetLicensesAndSummary,
  GetLicensesAndSummaryQueryParams
} from 'services/cd-ng'
import { useLicenseStore, handleUpdateLicenseStore } from 'framework/LicenseStore/LicenseStoreContext'
import type { AccountPathProps } from '@common/interfaces/RouteInterfaces'
import {
  useExtendTrialOrFeedbackModal,
  FORM_TYPE,
  FeedbackFormValues
} from '@common/modals/ExtendTrial/useExtendTrialOrFeedbackModal'
import { Editions } from '@common/constants/SubscriptionTypes'
import { useTelemetry } from '@common/hooks/useTelemetry'
import { Category, LicenseActions } from '@common/constants/TrackingConstants'
import css from './layouts.module.scss'
 
export const BANNER_KEY = 'license_banner_dismissed'
 
export const TrialLicenseBanner = (): React.ReactElement => {
  const { getString } = useStrings()
  const { module } = useModuleInfo()
  const { currentUserInfo } = useAppStore()
  const { accountId } = useParams<AccountPathProps>()
  const { licenseInformation, updateLicenseStore } = useLicenseStore()
  const { showError, showSuccess } = useToaster()
  const [isBannerDismissed, setIsBannerDismissed] = useLocalStorage<Partial<Record<Module, boolean>>>(
    BANNER_KEY,
    {},
    window.sessionStorage
  )
 
  const {
    data,
    refetch,
    loading: gettingLicense
  } = useGetLicensesAndSummary({
    queryParams: { moduleType: module?.toUpperCase() as GetLicensesAndSummaryQueryParams['moduleType'] },
    accountIdentifier: accountId,
    lazy: module === undefined || isBannerDismissed[module]
  })
 
  const { maxExpiryTime, edition, licenseType } = data?.data || {}
  const updatedLicenseInfo = data?.data &&
    module && {
      ...licenseInformation?.[module.toUpperCase()],
      ...pick(data?.data, ['licenseType', 'edition']),
      expiryTime: maxExpiryTime
    }
 
  useEffect(() => {
    Eif (module) {
      handleUpdateLicenseStore({ ...licenseInformation }, updateLicenseStore, module, updatedLicenseInfo)
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [data])
  const days = Math.round(moment(maxExpiryTime).diff(moment.now(), 'days', true))
  const isExpired = days < 0
  const expiredDays = Math.abs(days)
  const expiredClassName = isExpired ? css.expired : css.notExpired
 
  const moduleDescriptionMap: Record<string, keyof StringsMap> = {
    cd: 'cd.continuous',
    ce: 'ce.continuous',
    cf: 'cf.continuous',
    ci: 'ci.continuous',
    cv: 'cv.continuous'
  }
  const moduleDescription = (module && getString(moduleDescriptionMap[module])) || ''
 
  const descriptionModuleMap: Record<string, keyof StringsMap> = {
    cd: 'common.module.cd',
    ce: 'common.module.ce',
    cf: 'common.module.cf',
    ci: 'common.module.ci',
    cv: 'common.module.cv'
  }
  const descriptionModule = module && getString(descriptionModuleMap[module])
 
  const { mutate: extendTrial, loading: extendingTrial } = useExtendTrialLicense({
    queryParams: {
      accountIdentifier: accountId
    }
  })
 
  const { openMarketoContactSales, loading: loadingContactSales } = useContactSalesMktoModal({})
 
  const alertMsg = isExpired ? (
    <Text
      color={Color.WHITE}
      font={{ variation: FontVariation.FORM_MESSAGE_WARNING }}
      icon="issue"
      iconProps={{ padding: { right: 'small' }, className: css.issueIcon }}
    >
      {getString('common.banners.trial.expired.description', {
        expiredDays,
        moduleDescription
      })}
    </Text>
  ) : (
    <Text
      color={Color.PRIMARY_10}
      font={{ variation: FontVariation.FORM_MESSAGE_WARNING }}
      icon="info-message"
      iconProps={{ padding: { right: 'small' }, size: 25, className: css.infoIcon }}
    >
      {getString('common.banners.trial.description', {
        module: descriptionModule,
        days,
        moduleDescription,
        edition: capitalize(edition)
      })}
    </Text>
  )
  const { mutate: saveFeedback, loading: sendingFeedback } = useSaveFeedback({
    queryParams: {
      accountIdentifier: accountId
    }
  })
 
  const handleFeedbackSubmit = async (values: FeedbackFormValues): Promise<void> => {
    try {
      await saveFeedback({
        accountId,
        moduleType: module as FeedbackFormDTO['moduleType'],
        email: currentUserInfo.email,
        score: Number(values.experience),
        suggestion: values.suggestion
      }).then(() => {
        if (isExpired) {
          refetch?.()
        } else {
          closeExtendTrialOrFeedbackModal()
        }
      })
      showSuccess(getString('common.banners.trial.feedbackSuccess'))
    } catch (error) {
      showError(error.data?.message || error.message)
    }
  }
 
  const { openExtendTrialOrFeedbackModal, closeExtendTrialOrFeedbackModal } = useExtendTrialOrFeedbackModal({
    onSubmit: handleFeedbackSubmit,
    onCloseModal: () => {
      if (isExpired) {
        refetch?.()
      }
    },
    module: module || '',
    expiryDateStr: moment(maxExpiryTime).format('MMMM D YYYY'),
    formType: isExpired ? FORM_TYPE.EXTEND_TRIAL : FORM_TYPE.FEEDBACK,
    moduleDescription,
    loading: sendingFeedback
  })
 
  const { trackEvent } = useTelemetry()
 
  const handleExtendTrial = async (): Promise<void> => {
    try {
      trackEvent(LicenseActions.ExtendTrial, {
        category: Category.LICENSE
      })
 
      const extendedData = await extendTrial({
        moduleType: module as StartTrialDTO['moduleType'],
        edition: Editions.ENTERPRISE
      })
      if (module) {
        handleUpdateLicenseStore({ ...licenseInformation }, updateLicenseStore, module, extendedData?.data)
      }
      openExtendTrialOrFeedbackModal()
    } catch (error) {
      showError(error.data?.message || error.message)
    }
  }
 
  const loading = extendingTrial || loadingContactSales || sendingFeedback || gettingLicense
 
  const getExtendOrFeedBackBtn = (): React.ReactElement => {
    if (!isExpired) {
      return (
        <Text
          onClick={openExtendTrialOrFeedbackModal}
          color={Color.PRIMARY_7}
          className={css.link}
          flex={{ alignItems: 'center' }}
        >
          {getString('common.banners.trial.provideFeedback')}
        </Text>
      )
    }
    if (expiredDays > 14) {
      return <></>
    }
    return (
      <Text onClick={handleExtendTrial} color={Color.WHITE} className={css.link} flex={{ alignItems: 'center' }}>
        {getString('common.banners.trial.expired.extendTrial')}
      </Text>
    )
  }
 
  const contactSalesLink = (
    <Layout.Horizontal padding={{ left: 'large' }} flex={{ alignItems: 'center' }}>
      <Text onClick={openMarketoContactSales} color={isExpired ? Color.WHITE : Color.PRIMARY_6} className={css.link}>
        {getString('common.banners.trial.contactSales')}
      </Text>
      <Text padding={{ left: 'small', right: 'small' }} color={isExpired ? Color.WHITE : Color.PRIMARY_6}>
        {'or'}
      </Text>
    </Layout.Horizontal>
  )
 
  if (module === undefined || isBannerDismissed[module] || licenseType !== 'TRIAL') {
    return <></>
  }
 
  Iif (loading) {
    return <PageSpinner />
  }
 
  return (
    <div className={cx(css.trialLicenseBanner, expiredClassName)}>
      <Layout.Horizontal width="95%" padding={{ left: 'large' }}>
        {alertMsg}
        {contactSalesLink}
        {getExtendOrFeedBackBtn()}
      </Layout.Horizontal>
      <Button
        variation={ButtonVariation.ICON}
        size={ButtonSize.LARGE}
        icon="cross"
        data-testid="trial-banner-dismiss"
        onClick={() => setIsBannerDismissed(prev => (module ? { ...prev, [module]: true } : prev))}
      />
    </div>
  )
}