All files / modules/72-triggers/pages/triggers/views/subviews ScheduleUtils.ts

95.04% Statements 134/141
82.98% Branches 78/94
100% Functions 21/21
94.92% Lines 112/118

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                127x 127x 127x 127x 635x 889x 7620x 127x 3048x 4064x 127x 127x 1524x 127x 3937x 381x 3556x 254x 3302x 254x   3048x       127x                             127x                             127x           13x   1524x   127x 3937x 3937x   3937x     127x 127x 127x 127x 127x 127x 127x 127x   127x                   127x                                   127x                   127x               127x 127x 127x 127x 127x 127x                                           127x         127x                 127x                 127x             127x             127x               127x             127x                     120x 11x 109x 6x 103x   10x   93x     127x 41x   127x 6x   1x 5x                           5x 1x   1x             1x       4x 1x   1x             1x       3x 1x   1x     1x       2x 1x     1x               1x       1x 1x   1x     1x               127x 19x 16x 7x 3x         127x                 19x 19x 19x   19x     127x         127x 40x 30x 30x 3x 27x 2x     25x     127x 7x 7x                 127x  
/*
 * 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 type { SelectOption } from '@wings-software/uicore'
import { isValidCron } from 'cron-validator'
import { zeroFiftyNineDDOptions, amPmOptions, oneTwelveDDOptions } from '@common/components/TimeSelect/TimeSelectUtils'
const cronSensicalMinutes = [5, 10, 15, 20, 30]
const cronSensicalHours = [1, 2, 3, 4, 6, 8, 12]
export const cronSensicalMinutesOptions = cronSensicalMinutes.map(i => ({ label: `${i}`, value: `${i}` }))
export const cronSensicalHoursOptions = cronSensicalHours.map(i => ({ label: `${i}`, value: `${i}` }))
export const zeroFiftyNineOptions = Array.from({ length: 60 }, (_, i) => ({ label: `${i}`, value: `${i}` }))
export const oneFiftyNineOptions = zeroFiftyNineOptions.slice(1)
export const zeroTwentyThreeOptions = Array.from({ length: 24 }, (_, i) => ({ label: `${i}`, value: `${i}` }))
export const zeroThirtyOneOptions = Array.from({ length: 32 }, (_, i) => ({ label: `${i}`, value: `${i}` }))
export const oneThirtyOneOptions = zeroThirtyOneOptions.slice(1)
export const oneFiftyNineDDOptions = zeroFiftyNineDDOptions.slice(1)
export const oneTwelveOptions = Array.from({ length: 12 }, (_, i) => ({ label: `${i + 1}`, value: `${i + 1}` }))
const getPostPosition = (i: number): string => {
  if (i == 1 || i == 21 || i == 31) {
    return 'st'
  } else if (i == 2 || i == 22) {
    return 'nd'
  } else if (i == 3 || i == 23) {
    return 'rd'
  } else {
    return 'th'
  }
}
 
const months = [
  'January',
  'February',
  'March',
  'April',
  'May',
  'June',
  'July',
  'August',
  'September',
  'October',
  'November',
  'December'
]
 
const daysInMonth: { [key: string]: number } = {
  '1': 31,
  '2': 29, // allow lead year
  '3': 31,
  '4': 30,
  '5': 31,
  '6': 30,
  '7': 31,
  '8': 31,
  '9': 30,
  '10': 31,
  '11': 30,
  '12': 31
}
 
export const getDayOptionsToMonth = ({
  monthNo,
  options
}: {
  monthNo: string
  options: SelectOption[]
}): SelectOption[] => options.slice(0, daysInMonth[monthNo])
 
export const monthOptions = months.map((month, index) => ({ label: month, value: (index + 1).toString() }))
 
export const nthDayOptions = Array.from({ length: 31 }, (_, i) => {
  const value = i + 1
  const label = `${value}${getPostPosition(value)} Day`
 
  return { label, value: `${value}` }
})
 
export enum DaysOfWeek {
  MON = 'MON',
  TUE = 'TUE',
  WED = 'WED',
  THU = 'THU',
  FRI = 'FRI',
  SAT = 'SAT',
  SUN = 'SUN'
}
export const shortDays: DaysOfWeek[] = [
  DaysOfWeek.MON,
  DaysOfWeek.TUE,
  DaysOfWeek.WED,
  DaysOfWeek.THU,
  DaysOfWeek.FRI,
  DaysOfWeek.SAT,
  DaysOfWeek.SUN
]
 
export const defaultScheduleValues = {
  MINUTES_0: oneFiftyNineOptions[0].value,
  MINUTES_5: cronSensicalMinutesOptions[0].value,
  MINUTES_00: zeroFiftyNineDDOptions[0].value,
  DAY_OF_MONTH_1: oneThirtyOneOptions[0].value,
  HOURS_1: oneTwelveOptions[0].value,
  HOURS_01: oneTwelveDDOptions[0].value,
  MINUTES_1: oneFiftyNineOptions[0].value,
  AM_PM: amPmOptions[0].value,
  DAY_OF_MONTH_1ST: nthDayOptions[0].value,
  DAYS_OF_WEEK: [DaysOfWeek.MON],
  DAY_OF_WEEK_EMPTY: [],
  MONTH_1: oneTwelveOptions[0].value,
  JANUARY: monthOptions[0].value,
  MON: [DaysOfWeek.MON],
  ASTERISK: '*'
}
 
export const scheduleTabsId = {
  MINUTES: 'Minutes',
  HOURLY: 'Hourly',
  DAILY: 'Daily',
  WEEKLY: 'Weekly',
  MONTHLY: 'Monthly',
  YEARLY: 'Yearly',
  CUSTOM: 'Custom'
}
 
export const resetScheduleObject = {
  minutes: undefined,
  hours: undefined,
  dayOfMonth: undefined,
  month: undefined,
  dayOfWeek: undefined
}
 
export enum EXP_BREAKDOWN_INPUTS {
  MINUTES = 'MINUTES',
  HOURS = 'HOURS',
  DAY_OF_MONTH = 'DAY_OF_MONTH',
  MONTH = 'MONTH',
  DAY_OF_WEEK = 'DAY_OF_WEEK'
}
 
export interface ExpressionBreakdownInterface {
  minutes?: string
  hours?: string
  amPm?: string
  dayOfMonth?: string
  month?: string
  dayOfWeek?: DaysOfWeek[] | string[]
  expression?: string
}
 
export interface DefaultExpressionBreakdownInterface {
  minutes?: string
  hours?: string
  dayOfMonth?: string
  month?: string
  dayOfWeek?: DaysOfWeek[] | string[]
  expression?: string
}
 
const defaultTimeSelect = {
  hours: defaultScheduleValues.HOURS_01,
  minutes: defaultScheduleValues.MINUTES_00,
  amPm: defaultScheduleValues.AM_PM
}
const defaultMinutesValues = {
  minutes: defaultScheduleValues.MINUTES_5,
  hours: defaultScheduleValues.ASTERISK,
  amPm: defaultScheduleValues.AM_PM,
  dayOfMonth: defaultScheduleValues.ASTERISK,
  month: defaultScheduleValues.ASTERISK,
  dayOfWeek: defaultScheduleValues.DAY_OF_WEEK_EMPTY
}
 
const defaultHourlyValues = {
  minutes: defaultScheduleValues.MINUTES_00,
  hours: defaultScheduleValues.HOURS_1,
  amPm: defaultScheduleValues.AM_PM,
  dayOfMonth: defaultScheduleValues.ASTERISK,
  month: defaultScheduleValues.ASTERISK,
  dayOfWeek: defaultScheduleValues.DAY_OF_WEEK_EMPTY
}
 
export const defaultDailyValues = {
  dayOfMonth: defaultScheduleValues.ASTERISK,
  month: defaultScheduleValues.ASTERISK,
  dayOfWeek: defaultScheduleValues.DAY_OF_WEEK_EMPTY,
  ...defaultTimeSelect
}
 
export const defaultWeeklyValues = {
  dayOfMonth: defaultScheduleValues.ASTERISK,
  month: defaultScheduleValues.ASTERISK,
  dayOfWeek: defaultScheduleValues.MON,
  ...defaultTimeSelect
}
 
export const defaultMonthlyValues = {
  dayOfMonth: defaultScheduleValues.DAY_OF_MONTH_1ST,
  startMonth: defaultScheduleValues.JANUARY,
  month: defaultScheduleValues.MONTH_1,
  dayOfWeek: defaultScheduleValues.DAY_OF_WEEK_EMPTY,
  ...defaultTimeSelect
}
 
export const defaultYearlyValues = {
  dayOfMonth: defaultScheduleValues.DAY_OF_MONTH_1ST,
  month: defaultScheduleValues.JANUARY,
  dayOfWeek: defaultScheduleValues.DAY_OF_WEEK_EMPTY,
  ...defaultTimeSelect
}
 
export const getSlashValue = ({
  selectedScheduleTab,
  id,
  value,
  startMonth
}: {
  selectedScheduleTab: string
  id: string
  value: string
  startMonth?: string
}): string => {
  if (selectedScheduleTab === scheduleTabsId.MINUTES && id === 'minutes') {
    return `0/${value}`
  } else if (selectedScheduleTab === scheduleTabsId.HOURLY && id === 'hours') {
    return `0/${value}`
  } else if (selectedScheduleTab === scheduleTabsId.MONTHLY && id === 'month' && startMonth) {
    // cron expression: startMonth / monthInterval
    return `${startMonth}/${value}`
  }
  return value
}
 
export const getDayOfWeekStr = (days?: string[]): string =>
  days?.length ? shortDays.filter(day => days.includes(day)).join(',') : '*'
 
export const getDefaultExpressionBreakdownValues = (tabId: string): DefaultExpressionBreakdownInterface => {
  if (tabId === scheduleTabsId.CUSTOM) {
    // persist expression from formik values
    return { ...resetScheduleObject }
  } else Iif (tabId === scheduleTabsId.MINUTES) {
    const { minutes, hours, dayOfMonth, month, dayOfWeek } = defaultMinutesValues
    const constructedExpression =
      tabId !== scheduleTabsId.CUSTOM
        ? `${getSlashValue({
            selectedScheduleTab: tabId,
            id: 'minutes',
            value: minutes
          })} ${hours} ${dayOfMonth} ${month} ${getDayOfWeekStr(dayOfWeek)}`
        : undefined
    return {
      ...defaultMinutesValues,
      expression: constructedExpression
    }
  } else if (tabId === scheduleTabsId.HOURLY) {
    const { minutes, hours, dayOfMonth, month, dayOfWeek } = defaultHourlyValues
    const constructedExpression =
      tabId !== scheduleTabsId.CUSTOM
        ? `${minutes} ${getSlashValue({
            selectedScheduleTab: tabId,
            id: 'hours',
            value: hours
          })} ${dayOfMonth} ${month} ${getDayOfWeekStr(dayOfWeek)}`
        : undefined
    return {
      ...defaultHourlyValues,
      expression: constructedExpression
    }
  } else if (tabId === scheduleTabsId.DAILY) {
    const { minutes, hours, dayOfMonth, month, dayOfWeek } = defaultDailyValues
    const constructedExpression =
      tabId !== scheduleTabsId.CUSTOM
        ? `${minutes} ${hours} ${getSlashValue({
            selectedScheduleTab: tabId,
            id: 'dayOfMonth',
            value: dayOfMonth
          })} ${month} ${getDayOfWeekStr(dayOfWeek)}`
        : undefined
    return {
      ...defaultDailyValues,
      expression: constructedExpression
    }
  } else if (tabId === scheduleTabsId.WEEKLY) {
    const { minutes, hours, dayOfMonth, month, dayOfWeek } = defaultWeeklyValues
    const constructedExpression =
      tabId !== scheduleTabsId.CUSTOM
        ? `${minutes} ${hours} ${dayOfMonth} ${month} ${getDayOfWeekStr(dayOfWeek)}`
        : undefined
    return {
      ...defaultWeeklyValues,
      expression: constructedExpression
    }
  } else if (tabId === scheduleTabsId.MONTHLY) {
    const { minutes, hours, dayOfMonth, month, startMonth, dayOfWeek } = defaultMonthlyValues
    // startMonth only applicable for Monthly tab, handled in getSlashValue
    const constructedExpression =
      tabId !== scheduleTabsId.CUSTOM
        ? `${minutes} ${hours} ${dayOfMonth} ${getSlashValue({
            selectedScheduleTab: tabId,
            id: 'month',
            startMonth,
            value: month
          })} ${getDayOfWeekStr(dayOfWeek)}`
        : undefined
    return {
      ...defaultMonthlyValues,
      expression: constructedExpression
    }
  } else Eif (tabId === scheduleTabsId.YEARLY) {
    const { minutes, hours, dayOfMonth, month, dayOfWeek } = defaultYearlyValues
    const constructedExpression =
      tabId !== scheduleTabsId.CUSTOM
        ? `${minutes} ${hours} ${dayOfMonth} ${month} ${getDayOfWeekStr(dayOfWeek)}`
        : undefined
    return {
      ...defaultYearlyValues,
      expression: constructedExpression
    }
  }
  return {}
}
 
const getExpressionBreakdownIndexes = (id: string): number => {
  if (id === 'minutes') return 0
  else if (id === 'hours') return 1
  else if (id === 'dayOfMonth') return 2
  else Eif (id === 'month') return 3
  else if (id === 'dayOfWeek') return 4
  return -1
}
 
export const getUpdatedExpression = ({
  expression,
  id,
  value
}: {
  expression: string
  id: string
  value: string
}): string => {
  const breakdownIndex = getExpressionBreakdownIndexes(id)
  const updatedExpressionArr: string[] = expression.split(' ')
  updatedExpressionArr[breakdownIndex] = value
 
  return updatedExpressionArr?.join(' ')
}
 
export const AmPmMap = {
  AM: 'AM',
  PM: 'PM'
}
 
export const getMilitaryHours = ({ hours, amPm }: { hours: string; amPm: string }): string => {
  if (hours === '*') return '*'
  const hoursInt = parseInt(hours)
  if (hoursInt === 12 && amPm === AmPmMap.AM) {
    return '0'
  } else if (hoursInt === 12 && amPm === AmPmMap.PM) {
    return '12'
  }
 
  return amPm === AmPmMap.AM ? hoursInt.toString() : (hoursInt + 12).toString()
}
 
export const getBreakdownValues = (cronExpression: string): ExpressionBreakdownInterface => {
  const cronExpressionArr = cronExpression?.trim().split(' ')
  return {
    minutes: cronExpressionArr[0],
    hours: cronExpressionArr[1],
    dayOfMonth: cronExpressionArr[2],
    month: cronExpressionArr[3],
    dayOfWeek: Array.isArray(cronExpressionArr[4]) ? cronExpressionArr[4].split(',') : []
  }
}
 
export const isCronValid = (expression: string): boolean => isValidCron(expression, { alias: true })