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

82.05% Statements 32/39
70% Branches 42/60
33.33% Functions 3/9
82.05% Lines 32/39

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              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                                                                   4x                                                                                                                                                                                               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 from 'react'
import {
  Formik,
  FormikForm,
  Container,
  FormInput,
  Layout,
  FlexExpander,
  Button,
  Text,
  PageSpinner,
  useToaster
} from '@wings-software/uicore'
import { Menu, MenuItem, Popover, Position } from '@blueprintjs/core'
import { FontVariation } from '@harness/design-system'
import { useParams, useHistory } from 'react-router-dom'
import * as Yup from 'yup'
import { useUpdatePerspective, CEView } from 'services/ce'
import {
  QlceViewRuleInput,
  QlceViewFieldInputInput,
  ViewChartType,
  ViewTimeRangeType,
  QlceViewTimeGroupType
} from 'services/ce/services'
import { useStrings } from 'framework/strings'
import type { ViewIdCondition } from 'services/ce/'
import { DEFAULT_GROUP_BY, perspectiveDateLabelToDisplayText } from '@ce/utils/perspectiveUtils'
import { useTelemetry } from '@common/hooks/useTelemetry'
import { USER_JOURNEY_EVENTS } from '@ce/TrackingEventsConstants'
import PerspectiveFilters from '../PerspectiveFilters'
import PerspectiveBuilderPreview from '../PerspectiveBuilderPreview/PerspectiveBuilderPreview'
// import ProTipIcon from './images/pro-tip.svg'
import css from './PerspectiveBuilder.module.scss'
 
export const CREATE_CALL_OBJECT = {
  viewVersion: 'v1',
  viewTimeRange: {
    viewTimeRangeType: ViewTimeRangeType.Last_7
  },
  viewType: 'CUSTOMER',
  viewVisualization: {
    granularity: QlceViewTimeGroupType.Day
  }
}
 
export interface PerspectiveFormValues {
  name: string
  viewRules?: QlceViewRuleInput[]
  viewVisualization: {
    groupBy: QlceViewFieldInputInput
    chartType: ViewChartType
  }
}
 
