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

53.45% Statements 31/58
27.59% Branches 8/29
55.56% Functions 5/9
52.73% Lines 29/55

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              2x 2x 2x 2x 2x   2x 2x 2x 2x 2x                                                                   2x 6x 3x                               2x 7x       7x 7x 7x           7x 7x   7x 3x 3x   7x 3x 3x                     3x     7x                                                                       2x  
/*
 * 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, useState } from 'react'
import { Text, ModalErrorHandler, ModalErrorHandlerBinding, Page, TableV2 } from '@wings-software/uicore'
import moment from 'moment'
import { Color } from '@harness/design-system'
import { useParams } from 'react-router-dom'
import type { CellProps } from 'react-table'
import { useStrings } from 'framework/strings'
import { Service, SessionReportRow, useGatewaySessionReport } from 'services/lw'
import useRBACError from '@rbac/utils/useRBACError/useRBACError'
import { getTimestamp } from './Utils'
import css from './COGatewayList.module.scss'
 
interface COGatewayUsageTimeProps {
  service: Service | undefined
}
function convertToDuration(t: number): string {
  const durationMap = []
  const cd = 24 * 60 * 60 * 1000,
    ch = 60 * 60 * 1000
  let d = Math.floor(t / cd),
    h = Math.floor((t - d * cd) / ch),
    m = Math.round((t - d * cd - h * ch) / 60000)
  const pad = function (n: number) {
    return n < 10 ? '0' + n : n
  }
  if (m === 60) {
    h++
    m = 0
  }
  if (h === 24) {
    d++
    h = 0
  }
  if (d > 0) {
    durationMap.push(`${d} d`)
  }
  if (h > 0) {
    durationMap.push(`${pad(h)} h`)
  }
  if (m > 0) {
    durationMap.push(`${pad(m)} m`)
  }
  return durationMap.join(' ')
}
const DATE_FORMAT = 'YYYY-MM-DDTHH:mm:ssZ'
const today = () => moment()
const startOfDay = (time: moment.Moment) => time.startOf('day').toDate()
function TableCell(tableProps: CellProps<SessionReportRow>): JSX.Element {
  return (
    <Text lineClamp={3} color={Color.BLACK}>
      {getTimestamp(tableProps.value, 'DD-MM-YYYY HH:mm:ss')}
    </Text>
  )
}
function DurationCell(tableProps: CellProps<SessionReportRow>): JSX.Element {
  const milliseconds = tableProps.value * 60 * 60 * 1000
  return (
    <Text lineClamp={3} color={Color.BLACK}>
      {convertToDuration(milliseconds)}
    </Text>
  )
}
const COGatewayUsageTime: React.FC<COGatewayUsageTimeProps> = props => {
  const { accountId } = useParams<{
    orgIdentifier: string
    accountId: string
  }>()
  const { getRBACErrorMessage } = useRBACError()
  const { getString } = useStrings()
  const { mutate: getSessionReport } = useGatewaySessionReport({
    account_id: accountId,
    queryParams: {
      accountIdentifier: accountId
    }
  })
  const [sessionReportRows, setSessionReportRows] = useState<SessionReportRow[]>([])
  const [modalErrorHandler, setModalErrorHandler] = useState<ModalErrorHandlerBinding | undefined>()
 
  useEffect(() => {
    Iif (!props.service) return
    loadSessionReport()
  }, [props.service])
  const loadSessionReport = async (): Promise<void> => {
    try {
      const result = await getSessionReport({
        from: moment(startOfDay(today().subtract(7, 'days'))).format(DATE_FORMAT),
        to: today().format(DATE_FORMAT),
        report_name: 'GATEWAY-SESSION-WISE', // eslint-disable-line
        service_ids: [props.service?.id as number], // eslint-disable-line
        timezone: Intl.DateTimeFormat().resolvedOptions().timeZone
      })
      if (result && result.response && result.response.rows) {
        setSessionReportRows(result.response.rows)
      }
    } catch (e) {
      modalErrorHandler?.showDanger(getRBACErrorMessage(e))
    }
  }
  return (
    <Page.Body className={css.pageContainer}>
      <ModalErrorHandler bind={setModalErrorHandler} />
      {sessionReportRows.length ? (
        <TableV2<SessionReportRow>
          data={sessionReportRows}
          columns={[
            {
              accessor: 'start',
              Header: 'Started At',
              width: '35%',
              Cell: TableCell
            },
            {
              accessor: 'end',
              Header: 'Ended At',
              width: '35%',
              Cell: TableCell
            },
            {
              accessor: 'hours',
              Header: 'Duration',
              width: '30%',
              Cell: DurationCell
            }
          ]}
        />
      ) : (
        <Text style={{ alignSelf: 'center', fontSize: 'var(--font-size-medium)', padding: 'var(--spacing-large)' }}>
          {getString('ce.co.noData')}
        </Text>
      )}
    </Page.Body>
  )
}
 
export default COGatewayUsageTime