All files / framework/LicenseStore LicenseStoreContext.tsx

85.27% Statements 110/129
65.78% Branches 123/187
72% Functions 18/25
85.83% Lines 103/120

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              1070x 1070x 1070x 1070x   1070x 1070x 1070x 1070x   1070x           1070x   1070x 1070x 1070x 1070x 1070x 1070x 1070x                                                 1070x             1070x                   1070x 26858x     1070x 6x 5x 5x 5x       5x   5x       5x   5x                             5x                           5x           5x                     5x 2x                           5x   5x               5x 2x                                                                                             2x 2x         5x   5x   9x 6x     3x 3x   3x       3x         5x 2x 2x 2x 2x 2x 2x       2x 2x 2x 2x   2x 2x 2x 2x   2x                 2x 2x         5x                 1x 1x 1x 1x   1x                                           5x           5x 2x   3x     5x                                 1070x           65x 23x                     42x 11x 11x     31x 6x 6x     25x 6x 6x     19x 19x 19x         42x 42x       1070x     8200x     1070x       37x     1070x       16x     1070x       16x    
/*
 * 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 moment from 'moment'
import { useParams } from 'react-router-dom'
import { isEqual } from 'lodash-es'
 
import isEmpty from 'lodash/isEmpty'
import { PageSpinner } from '@harness/uicore'
import { useDeepCompareEffect } from '@common/hooks'
import { useAppStore } from 'framework/AppStore/AppStoreContext'
 
import {
  getLastModifiedTimeForAllModuleTypesPromise,
  ModuleLicenseDTO,
  useGetAccountLicenses,
  useGetLastModifiedTimeForAllModuleTypes
} from 'services/cd-ng'
import { ModuleName } from 'framework/types/ModuleName'
import type { Module } from '@common/interfaces/RouteInterfaces'
import { useFeatureFlags } from '@common/hooks/useFeatureFlag'
import GenericErrorPage, { GENERIC_ERROR_CODES } from '@common/pages/GenericError/GenericErrorPage'
import { Editions } from '@common/constants/SubscriptionTypes'
import { useStrings } from 'framework/strings'
import { FeatureIdentifier } from 'framework/featureStore/FeatureIdentifier'
import { useFeaturesContext } from 'framework/featureStore/FeaturesContext'
import { VersionMap, LICENSE_STATE_VALUES } from './licenseStoreUtil'
 
// Only keep GA modules for now
export interface LicenseStoreContextProps {
  readonly licenseInformation: { [key: string]: ModuleLicenseDTO } | Record<string, undefined>
  readonly versionMap: VersionMap
  readonly CI_LICENSE_STATE: LICENSE_STATE_VALUES
  readonly FF_LICENSE_STATE: LICENSE_STATE_VALUES
  readonly CCM_LICENSE_STATE: LICENSE_STATE_VALUES
  readonly CD_LICENSE_STATE: LICENSE_STATE_VALUES
 
  updateLicenseStore(data: Partial<Pick<LicenseStoreContextProps, 'licenseInformation'>>): void
}
 
export interface LicenseRedirectProps {
  licenseStateName: keyof Omit<LicenseStoreContextProps, 'licenseInformation' | 'updateLicenseStore' | 'versionMap'>
  startTrialRedirect: () => React.ReactElement
  expiredTrialRedirect: () => React.ReactElement
}
 
type licenseStateNames = keyof Omit<
  LicenseStoreContextProps,
  'licenseInformation' | 'updateLicenseStore' | 'versionMap'
>
 
export const LICENSE_STATE_NAMES: { [T in licenseStateNames]: T } = {
  CI_LICENSE_STATE: 'CI_LICENSE_STATE',
  FF_LICENSE_STATE: 'FF_LICENSE_STATE',
  CCM_LICENSE_STATE: 'CCM_LICENSE_STATE',
  CD_LICENSE_STATE: 'CD_LICENSE_STATE'
}
 
export const LicenseStoreContext = React.createContext<LicenseStoreContextProps>({
  licenseInformation: {},
  versionMap: {},
  CI_LICENSE_STATE: LICENSE_STATE_VALUES.NOT_STARTED,
  FF_LICENSE_STATE: LICENSE_STATE_VALUES.NOT_STARTED,
  CCM_LICENSE_STATE: LICENSE_STATE_VALUES.NOT_STARTED,
  CD_LICENSE_STATE: LICENSE_STATE_VALUES.NOT_STARTED,
  updateLicenseStore: () => void 0
})
 
export function useLicenseStore(): LicenseStoreContextProps {
  return React.useContext(LicenseStoreContext)
}
 
export function LicenseStoreProvider(props: React.PropsWithChildren<unknown>): React.ReactElement {
  const { currentUserInfo } = useAppStore()
  const { NG_LICENSES_ENABLED } = useFeatureFlags()
  const { getString } = useStrings()
  const { accountId } = useParams<{
    accountId: string
  }>()
 
  const { accounts } = currentUserInfo
 
  const createdFromNG = accounts?.find(account => account.uuid === accountId)?.createdFromNG
 
  // If the user has been created from NG signup we will always enforce licensing
  // If the user is a CG user we will look at the NG_LICENSES_ENABLED feature flag to determine whether or not we should enforce licensing
  const shouldLicensesBeDisabled = __DEV__ || (!createdFromNG && !NG_LICENSES_ENABLED)
 
  const defaultLicenses = {
    CD: {
      edition: Editions.FREE
    },
    CI: {
      edition: Editions.FREE
    },
    CF: {
      edition: Editions.FREE
    },
    CE: {
      edition: Editions.FREE
    }
  }
 
  const [state, setState] = useState<Omit<LicenseStoreContextProps, 'updateLicenseStore' | 'strings'>>({
    licenseInformation: shouldLicensesBeDisabled ? defaultLicenses : {},
    versionMap: {},
    CI_LICENSE_STATE: shouldLicensesBeDisabled ? LICENSE_STATE_VALUES.ACTIVE : LICENSE_STATE_VALUES.NOT_STARTED,
    FF_LICENSE_STATE: shouldLicensesBeDisabled ? LICENSE_STATE_VALUES.ACTIVE : LICENSE_STATE_VALUES.NOT_STARTED,
    CCM_LICENSE_STATE: shouldLicensesBeDisabled ? LICENSE_STATE_VALUES.ACTIVE : LICENSE_STATE_VALUES.NOT_STARTED,
    CD_LICENSE_STATE: shouldLicensesBeDisabled ? LICENSE_STATE_VALUES.ACTIVE : LICENSE_STATE_VALUES.NOT_STARTED
  })
 
  const {
    data: accountLicensesData,
    refetch: getAccountLicenses,
    error,
    loading: getAccountLicensesLoading
  } = useGetAccountLicenses({
    queryParams: {
      accountIdentifier: accountId
    }
  })
 
  const { mutate: getVersionMap } = useGetLastModifiedTimeForAllModuleTypes({
    queryParams: {
      accountIdentifier: accountId
    },
    requestOptions: {
      headers: {
        'content-type': 'application/json'
      }
    }
  })
 
  useEffect(() => {
    getVersionMap()
      .then(response => {
        setState(prevState => ({
          ...prevState,
          versionMap: response.data || {}
        }))
      })
      .catch(_err => {
        // do nothing
      })
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])
 
  // 1000 milliseconds * 60 seconds * 1 minute
  const POLL_VERSION_INTERVAL = 1000 * 60 * 1
 
  const { requestFeatures } = useFeaturesContext()
 
  /*
   * this is to poll versionMap every minute
   * if versionMap changes, refresh license
   * and refresh feature context
   * if versionMap call fails, stop calling
   */
  useEffect(() => {
    let getVersionTimeOut = setTimeout(() => {
      pollVersionMap(state.versionMap)
    }, POLL_VERSION_INTERVAL)
 
    async function pollVersionMap(versionMap: VersionMap): Promise<void> {
      try {
        // We are using promise since mutate was rerendering the whole applications every 60 seconds
        // even if no data change in store
        const response = await getLastModifiedTimeForAllModuleTypesPromise({
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          queryParams: { accountIdentifier: accountId, routingId: accountId } as any,
          body: undefined,
          requestOptions: {
            headers: {
              'content-type': 'application/json'
            }
          }
        })
        const latestVersionMap = response.data
        if (latestVersionMap && !isEqual(latestVersionMap, versionMap)) {
          // refresh licenses
          getAccountLicenses()
 
          // refresh feature context
          requestFeatures(
            { featureName: FeatureIdentifier.BUILDS },
            {
              skipCache: true
            }
          )
 
          // refresh versionMap
          setState(prevState => ({
            ...prevState,
            versionMap: response.data || {}
          }))
        }
 
        // set next poll
        getVersionTimeOut = setTimeout(() => {
          pollVersionMap(latestVersionMap || versionMap)
        }, POLL_VERSION_INTERVAL)
      } catch (_err) {
        clearTimeout(getVersionTimeOut)
      }
    }
 
    return () => {
      clearTimeout(getVersionTimeOut)
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])
 
  const [isLoading, setIsLoading] = useState(true)
 
  const getLicenseState = React.useCallback(
    (expiryTime?: number): LICENSE_STATE_VALUES => {
      if (!expiryTime) {
        return LICENSE_STATE_VALUES.NOT_STARTED
      }
 
      const days = Math.round(moment(expiryTime).diff(moment.now(), 'days', true))
      const isExpired = days < 0
 
      Iif (shouldLicensesBeDisabled) {
        return LICENSE_STATE_VALUES.ACTIVE
      }
 
      return isExpired ? LICENSE_STATE_VALUES.EXPIRED : LICENSE_STATE_VALUES.ACTIVE
    },
    [shouldLicensesBeDisabled]
  )
 
  useDeepCompareEffect(() => {
    const allLicenses = accountLicensesData?.data?.allModuleLicenses || {}
    const licenses: { [key: string]: ModuleLicenseDTO } = {}
    Object.keys(allLicenses).forEach((key: string) => {
      const moduleLicenses = allLicenses[key]
      Eif (moduleLicenses?.length > 0) {
        licenses[key] = moduleLicenses[moduleLicenses.length - 1]
      }
    })
 
    const CIModuleLicenseData = licenses['CI']
    const FFModuleLicenseData = licenses['CF']
    const CCMModuleLicenseData = licenses['CE']
    const CDModuleLicenseData = licenses['CD']
 
    const updatedCILicenseState: LICENSE_STATE_VALUES = getLicenseState(CIModuleLicenseData?.expiryTime)
    const updatedFFLicenseState: LICENSE_STATE_VALUES = getLicenseState(FFModuleLicenseData?.expiryTime)
    const updatedCCMLicenseState: LICENSE_STATE_VALUES = getLicenseState(CCMModuleLicenseData?.expiryTime)
    const updatedCDLicenseState: LICENSE_STATE_VALUES = getLicenseState(CDModuleLicenseData?.expiryTime)
 
    setState(prevState => ({
      ...prevState,
      licenseInformation: shouldLicensesBeDisabled ? { ...defaultLicenses, ...licenses } : licenses,
      CI_LICENSE_STATE: shouldLicensesBeDisabled ? LICENSE_STATE_VALUES.ACTIVE : updatedCILicenseState,
      FF_LICENSE_STATE: shouldLicensesBeDisabled ? LICENSE_STATE_VALUES.ACTIVE : updatedFFLicenseState,
      CCM_LICENSE_STATE: shouldLicensesBeDisabled ? LICENSE_STATE_VALUES.ACTIVE : updatedCCMLicenseState,
      CD_LICENSE_STATE: shouldLicensesBeDisabled ? LICENSE_STATE_VALUES.ACTIVE : updatedCDLicenseState
    }))
 
    Eif (!getAccountLicensesLoading && !isEmpty(currentUserInfo)) {
      setIsLoading(false)
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [accountLicensesData?.data?.allModuleLicenses, currentUserInfo])
 
  const updateLicenseStore = React.useCallback(
    (
      updateData: Partial<
        Pick<
          LicenseStoreContextProps,
          'licenseInformation' | 'CI_LICENSE_STATE' | 'FF_LICENSE_STATE' | 'CCM_LICENSE_STATE' | 'CD_LICENSE_STATE'
        >
      >
    ): void => {
      const CIModuleLicenseData = updateData.licenseInformation?.['CI']
      const FFModuleLicenseData = updateData.licenseInformation?.['CF']
      const CCMModuleLicenseData = updateData.licenseInformation?.['CE']
      const CDModuleLicenseData = updateData.licenseInformation?.['CD']
 
      setState(prevState => ({
        ...prevState,
        licenseInformation: updateData.licenseInformation || prevState.licenseInformation,
        CI_LICENSE_STATE: CIModuleLicenseData?.expiryTime
          ? getLicenseState(CIModuleLicenseData.expiryTime)
          : prevState.CI_LICENSE_STATE,
        FF_LICENSE_STATE: FFModuleLicenseData?.expiryTime
          ? getLicenseState(FFModuleLicenseData.expiryTime)
          : prevState.FF_LICENSE_STATE,
        CCM_LICENSE_STATE: CCMModuleLicenseData?.expiryTime
          ? getLicenseState(CCMModuleLicenseData.expiryTime)
          : prevState.CCM_LICENSE_STATE,
        CD_LICENSE_STATE: CDModuleLicenseData?.expiryTime
          ? getLicenseState(CDModuleLicenseData.expiryTime)
          : prevState.CD_LICENSE_STATE
      }))
    },
    [getLicenseState]
  )
 
  let childComponent
 
  Iif (error) {
    if ((error.data as any)?.code === 'NG_ACCESS_DENIED') {
      childComponent = <GenericErrorPage code={GENERIC_ERROR_CODES.UNAUTHORIZED} />
    } else {
      childComponent = <GenericErrorPage message={getString('common.genericErrors.licenseCallFailed')} />
    }
  } else if (isLoading) {
    childComponent = <PageSpinner />
  } else {
    childComponent = props.children
  }
 
  return (
    <LicenseStoreContext.Provider
      value={{
        CCM_LICENSE_STATE: state.CCM_LICENSE_STATE,
        CD_LICENSE_STATE: state.CD_LICENSE_STATE,
        CI_LICENSE_STATE: state.CI_LICENSE_STATE,
        FF_LICENSE_STATE: state.FF_LICENSE_STATE,
        licenseInformation: state.licenseInformation,
        versionMap: state.versionMap,
        updateLicenseStore
      }}
    >
      {childComponent}
    </LicenseStoreContext.Provider>
  )
}
 
export function handleUpdateLicenseStore(
  newLicenseInformation: Record<string, ModuleLicenseDTO> | Record<string, undefined>,
  updateLicenseStore: (data: Partial<Pick<LicenseStoreContextProps, 'licenseInformation'>>) => void,
  module: Module,
  data?: ModuleLicenseDTO
): void {
  if (!data) {
    return
  }
  let licenseStoreData:
    | Partial<
        Pick<
          LicenseStoreContextProps,
          'licenseInformation' | 'CI_LICENSE_STATE' | 'FF_LICENSE_STATE' | 'CCM_LICENSE_STATE' | 'CD_LICENSE_STATE'
        >
      >
    | undefined
 
  if (module.toUpperCase() === ModuleName.CI) {
    newLicenseInformation[ModuleName.CI] = data
    licenseStoreData = {
      licenseInformation: newLicenseInformation
    }
  } else if (module.toUpperCase() === ModuleName.CF) {
    newLicenseInformation[ModuleName.CF] = data
    licenseStoreData = {
      licenseInformation: newLicenseInformation
    }
  } else if (module.toUpperCase() === ModuleName.CE) {
    newLicenseInformation[ModuleName.CE] = data
    licenseStoreData = {
      licenseInformation: newLicenseInformation
    }
  } else Eif (module.toUpperCase() === ModuleName.CD) {
    newLicenseInformation[ModuleName.CD] = data
    licenseStoreData = {
      licenseInformation: newLicenseInformation
    }
  }
 
  Eif (licenseStoreData) {
    updateLicenseStore(licenseStoreData)
  }
}
 
export const isCDCommunity = (
  license: { [p: string]: ModuleLicenseDTO } | undefined | Record<string, undefined>
): boolean => {
  return license?.CD?.edition === Editions.COMMUNITY
}
 
export const isFreePlan = (
  license: { [p: string]: ModuleLicenseDTO } | undefined | Record<string, undefined>,
  moduleName: ModuleName
): boolean => {
  return license?.[moduleName]?.edition === Editions.FREE
}
 
export const isEnterprisePlan = (
  license: { [p: string]: ModuleLicenseDTO } | undefined | Record<string, undefined>,
  moduleName: ModuleName
): boolean => {
  return license?.[moduleName]?.edition === Editions.ENTERPRISE
}
 
export const isTeamPlan = (
  license: { [p: string]: ModuleLicenseDTO } | undefined | Record<string, undefined>,
  moduleName: ModuleName
): boolean => {
  return license?.[moduleName]?.edition === Editions.TEAM
}