const PerspectiveBuilder: React.FC<{ perspectiveData?: CEView; onNext: (resource: CEView) => void }> = props => {
  const { getString } = useStrings()
  const { perspectiveId, accountId } = useParams<{ perspectiveId: string; accountId: string }>()
  const history = useHistory()
  const { showError } = useToaster()
  const { trackEvent } = useTelemetry()
 
  const { perspectiveData } = props
 
  const { mutate: createView, loading } = useUpdatePerspective({
    queryParams: {
      accountIdentifier: accountId
    }
  })
 
  /* istanbul ignore next */
  const makeCreateCall: (value: CEView) => void = async values => {
    const apiObject = {
      ...CREATE_CALL_OBJECT,
      ...values,
      viewState: 'DRAFT',
      viewType: 'CUSTOMER',
      uuid: perspectiveId
    }
 
    if (apiObject.viewRules) {
      apiObject.viewRules.forEach((item, index) => {
        if (item?.viewConditions && item.viewConditions.length === 0 && apiObject.viewRules) {
          delete apiObject.viewRules[index]
        } else if (item.viewConditions) {
          item.viewConditions.forEach(x => {
            const viewFieldObj = x as ViewIdCondition
            if (viewFieldObj.viewField?.identifierName) {
              delete viewFieldObj.viewField.identifierName
            }
          })
        }
      })
      apiObject.viewRules = apiObject.viewRules.filter(x => x !== null)
    } else {
      apiObject['viewRules'] = []
    }
 
    try {
      const { data } = await createView(apiObject as CEView)
      if (data) {
        props.onNext(data)
      }
    } catch (err: any) {
      const errMessage = err.data.message
      showError(errMessage)
    }
  }
 
  const goBack: () => void = () => {
    history.goBack()
  }
 
  const dateLabelToDisplayText = perspectiveDateLabelToDisplayText(getString)
 
  const ViewTimeRange = [
    {
      value: ViewTimeRangeType.Last_7,
      label: dateLabelToDisplayText[ViewTimeRangeType.Last_7]
    },
    {
      value: ViewTimeRangeType.Last_30,
      label: dateLabelToDisplayText[ViewTimeRangeType.Last_30]
    },
    {
      value: ViewTimeRangeType.LastMonth,
      label: dateLabelToDisplayText[ViewTimeRangeType.LastMonth]
    },
    {
      value: ViewTimeRangeType.CurrentMonth,
      label: dateLabelToDisplayText[ViewTimeRangeType.CurrentMonth]
    }
  ]
 
  const validationSchema = Yup.object().shape({
    name: Yup.string()
      .trim()
      .required(getString('ce.perspectives.createPerspective.validationErrors.nameError'))
      .min(1, getString('ce.perspectives.createPerspective.validationErrors.nameLengthError'))
      .max(32, getString('ce.perspectives.createPerspective.validationErrors.nameLengthError')),
    viewRules: Yup.array().of(
      Yup.object().shape({
        viewConditions: Yup.array().of(
          Yup.object().shape({
            viewOperator: Yup.string(),
            viewField: Yup.object().shape({
              fieldId: Yup.string().required(),
              fieldName: Yup.string(),
              identifier: Yup.string().required(),
              identifierName: Yup.string().nullable()
            })
          })
        )
      })
    )
  })
 
  return (
    <Container className={css.mainContainer}>
      {loading && <PageSpinner />}
      <Formik<CEView>
        formName="createPerspective"
        /* istanbul ignore next */
        initialValues={{
          name: perspectiveData?.name,
          viewVisualization: {
            groupBy: perspectiveData?.viewVisualization?.groupBy || DEFAULT_GROUP_BY,
            chartType: perspectiveData?.viewVisualization?.chartType || ViewChartType.StackedLineChart
          },
          viewTimeRange: {
            viewTimeRangeType: perspectiveData?.viewTimeRange?.viewTimeRangeType || ViewTimeRangeType.Last_7
          },
          viewRules: perspectiveData?.viewRules || []
        }}
        enableReinitialize={true}
        onSubmit={() => {
          Promise.resolve()
        }}
        validationSchema={validationSchema}
        render={formikProps => {
          return (
            <FormikForm className={css.formContainer}>
              <Container className={css.innerContainer}>
                <Layout.Vertical
                  spacing="medium"
                  height="100%"
                  className={css.builderContainer}
                  padding={{ left: 'large', right: 'xxlarge', bottom: 'xxlarge', top: 'xxlarge' }}
                >
                  <Text font={{ variation: FontVariation.H4 }} margin={{ bottom: 'large' }}>
                    {getString('ce.perspectives.createPerspective.title')}
                  </Text>
                  <Layout.Horizontal>
                    <FormInput.Text
                      name="name"
                      label={getString('ce.perspectives.createPerspective.nameLabel')}
                      placeholder={getString('ce.perspectives.createPerspective.name')}
                      tooltipProps={{
                        dataTooltipId: 'perspectiveNameInput'
                      }}
                      className={css.perspectiveNameInput}
                    />
                    <FlexExpander />
                    <Popover
                      position={Position.BOTTOM_LEFT}
                      modifiers={{
                        arrow: { enabled: false },
                        flip: { enabled: true },
                        keepTogether: { enabled: true },
                        preventOverflow: { enabled: true }
                      }}
                      content={
                        <Menu>
                          {ViewTimeRange.map(timeRange => (
                            <MenuItem
                              onClick={() => {
                                formikProps.setFieldValue('viewTimeRange.viewTimeRangeType', timeRange.value)
                              }}
                              text={timeRange.label}
                              key={timeRange.value}
                            />
                          ))}
                        </Menu>
                      }
                    >
                      <Button
                        minimal
                        text={
                          formikProps.values.viewTimeRange?.viewTimeRangeType
                            ? dateLabelToDisplayText[formikProps.values.viewTimeRange?.viewTimeRangeType]
                            : 'Select Time Range'
                        }
                        rightIcon="calendar"
                      />
                    </Popover>
                  </Layout.Horizontal>
 
                  <div>
                    <PerspectiveFilters formikProps={formikProps} />
                  </div>
                  <FlexExpander />
 
                  {/*
                    this block is commented out, we will uncomment it once custom fields are Done
 
                  {<Container padding="medium" background="grey100" className={css.proTipContainer}>
                    <Layout.Horizontal spacing="medium">
                      <img src={ProTipIcon} />
                      <Container>
                        <Text font="small">{getString('ce.perspectives.createPerspective.proTipText')}</Text>
                        <Layout.Horizontal
                          spacing="xlarge"
                          margin={{
                            top: 'medium'
                          }}
                        >
                          <Text font="small" color="primary7" className={css.linkText}>
                            {getString('ce.perspectives.createPerspective.createCustomField')}
                          </Text>
                          <Text font="small" color="primary7" className={css.linkText}>
                            {getString('ce.perspectives.createPerspective.learnMoreCustomField')}
                          </Text>
                        </Layout.Horizontal>
                      </Container>
                    </Layout.Horizontal>
                  </Container>} */}
                  <Layout.Horizontal
                    padding={{
                      top: 'medium'
                    }}
                    spacing="large"
                  >
                    <Button
                      icon="chevron-left"
                      text={getString('ce.perspectives.createPerspective.prevButton')}
                      onClick={goBack}
                    />
                    <Button
                      icon="chevron-right"
                      intent="primary"
                      disabled={!!Object.keys(formikProps.errors).length}
                      text={getString('ce.perspectives.createPerspective.nextButton')}
                      onClick={() => {
                        trackEvent(USER_JOURNEY_EVENTS.PERSPECTIVE_STEP1_NEXT, {})
                        makeCreateCall(formikProps.values)
                      }}
                    />
                  </Layout.Horizontal>
                </Layout.Vertical>
                <PerspectiveBuilderPreview
                  setGroupBy={(groupBy: QlceViewFieldInputInput) => {
                    formikProps.setFieldValue('viewVisualization.groupBy', groupBy)
                  }}
                  showBusinessMappingButton={true}
                  formValues={formikProps.values}
                  groupBy={formikProps.values.viewVisualization?.groupBy as any}
                  chartType={formikProps.values.viewVisualization?.chartType as any}
                  setChartType={(type: ViewChartType) => {
                    formikProps.setFieldValue('viewVisualization.chartType', type)
                  }}
                />
              </Container>
            </FormikForm>
          )
        }}
      />
    </Container>
  )
}
 
export default PerspectiveBuilder