All files / modules/75-ce/common/FixedSchedule FixedScheduleForm.tsx

72.83% Statements 67/92
57.38% Branches 35/61
53.85% Functions 14/26
72.53% Lines 66/91

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 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425              8x 8x 8x 8x 8x 8x                           8x   8x 8x 8x 8x 8x               8x 8x 8x 8x 8x 8x                                     8x 34x 34x 34x 34x     8x 8x 8x 8x   8x   8x   8x 8x                                   8x 11x 11x         11x     8x 1x 1x 1x         1x                         1x       1x     8x                                   12x                   17x                                               1x                                                                           8x 17x 17x       17x       17x       17x               17x   17x                                                                                                                           8x 17x   17x                 17x                                                             1x 1x     1x 1x                                                                       1x                     1x 1x                           8x  
/*
 * 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, { useState } from 'react'
import { TimePicker } from '@blueprintjs/datetime'
import { Radio } from '@blueprintjs/core'
import { defaultTo as _defaultTo, isEmpty as _isEmpty, capitalize as _capitalize } from 'lodash-es'
import * as Yup from 'yup'
import {
  Button,
  Container,
  DateInput,
  Formik,
  FormikForm,
  FormInput,
  Heading,
  Label,
  Layout,
  Text,
  PillToggle,
  Checkbox
} from '@wings-software/uicore'
import { Color } from '@harness/design-system'
import type { FormikProps } from 'formik'
import { useParams } from 'react-router-dom'
import DaysOfWeekSelector from '@ce/common/DaysOfWeekSelector/DaysOfWeekSelector'
import { useStrings } from 'framework/strings'
import { useAppStore } from 'framework/AppStore/AppStoreContext'
import {
  getMinDate,
  getStaticSchedulePeriodString,
  getStaticSchedulePeriodTime,
  getUserTimeZone
} from '@ce/utils/momentUtils'
import type { FixedScheduleClient, ScheduleTime } from '@ce/components/COCreateGateway/models'
import type { AccountPathProps } from '@common/interfaces/RouteInterfaces'
import { useValidateStaticScheduleList } from 'services/lw'
import { DaysOfWeek } from '@ce/constants'
import { Utils } from '../Utils'
import { ScheduleDescription } from '../FixedSchedulesList/FixedSchedulesList'
import TimezoneSelector from '../TimeZoneSelector/TimeZoneSelector'
import css from './FixedScheduleForm.module.scss'
 
interface FixedScheduleFormProps {
  schedule?: FixedScheduleClient
  scheduleIndex?: number
  closeDialog: () => void
  isEdit?: boolean
  addSchedule: (schedule: FixedScheduleClient) => void
  allSchedules: FixedScheduleClient[]
}
 
interface DaysAndTimeSelectorProps {
  formikProps: FormikProps<FixedScheduleClient>
}
 
interface PeriodSelectionProps {
  formikProps: FormikProps<FixedScheduleClient>
}
 
const getTime = (timeVal: ScheduleTime | null) => {
  const date = new Date()
  date.setHours(_defaultTo(timeVal?.hour, 0))
  date.setMinutes(_defaultTo(timeVal?.min, 0))
  return date
}
 
const FixedScheduleForm: React.FC<FixedScheduleFormProps> = props => {
  const { getString } = useStrings()
  const { accountId } = useParams<AccountPathProps>()
  const { currentUserInfo } = useAppStore()
 
  const [errorString, setErrorString] = useState<string>('')
 
  const { mutate: validateSchedules } = useValidateStaticScheduleList({ account_id: accountId })
 
  const getInitialValues = () => {
    return (
      props.schedule ||
      ({
        name: '',
        type: 'uptime',
        beginsOn: null,
        endsOn: null,
        startTime: null,
        endTime: null,
        allDay: true,
        repeats: [],
        everyday: true,
        timezone: getUserTimeZone(),
        isDeleted: false
      } as FixedScheduleClient)
    )
  }
 
  const getUpdatedScheduleData = (data: FixedScheduleClient) => {
    const updatedData = { ...data }
    Iif (data.everyday && _isEmpty(data.repeats)) {
      updatedData.repeats = Object.keys(DaysOfWeek)
        .filter(val => isNaN(Number(val)))
        .map((_k, i) => i)
    }
    return updatedData
  }
 
  const handleSubmit = async (data: FixedScheduleClient): Promise<FixedScheduleClient> => {
    const updatedData = getUpdatedScheduleData(data)
    try {
      const idParams = {
        accountId,
        userId: _defaultTo(currentUserInfo.uuid, ''),
        ruleId: 0
      }
      await validateSchedules(
        {
          schedules: [
            ...props.allSchedules
              .filter((s, i) => !s.isDeleted && i !== props.scheduleIndex)
              .map(s => Utils.convertScheduleClientToSchedule(s, idParams)),
            Utils.convertScheduleClientToSchedule(updatedData, idParams)
          ]
        },
        {
          queryParams: { accountIdentifier: accountId }
        }
      )
      props.addSchedule(updatedData)
    } catch (e) {
      setErrorString(e?.data?.errors?.join('\n'))
    }
    return updatedData
  }
 
  return (
    <Layout.Vertical spacing="xlarge" className={css.fixedScheduleFormContainer}>
      <Heading color={Color.GREY_800} level={2}>
        {props.isEdit
          ? getString('ce.co.autoStoppingRule.configuration.step4.tabs.schedules.fixedSchedule')
          : getString('ce.co.autoStoppingRule.configuration.step4.tabs.schedules.newScheduleTitle')}
      </Heading>
      {!_isEmpty(errorString) && <Text className={css.errorDisplayContainer}>{errorString}</Text>}
      <Formik
        initialValues={getInitialValues()}
        enableReinitialize
        onSubmit={handleSubmit}
        formName={'newScheduleForm'}
        validationSchema={Yup.object().shape({
          name: Yup.string().max(25).required(),
          type: Yup.string().required(),
          repeats: Yup.array()
            .when('beginsOn', {
              is: val => !val,
              then: Yup.array().min(1).required()
            })
            .when('everyday', {
              is: false,
              then: Yup.array().min(1).required()
            })
        })}
      >
        {_formikProps => (
          <FormikForm>
            <Layout.Vertical spacing={'large'}>
              <FormInput.Text name="name" label={getString('name') + '*'} />
              <Container className={css.inputRow}>
                <Layout.Horizontal spacing={'large'}>
                  <Container style={{ flex: 1 }}>
                    <Label>{_capitalize(getString('ce.co.gatewayReview.type')) + '*'}</Label>
                    <PillToggle
                      selectedView={_formikProps.values.type}
                      options={[
                        {
                          label: getString(
                            'ce.co.autoStoppingRule.configuration.step4.tabs.schedules.uptime'
                          ).toUpperCase(),
                          value: getString('ce.co.autoStoppingRule.configuration.step4.tabs.schedules.uptime')
                        },
                        {
                          label: getString(
                            'ce.co.autoStoppingRule.configuration.step4.tabs.schedules.downtime'
                          ).toUpperCase(),
                          value: getString('ce.co.autoStoppingRule.configuration.step4.tabs.schedules.downtime')
                        }
                      ]}
                      onChange={val => {
                        _formikProps.setFieldValue('type', val)
                      }}
                      className={css.typeToggle}
                    />
                  </Container>
                  <Container style={{ flex: 1 }}>
                    <Label>{getString('ce.co.autoStoppingRule.configuration.step4.tabs.schedules.timezone')}</Label>
                    <TimezoneSelector
                      onTimezoneSelect={val => {
                        _formikProps.setFieldValue('timezone', val)
                      }}
                      timezone={_formikProps.values.timezone}
                    />
                  </Container>
                </Layout.Horizontal>
              </Container>
              <PeriodSelection formikProps={_formikProps} />
              <DaysAndTimeSelector formikProps={_formikProps} />
            </Layout.Vertical>
            {(_formikProps.values.beginsOn || !_isEmpty(_formikProps.values.repeats)) && (
              <ScheduleDescription schedule={getUpdatedScheduleData(_formikProps.values)} />
            )}
            <Layout.Horizontal className={css.ctaContainer} spacing="medium">
              <Button
                text={getString('common.apply')}
                intent="primary"
                disabled={!_formikProps.isValid}
                type="submit"
              />
              <Button text={getString('cancel')} onClick={props.closeDialog} />
            </Layout.Horizontal>
          </FormikForm>
        )}
      </Formik>
    </Layout.Vertical>
  )
}
 
const PeriodSelection = ({ formikProps }: PeriodSelectionProps) => {
  const { getString } = useStrings()
  const [neverEnds, setNeverEnds] = useState(
    !_isEmpty(formikProps.values.beginsOn) ? _isEmpty(formikProps.values.endsOn) : true
  )
 
  const handleStartDateChange = (value: string | undefined, _err?: string) => {
    formikProps.setFieldValue('beginsOn', !_isEmpty(value) ? getStaticSchedulePeriodString(Number(value)) : null)
  }
 
  const handleEndDateChange = (value: string | undefined, _err?: string) => {
    formikProps.setFieldValue('endsOn', getStaticSchedulePeriodString(Number(value)))
  }
 
  const handleNeverEndsChange = (e: React.FormEvent<HTMLInputElement>) => {
    const checked = e.currentTarget.checked
    if (checked) {
      formikProps.setFieldValue('endsOn', null)
    }
    setNeverEnds(checked)
  }
 
  const hasBeginningDate = !_isEmpty(formikProps.values.beginsOn)
 
  return (
    <Container className={css.inputRow}>
      <Heading level={3} className={css.heading}>
        {getString('ce.co.gatewayConfig.setSchedulePeriodHeader')}
      </Heading>
      <Layout.Horizontal spacing={'large'}>
        <div style={{ flex: 1 }}>
          <Label>{getString('ce.co.autoStoppingRule.configuration.step4.tabs.schedules.beginsOn')}</Label>
          <DateInput
            timePrecision="minute"
            disabled={true}
            dateProps={{
              timePickerProps: { useAmPm: true },
              highlightCurrentDay: true,
              minDate: hasBeginningDate
                ? new Date(getMinDate([new Date(formikProps.values.beginsOn as string), new Date()]))
                : new Date(),
              defaultValue: undefined
            }}
            value={formikProps.values.beginsOn ? `${getStaticSchedulePeriodTime(formikProps.values.beginsOn)}` : ''}
            onChange={handleStartDateChange}
            data-testid="beginsOn"
          />
        </div>
        <div style={{ flex: 1 }}>
          <Label>{getString('ce.co.autoStoppingRule.configuration.step4.tabs.schedules.endsOn')}</Label>
          {neverEnds && (
            <div className={css.disabledDateInput}>
              <DateInput disabled timePrecision="minute" dateProps={{ timePickerProps: { useAmPm: true } }} />
            </div>
          )}
          {!neverEnds && (
            <DateInput
              timePrecision="minute"
              disabled={true}
              dateProps={{
                timePickerProps: { useAmPm: true },
                defaultValue: undefined,
                minDate: hasBeginningDate ? new Date(formikProps.values.beginsOn as string) : new Date()
              }}
              value={
                !_isEmpty(formikProps.values.endsOn)
                  ? `${getStaticSchedulePeriodTime(formikProps.values.endsOn as string)}`
                  : ''
              }
              onChange={handleEndDateChange}
              data-testid="endsOn"
            />
          )}
        </div>
      </Layout.Horizontal>
      <Checkbox
        name={'neverEnds'}
        label={getString('ce.co.autoStoppingRule.configuration.step4.tabs.schedules.neverEnds')}
        checked={neverEnds}
        onChange={handleNeverEndsChange}
        style={{ width: '20%' }}
      />
    </Container>
  )
}
 
const DaysAndTimeSelector = ({ formikProps }: DaysAndTimeSelectorProps) => {
  const { getString } = useStrings()
 
  const handleTimeRangeRadioSelection = () => {
    formikProps.setValues({
      ...formikProps.values,
      allDay: false,
      endTime: { hour: 0, min: 0 },
      startTime: { hour: 0, min: 0 }
    })
  }
 
  return (
    <Container>
      <Heading level={3} className={css.heading}>
        {getString('ce.co.gatewayConfig.setScheduleTimeHeader')}
      </Heading>
      <Layout.Horizontal spacing="large">
        <Container style={{ flex: 1 }}>
          <Label>{getString('ce.co.autoStoppingRule.configuration.step4.tabs.schedules.repeats')}</Label>
          <Radio
            label={getString('ce.co.autoStoppingRule.configuration.step4.tabs.schedules.everyday')}
            value="everyday"
            checked={formikProps.values.everyday}
            onChange={_ => {
              formikProps.setFieldValue('everyday', true)
              formikProps.setFieldValue('repeats', [])
            }}
          />
          <Layout.Horizontal flex={{ alignItems: 'center', justifyContent: 'start' }}>
            <Radio
              label=""
              value="somedays"
              checked={!formikProps.values.everyday}
              onChange={_ => {
                formikProps.setFieldValue('everyday', false)
                formikProps.setFieldValue('repeats', [])
              }}
            />
            <DaysOfWeekSelector
              disable={formikProps.values.everyday}
              selection={formikProps.values.repeats}
              onChange={days => {
                const allDaysSelected = days.length === 7
                Iif (allDaysSelected) {
                  formikProps.setFieldValue('everyday', true)
                }
                formikProps.setFieldValue('repeats', allDaysSelected ? [] : days.map(d => d.id))
                Iif (days.length === 0) {
                  formikProps.setFieldValue('startTime', null)
                  formikProps.setFieldValue('endTime', null)
                  // formikProps.setFieldValue('allDay', false)
                }
              }}
            />
          </Layout.Horizontal>
        </Container>
        <Container style={{ flex: 1 }}>
          <Label>{getString('timeLabel')}</Label>
          <Radio
            label={getString('ce.co.autoStoppingRule.configuration.step4.tabs.schedules.allDay')}
            value={'allDay'}
            checked={formikProps.values.allDay}
            onChange={_ => {
              formikProps.setFieldValue('allDay', true)
              formikProps.setFieldValue('startTime', null)
              formikProps.setFieldValue('endTime', null)
            }}
          />
          <Layout.Horizontal flex={{ alignItems: 'baseline', justifyContent: 'start' }}>
            <Radio
              label=""
              value={'sometime'}
              checked={!formikProps.values.allDay}
              onChange={handleTimeRangeRadioSelection}
            />
            <Container>
              <Layout.Horizontal flex={{ alignItems: 'center', justifyContent: 'start' }} className={css.fromTime}>
                <Text>{getString('ce.co.autoStoppingRule.configuration.step4.tabs.schedules.fromText')}</Text>
                <TimePicker
                  useAmPm
                  value={getTime(formikProps.values.startTime)}
                  disabled={formikProps.values.allDay}
                  onChange={d => {
                    formikProps.setFieldValue('startTime', { hour: d.getHours(), min: d.getMinutes() })
                  }}
                />
              </Layout.Horizontal>
              <Layout.Horizontal flex={{ alignItems: 'center', justifyContent: 'start' }} className={css.toTime}>
                <Text>{getString('ce.co.autoStoppingRule.configuration.step4.tabs.schedules.toText')}</Text>
                <TimePicker
                  useAmPm
                  value={getTime(formikProps.values.endTime)}
                  disabled={formikProps.values.allDay}
                  onChange={d => {
                    formikProps.setFieldValue('endTime', { hour: d.getHours(), min: d.getMinutes() })
                    Iif (_isEmpty(formikProps.values.startTime)) {
                      formikProps.setFieldValue('startTime', { hour: 0, min: 0 })
                    }
                  }}
                />
              </Layout.Horizontal>
            </Container>
          </Layout.Horizontal>
        </Container>
      </Layout.Horizontal>
    </Container>
  )
}
 
export default FixedScheduleForm