All files / modules/72-triggers/pages/triggers/views TriggersListSection.tsx

70.99% Statements 93/131
64.56% Branches 133/206
66.67% Functions 16/24
71.09% Lines 91/128

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 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647              5x 5x 5x   5x                             5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x   5x           5x   5x                                                                       5x             49x 49x 49x                 49x                 1x 1x 1x       1x             1x               49x         3x                   2x 2x                   1x 1x     1x 1x   1x                   1x 1x     1x 1x                 10x   5x             42x 42x                                                             5x             42x 42x 42x   42x 6x 36x 6x 30x       42x                                                   5x             42x 42x 42x 42x 42x 42x                     5x 42x 42x 42x   42x                                             5x                                     42x 42x 24x     18x 6x       6x                                                                                         12x                               5x                         42x   42x                         5x                                 42x   42x                     42x                                                                                         5x             5x 5x 5x           5x                                     5x   5x   5x                                                                                                                                                                   5x                  
/*
 * 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 ReactTimeago from 'react-timeago'
import { useParams } from 'react-router-dom'
import type { CellProps, Renderer } from 'react-table'
import {
  Button,
  Layout,
  Popover,
  Text,
  Icon,
  Switch,
  Container,
  SparkChart,
  TagsPopover,
  tagsType,
  useConfirmationDialog,
  useToaster,
  TableV2
} from '@wings-software/uicore'
import { Color } from '@harness/design-system'
import copy from 'clipboard-copy'
import { Classes, Intent, Menu, Position } from '@blueprintjs/core'
import { isUndefined, isEmpty, sum } from 'lodash-es'
import cx from 'classnames'
import { NGTriggerDetailsResponse, useDeleteTrigger, useUpdateTrigger } from 'services/pipeline-ng'
import { usePermission } from '@rbac/hooks/usePermission'
import { PermissionIdentifier } from '@rbac/interfaces/PermissionIdentifier'
import { ResourceType } from '@rbac/interfaces/ResourceType'
import { useStrings } from 'framework/strings'
import { yamlStringify } from '@common/utils/YamlHelperMethods'
import type { UseStringsReturn } from 'framework/strings'
import {
  getTriggerIcon,
  GitSourceProviders,
  getEnabledStatusTriggerValues,
  errorStatusList
} from '../utils/TriggersListUtils'
import { TriggerTypes, clearNullUndefined, ResponseStatus } from '../utils/TriggersWizardPageUtils'
 
import css from './TriggersListSection.module.scss'
export interface GoToEditWizardInterface {
  triggerIdentifier: string
  // only used for url not showing undefined
  triggerType?: string
}
interface TriggersListSectionProps {
  data?: NGTriggerDetailsResponse[] // BE accidentally reversed. Will be changed to NGTriggerResponse later
  refetchTriggerList: () => void
  goToEditWizard: ({ triggerIdentifier, triggerType }: GoToEditWizardInterface) => void
  goToDetails: ({ triggerIdentifier, triggerType }: GoToEditWizardInterface) => void
  isPipelineInvalid?: boolean
}
 
// type CustomColumn<T extends object> = Column<T> & {
//   refetchTriggerList?: () => void
//   goToEditWizard?: ({ triggerIdentifier, triggerType }: GoToEditWizardInterface) => void
//   getString?: (key: string) => string
// }
 
interface RenderColumnRow {
  original: NGTriggerDetailsResponse
}
interface RenderColumnMenuColumn {
  refetchTriggerList: () => void
  goToEditWizard: ({ triggerIdentifier, triggerType }: GoToEditWizardInterface) => void
  showSuccess: (str: string) => void
  showError: (str: string) => void
  getString: UseStringsReturn['getString']
  projectIdentifier: string
  orgIdentifier: string
  accountId: string
  pipelineIdentifier: string
  isTriggerRbacDisabled: boolean
}
 
const RenderColumnMenu: Renderer<CellProps<NGTriggerDetailsResponse>> = ({
  row,
  column
}: {
  row: RenderColumnRow
  column: RenderColumnMenuColumn
}) => {
  const data = row.original
  const [menuOpen, setMenuOpen] = React.useState(false)
  const { mutate: deleteTrigger } = useDeleteTrigger({
    queryParams: {
      accountIdentifier: column.accountId,
      orgIdentifier: column.orgIdentifier,
      projectIdentifier: column.projectIdentifier,
      targetIdentifier: column.pipelineIdentifier
    }
  })
 
  const { openDialog: confirmDelete } = useConfirmationDialog({
    contentText: `${column.getString('triggers.confirmDelete')} ${data.name || /* istanbul ignore next */ ''}`,
    titleText: column.getString('common.triggerLabel'),
    confirmButtonText: column.getString('delete'),
    cancelButtonText: column.getString('cancel'),
    intent: Intent.DANGER,
    buttonIntent: Intent.DANGER,
    onCloseDialog: async (isConfirmed: boolean) => {
      /* istanbul ignore else */
      if (isConfirmed) {
        try {
          const deleted = await deleteTrigger(data.identifier || /* istanbul ignore next */ '', {
            headers: { 'content-type': 'application/json' }
          })
          /* istanbul ignore else */
          Iif (deleted.status === ResponseStatus.SUCCESS) {
            column.showSuccess(
              `${column.getString('common.triggerLabel')} ${
                data.name || /* istanbul ignore next */ ''
              } ${column.getString('deleted')}`
            )
          }
          column.refetchTriggerList?.()
        } catch (err) {
          /* istanbul ignore next */
          column.showError(err?.data?.message)
        }
      }
    }
  })
  return (
    <Layout.Horizontal style={{ justifyContent: 'flex-end' }}>
      <Popover
        isOpen={menuOpen}
        onInteraction={nextOpenState => {
          setMenuOpen(nextOpenState)
        }}
        className={Classes.DARK}
        position={Position.BOTTOM_RIGHT}
      >
        <Button
          minimal
          className={css.actionButton}
          icon="more"
          onClick={e => {
            e.stopPropagation()
            setMenuOpen(true)
          }}
        />
        <Menu style={{ minWidth: 'unset' }}>
          <Menu.Item
            icon="edit"
            className={column.isTriggerRbacDisabled ? css.disabledOption : ''}
            textClassName={column.isTriggerRbacDisabled ? css.disabledOption : ''}
            text={column.getString('edit')}
            onClick={(e: React.MouseEvent) => {
              e.stopPropagation()
              Iif (column.isTriggerRbacDisabled) {
                return
              }
              Eif (data?.identifier && data.type) {
                column.goToEditWizard({ triggerIdentifier: data.identifier, triggerType: data.type })
              }
              setMenuOpen(false)
            }}
          />
          <Menu.Divider />
          <Menu.Item
            icon="trash"
            className={column.isTriggerRbacDisabled ? css.disabledOption : ''}
            textClassName={column.isTriggerRbacDisabled ? css.disabledOption : ''}
            text={column.getString('delete')}
            onClick={(e: React.MouseEvent) => {
              e.stopPropagation()
              Iif (column.isTriggerRbacDisabled) {
                return
              }
              confirmDelete()
              setMenuOpen(false)
            }}
          />
        </Menu>
      </Popover>
    </Layout.Horizontal>
  )
}
 
const RenderCenteredColumnHeader = (header: string): JSX.Element => <div className={css.textCentered}>{header}</div>
 
const RenderColumnTrigger: Renderer<CellProps<NGTriggerDetailsResponse>> = ({
  row,
  column
}: {
  row: RenderColumnRow
  column: { getString: UseStringsReturn['getString'] }
}) => {
  const data = row.original
  return (
    <>
      <Layout.Horizontal spacing="small" data-testid={data.identifier}>
        <Icon
          name={
            data.type
              ? getTriggerIcon({
                  type: data.type,
                  webhookSourceRepo: data?.webhookDetails?.webhookSourceRepo,
                  buildType: data?.buildDetails?.buildType
                })
              : 'yaml-builder-trigger'
          }
          size={26}
        />
        <Layout.Vertical padding={{ left: 'small' }}>
          <Layout.Horizontal spacing="small" data-testid={data.identifier}>
            <Text color={Color.BLACK} lineClamp={1} width={!isEmpty(data.tags) ? '270px' : '300px'}>
              {data.name}
            </Text>
            {!isEmpty(data.tags) ? <TagsPopover className={css.tags} tags={data.tags as tagsType} /> : null}
          </Layout.Horizontal>
          <Text color={Color.GREY_400} lineClamp={1} width={300}>
            {column.getString('idLabel', { id: data.identifier })}
          </Text>
        </Layout.Vertical>
      </Layout.Horizontal>
    </>
  )
}
 
const RenderColumnStatus: Renderer<CellProps<NGTriggerDetailsResponse>> = ({
  row,
  column
}: {
  row: RenderColumnRow
  column: { getString: UseStringsReturn['getString'] }
}) => {
  const data = row.original
  const { validationStatus, pollingSubscriptionStatus, webhookAutoRegistrationStatus } = data?.triggerStatus || {}
  let statusMessage: string | undefined = ''
 
  if (errorStatusList.includes(validationStatus?.statusResult || '')) {
    statusMessage = validationStatus?.detailedMessage
  } else if (errorStatusList.includes(pollingSubscriptionStatus?.statusResult || '')) {
    statusMessage = pollingSubscriptionStatus?.detailedMessage
  } else Iif (errorStatusList.includes(webhookAutoRegistrationStatus?.registrationResult || '')) {
    statusMessage = webhookAutoRegistrationStatus?.detailedMessage
  }
 
  return (
    <Layout.Horizontal spacing="small" data-testid={data.identifier}>
      {statusMessage && (
        <Text
          inline
          icon="warning-sign"
          iconProps={{
            size: 12,
            color: Color.RED_500
          }}
          tooltip={
            <Layout.Vertical font={{ size: 'small' }} spacing="small" padding="small">
              <Text font={{ size: 'small' }} color={Color.WHITE}>
                {statusMessage}
              </Text>
            </Layout.Vertical>
          }
          tooltipProps={{ isDark: true, position: 'bottom', popoverClassName: css.tooltip }}
        >
          {column.getString('failed').toLowerCase()}
        </Text>
      )}
    </Layout.Horizontal>
  )
}
 
const RenderColumnActivity: Renderer<CellProps<NGTriggerDetailsResponse>> = ({
  row,
  column
}: {
  row: RenderColumnRow
  column: { getString: UseStringsReturn['getString'] }
}) => {
  const data = row.original as any // temporary until API ready
  const executions = data.executions
  const numDays = executions?.length
  Iif (numDays === 0) return undefined
  const numActivations = sum(executions)
  return (
    <Layout.Horizontal flex={{ align: 'center-center' }} style={{ justifyContent: 'flex-start' }} spacing="xsmall">
      <span className={css.activityChart}>{numActivations !== 0 && <SparkChart data={executions} />}</span>
      <Container style={{ textAlign: 'start' }}>
        <span>{column.getString('triggers.activityActivation', { numActivations })}</span>
        <Text>{column.getString('triggers.activityDays', { numDays })}</Text>
      </Container>
    </Layout.Horizontal>
  )
}
 
const RenderColumnLastActivation: Renderer<CellProps<NGTriggerDetailsResponse>> = ({ row }) => {
  const data = row.original
  const lastExecutionTime = data.lastTriggerExecutionDetails?.lastExecutionTime
  const lastExecutionSuccessful = data.lastTriggerExecutionDetails?.lastExecutionSuccessful
 
  return (
    <Layout.Horizontal style={{ justifyContent: 'flex-start' }} spacing="small" data-testid={data.identifier}>
      <div className={css.activityStatement}>
        {!isUndefined(lastExecutionTime) && !isUndefined(lastExecutionSuccessful) ? (
          <>
            <Layout.Horizontal style={{ alignItems: 'center' }}>
              <Container style={{ textAlign: 'start' }}>
                <Text>{lastExecutionTime ? <ReactTimeago date={lastExecutionTime} /> : null}</Text>
              </Container>
              <Icon
                style={{ paddingLeft: 'var(--spacing-xsmall)' }}
                name="dot"
                color={lastExecutionSuccessful ? 'green500' : 'red500'}
                size={20}
              />
            </Layout.Horizontal>
          </>
        ) : null}
      </div>
    </Layout.Horizontal>
  )
}
 
const RenderWebhookIcon = ({
  type,
  webhookSourceRepo,
  webhookSecret,
  webhookUrl,
  column
}: {
  type?: string
  webhookSourceRepo?: string
  webhookSecret?: string
  webhookUrl?: string
  column: {
    accountId: string
    orgIdentifier: string
    projectIdentifier: string
    getString: UseStringsReturn['getString']
    isTriggerRbacDisabled: boolean
  }
}): JSX.Element => {
  const [optionsOpen, setOptionsOpen] = React.useState(false)
  if (!type || type !== TriggerTypes.WEBHOOK || !webhookUrl) {
    return <Text color={Color.GREY_400}>{column.getString('na')}</Text>
  }
 
  if (webhookSourceRepo?.toLowerCase() === GitSourceProviders.CUSTOM.value.toLowerCase()) {
    const curlCommand = `curl -X POST ${
      (webhookSecret && `-H 'X-Harness-Webhook-Token: ${webhookSecret}'`) || ''
    } -H 'content-type: application/json' --url '${webhookUrl}' -d '{"sample_key": "sample_value"}'`
 
    return (
      <Popover
        isOpen={optionsOpen}
        onInteraction={nextOpenState => {
          setOptionsOpen(nextOpenState)
        }}
        className={Classes.DARK}
        position={Position.BOTTOM_RIGHT}
      >
        <Button
          minimal
          className={cx(css.webhookUrl, column.isTriggerRbacDisabled ? css.disabledOption : '')}
          icon="main-link"
          onClick={e => {
            e.stopPropagation()
            if (column.isTriggerRbacDisabled) {
              return
            }
            setOptionsOpen(true)
          }}
        />
        <Menu style={{ minWidth: 'unset' }}>
          <Menu.Item
            text={column.getString('triggers.copyAsUrl')}
            onClick={(e: React.MouseEvent) => {
              e.stopPropagation()
              copy(webhookUrl)
              ;(column as any).showSuccess(column.getString('triggers.toast.webhookUrlCopied'))
              setOptionsOpen(false)
            }}
          />
          <Menu.Divider />
          <Menu.Item
            text={column.getString('triggers.copyAsCurl')}
            onClick={(e: React.MouseEvent) => {
              e.stopPropagation()
              copy(curlCommand)
              ;(column as any).showSuccess(column.getString('triggers.toast.webhookCurlCopied'))
              setOptionsOpen(false)
            }}
          />
        </Menu>
      </Popover>
    )
  } else {
    return (
      <Button
        className={css.webhookUrl}
        icon="main-link"
        color={Color.BLUE_500}
        minimal
        onClick={e => {
          e.stopPropagation()
          copy(webhookUrl)
          ;(column as any).showSuccess(column.getString('triggers.toast.webhookUrlCopied'))
        }}
      />
    )
  }
}
 
const RenderColumnWebhook: Renderer<CellProps<NGTriggerDetailsResponse>> = ({
  row,
  column
}: {
  row: RenderColumnRow
  column: {
    accountId: string
    orgIdentifier: string
    projectIdentifier: string
    getString: UseStringsReturn['getString']
    isTriggerRbacDisabled: boolean
  }
}) => {
  const data = row.original
 
  return (
    <div className={css.textCentered}>
      {RenderWebhookIcon({
        type: data?.type,
        webhookSourceRepo: data?.webhookDetails?.webhookSourceRepo,
        webhookUrl: data?.webhookUrl,
        webhookSecret: data?.webhookDetails?.webhookSecret,
        column
      })}
    </div>
  )
}
 
const RenderColumnEnable: Renderer<CellProps<NGTriggerDetailsResponse>> = ({
  row,
  column
}: {
  row: RenderColumnRow
  column: {
    showSuccess: (str: string) => void
    showError: (str: string) => void
    getString: UseStringsReturn['getString']
    refetchTriggerList: () => void
    projectIdentifier: string
    orgIdentifier: string
    accountId: string
    pipelineIdentifier: string
    isTriggerRbacDisabled: boolean
  }
}) => {
  const data = row.original
 
  const { mutate: updateTrigger, loading: updateTriggerLoading } = useUpdateTrigger({
    triggerIdentifier: data.identifier as string,
    queryParams: {
      accountIdentifier: column.accountId,
      orgIdentifier: column.orgIdentifier,
      projectIdentifier: column.projectIdentifier,
      targetIdentifier: column.pipelineIdentifier
    },
    requestOptions: { headers: { 'content-type': 'application/yaml' } }
  })
 
  return (
    <div className={css.textCentered} onClick={e => e.stopPropagation()}>
      <Switch
        label=""
        className={column.isTriggerRbacDisabled ? css.disabledOption : ''}
        checked={data.enabled}
        disabled={updateTriggerLoading || column.isTriggerRbacDisabled}
        onChange={async () => {
          if (column.isTriggerRbacDisabled) {
            return
          }
          const { values, error } = getEnabledStatusTriggerValues({
            data,
            enabled: !data.enabled,
            getString: column.getString
          })
          if (error) {
            column.showError(error)
            return
          }
          try {
            const { status, data: dataResponse } = await updateTrigger(
              yamlStringify({ trigger: clearNullUndefined(values) }) as any
            )
            if (dataResponse?.errors && !isEmpty(dataResponse?.errors)) {
              column.showError(column.getString('triggers.toast.existingTriggerError'))
              return
            } else if (status === ResponseStatus.SUCCESS && dataResponse) {
              column.showSuccess(
                column.getString('triggers.toast.toggleEnable', {
                  enabled: dataResponse.enabled ? 'enabled' : 'disabled',
                  name: dataResponse.name || ''
                })
              )
              column.refetchTriggerList?.()
            }
          } catch (err) {
            column.showError(err?.data?.message)
          }
        }}
      />
    </div>
  )
}
 
export const TriggersListSection: React.FC<TriggersListSectionProps> = ({
  data,
  refetchTriggerList,
  goToEditWizard,
  goToDetails,
  isPipelineInvalid
}): JSX.Element => {
  const { getString } = useStrings()
  const { showSuccess, showError } = useToaster()
  const { projectIdentifier, orgIdentifier, accountId, pipelineIdentifier } = useParams<{
    projectIdentifier: string
    orgIdentifier: string
    accountId: string
    pipelineIdentifier: string
  }>()
  const [isExecutable] = usePermission(
    {
      resourceScope: {
        projectIdentifier: projectIdentifier,
        orgIdentifier: orgIdentifier,
        accountIdentifier: accountId
      },
      resource: {
        resourceType: ResourceType.PIPELINE,
        resourceIdentifier: pipelineIdentifier
      },
      permissions: [PermissionIdentifier.EXECUTE_PIPELINE],
      options: {
        skipCache: true
      }
    },
    [projectIdentifier, orgIdentifier, accountId, pipelineIdentifier]
  )
 
  const isTriggerRbacDisabled = !isExecutable || isPipelineInvalid
 
  const columns: any = React.useMemo(
    // const columns: CustomColumn<NGTriggerDetailsResponse>[] = React.useMemo( // wait for backend to support condition
    () => [
      {
        Header: getString('common.triggerLabel').toUpperCase(),
        accessor: 'name',
        width: '25%',
        Cell: RenderColumnTrigger,
        getString
      },
      {
        Header: 'STATUS',
        accessor: 'status',
        width: '20%',
        disableSortBy: true,
        Cell: RenderColumnStatus,
        getString
      },
      {
        Header: getString('activity').toUpperCase(),
        accessor: 'activity',
        width: '18%',
        Cell: RenderColumnActivity,
        disableSortBy: true,
        getString
      },
      {
        Header: getString('triggers.lastActivationLabel'),
        accessor: 'lastExecutionTime',
        width: '14%',
        Cell: RenderColumnLastActivation,
        disableSortBy: true
      },
 
      {
        Header: RenderCenteredColumnHeader(getString('execution.triggerType.WEBHOOK').toUpperCase()),
        accessor: 'webhook',
        width: '10%',
        Cell: RenderColumnWebhook,
        disableSortBy: true,
        showSuccess,
        orgIdentifier,
        projectIdentifier,
        accountId,
        getString,
        isTriggerRbacDisabled
      },
      {
        Header: RenderCenteredColumnHeader(getString('enabledLabel').toUpperCase()),
        accessor: 'enable',
        width: '10%',
        Cell: RenderColumnEnable,
        disableSortBy: true,
        projectIdentifier,
        orgIdentifier,
        accountId,
        pipelineIdentifier,
        showSuccess,
        showError,
        refetchTriggerList,
        getString,
        isTriggerRbacDisabled
      },
      {
        Header: '',
        accessor: 'type',
        width: '3%',
        Cell: RenderColumnMenu,
        disableSortBy: true,
        refetchTriggerList,
        goToEditWizard,
        showSuccess,
        showError,
        projectIdentifier,
        orgIdentifier,
        accountId,
        pipelineIdentifier,
        getString,
        isTriggerRbacDisabled
      }
    ],
    [goToEditWizard, refetchTriggerList, getString]
  )
 
  return (
    <TableV2<NGTriggerDetailsResponse>
      className={css.table}
      columns={columns}
      data={data || /* istanbul ignore next */ []}
      onRowClick={item => goToDetails({ triggerIdentifier: item.identifier || '' })}
    />
  )
}