Skip to content

SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.

feat(alerts): show routing policies and planned downtime as tables (#13259)

ashu89124aab7f48c981
diff --git a/frontend/src/container/PlannedDowntime/AlertRuleTags.tsx b/frontend/src/container/PlannedDowntime/AlertRuleTags.tsx
new file mode 100644
index 0000000000..100f1b5c00
--- /dev/null
+++ b/frontend/src/container/PlannedDowntime/AlertRuleTags.tsx
@@ -0,0 +1,55 @@
+import { Badge } from '@signozhq/ui/badge';
+import { Pill } from '@signozhq/ui/pill';
+import { Tooltip } from '@signozhq/ui/tooltip';
+import cx from 'classnames';
+
+import type { DowntimeAlertOption } from './types';
+
+interface AlertRuleTagsProps {
+ selectedTags: DowntimeAlertOption[];
+ closable: boolean;
+ handleClose?: (removedTag: DowntimeAlertOption['value']) => void;
+ classname?: string;
+}
+export function AlertRuleTags(props: AlertRuleTagsProps): JSX.Element {
+ const { closable, selectedTags, handleClose, classname } = props;
+ return (
+ <div
+ style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginBottom: 8 }}
+ className={cx('alert-rule-tags', classname)}
+ >
+ {selectedTags?.map((tag: DowntimeAlertOption, index: number) => {
+ if (closable) {
+ return (
+ <Pill.Closeable
+ key={tag.value}
+ maxWidth={200}
+ onClose={(): void => handleClose?.(tag.value)}
+ >
+ {tag.label}
+ </Pill.Closeable>
+ );
+ }
+
+ const isLongTag = (tag?.label as string)?.length > 20;
+ const tagElem = (
+ <Badge
+ textTransform="none"
+ key={tag.value}
+ color={index % 2 ? 'highlight-danger' : 'primary'}
+ variant="outlined"
+ >
+ {isLongTag
+ ? `${(tag?.label as string | null)?.slice(0, 20)}...`
+ : tag?.label}
+ </Badge>
+ );
+ return (
+ <Tooltip title={isLongTag ? tag?.label : undefined} key={tag?.value}>
+ {tagElem}
+ </Tooltip>
+ );
+ })}
+ </div>
+ );
+}
diff --git a/frontend/src/container/PlannedDowntime/PlannedDowntime.module.scss b/frontend/src/container/PlannedDowntime/PlannedDowntime.module.scss
new file mode 100644
index 0000000000..2683d159ba
--- /dev/null
+++ b/frontend/src/container/PlannedDowntime/PlannedDowntime.module.scss
@@ -0,0 +1,176 @@
+.container {
+ display: flex;
+ flex-direction: column;
+ flex: 1;
+ min-height: 0;
+}
+
+.headerBand {
+ --control-height: 2rem;
+ --input-height: var(--control-height);
+ --input-wrapper-height: var(--control-height);
+
+ display: flex;
+ flex-direction: column;
+ gap: var(--spacing-6);
+ flex-shrink: 0;
+ padding: 0 var(--spacing-8) var(--spacing-6) var(--spacing-8);
+}
+
+.commandHeader {
+ display: flex;
+ align-items: center;
+ gap: var(--spacing-4);
+}
+
+.headingBlock {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ min-width: 0;
+}
+
+.title {
+ margin: 0;
+ color: var(--l1-foreground);
+ font-size: var(--font-size-lg);
+ font-weight: var(--font-weight-medium);
+ line-height: 28px;
+ letter-spacing: -0.09px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.countPill {
+ padding: 2px 9px;
+ border-radius: 999px;
+ background: var(--l2-background);
+ border: 1px solid var(--l2-border);
+ color: var(--l2-foreground);
+ font-size: var(--font-size-xs);
+ font-variant-numeric: tabular-nums;
+}
+
+.grow {
+ flex: 1;
+}
+
+.filtersRow {
+ position: relative;
+ z-index: 10;
+ display: flex;
+ align-items: center;
+ gap: var(--spacing-4);
+}
+
+.searchInput {
+ flex: 1 1 0;
+ min-width: 220px;
+}
+
+.searchIcon {
+ color: var(--l2-foreground);
+}
+
+.actionsHeader {
+ display: block;
+ text-align: right;
+}
+
+.actions {
+ display: flex;
+ align-items: center;
+ justify-content: flex-end;
+}
+
+.tableContainer {
+ flex: 1;
+ min-height: 0;
+ display: flex;
+ flex-direction: column;
+
+ --tanstack-table-row-hover-bg: var(--l2-background-hover);
+ --tanstack-table-row-active-bg: var(--l2-background-active);
+ --tanstack-table-row-height: 42px;
+
+ --tanstack-cell-padding-top-override: 5px;
+ --tanstack-cell-padding-bottom-override: 5px;
+ --tanstack-cell-padding-left-override: 16px;
+ --tanstack-cell-padding-right-override: 16px;
+
+ --tanstack-table-row-odd-bg: color-mix(
+ in srgb,
+ var(--l1-foreground) 2%,
+ transparent
+ );
+ --tanstack-table-row-even-bg: color-mix(
+ in srgb,
+ var(--l1-foreground) 1%,
+ transparent
+ );
+}
+
+.paginationContainer {
+ padding-right: var(--spacing-12);
+ height: 62px;
+}
+
+.expression {
+ font-family: var(--font-mono, monospace);
+ font-size: 13px;
+}
+
+.badges {
+ display: flex;
+ gap: var(--spacing-2);
+ overflow: hidden;
+ white-space: nowrap;
+}
+
+.timeText {
+ display: inline-block;
+ white-space: nowrap;
+ font-size: var(--tanstack-plain-cell-font-size, 14px);
+ line-height: var(--tanstack-plain-cell-line-height, 18px);
+ color: inherit;
+}
+
+.emptyState {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: var(--spacing-3);
+ padding: 48px 24px;
+ text-align: center;
+}
+
+.emptyIcon {
+ color: var(--l2-foreground);
+}
+
+.emptyTitle {
+ color: var(--l1-foreground);
+ font-size: 16px;
+ font-weight: 500;
+ line-height: 24px;
+}
+
+.emptySubtitle {
+ color: var(--l2-foreground);
+ font-size: 14px;
+ line-height: 20px;
+ max-width: 420px;
+}
+
+.docsLink {
+ color: var(--l2-foreground);
+ font-size: 13px;
+ text-decoration: none;
+
+ &:hover {
+ color: var(--l1-foreground);
+ text-decoration: underline;
+ }
+}
diff --git a/frontend/src/container/PlannedDowntime/PlannedDowntime.styles.scss b/frontend/src/container/PlannedDowntime/PlannedDowntime.styles.scss
index e65ec04b5b..ab33f270d0 100644
--- a/frontend/src/container/PlannedDowntime/PlannedDowntime.styles.scss
+++ b/frontend/src/container/PlannedDowntime/PlannedDowntime.styles.scss
@@ -109,191 +109,6 @@
}
}
-.planned-downtime-container {
- display: flex;
- justify-content: center;
- width: 100%;
-
- .planned-downtime-content {
- width: calc(100% - 30px);
- max-width: 736px;
-
- .title {
- color: var(--l1-foreground);
- font-size: var(--font-size-lg);
- font-style: normal;
- font-weight: var(--font-weight-normal);
- line-height: 28px;
- letter-spacing: -0.09px;
- }
-
- .subtitle {
- color: var(---bg-vanilla-400);
- font-size: var(--font-size-sm);
- font-style: normal;
- font-weight: var(--font-weight-normal);
- line-height: 20px;
- letter-spacing: -0.07px;
- }
-
- .ant-input-affix-wrapper {
- margin-top: 16px;
- margin-bottom: 8px;
- }
-
- .toolbar {
- display: flex;
- align-items: center;
- gap: 8px;
- margin-top: 12px;
- }
-
- .schedule-created-at {
- border: 1px solid var(--l1-border);
- background-color: var(--l2-background);
- border-top: 0px;
- width: 100%;
- padding: 8px 16px;
- gap: 6px;
- height: 40px;
- border-bottom-left-radius: 6px;
- border-bottom-right-radius: 6px;
-
- display: flex;
- align-items: center;
- .ant-typography {
- color: var(--l2-foreground);
- font-variant-numeric: lining-nums tabular-nums stacked-fractions
- slashed-zero;
- font-feature-settings:
- 'dlig' on,
- 'salt' on,
- 'cpsp' on,
- 'case' on;
- font-family: Inter;
- font-size: 14px;
- font-style: normal;
- font-weight: 400;
- line-height: 18px;
- letter-spacing: -0.07px;
- }
- }
-
- .ant-collapse-header {
- height: 56px;
- align-items: center;
- }
-
- .header-content {
- display: flex;
- gap: 8px;
-
- .ant-typography {
- color: var(--l2-foreground);
- font-variant-numeric: lining-nums tabular-nums stacked-fractions
- slashed-zero;
- font-feature-settings:
- 'dlig' on,
- 'salt' on,
- 'cpsp' on,
- 'case' on;
- font-family: Inter;
- font-size: 14px;
- font-style: normal;
- font-weight: 400;
- line-height: 18px;
- letter-spacing: -0.07px;
- }
-
- .action-btn {
- display: flex;
- align-items: center;
- gap: 20px;
- cursor: pointer;
-
- .hidden {
- display: none;
- }
- }
- }
- }
-}
-
-.new-downtime-menu {
- .create-downtime-menu-item {
- display: flex;
- align-items: center;
- gap: 8px;
- }
-}
-
-.planned-downtime-table {
- .ant-table {
- background: none !important;
- }
- .ant-table-cell {
- padding: 0 !important;
- border: 0 !important;
- width: 736px;
- }
-
- .ant-table-tbody {
- display: flex;
- flex-direction: column;
- gap: 16px;
-
- .collapse-list {
- border: 1px solid var(--l1-border);
- background-color: var(--l2-background);
- border-top-left-radius: 6px;
- border-top-right-radius: 6px;
-
- .render-item-collapse-list {
- margin-bottom: 13px;
- display: grid;
- grid-template-columns: 128px 1fr;
- }
-
- .alert-rule-collapse-list {
- width: 540px;
- max-height: 100px;
- overflow: auto;
- }
- .ant-collapse-content-active {
- border-top: 0;
- }
-
- .ant-collapse-item {
- border: none;
- }
- .ant-collapse-content-box {
- padding: 8px 20px 12px 38px;
-
- .render-item-value {
- .ant-typography {
- color: var(--l1-foreground);
- font-family: Inter;
- font-size: 14px;
- font-style: normal;
- font-weight: 400;
- line-height: 18px;
- }
- }
- }
-
- .ant-typography {
- color: var(--l2-foreground);
- font-family: Inter;
- font-size: 14px;
- font-style: normal;
- font-weight: 400;
- line-height: 20px; /* 142.857% */
- letter-spacing: -0.07px;
- }
- }
- }
-}
-
.delete-schedule-modal {
width: calc(100% - 30px) !important; /* Adjust the 20px as needed */
max-width: 384px;
diff --git a/frontend/src/container/PlannedDowntime/PlannedDowntime.tsx b/frontend/src/container/PlannedDowntime/PlannedDowntime.tsx
index 3b8d92ca93..72ae988ef1 100644
--- a/frontend/src/container/PlannedDowntime/PlannedDowntime.tsx
+++ b/frontend/src/container/PlannedDowntime/PlannedDowntime.tsx
@@ -1,36 +1,51 @@
-import React, { ChangeEvent, useEffect, useState } from 'react';
+import React, {
+ ChangeEvent,
+ useCallback,
+ useEffect,
+ useMemo,
+ useState,
+} from 'react';
import { useHistory } from 'react-router-dom';
import { Plus, Search } from '@signozhq/icons';
-import { Color } from '@signozhq/design-tokens';
+import { Button } from '@signozhq/ui/button';
import { Input } from '@signozhq/ui/input';
-import { Button, Flex, Form, Tooltip } from 'antd';
import { Typography } from '@signozhq/ui/typography';
+import { Form } from 'antd';
import {
useDeleteDowntimeScheduleByID,
useListDowntimeSchedules,
} from 'api/generated/services/downtimeschedules';
import { useListRules } from 'api/generated/services/rules';
import type { AlertmanagertypesPlannedMaintenanceDTO } from 'api/generated/services/sigNoz.schemas';
+import { ColumnSelector } from 'components/TanStackTableView';
+import TextToolTip from 'components/TextToolTip';
import dayjs from 'dayjs';
import useDebouncedFn from 'hooks/useDebouncedFunction';
import { useNotifications } from 'hooks/useNotifications';
import useUrlQuery from 'hooks/useUrlQuery';
import { useAppContext } from 'providers/App/App';
import { useErrorModal } from 'providers/ErrorModalProvider';
+import { useTimezone } from 'providers/Timezone';
import { USER_ROLES } from 'types/roles';
import 'dayjs/locale/en';
+import styles from './PlannedDowntime.module.scss';
import { PlannedDowntimeDeleteModal } from './PlannedDowntimeDeleteModal';
import { PlannedDowntimeForm } from './PlannedDowntimeForm';
-import { PlannedDowntimeList } from './PlannedDowntimeList';
+import PlannedDowntimeList from './PlannedDowntimeList';
import {
defaultInitialValues,
deleteDowntimeHandler,
} from './PlannedDowntimeutils';
+import { getPlannedDowntimeColumns } from './table.config';
+import { DowntimeSchedulesTableData } from './types';
+import usePlannedDowntimeTable from './usePlannedDowntimeTable';
import './PlannedDowntime.styles.scss';
+const COLUMNS_STORAGE_KEY = 'planned-downtime-columns';
+
dayjs.locale('en');
export function PlannedDowntime(): JSX.Element {
@@ -69,7 +84,7 @@ export function PlannedDowntime(): JSX.Element {
}
}, [form, isOpen]);
- const [searchValue, setSearchValue] = React.useState<string | number>(
+ const [searchValue, setSearchValue] = React.useState<string>(
urlQuery.get('search') || '',
);
const [deleteData, setDeleteData] = useState<{ id: string; name: string }>();
@@ -86,16 +101,62 @@ export function PlannedDowntime(): JSX.Element {
history.replace(url);
}, 300);
+ const {
+ containerRef,
+ calculatedPageSize,
+ filteredDowntimes,
+ pagedDowntimes,
+ setPage,
+ setLimit,
+ } = usePlannedDowntimeTable(
+ downtimeSchedules.data?.data || [],
+ alertOptions || [],
+ searchValue,
+ );
+
const handleSearch = (e: ChangeEvent<HTMLInputElement>): void => {
setSearchValue(e.target.value);
updateUrlWithSearch(e.target.value);
+ setPage(1);
};
const clearSearch = (): void => {
setSearchValue('');
updateUrlWithSearch('');
+ setPage(1);
};
+ const canEdit = user?.role !== USER_ROLES.VIEWER;
+ const { formatTimezoneAdjustedTimestamp } = useTimezone();
+ const columns = React.useMemo(
+ () => getPlannedDowntimeColumns(formatTimezoneAdjustedTimestamp),
+ [formatTimezoneAdjustedTimestamp],
+ );
+
+ const handleCreate = useCallback((): void => {
+ setInitialValues(defaultInitialValues);
+ setIsOpen(true);
+ setEditMode(false);
+ form.resetFields();
+ }, [form]);
+
+ const handleEdit = useCallback(
+ (downtime: DowntimeSchedulesTableData): void => {
+ setInitialValues({ ...downtime });
+ setIsOpen(true);
+ setEditMode(true);
+ },
+ [],
+ );
+
+ const handleDelete = useCallback(
+ (downtime: DowntimeSchedulesTableData): void => {
+ setDeleteData({ id: downtime.id, name: downtime.name });
+ setIsDeleteModalOpen(true);
+ },
+ [],
+ );
+
// Delete Downtime Schedule
const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
const { notifications } = useNotifications();
@@ -125,78 +186,107 @@ export function PlannedDowntime(): JSX.Element {
});
};
+ const isFetching = useMemo(
+ () => downtimeSchedules.isLoading || downtimeSchedules.isFetching,
+ [downtimeSchedules.isLoading, downtimeSchedules.isFetching],
+ );
+ const totalDowntimes = useMemo(
+ () => downtimeSchedules.data?.data?.length ?? 0,
+ [downtimeSchedules.data?.data?.length],
+ );
+ const isEmpty = useMemo(
+ () => !isFetching && !searchValue && totalDowntimes === 0,
+ [isFetching, searchValue, totalDowntimes],
+ );
+
return (
- <div className="planned-downtime-container">
- <div className="planned-downtime-content">
- <Typography.Title className="title">Planned Downtime</Typography.Title>
- <Typography.Text className="subtitle">
- Create and manage planned downtimes.
- </Typography.Text>
- <Flex className="toolbar">
+ <div className={styles.container}>
+ <header className={styles.headerBand}>
+ <div className={styles.commandHeader}>
+ <div className={styles.headingBlock}>
+ <Typography.Title className={styles.title}>
+ Planned Downtime
+ </Typography.Title>
+ <span className={styles.countPill}>{totalDowntimes}</span>
+ </div>
+ <div className={styles.grow} />
+ {!isEmpty && (
+ <ColumnSelector
+ columns={columns}
+ storageKey={COLUMNS_STORAGE_KEY}
+ testId="planned-downtime-columns"
+ />
+ )}
+ <Button
+ variant="solid"
+ color="primary"
+ size="sm"
+ prefix={<Plus size={14} />}
+ onClick={handleCreate}
+ disabled={!canEdit}
+ disabledTooltip="You need edit permissions to create a planned downtime"
+ testId="planned-downtime-create"
+ >
+ New downtime
+ </Button>
+ <TextToolTip
+ text="More details on how to schedule planned downtime"
+ url="https://signoz.io/docs/alerts-management/planned-maintenance/"
+ urlText="Learn More"
+ />
+ </div>
+
+ <div className={styles.filtersRow}>
<Input
- placeholder="Search for a planned downtime..."
- prefix={<Search size={12} color={Color.BG_VANILLA_400} />}
+ containerClassName={styles.searchInput}
+ placeholder="Search by name"
value={searchValue}
onChange={handleSearch}
+ suffix={<Search size={14} className={styles.searchIcon} />}
+ testId="planned-downtime-search"
/>
- <Tooltip
- title={
- user?.role === USER_ROLES.VIEWER
- ? 'You need edit permissions to create a planned downtime'
- : ''
- }
- >
- <Button
- type="primary"
- onClick={(): void => {
- setInitialValues(defaultInitialValues);
- setIsOpen(true);
- setEditMode(false);
- form.resetFields();
- }}
- disabled={user?.role === USER_ROLES.VIEWER}
- >
- <Flex align="center" gap={4}>
- <Plus size={16} />
- New downtime
- </Flex>
- </Button>
- </Tooltip>
- </Flex>
- <br />
+ </div>
+ </header>
+
+ <div ref={containerRef} className={styles.tableContainer}>
<PlannedDowntimeList
- downtimeSchedules={downtimeSchedules}
- alertOptions={alertOptions || []}
- setInitialValues={setInitialValues}
- setModalOpen={setIsOpen}
- handleDeleteDowntime={(id, name): void => {
- setDeleteData({ id, name });
- setIsDeleteModalOpen(true);
- }}
- setEditMode={setEditMode}
- searchValue={searchValue}
- />
- {isOpen && (
- <PlannedDowntimeForm
- alertOptions={alertOptions || []}
- initialValues={initialValues}
- isError={isError}
- isLoading={isLoading}
- isOpen={isOpen}
- setIsOpen={setIsOpen}
- refetchAllSchedules={refetchAllSchedules}
- isEditMode={isEditMode}
- form={form}
- />
- )}
- <PlannedDowntimeDeleteModal
- isDeleteLoading={isDeleteLoading}
- isDeleteModalOpen={isDeleteModalOpen}
- onDeleteHandler={onDeleteHandler}
- setIsDeleteModalOpen={setIsDeleteModalOpen}
- downtimeSchedule={deleteData?.name || ''}
+ columns={columns}
+ downtimes={filteredDowntimes}
+ pagedDowntimes={pagedDowntimes}
+ calculatedPageSize={calculatedPageSize}
+ onLimitChange={setLimit}
+ isFetching={isFetching}
+ isError={downtimeSchedules.isError}
+ refetch={refetchAllSchedules}
+ canEdit={canEdit}
+ onEdit={handleEdit}
+ onDelete={handleDelete}
+ onCreate={handleCreate}
+ hasSearchTerm={searchValue.length > 0}
+ onClearSearch={clearSearch}
/>
</div>
+
+ {isOpen && (
+ <PlannedDowntimeForm
+ alertOptions={alertOptions || []}
+ initialValues={initialValues}
+ isError={isError}
+ isLoading={isLoading}
+ isOpen={isOpen}
+ setIsOpen={setIsOpen}
+ refetchAllSchedules={refetchAllSchedules}
+ isEditMode={isEditMode}
+ form={form}
+ />
+ )}
+ <PlannedDowntimeDeleteModal
+ isDeleteLoading={isDeleteLoading}
+ isDeleteModalOpen={isDeleteModalOpen}
+ onDeleteHandler={onDeleteHandler}
+ setIsDeleteModalOpen={setIsDeleteModalOpen}
+ downtimeSchedule={deleteData?.name || ''}
+ />
</div>
);
}
diff --git a/frontend/src/container/PlannedDowntime/PlannedDowntimeActionsMenu.tsx b/frontend/src/container/PlannedDowntime/PlannedDowntimeActionsMenu.tsx
new file mode 100644
index 0000000000..1b114b9b01
--- /dev/null
+++ b/frontend/src/container/PlannedDowntime/PlannedDowntimeActionsMenu.tsx
@@ -0,0 +1,65 @@
+import { useMemo } from 'react';
+import { Ellipsis, PenLine, Trash2 } from '@signozhq/icons';
+import { Button } from '@signozhq/ui/button';
+import { Dropdown, type DropdownItemType } from '@signozhq/ui/dropdown';
+
+import styles from './PlannedDowntime.module.scss';
+import { DowntimeSchedulesTableData } from './types';
+
+interface PlannedDowntimeActionsMenuProps {
+ downtime: DowntimeSchedulesTableData;
+ onEdit: (downtime: DowntimeSchedulesTableData) => void;
+ onDelete: (downtime: DowntimeSchedulesTableData) => void;
+}
+
+function PlannedDowntimeActionsMenu({
+ downtime,
+ onEdit,
+ onDelete,
+}: PlannedDowntimeActionsMenuProps): JSX.Element {
+ const menuItems = useMemo<DropdownItemType[]>(
+ () => [
+ {
+ type: 'item',
+ value: 'edit',
+ label: 'Edit',
+ prefix: <PenLine size={14} />,
+ onClick: (): void => onEdit(downtime),
+ },
+ { type: 'separator', value: 'before-delete' },
+ {
+ type: 'item',
+ value: 'delete',
+ label: 'Delete',
+ prefix: <Trash2 size={14} />,
+ danger: true,
+ onClick: (): void => onDelete(downtime),
+ },
+ ],
+ [downtime, onEdit, onDelete],
+ );
+
+ return (
+ // the row itself opens the downtime, so the actions keep their clicks
+ // eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions
+ <div
+ className={styles.actions}
+ onClick={(event): void => event.stopPropagation()}
+ >
+ <Dropdown items={menuItems} nativeButton align="end" side="bottom">
+ <Button
+ variant="outlined"
+ color="secondary"
+ size="sm"
+ icon
+ testId={`downtime-actions-${downtime.id}`}
+ aria-label={`Actions for ${downtime.name}`}
+ >
+ <Ellipsis size={16} />
+ </Button>
+ </Dropdown>
+ </div>
+ );
+}
+
+export default PlannedDowntimeActionsMenu;
diff --git a/frontend/src/container/PlannedDowntime/PlannedDowntimeEmptyState.tsx b/frontend/src/container/PlannedDowntime/PlannedDowntimeEmptyState.tsx
new file mode 100644
index 0000000000..ea9597788b
--- /dev/null
+++ b/frontend/src/container/PlannedDowntime/PlannedDowntimeEmptyState.tsx
@@ -0,0 +1,53 @@
+import { CalendarClock, Plus } from '@signozhq/icons';
+import { Button } from '@signozhq/ui/button';
+import { Typography } from '@signozhq/ui/typography';
+
+import styles from './PlannedDowntime.module.scss';
+
+const DOCS_URL =
+ 'https://signoz.io/docs/alerts-management/planned-maintenance/';
+
+interface PlannedDowntimeEmptyStateProps {
+ canCreate: boolean;
+ onCreate: () => void;
+}
+
+function PlannedDowntimeEmptyState({
+ canCreate,
+ onCreate,
+}: PlannedDowntimeEmptyStateProps): JSX.Element {
+ return (
+ <div className={styles.emptyState} data-testid="planned-downtime-empty-state">
+ <CalendarClock className={styles.emptyIcon} size={16} />
+ <Typography.Text className={styles.emptyTitle}>
+ No planned downtime yet
+ </Typography.Text>
+ <Typography.Text className={styles.emptySubtitle}>
+ A planned downtime silences alert rules for a window you schedule, once or
+ on repeat, so maintenance does not page anyone.
+ </Typography.Text>
+ {canCreate && (
+ <Button
+ variant="solid"
+ color="primary"
+ size="md"
+ prefix={<Plus size={14} />}
+ onClick={onCreate}
+ testId="planned-downtime-empty-create"
+ >
+ New downtime
+ </Button>
+ )}
+ <a
+ className={styles.docsLink}
+ href={DOCS_URL}
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ Read the planned downtime guide
+ </a>
+ </div>
+ );
+}
+
+export default PlannedDowntimeEmptyState;
diff --git a/frontend/src/container/PlannedDowntime/PlannedDowntimeForm.tsx b/frontend/src/container/PlannedDowntime/PlannedDowntimeForm.tsx
index e26e2c5678..16b46b9869 100644
--- a/frontend/src/container/PlannedDowntime/PlannedDowntimeForm.tsx
+++ b/frontend/src/container/PlannedDowntime/PlannedDowntimeForm.tsx
@@ -43,7 +43,7 @@ import { ALL_TIME_ZONES } from 'utils/timeZoneUtil';
import 'dayjs/locale/en';
-import { AlertRuleTags } from './PlannedDowntimeList';
+import { AlertRuleTags } from './AlertRuleTags';
import {
getAlertOptionsFromIds,
getDurationInfo,
diff --git a/frontend/src/container/PlannedDowntime/PlannedDowntimeList.tsx b/frontend/src/container/PlannedDowntime/PlannedDowntimeList.tsx
index 8b9de16b03..99b72d6f66 100644
--- a/frontend/src/container/PlannedDowntime/PlannedDowntimeList.tsx
+++ b/frontend/src/container/PlannedDowntime/PlannedDowntimeList.tsx
@@ -1,379 +1,109 @@
-import React, { ReactNode, useEffect } from 'react';
-import { UseQueryResult } from 'react-query';
-import { Color } from '@signozhq/design-tokens';
-import { Collapse, Flex, Space, Table, TableProps, Tooltip } from 'antd';
-import { Badge } from '@signozhq/ui/badge';
-import { Pill } from '@signozhq/ui/pill';
-import { Typography } from '@signozhq/ui/typography';
-import type { DefaultOptionType } from 'antd/es/select';
-import type {
- ListDowntimeSchedules200,
- RenderErrorResponseDTO,
- AlertmanagertypesPlannedMaintenanceDTO,
- AlertmanagertypesScheduleDTO,
-} from 'api/generated/services/sigNoz.schemas';
-import type { ErrorType } from 'api/generatedAPIInstance';
-import cx from 'classnames';
-import dayjs from 'dayjs';
-import { useNotifications } from 'hooks/useNotifications';
-import { defaultTo } from 'lodash-es';
-import { CalendarClock, PenLine, Trash2 } from '@signozhq/icons';
-import { useAppContext } from 'providers/App/App';
-import { USER_ROLES } from 'types/roles';
-
-import { showErrorNotification } from 'utils/error';
-import {
- formatDateTime,
- getAlertOptionsFromIds,
- getDuration,
- recurrenceInfo,
-} from './PlannedDowntimeutils';
-
-import './PlannedDowntime.styles.scss';
-
-const { Panel } = Collapse;
-
-interface AlertRuleTagsProps {
- selectedTags: DefaultOptionType | DefaultOptionType[];
- closable: boolean;
- handleClose?: (removedTag: DefaultOptionType['value']) => void;
- classname?: string;
-}
-export function AlertRuleTags(props: AlertRuleTagsProps): JSX.Element {
- const { closable, selectedTags, handleClose, classname } = props;
- return (
- <Space
- wrap
- style={{ marginBottom: 8 }}
- className={cx('alert-rule-tags', classname)}
- >
- {selectedTags?.map((tag: DefaultOptionType, index: number) => {
- if (closable) {
- return (
- <Pill.Closeable
- key={tag.value}
- maxWidth={200}
- onClose={(): void => handleClose?.(tag.value)}
- >
- {tag.label}
- </Pill.Closeable>
- );
- }
-
- const isLongTag = (tag?.label as string)?.length > 20;
- const tagElem = (
- <Badge
- textTransform="none"
- key={tag.value}
- color={index % 2 ? 'highlight-danger' : 'primary'}
- variant="outlined"
- >
- {isLongTag
- ? `${(tag?.label as string | null)?.slice(0, 20)}...`
- : tag?.label}
- </Badge>
- );
- return (
- <Tooltip title={isLongTag ? tag?.label : undefined} key={tag?.value}>
- {tagElem}
- </Tooltip>
- );
- })}
- </Space>
- );
-}
-
-function HeaderComponent({
- name,
- duration,
- handleEdit,
- handleDelete,
-}: {
- name: string;
- duration: string;
- handleEdit: () => void;
- handleDelete: () => void;
-}): JSX.Element {
- const { user } = useAppContext();
- const isCrudEnabled = user?.role !== USER_ROLES.VIEWER;
- return (
- <Flex className="header-content" justify="space-between">
- <Flex gap={8}>
- <Typography>{name}</Typography>
- <Badge textTransform="none" variant="solid" color="secondary">
- {duration}
- </Badge>
- </Flex>
-
- {isCrudEnabled && (
- <div className="action-btn">
- <PenLine
- size={14}
- onClick={(e): void => {
- e.preventDefault();
- e.stopPropagation();
- handleEdit();
- }}
- />
- <Trash2
- size={14}
- color={Color.BG_CHERRY_500}
- onClick={(e): void => {
- e.preventDefault();
- e.stopPropagation();
- handleDelete();
- }}
- />
- </div>
- )}
- </Flex>
- );
-}
-
-export function CollapseListContent({
- created_at,
- created_by_name,
- created_by_email,
- schedule,
- updated_at,
- updated_by_name,
- alertOptions,
-}: {
- created_at?: string;
- created_by_name?: string;
- created_by_email?: string;
- schedule?: AlertmanagertypesScheduleDTO;
- updated_at?: string;
- updated_by_name?: string;
- alertOptions?: DefaultOptionType[];
-}): JSX.Element {
- const renderItems = (title: string, value: ReactNode): JSX.Element => (
- <div className="render-item-collapse-list">
- <Typography>{title}</Typography>
- <div className="render-item-value">{value}</div>
- </div>
- );
- const startTime = formatDateTime(schedule?.startTime, schedule?.timezone);
- const endTime = formatDateTime(schedule?.endTime, schedule?.timezone);
-
- return (
- <Flex vertical>
- {renderItems(
- 'Created by',
- created_by_name ? (
- <Flex gap={8}>
- <Typography>{created_by_name}</Typography>
- {created_by_email && (
- <Badge textTransform="none" variant="solid" color="secondary">
- {created_by_email}
- </Badge>
- )}
- </Flex>
- ) : (
- '-'
- ),
- )}
- {renderItems(
- 'Created on',
- created_at ? (
- <Typography>{`${formatDateTime(created_at)}`}</Typography>
- ) : (
- '-'
- ),
- )}
- {updated_at &&
- renderItems(
- 'Updated on',
- <Typography>{`${formatDateTime(updated_at)}`}</Typography>,
- )}
- {updated_by_name &&
- renderItems('Updated by', <Typography>{updated_by_name}</Typography>)}
-
- {renderItems(
- 'Timeframe',
- schedule?.startTime ? (
- <Typography>{`${startTime} ⎯ ${endTime}`}</Typography>
- ) : (
- '-'
- ),
- )}
- {renderItems(
- 'Timezone',
- <Typography>{schedule?.timezone || '-'}</Typography>,
- )}
- {renderItems('Repeats', <Typography>{recurrenceInfo(schedule)}</Typography>)}
- {renderItems(
- 'Alerts silenced',
- alertOptions?.length ? (
- <AlertRuleTags
- closable={false}
- classname="alert-rule-collapse-list"
- selectedTags={alertOptions}
- />
- ) : (
- <Badge variant="solid" color="secondary">
- All alert rules
- </Badge>
- ),
- )}
- </Flex>
- );
-}
-
-export function CustomCollapseList(
- props: DowntimeSchedulesTableData & {
- setInitialValues: React.Dispatch<
- React.SetStateAction<Partial<AlertmanagertypesPlannedMaintenanceDTO>>
- >;
- setModalOpen: React.Dispatch<React.SetStateAction<boolean>>;
- handleDeleteDowntime: (id: string, name: string) => void;
- setEditMode: React.Dispatch<React.SetStateAction<boolean>>;
- },
-): JSX.Element {
- const {
- createdAt,
- createdBy,
- schedule,
- updatedAt,
- updatedBy,
- name,
- id,
- alertOptions,
- setInitialValues,
- setModalOpen,
- handleDeleteDowntime,
- setEditMode,
- } = props;
-
- const scheduleTime = schedule?.startTime
- ? dayjs(schedule.startTime).tz(schedule.timezone)
- : createdAt || '';
- const formattedDateAndTime = `Start time ⎯ ${formatDateTime(scheduleTime)} ${schedule?.timezone}`;
-
- return (
- <>
- <Collapse accordion className="collapse-list">
- <Panel
- header={
- <HeaderComponent
- duration={
- schedule?.recurrence?.duration
- ? schedule.recurrence.duration
- : getDuration(schedule?.startTime || '', schedule?.endTime || '')
- }
- name={defaultTo(name, '')}
- handleEdit={() => {
- setInitialValues({ ...props });
- setModalOpen(true);
- setEditMode(true);
- }}
- handleDelete={() => handleDeleteDowntime(id ?? '', name || '')}
- />
- }
- key={id ?? ''}
- >
- <CollapseListContent
- created_at={createdAt ? dayjs(createdAt).toISOString() : ''}
- created_by_name={defaultTo(createdBy, '')}
- schedule={schedule}
- updated_at={updatedAt ? dayjs(updatedAt).toISOString() : ''}
- updated_by_name={defaultTo(updatedBy, '')}
- alertOptions={alertOptions}
- />
- </Panel>
- </Collapse>
- <div className="schedule-created-at">
- <CalendarClock size={14} />
- <Typography.Text>{formattedDateAndTime}</Typography.Text>
- </div>
- </>
- );
-}
-
-export type DowntimeSchedulesTableData =
- AlertmanagertypesPlannedMaintenanceDTO & {
- alertOptions: DefaultOptionType[];
- };
-
-export function PlannedDowntimeList({
- downtimeSchedules,
- alertOptions,
- setInitialValues,
- setModalOpen,
- handleDeleteDowntime,
- setEditMode,
- searchValue,
-}: {
- downtimeSchedules: UseQueryResult<
- ListDowntimeSchedules200,
- ErrorType<RenderErrorResponseDTO>
- >;
- alertOptions: DefaultOptionType[];
- setInitialValues: React.Dispatch<
- React.SetStateAction<Partial<AlertmanagertypesPlannedMaintenanceDTO>>
- >;
- setModalOpen: React.Dispatch<React.SetStateAction<boolean>>;
- handleDeleteDowntime: (id: string, name: string) => void;
- setEditMode: React.Dispatch<React.SetStateAction<boolean>>;
- searchValue: string | number;
-}): JSX.Element {
- const columns: TableProps<DowntimeSchedulesTableData>['columns'] = [
- {
- title: 'Downtime',
- key: 'downtime',
- render: (data: DowntimeSchedulesTableData): JSX.Element =>
- CustomCollapseList({
- ...data,
- setInitialValues,
- setModalOpen,
- handleDeleteDowntime,
- setEditMode,
- }),
- },
- ];
- const { notifications } = useNotifications();
-
- const tableData = [...(downtimeSchedules.data?.data || [])]
- .sort((a, b): number => {
- if (a?.updatedAt && b?.updatedAt) {
- return dayjs(b.updatedAt).diff(dayjs(a.updatedAt));
+import { useMemo } from 'react';
+import ErrorEmptyState from 'components/Alerts/ErrorEmptyState';
+import NoResultsEmptyState from 'components/Alerts/NoResultsEmptyState';
+import TanStackTable, { TableColumnDef } from 'components/TanStackTableView';
+
+import styles from './PlannedDowntime.module.scss';
+import PlannedDowntimeActionsMenu from './PlannedDowntimeActionsMenu';
+import PlannedDowntimeEmptyState from './PlannedDowntimeEmptyState';
+import { DowntimeSchedulesTableData, PlannedDowntimeListProps } from './types';
+import { PLANNED_DOWNTIME_QUERY_PARAMS } from './usePlannedDowntimeTable';
+
+function PlannedDowntimeList({
+ columns,
+ downtimes,
+ pagedDowntimes,
+ calculatedPageSize,
+ onLimitChange,
+ isFetching,
+ isError,
+ refetch,
+ canEdit,
+ onEdit,
+ onDelete,
+ onCreate,
+ hasSearchTerm,
+ onClearSearch,
+}: PlannedDowntimeListProps): JSX.Element {
+ const columnsWithActions =
+ useMemo((): TableColumnDef<DowntimeSchedulesTableData>[] => {
+ if (!canEdit) {
+ return columns;
}
- return 0;
- })
- .filter(
- (data) =>
- data.name.includes(searchValue.toLocaleString()) ||
- data.id === searchValue.toLocaleString(),
- )
- .map((data) => {
- const specificAlertOptions = getAlertOptionsFromIds(
- data.alertIds || [],
- alertOptions,
- );
-
- return { ...data, alertOptions: specificAlertOptions };
- });
- useEffect(() => {
- if (downtimeSchedules.isError) {
- showErrorNotification(notifications, downtimeSchedules.error);
- }
- }, [downtimeSchedules.error, downtimeSchedules.isError, notifications]);
+ return [
+ ...columns,
+ {
+ id: 'actions',
+ header: (): JSX.Element => (
+ <span className={styles.actionsHeader}>Actions</span>
+ ),
+ accessorKey: 'id',
+ width: { fixed: '96px', ignoreLastColumnFill: true },
+ enableSort: false,
+ enableResize: false,
+ enableRemove: false,
+ enableMove: false,
+ pin: 'right',
+ cell: ({ row }): JSX.Element => (
+ <PlannedDowntimeActionsMenu
+ downtime={row}
+ onEdit={onEdit}
+ onDelete={onDelete}
+ />
+ ),
+ },
+ ];
+ }, [canEdit, columns, onEdit, onDelete]);
+
+ const isEmpty = !isFetching && downtimes.length === 0;
+
+ if (isError) {
+ return (
+ <ErrorEmptyState
+ title="Failed to load planned downtime"
+ onRefresh={refetch}
+ />
+ );
+ }
+
+ if (isEmpty && hasSearchTerm) {
+ return (
+ <NoResultsEmptyState
+ title="No matching planned downtime"
+ subtitle="No planned downtime matches your search. Try adjusting your search criteria."
+ onClear={onClearSearch}
+ clearButtonText="Clear Search"
+ />
+ );
+ }
+
+ if (isEmpty) {
+ return <PlannedDowntimeEmptyState canCreate={canEdit} onCreate={onCreate} />;
+ }
- const paginationConfig = {
- pageSize: 5,
- showSizeChanger: false,
- hideOnSinglePage: true,
- };
return (
- <Table<DowntimeSchedulesTableData>
- columns={columns}
- className="planned-downtime-table"
- bordered={false}
- dataSource={tableData || []}
- loading={downtimeSchedules.isLoading || downtimeSchedules.isFetching}
- showHeader={false}
- pagination={paginationConfig}
+ <TanStackTable<DowntimeSchedulesTableData>
+ data={pagedDowntimes}
+ columns={columnsWithActions}
+ isLoading={isFetching}
+ getRowKey={(row): string => row.id}
+ getItemKey={(row): string => row.id}
+ getRowTestId={(row): string => `downtime-row-${row.id}`}
+ columnStorageKey="planned-downtime-columns"
+ enableQueryParams={PLANNED_DOWNTIME_QUERY_PARAMS}
+ onRowClick={canEdit ? onEdit : undefined}
+ pagination={{
+ total: downtimes.length,
+ calculatedPageSize,
+ onLimitChange,
+ showTotalCount: true,
+ }}
+ paginationClassname={styles.paginationContainer}
+ enableAlternatingRowColors
+ plainTextCellLineClamp={1}
/>
);
}
+
+export default PlannedDowntimeList;
diff --git a/frontend/src/container/PlannedDowntime/PlannedDowntimeutils.ts b/frontend/src/container/PlannedDowntime/PlannedDowntimeutils.ts
index 5e53ae7802..dc81ae2805 100644
--- a/frontend/src/container/PlannedDowntime/PlannedDowntimeutils.ts
+++ b/frontend/src/container/PlannedDowntime/PlannedDowntimeutils.ts
@@ -1,6 +1,5 @@
import { UseMutateAsyncFunction } from 'react-query';
import type { NotificationInstance } from 'antd/es/notification/interface';
-import type { DefaultOptionType } from 'antd/es/select';
import { convertToApiError } from 'api/ErrorResponseHandlerForGeneratedAPIs';
import type {
DeleteDowntimeScheduleByIDPathParameters,
@@ -13,6 +12,8 @@ import { AxiosError } from 'axios';
import { DATE_TIME_FORMATS } from 'constants/dateTimeFormats';
import dayjs, { Dayjs } from 'dayjs';
import { isEmpty } from 'lodash-es';
+
+import type { DowntimeAlertOption } from './types';
import APIError from 'types/api/error';
type DateTimeString = string | null | undefined;
@@ -56,8 +57,8 @@ export const formatDateTime = (
export const getAlertOptionsFromIds = (
alertIds: string[],
- alertOptions: DefaultOptionType[],
-): DefaultOptionType[] =>
+ alertOptions: DowntimeAlertOption[],
+): DowntimeAlertOption[] =>
alertOptions.filter(
(alert) =>
alert !== undefined &&
@@ -221,3 +222,48 @@ export const recurrenceOptionWithSubmenu: Option[] = [
export const isScheduleRecurring = (
schedule?: AlertmanagertypesPlannedMaintenanceDTO['schedule'] | null,
): boolean => (schedule ? !isEmpty(schedule?.recurrence) : false);
+
+const REPEAT_TYPE_LABEL: Record<string, string> = {
+ daily: 'Daily',
+ weekly: 'Weekly',
+ monthly: 'Monthly',
+};
+
+export const formatRepeats = (
+ schedule: AlertmanagertypesScheduleDTO,
+): string => {
+ const recurrence = schedule.recurrence;
+ if (!recurrence) {
+ return 'Does not repeat';
+ }
+
+ const label =
+ REPEAT_TYPE_LABEL[recurrence.repeatType] ?? recurrence.repeatType;
+ const days = recurrence.repeatOn?.length
+ ? ` on ${recurrence.repeatOn
+ .map((day) => day.charAt(0).toUpperCase() + day.slice(1, 3))
+ .join(', ')}`
+ : '';
+ const duration = recurrence.duration ? ` · ${recurrence.duration}` : '';
+ return `${label}${days}${duration}`;
+};
+
+export const formatWindow = (
+ schedule: AlertmanagertypesScheduleDTO,
+): string => {
+ if (!schedule.startTime) {
+ return '-';
+ }
+ const start = formatDateTime(schedule.startTime, schedule.timezone);
+ const timezone = schedule.timezone ? ` (${schedule.timezone})` : '';
+ if (!schedule.endTime) {
+ return `From ${start}${timezone}`;
+ }
+ return `${start} ⎯ ${formatDateTime(schedule.endTime, schedule.timezone)}${timezone}`;
+};
+
+export const formatScheduleDuration = (
+ schedule: AlertmanagertypesScheduleDTO,
+): string =>
+ schedule.recurrence?.duration ||
+ getDuration(schedule.startTime, schedule.endTime);
diff --git a/frontend/src/container/PlannedDowntime/__test__/AlertRuleTags.test.tsx b/frontend/src/container/PlannedDowntime/__test__/AlertRuleTags.test.tsx
index 101d8af886..e674a9e940 100644
--- a/frontend/src/container/PlannedDowntime/__test__/AlertRuleTags.test.tsx
+++ b/frontend/src/container/PlannedDowntime/__test__/AlertRuleTags.test.tsx
@@ -2,7 +2,7 @@ import { screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { render } from 'tests/test-utils';
-import { AlertRuleTags } from '../PlannedDowntimeList';
+import { AlertRuleTags } from '../AlertRuleTags';
const RULES = [
{ label: 'Postgres connections near limit', value: 'rule-5' },
diff --git a/frontend/src/container/PlannedDowntime/__test__/PlannedDowntime.test.tsx b/frontend/src/container/PlannedDowntime/__test__/PlannedDowntime.test.tsx
index e485c3af7e..bdf1c896c8 100644
--- a/frontend/src/container/PlannedDowntime/__test__/PlannedDowntime.test.tsx
+++ b/frontend/src/container/PlannedDowntime/__test__/PlannedDowntime.test.tsx
@@ -1,21 +1,34 @@
import { UseQueryResult } from 'react-query';
+import { VirtuosoMockContext } from 'react-virtuoso';
import { fireEvent, screen } from '@testing-library/react';
import type {
ListDowntimeSchedules200,
RenderErrorResponseDTO,
} from 'api/generated/services/sigNoz.schemas';
-import type { ErrorType } from 'api/generatedAPIInstance';
import {
- mockLocation,
- mockQueryParams,
-} from 'container/RoutingPolicies/__tests__/testUtils';
-import { render } from 'tests/test-utils';
+ AlertmanagertypesRepeatOnDTO,
+ AlertmanagertypesRepeatTypeDTO,
+} from 'api/generated/services/sigNoz.schemas';
+import type { ErrorType } from 'api/generatedAPIInstance';
+import { mockLocation } from 'container/RoutingPolicies/__tests__/testUtils';
+import { render, userEvent } from 'tests/test-utils';
import { USER_ROLES } from 'types/roles';
import { PlannedDowntime } from '../PlannedDowntime';
import { buildSchedule, createMockDowntime } from './testUtils';
-const SEARCH_PLACEHOLDER = 'Search for a planned downtime...';
+const SEARCH_TEST_ID = 'planned-downtime-search';
+const CREATE_TEST_ID = 'planned-downtime-create';
+
+function renderPage(role: string = USER_ROLES.ADMIN): void {
+ render(
+ <VirtuosoMockContext.Provider value={{ viewportHeight: 800, itemHeight: 46 }}>
+ <PlannedDowntime />
+ </VirtuosoMockContext.Provider>,
+ {},
+ { role },
+ );
+}
const MOCK_DOWNTIME_1_NAME = 'Mock Downtime 1';
const MOCK_DOWNTIME_2_NAME = 'Mock Downtime 2';
@@ -27,11 +40,19 @@ const MOCK_DATE_3 = '2024-01-03';
const MOCK_DOWNTIME_1 = createMockDowntime({
id: '1',
name: MOCK_DOWNTIME_1_NAME,
+ description: 'Database maintenance',
createdAt: MOCK_DATE_1,
+ createdBy: '[email protected]',
updatedAt: MOCK_DATE_1,
+ updatedBy: '[email protected]',
schedule: buildSchedule({
startTime: MOCK_DATE_1,
- timezone: 'UTC',
+ timezone: 'Asia/Kolkata',
+ recurrence: {
+ duration: '2h',
+ repeatType: AlertmanagertypesRepeatTypeDTO.weekly,
+ repeatOn: [AlertmanagertypesRepeatOnDTO.monday],
+ },
}),
alertIds: [],
});
@@ -126,113 +147,152 @@ jest.mock('api/generated/services/rules', () => ({
describe('PlannedDowntime Component', () => {
beforeEach(() => {
jest.clearAllMocks();
- mockUrlQuery = mockQueryParams({});
+ mockUrlQuery = new URLSearchParams();
mockLocation('/alerts');
});
- it('renders the PlannedDowntime component properly', () => {
- render(<PlannedDowntime />, {}, { role: 'ADMIN' });
+ it('renders the header, search and create action', () => {
+ renderPage();
- // Check if title is rendered
expect(screen.getByText('Planned Downtime')).toBeInTheDocument();
-
- // Check if subtitle is rendered
- expect(
- screen.getByText('Create and manage planned downtimes.'),
- ).toBeInTheDocument();
-
- // Check if search input is rendered
- expect(screen.getByPlaceholderText(SEARCH_PLACEHOLDER)).toBeInTheDocument();
-
- // Check if "New downtime" button is enabled for ADMIN
- const newDowntimeButton = screen.getByRole('button', {
- name: /new downtime/i,
- });
- expect(newDowntimeButton).toBeInTheDocument();
- expect(newDowntimeButton).not.toBeDisabled();
+ expect(screen.getByTestId(SEARCH_TEST_ID)).toBeInTheDocument();
+ expect(screen.getByTestId(CREATE_TEST_ID)).toHaveAttribute(
+ 'aria-disabled',
+ 'false',
+ );
});
it('disables the "New downtime" button for users with VIEWER role', () => {
- render(<PlannedDowntime />, {}, { role: USER_ROLES.VIEWER });
-
- // Check if "New downtime" button is disabled for VIEWER
- const newDowntimeButton = screen.getByRole('button', {
- name: /new downtime/i,
- });
- expect(newDowntimeButton).toBeInTheDocument();
- expect(newDowntimeButton).toBeDisabled();
+ renderPage(USER_ROLES.VIEWER);
- expect(newDowntimeButton).toHaveAttribute('disabled');
+ expect(screen.getByTestId(CREATE_TEST_ID)).toHaveAttribute(
+ 'aria-disabled',
+ 'true',
+ );
});
it('should load with search term from URL query params', () => {
const searchTerm = 'existing search';
- mockUrlQuery = mockQueryParams({ search: searchTerm });
+ mockUrlQuery = new URLSearchParams({ search: searchTerm });
- render(<PlannedDowntime />, {}, { role: USER_ROLES.ADMIN });
+ renderPage();
- const searchInput = screen.getByPlaceholderText(
- SEARCH_PLACEHOLDER,
- ) as HTMLInputElement;
+ const searchInput = screen.getByTestId(SEARCH_TEST_ID) as HTMLInputElement;
expect(searchInput.value).toBe(searchTerm);
});
it('should initialize with empty search when no search param is in URL', () => {
- mockUrlQuery = mockQueryParams({});
-
- render(<PlannedDowntime />, {}, { role: USER_ROLES.ADMIN });
+ renderPage();
- const searchInput = screen.getByPlaceholderText(
- SEARCH_PLACEHOLDER,
- ) as HTMLInputElement;
+ const searchInput = screen.getByTestId(SEARCH_TEST_ID) as HTMLInputElement;
expect(searchInput.value).toBe('');
});
it('should display all downtime schedules when no search term is entered', async () => {
- render(<PlannedDowntime />, {}, { role: USER_ROLES.ADMIN });
+ renderPage();
- expect(screen.getByText(MOCK_DOWNTIME_1_NAME)).toBeInTheDocument();
+ await expect(
+ screen.findByText(MOCK_DOWNTIME_1_NAME),
+ ).resolves.toBeInTheDocument();
expect(screen.getByText(MOCK_DOWNTIME_2_NAME)).toBeInTheDocument();
expect(screen.getByText(MOCK_DOWNTIME_3_NAME)).toBeInTheDocument();
});
- it('should filter downtime schedules by name when searching', async () => {
- render(<PlannedDowntime />, {}, { role: USER_ROLES.ADMIN });
+ it('shows the key schedule details and hides secondary columns by default', async () => {
+ renderPage();
+
+ await screen.findByText(MOCK_DOWNTIME_1_NAME);
+ expect(screen.getByText(/\(Asia\/Kolkata\)$/)).toBeInTheDocument();
+ expect(screen.getByText('Weekly on Mon · 2h')).toBeInTheDocument();
+ expect(screen.queryByText('Asia/Kolkata')).not.toBeInTheDocument();
+ expect(screen.queryByText('2h')).not.toBeInTheDocument();
+ expect(screen.queryByText('Database maintenance')).not.toBeInTheDocument();
+ expect(screen.queryByText('[email protected]')).not.toBeInTheDocument();
+ expect(screen.queryByText('[email protected]')).not.toBeInTheDocument();
+ expect(screen.getAllByText('All alert rules')).toHaveLength(3);
+ expect(screen.getAllByText('Active')).toHaveLength(3);
+ });
+
+ it('lets every data column be resized', async () => {
+ renderPage();
+
+ await screen.findByText(MOCK_DOWNTIME_1_NAME);
+ const resizable = Array.from(document.querySelectorAll('th'))
+ .filter((th) => th.querySelector('[title="Drag to resize column"]'))
+ .map((th) => th.textContent?.trim());
+ expect(resizable).toStrictEqual([
+ 'Downtime',
+ 'Status',
+ 'Schedule',
+ 'Repeats',
+ 'Alerts Silenced',
+ ]);
+ });
- expect(screen.getByText(MOCK_DOWNTIME_1_NAME)).toBeInTheDocument();
+ it('should filter downtime schedules by name when searching', async () => {
+ renderPage();
- const searchInput = screen.getByPlaceholderText(SEARCH_PLACEHOLDER);
+ await expect(
+ screen.findByText(MOCK_DOWNTIME_1_NAME),
+ ).resolves.toBeInTheDocument();
- fireEvent.change(searchInput, { target: { value: MOCK_DOWNTIME_1_NAME } });
+ fireEvent.change(screen.getByTestId(SEARCH_TEST_ID), {
+ target: { value: MOCK_DOWNTIME_1_NAME },
+ });
- expect(screen.getByText(MOCK_DOWNTIME_1_NAME)).toBeInTheDocument();
+ await expect(
+ screen.findByText(MOCK_DOWNTIME_1_NAME),
+ ).resolves.toBeInTheDocument();
expect(screen.queryByText(MOCK_DOWNTIME_2_NAME)).not.toBeInTheDocument();
expect(screen.queryByText(MOCK_DOWNTIME_3_NAME)).not.toBeInTheDocument();
});
it('should filter downtime schedules with partial name match', async () => {
- render(<PlannedDowntime />, {}, { role: USER_ROLES.ADMIN });
+ renderPage();
- expect(screen.getByText(MOCK_DOWNTIME_1_NAME)).toBeInTheDocument();
+ await expect(
+ screen.findByText(MOCK_DOWNTIME_1_NAME),
+ ).resolves.toBeInTheDocument();
- const searchInput = screen.getByPlaceholderText(SEARCH_PLACEHOLDER);
-
- fireEvent.change(searchInput, { target: { value: '2' } });
+ fireEvent.change(screen.getByTestId(SEARCH_TEST_ID), {
+ target: { value: '2' },
+ });
- expect(screen.getByText(MOCK_DOWNTIME_2_NAME)).toBeInTheDocument();
+ await expect(
+ screen.findByText(MOCK_DOWNTIME_2_NAME),
+ ).resolves.toBeInTheDocument();
expect(screen.queryByText(MOCK_DOWNTIME_1_NAME)).not.toBeInTheDocument();
expect(screen.queryByText(MOCK_DOWNTIME_3_NAME)).not.toBeInTheDocument();
});
it('should show no results when search term matches nothing', async () => {
- render(<PlannedDowntime />, {}, { role: USER_ROLES.ADMIN });
-
- const searchInput = screen.getByPlaceholderText(SEARCH_PLACEHOLDER);
+ renderPage();
- fireEvent.change(searchInput, { target: { value: 'NonExistentDowntime' } });
+ fireEvent.change(screen.getByTestId(SEARCH_TEST_ID), {
+ target: { value: 'NonExistentDowntime' },
+ });
+ await expect(
+ screen.findByTestId('no-results-empty-state'),
+ ).resolves.toBeInTheDocument();
expect(screen.queryByText(MOCK_DOWNTIME_1_NAME)).not.toBeInTheDocument();
- expect(screen.queryByText(MOCK_DOWNTIME_2_NAME)).not.toBeInTheDocument();
- expect(screen.queryByText(MOCK_DOWNTIME_3_NAME)).not.toBeInTheDocument();
+ });
+
+ it('opens the delete confirmation from the row actions', async () => {
+ renderPage();
+
+ await userEvent.click(await screen.findByTestId('downtime-actions-1'));
+ await userEvent.click(await screen.findByText('Delete'));
+
+ await expect(
+ screen.findByRole('button', { name: 'Delete Schedule' }),
+ ).resolves.toBeInTheDocument();
+ });
+
+ it('hides row actions for viewers', async () => {
+ renderPage(USER_ROLES.VIEWER);
+
+ await screen.findByText(MOCK_DOWNTIME_1_NAME);
+ expect(screen.queryByTestId('downtime-actions-1')).not.toBeInTheDocument();
});
});
diff --git a/frontend/src/container/PlannedDowntime/table.config.tsx b/frontend/src/container/PlannedDowntime/table.config.tsx
new file mode 100644
index 0000000000..d56f81b1f1
--- /dev/null
+++ b/frontend/src/container/PlannedDowntime/table.config.tsx
@@ -0,0 +1,236 @@
+import { Badge } from '@signozhq/ui/badge';
+import { AlertmanagertypesMaintenanceStatusDTO } from 'api/generated/services/sigNoz.schemas';
+import type { TableColumnDef } from 'components/TanStackTableView';
+import TanStackTable from 'components/TanStackTableView';
+import { DATE_TIME_FORMATS } from 'constants/dateTimeFormats';
+import { toRelativeTime } from 'pages/AlertList/NotificationChannels/utils/relativeTime';
+
+import styles from './PlannedDowntime.module.scss';
+import {
+ formatRepeats,
+ formatScheduleDuration,
+ formatWindow,
+} from './PlannedDowntimeutils';
+import { DowntimeSchedulesTableData } from './types';
+
+const STATUS_BADGE: Record<
+ AlertmanagertypesMaintenanceStatusDTO,
+ { label: string; color: 'success' | 'info' | 'secondary' }
+> = {
+ [AlertmanagertypesMaintenanceStatusDTO.active]: {
+ label: 'Active',
+ color: 'success',
+ },
+ [AlertmanagertypesMaintenanceStatusDTO.upcoming]: {
+ label: 'Upcoming',
+ color: 'info',
+ },
+ [AlertmanagertypesMaintenanceStatusDTO.expired]: {
+ label: 'Expired',
+ color: 'secondary',
+ },
+};
+
+export function getPlannedDowntimeColumns(
+ formatTimezoneAdjustedTimestamp: (date: string, format: string) => string,
+): TableColumnDef<DowntimeSchedulesTableData>[] {
+ const textCell = (value: string | undefined): JSX.Element => (
+ <TanStackTable.Text title={value || undefined}>
+ {value || '-'}
+ </TanStackTable.Text>
+ );
+
+ const timestampCell = (
+ row: DowntimeSchedulesTableData,
+ value: string | undefined,
+ ): JSX.Element => {
+ if (!value) {
+ return <TanStackTable.Text>-</TanStackTable.Text>;
+ }
+
+ return (
+ <TanStackTable.HoverTooltip
+ rowId={row.id}
+ title={formatTimezoneAdjustedTimestamp(
+ value,
+ DATE_TIME_FORMATS.DASH_DATETIME,
+ )}
+ >
+ <span className={styles.timeText}>{toRelativeTime(value)}</span>
+ </TanStackTable.HoverTooltip>
+ );
+ };
+
+ return [
+ {
+ id: 'name',
+ header: 'Downtime',
+ accessorKey: 'name',
+ width: { default: '100%', min: '200px' },
+ enableSort: true,
+ enableResize: true,
+ enableRemove: false,
+ enableMove: false,
+ cell: ({ row }): JSX.Element => (
+ <TanStackTable.Text
+ title={row.name}
+ data-testid={`downtime-row-${row.id}-name`}
+ >
+ {row.name}
+ </TanStackTable.Text>
+ ),
+ },
+ {
+ id: 'status',
+ header: 'Status',
+ accessorKey: 'status',
+ width: { default: '110px', min: '100px' },
+ enableSort: true,
+ enableResize: true,
+ enableMove: false,
+ cell: ({ row }): JSX.Element => {
+ const status = STATUS_BADGE[row.status];
+ return status ? (
+ <Badge textTransform="none" variant="outlined" color={status.color}>
+ {status.label}
+ </Badge>
+ ) : (
+ textCell(row.status)
+ );
+ },
+ },
+ {
+ id: 'window',
+ header: 'Schedule',
+ accessorFn: (row) => row.schedule?.startTime,
+ width: { default: '340px', min: '220px' },
+ enableSort: true,
+ enableResize: true,
+ enableMove: false,
+ cell: ({ row }): JSX.Element => textCell(formatWindow(row.schedule)),
+ },
+ {
+ id: 'timezone',
+ header: 'Timezone',
+ accessorFn: (row) => row.schedule?.timezone,
+ width: { default: '130px', min: '110px' },
+ defaultVisibility: false,
+ enableSort: false,
+ enableResize: true,
+ enableMove: false,
+ cell: ({ row }): JSX.Element => textCell(row.schedule?.timezone),
+ },
+ {
+ id: 'repeats',
+ header: 'Repeats',
+ accessorFn: (row) => row.schedule?.recurrence?.repeatType,
+ width: { default: '180px', min: '120px' },
+ enableSort: false,
+ enableResize: true,
+ enableMove: false,
+ cell: ({ row }): JSX.Element => textCell(formatRepeats(row.schedule)),
+ },
+ {
+ id: 'duration',
+ header: 'Duration',
+ accessorFn: (row) => row.schedule?.recurrence?.duration,
+ width: { default: '110px', min: '90px' },
+ defaultVisibility: false,
+ enableSort: false,
+ enableResize: true,
+ enableMove: false,
+ cell: ({ row }): JSX.Element =>
+ textCell(formatScheduleDuration(row.schedule)),
+ },
+ {
+ id: 'alertsSilenced',
+ header: 'Alerts Silenced',
+ accessorKey: 'alertIds',
+ width: { default: '200px', min: '140px' },
+ enableSort: false,
+ enableResize: true,
+ enableMove: false,
+ cell: ({ row }): JSX.Element =>
+ row.alertOptions.length ? (
+ <div
+ className={styles.badges}
+ title={row.alertOptions
+ .flatMap((alert) =>
+ typeof alert.label === 'string' ? [alert.label] : [],
+ )
+ .join(', ')}
+ >
+ {row.alertOptions.map((alert) => (
+ <Badge
+ key={alert.value}
+ textTransform="none"
+ variant="solid"
+ color="secondary"
+ >
+ {alert.label}
+ </Badge>
+ ))}
+ </div>
+ ) : (
+ <Badge textTransform="none" variant="solid" color="secondary">
+ All alert rules
+ </Badge>
+ ),
+ },
+ {
+ id: 'description',
+ header: 'Description',
+ accessorKey: 'description',
+ width: { default: '200px', min: '120px' },
+ defaultVisibility: false,
+ enableSort: false,
+ enableResize: true,
+ enableMove: false,
+ cell: ({ row }): JSX.Element => textCell(row.description),
+ },
+ {
+ id: 'createdBy',
+ header: 'Created By',
+ accessorKey: 'createdBy',
+ width: { default: '180px', min: '120px' },
+ defaultVisibility: false,
+ enableSort: false,
+ enableResize: true,
+ enableMove: false,
+ cell: ({ row }): JSX.Element => textCell(row.createdBy),
+ },
+ {
+ id: 'createdAt',
+ header: 'Created At',
+ accessorKey: 'createdAt',
+ width: { default: '150px', min: '120px' },
+ defaultVisibility: false,
+ enableSort: true,
+ enableResize: true,
+ enableMove: false,
+ cell: ({ row }): JSX.Element => timestampCell(row, row.createdAt),
+ },
+ {
+ id: 'updatedBy',
+ header: 'Updated By',
+ accessorKey: 'updatedBy',
+ width: { default: '180px', min: '120px' },
+ defaultVisibility: false,
+ enableSort: false,
+ enableResize: true,
+ enableMove: false,
+ cell: ({ row }): JSX.Element => textCell(row.updatedBy),
+ },
+ {
+ id: 'updatedAt',
+ header: 'Updated At',
+ accessorKey: 'updatedAt',
+ width: { default: '150px', min: '120px' },
+ defaultVisibility: false,
+ enableSort: true,
+ enableResize: true,
+ enableMove: false,
+ cell: ({ row }): JSX.Element => timestampCell(row, row.updatedAt),
+ },
+ ];
+}
diff --git a/frontend/src/container/PlannedDowntime/types.ts b/frontend/src/container/PlannedDowntime/types.ts
new file mode 100644
index 0000000000..8a1c82001f
--- /dev/null
+++ b/frontend/src/container/PlannedDowntime/types.ts
@@ -0,0 +1,33 @@
+import type { ReactNode } from 'react';
+import type { AlertmanagertypesPlannedMaintenanceDTO } from 'api/generated/services/sigNoz.schemas';
+import type { TableColumnDef } from 'components/TanStackTableView';
+import type { SelectOption } from 'types/common/select';
+
+export type DowntimeAlertOption = Omit<
+ SelectOption<string | number | null, ReactNode>,
+ 'value'
+> & {
+ value?: string | number | null;
+};
+
+export type DowntimeSchedulesTableData =
+ AlertmanagertypesPlannedMaintenanceDTO & {
+ alertOptions: DowntimeAlertOption[];
+ };
+
+export interface PlannedDowntimeListProps {
+ columns: TableColumnDef<DowntimeSchedulesTableData>[];
+ downtimes: DowntimeSchedulesTableData[];
+ pagedDowntimes: DowntimeSchedulesTableData[];
+ calculatedPageSize: number | null;
+ onLimitChange: (limit: number) => void;
+ isFetching: boolean;
+ isError: boolean;
+ refetch: () => void;
+ canEdit: boolean;
+ onEdit: (downtime: DowntimeSchedulesTableData) => void;
+ onDelete: (downtime: DowntimeSchedulesTableData) => void;
+ onCreate: () => void;
+ hasSearchTerm: boolean;
+ onClearSearch: () => void;
+}
diff --git a/frontend/src/container/PlannedDowntime/usePlannedDowntimeTable.ts b/frontend/src/container/PlannedDowntime/usePlannedDowntimeTable.ts
new file mode 100644
index 0000000000..207b1022fe
--- /dev/null
+++ b/frontend/src/container/PlannedDowntime/usePlannedDowntimeTable.ts
@@ -0,0 +1,108 @@
+import { RefObject, useMemo } from 'react';
+import type { AlertmanagertypesPlannedMaintenanceDTO } from 'api/generated/services/sigNoz.schemas';
+import { sortByColumn } from 'components/Alerts/utils';
+import type { SortState } from 'components/TanStackTableView/types';
+import { useCalculatedPageSize } from 'components/TanStackTableView/useCalculatedPageSize';
+import { useTableParams } from 'components/TanStackTableView/useTableParams';
+
+import { getAlertOptionsFromIds } from './PlannedDowntimeutils';
+import { DowntimeAlertOption, DowntimeSchedulesTableData } from './types';
+
+export const PLANNED_DOWNTIME_QUERY_PARAMS = {
+ orderBy: 'orderBy',
+ page: 'page',
+ limit: 'limit',
+} as const;
+
+const DEFAULT_PAGE = 1;
+const DEFAULT_LIMIT = 10;
+const DEFAULT_SORT: SortState = { columnName: 'updatedAt', order: 'desc' };
+
+const toTime = (value: string | undefined): number =>
+ value ? new Date(value).getTime() : 0;
+
+function getSortValue(
+ downtime: DowntimeSchedulesTableData,
+ columnName: string,
+): string | number {
+ switch (columnName) {
+ case 'name':
+ return downtime.name.toLowerCase();
+ case 'status':
+ return downtime.status;
+ case 'window':
+ return toTime(downtime.schedule?.startTime);
+ case 'createdAt':
+ return toTime(downtime.createdAt);
+ case 'updatedAt':
+ return toTime(downtime.updatedAt);
+ default:
+ return '';
+ }
+}
+
+interface UsePlannedDowntimeTableReturn {
+ containerRef: RefObject<HTMLDivElement>;
+ calculatedPageSize: number | null;
+ filteredDowntimes: DowntimeSchedulesTableData[];
+ pagedDowntimes: DowntimeSchedulesTableData[];
+ setPage: (page: number) => void;
+ setLimit: (limit: number) => void;
+}
+
+function usePlannedDowntimeTable(
+ downtimes: AlertmanagertypesPlannedMaintenanceDTO[],
+ alertOptions: DowntimeAlertOption[],
+ searchValue: string,
+): UsePlannedDowntimeTableReturn {
+ const { containerRef, calculatedPageSize } = useCalculatedPageSize({
+ rowHeight: 46,
+ });
+
+ const { orderBy, page, limit, setLimit, setPage } = useTableParams(
+ PLANNED_DOWNTIME_QUERY_PARAMS,
+ {
+ page: DEFAULT_PAGE,
+ limit: DEFAULT_LIMIT,
+ storageKey: 'planned-downtime',
+ calculatedPageSize,
+ cleanupOnUnmount: true,
+ },
+ );
+
+ const filteredDowntimes = useMemo(() => {
+ const search = searchValue.toLowerCase();
+ return downtimes
+ .filter(
+ (downtime) =>
+ downtime.name.toLowerCase().includes(search) ||
+ downtime.id === searchValue,
+ )
+ .map((downtime) => ({
+ ...downtime,
+ alertOptions: getAlertOptionsFromIds(downtime.alertIds || [], alertOptions),
+ }));
+ }, [downtimes, alertOptions, searchValue]);
+
+ const pagedDowntimes = useMemo(() => {
+ const sorted = sortByColumn(
+ filteredDowntimes,
+ orderBy,
+ getSortValue,
+ DEFAULT_SORT,
+ );
+ const start = (page - 1) * limit;
+ return sorted.slice(start, start + limit);
+ }, [filteredDowntimes, orderBy, page, limit]);
+
+ return {
+ containerRef,
+ calculatedPageSize,
+ filteredDowntimes,
+ pagedDowntimes,
+ setPage,
+ setLimit,
+ };
+}
+
+export default usePlannedDowntimeTable;
diff --git a/frontend/src/container/RoutingPolicies/RoutingPolicies.module.scss b/frontend/src/container/RoutingPolicies/RoutingPolicies.module.scss
new file mode 100644
index 0000000000..2683d159ba
--- /dev/null
+++ b/frontend/src/container/RoutingPolicies/RoutingPolicies.module.scss
@@ -0,0 +1,176 @@
+.container {
+ display: flex;
+ flex-direction: column;
+ flex: 1;
+ min-height: 0;
+}
+
+.headerBand {
+ --control-height: 2rem;
+ --input-height: var(--control-height);
+ --input-wrapper-height: var(--control-height);
+
+ display: flex;
+ flex-direction: column;
+ gap: var(--spacing-6);
+ flex-shrink: 0;
+ padding: 0 var(--spacing-8) var(--spacing-6) var(--spacing-8);
+}
+
+.commandHeader {
+ display: flex;
+ align-items: center;
+ gap: var(--spacing-4);
+}
+
+.headingBlock {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ min-width: 0;
+}
+
+.title {
+ margin: 0;
+ color: var(--l1-foreground);
+ font-size: var(--font-size-lg);
+ font-weight: var(--font-weight-medium);
+ line-height: 28px;
+ letter-spacing: -0.09px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.countPill {
+ padding: 2px 9px;
+ border-radius: 999px;
+ background: var(--l2-background);
+ border: 1px solid var(--l2-border);
+ color: var(--l2-foreground);
+ font-size: var(--font-size-xs);
+ font-variant-numeric: tabular-nums;
+}
+
+.grow {
+ flex: 1;
+}
+
+.filtersRow {
+ position: relative;
+ z-index: 10;
+ display: flex;
+ align-items: center;
+ gap: var(--spacing-4);
+}
+
+.searchInput {
+ flex: 1 1 0;
+ min-width: 220px;
+}
+
+.searchIcon {
+ color: var(--l2-foreground);
+}
+
+.actionsHeader {
+ display: block;
+ text-align: right;
+}
+
+.actions {
+ display: flex;
+ align-items: center;
+ justify-content: flex-end;
+}
+
+.tableContainer {
+ flex: 1;
+ min-height: 0;
+ display: flex;
+ flex-direction: column;
+
+ --tanstack-table-row-hover-bg: var(--l2-background-hover);
+ --tanstack-table-row-active-bg: var(--l2-background-active);
+ --tanstack-table-row-height: 42px;
+
+ --tanstack-cell-padding-top-override: 5px;
+ --tanstack-cell-padding-bottom-override: 5px;
+ --tanstack-cell-padding-left-override: 16px;
+ --tanstack-cell-padding-right-override: 16px;
+
+ --tanstack-table-row-odd-bg: color-mix(
+ in srgb,
+ var(--l1-foreground) 2%,
+ transparent
+ );
+ --tanstack-table-row-even-bg: color-mix(
+ in srgb,
+ var(--l1-foreground) 1%,
+ transparent
+ );
+}
+
+.paginationContainer {
+ padding-right: var(--spacing-12);
+ height: 62px;
+}
+
+.expression {
+ font-family: var(--font-mono, monospace);
+ font-size: 13px;
+}
+
+.badges {
+ display: flex;
+ gap: var(--spacing-2);
+ overflow: hidden;
+ white-space: nowrap;
+}
+
+.timeText {
+ display: inline-block;
+ white-space: nowrap;
+ font-size: var(--tanstack-plain-cell-font-size, 14px);
+ line-height: var(--tanstack-plain-cell-line-height, 18px);
+ color: inherit;
+}
+
+.emptyState {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: var(--spacing-3);
+ padding: 48px 24px;
+ text-align: center;
+}
+
+.emptyIcon {
+ color: var(--l2-foreground);
+}
+
+.emptyTitle {
+ color: var(--l1-foreground);
+ font-size: 16px;
+ font-weight: 500;
+ line-height: 24px;
+}
+
+.emptySubtitle {
+ color: var(--l2-foreground);
+ font-size: 14px;
+ line-height: 20px;
+ max-width: 420px;
+}
+
+.docsLink {
+ color: var(--l2-foreground);
+ font-size: 13px;
+ text-decoration: none;
+
+ &:hover {
+ color: var(--l1-foreground);
+ text-decoration: underline;
+ }
+}
diff --git a/frontend/src/container/RoutingPolicies/RoutingPolicies.tsx b/frontend/src/container/RoutingPolicies/RoutingPolicies.tsx
index f64667ed65..d740526e74 100644
--- a/frontend/src/container/RoutingPolicies/RoutingPolicies.tsx
+++ b/frontend/src/container/RoutingPolicies/RoutingPolicies.tsx
@@ -1,21 +1,30 @@
-import { ChangeEvent, useMemo } from 'react';
+import { ChangeEvent, useCallback, useMemo } from 'react';
import { Plus, Search } from '@signozhq/icons';
-import { Color } from '@signozhq/design-tokens';
+import { Button } from '@signozhq/ui/button';
import { Input } from '@signozhq/ui/input';
-import { Button, Flex, Tooltip } from 'antd';
import { Typography } from '@signozhq/ui/typography';
+import { ColumnSelector } from 'components/TanStackTableView';
+import TextToolTip from 'components/TextToolTip';
import { useAppContext } from 'providers/App/App';
+import { useTimezone } from 'providers/Timezone';
import { USER_ROLES } from 'types/roles';
import DeleteRoutingPolicy from './DeleteRoutingPolicy';
+import styles from './RoutingPolicies.module.scss';
import RoutingPolicyDetails from './RoutingPolicyDetails';
import RoutingPolicyList from './RoutingPolicyList';
+import { getRoutingPolicyColumns } from './table.config';
+import { RoutingPolicy } from './types';
import useRoutingPolicies from './useRoutingPolicies';
+import useRoutingPoliciesTable from './useRoutingPoliciesTable';
import './styles.scss';
+const COLUMNS_STORAGE_KEY = 'routing-policies-columns';
+
function RoutingPolicies(): JSX.Element {
const { user } = useAppContext();
+ const { formatTimezoneAdjustedTimestamp } = useTimezone();
const {
// Routing Policies
selectedRoutingPolicy,
@@ -46,79 +55,136 @@ function RoutingPolicies(): JSX.Element {
isPolicyDetailsModalActionLoading,
} = useRoutingPolicies();
- const disableCreateButton = user?.role === USER_ROLES.VIEWER;
+ const { containerRef, calculatedPageSize, pagedPolicies, setPage, setLimit } =
+ useRoutingPoliciesTable(routingPoliciesData);
+
+ const canEdit = user?.role !== USER_ROLES.VIEWER;
- const tooltipTitle = useMemo(() => {
- if (user?.role === USER_ROLES.VIEWER) {
- return 'You need edit permissions to create a routing policy';
- }
- return '';
- }, [user?.role]);
+ const columns = useMemo(
+ () => getRoutingPolicyColumns(formatTimezoneAdjustedTimestamp),
+ [formatTimezoneAdjustedTimestamp],
+ );
const handleSearch = (e: ChangeEvent<HTMLInputElement>): void => {
setSearchTerm(e.target.value || '');
+ setPage(1);
};
+ const handleClearSearch = useCallback((): void => {
+ setSearchTerm('');
+ setPage(1);
+ }, [setSearchTerm, setPage]);
+
+ const handleCreate = useCallback(
+ (): void => handlePolicyDetailsModalOpen('create', null),
+ [handlePolicyDetailsModalOpen],
+ );
+
+ const handleEdit = useCallback(
+ (routingPolicy: RoutingPolicy): void =>
+ handlePolicyDetailsModalOpen('edit', routingPolicy),
+ [handlePolicyDetailsModalOpen],
+ );
+
+ const isFetching = useMemo(
+ () => isLoadingRoutingPolicies || isFetchingRoutingPolicies,
+ [isLoadingRoutingPolicies, isFetchingRoutingPolicies],
+ );
+ const hasSearchTerm = useMemo(() => searchTerm.length > 0, [searchTerm]);
+ const isEmpty = useMemo(
+ () => !isFetching && !hasSearchTerm && routingPoliciesData.length === 0,
+ [isFetching, hasSearchTerm, routingPoliciesData.length],
+ );
+
return (
- <div className="routing-policies-container">
- <div className="routing-policies-content">
- <Typography.Title className="title">Routing Policies</Typography.Title>
- <Typography.Text className="subtitle">
- Create and manage routing policies.
- </Typography.Text>
- <Flex className="toolbar">
+ <div className={styles.container}>
+ <header className={styles.headerBand}>
+ <div className={styles.commandHeader}>
+ <div className={styles.headingBlock}>
+ <Typography.Title className={styles.title}>
+ Routing Policies
+ </Typography.Title>
+ <span className={styles.countPill}>{routingPoliciesData.length}</span>
+ </div>
+ <div className={styles.grow} />
+ {!isEmpty && (
+ <ColumnSelector
+ columns={columns}
+ storageKey={COLUMNS_STORAGE_KEY}
+ testId="routing-policies-columns"
+ />
+ )}
+ <Button
+ variant="solid"
+ color="primary"
+ size="sm"
+ prefix={<Plus size={14} />}
+ onClick={handleCreate}
+ disabled={!canEdit}
+ disabledTooltip="You need edit permissions to create a routing policy"
+ testId="routing-policies-create"
+ >
+ New routing policy
+ </Button>
+ <TextToolTip
+ text="More details on how to configure routing policies"
+ url="https://signoz.io/docs/alerts-management/routing-policy"
+ urlText="Learn More"
+ />
+ </div>
+
+ <div className={styles.filtersRow}>
<Input
- placeholder="Search for a routing policy..."
- prefix={<Search size={12} color={Color.BG_VANILLA_400} />}
+ containerClassName={styles.searchInput}
+ placeholder="Search by name or description"
value={searchTerm}
onChange={handleSearch}
+ suffix={<Search size={14} className={styles.searchIcon} />}
+ testId="routing-policies-search"
/>
- <Tooltip title={tooltipTitle}>
- <Button
- type="primary"
- onClick={(): void => handlePolicyDetailsModalOpen('create', null)}
- disabled={disableCreateButton}
- >
- <Flex gap={4} align="center">
- <Plus size={16} />
- New routing policy
- </Flex>
- </Button>
- </Tooltip>
- </Flex>
- <br />
+ </div>
+ </header>
+
+ <div ref={containerRef} className={styles.tableContainer}>
<RoutingPolicyList
+ columns={columns}
routingPolicies={routingPoliciesData}
- refetchRoutingPolicies={refetchRoutingPolicies}
- isRoutingPoliciesFetching={isFetchingRoutingPolicies}
- isRoutingPoliciesLoading={isLoadingRoutingPolicies}
- isRoutingPoliciesError={isErrorRoutingPolicies}
- handlePolicyDetailsModalOpen={handlePolicyDetailsModalOpen}
- handleDeleteModalOpen={handleDeleteModalOpen}
- hasSearchTerm={(searchTerm?.length ?? 0) > 0}
+ pagedPolicies={pagedPolicies}
+ calculatedPageSize={calculatedPageSize}
+ onLimitChange={setLimit}
+ isFetching={isFetching}
+ isError={isErrorRoutingPolicies}
+ refetch={refetchRoutingPolicies}
+ canEdit={canEdit}
+ onEdit={handleEdit}
+ onDelete={handleDeleteModalOpen}
+ onCreate={handleCreate}
+ hasSearchTerm={hasSearchTerm}
+ onClearSearch={handleClearSearch}
/>
- {policyDetailsModalState.isOpen && (
- <RoutingPolicyDetails
- routingPolicy={selectedRoutingPolicy}
- closeModal={handlePolicyDetailsModalClose}
- mode={policyDetailsModalState.mode}
- channels={channels}
- isErrorChannels={isErrorChannels}
- isLoadingChannels={isLoadingChannels}
- handlePolicyDetailsModalAction={handlePolicyDetailsModalAction}
- isPolicyDetailsModalActionLoading={isPolicyDetailsModalActionLoading}
- refreshChannels={refreshChannels}
- />
- )}
- {isDeleteModalOpen && (
- <DeleteRoutingPolicy
- isDeletingRoutingPolicy={isDeletingRoutingPolicy}
- handleDelete={handleDeleteRoutingPolicy}
- handleClose={handleDeleteModalClose}
- routingPolicy={selectedRoutingPolicy}
- />
- )}
</div>
+
+ {policyDetailsModalState.isOpen && (
+ <RoutingPolicyDetails
+ routingPolicy={selectedRoutingPolicy}
+ closeModal={handlePolicyDetailsModalClose}
+ mode={policyDetailsModalState.mode}
+ channels={channels}
+ isErrorChannels={isErrorChannels}
+ isLoadingChannels={isLoadingChannels}
+ handlePolicyDetailsModalAction={handlePolicyDetailsModalAction}
+ isPolicyDetailsModalActionLoading={isPolicyDetailsModalActionLoading}
+ refreshChannels={refreshChannels}
+ />
+ )}
+ {isDeleteModalOpen && (
+ <DeleteRoutingPolicy
+ isDeletingRoutingPolicy={isDeletingRoutingPolicy}
+ handleDelete={handleDeleteRoutingPolicy}
+ handleClose={handleDeleteModalClose}
+ routingPolicy={selectedRoutingPolicy}
+ />
+ )}
</div>
);
}
diff --git a/frontend/src/container/RoutingPolicies/RoutingPoliciesEmptyState.tsx b/frontend/src/container/RoutingPolicies/RoutingPoliciesEmptyState.tsx
new file mode 100644
index 0000000000..81acf158d8
--- /dev/null
+++ b/frontend/src/container/RoutingPolicies/RoutingPoliciesEmptyState.tsx
@@ -0,0 +1,52 @@
+import { Plus, Route } from '@signozhq/icons';
+import { Button } from '@signozhq/ui/button';
+import { Typography } from '@signozhq/ui/typography';
+
+import styles from './RoutingPolicies.module.scss';
+
+const DOCS_URL = 'https://signoz.io/docs/alerts-management/routing-policy';
+
+interface RoutingPoliciesEmptyStateProps {
+ canCreate: boolean;
+ onCreate: () => void;
+}
+
+function RoutingPoliciesEmptyState({
+ canCreate,
+ onCreate,
+}: RoutingPoliciesEmptyStateProps): JSX.Element {
+ return (
+ <div className={styles.emptyState} data-testid="routing-policies-empty-state">
+ <Route className={styles.emptyIcon} size={16} />
+ <Typography.Text className={styles.emptyTitle}>
+ No routing policies yet
+ </Typography.Text>
+ <Typography.Text className={styles.emptySubtitle}>
+ A routing policy sends alerts matching an expression to the channels you
+ pick, without editing each alert rule.
+ </Typography.Text>
+ {canCreate && (
+ <Button
+ variant="solid"
+ color="primary"
+ size="md"
+ prefix={<Plus size={14} />}
+ onClick={onCreate}
+ testId="routing-policies-empty-create"
+ >
+ New routing policy
+ </Button>
+ )}
+ <a
+ className={styles.docsLink}
+ href={DOCS_URL}
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ Read the routing policy guide
+ </a>
+ </div>
+ );
+}
+
+export default RoutingPoliciesEmptyState;
diff --git a/frontend/src/container/RoutingPolicies/RoutingPolicyActionsMenu.tsx b/frontend/src/container/RoutingPolicies/RoutingPolicyActionsMenu.tsx
new file mode 100644
index 0000000000..fc12aa0f62
--- /dev/null
+++ b/frontend/src/container/RoutingPolicies/RoutingPolicyActionsMenu.tsx
@@ -0,0 +1,65 @@
+import { useMemo } from 'react';
+import { Ellipsis, PenLine, Trash2 } from '@signozhq/icons';
+import { Button } from '@signozhq/ui/button';
+import { Dropdown, type DropdownItemType } from '@signozhq/ui/dropdown';
+
+import styles from './RoutingPolicies.module.scss';
+import { RoutingPolicy } from './types';
+
+interface RoutingPolicyActionsMenuProps {
+ routingPolicy: RoutingPolicy;
+ onEdit: (routingPolicy: RoutingPolicy) => void;
+ onDelete: (routingPolicy: RoutingPolicy) => void;
+}
+
+function RoutingPolicyActionsMenu({
+ routingPolicy,
+ onEdit,
+ onDelete,
+}: RoutingPolicyActionsMenuProps): JSX.Element {
+ const menuItems = useMemo<DropdownItemType[]>(
+ () => [
+ {
+ type: 'item',
+ value: 'edit',
+ label: 'Edit',
+ prefix: <PenLine size={14} />,
+ onClick: (): void => onEdit(routingPolicy),
+ },
+ { type: 'separator', value: 'before-delete' },
+ {
+ type: 'item',
+ value: 'delete',
+ label: 'Delete',
+ prefix: <Trash2 size={14} />,
+ danger: true,
+ onClick: (): void => onDelete(routingPolicy),
+ },
+ ],
+ [routingPolicy, onEdit, onDelete],
+ );
+
+ return (
+ // the row itself opens the policy, so the actions keep their clicks
+ // eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions
+ <div
+ className={styles.actions}
+ onClick={(event): void => event.stopPropagation()}
+ >
+ <Dropdown items={menuItems} nativeButton align="end" side="bottom">
+ <Button
+ variant="outlined"
+ color="secondary"
+ size="sm"
+ icon
+ testId={`routing-policy-actions-${routingPolicy.id}`}
+ aria-label={`Actions for ${routingPolicy.name}`}
+ >
+ <Ellipsis size={16} />
+ </Button>
+ </Dropdown>
+ </div>
+ );
+}
+
+export default RoutingPolicyActionsMenu;
diff --git a/frontend/src/container/RoutingPolicies/RoutingPolicyList.tsx b/frontend/src/container/RoutingPolicies/RoutingPolicyList.tsx
index 12e27a7422..c463ef94ac 100644
--- a/frontend/src/container/RoutingPolicies/RoutingPolicyList.tsx
+++ b/frontend/src/container/RoutingPolicies/RoutingPolicyList.tsx
@@ -1,98 +1,106 @@
import { useMemo } from 'react';
-import { Button, Table, TableProps } from 'antd';
-import { Typography } from '@signozhq/ui/typography';
-import { RotateCw } from '@signozhq/icons';
+import ErrorEmptyState from 'components/Alerts/ErrorEmptyState';
+import NoResultsEmptyState from 'components/Alerts/NoResultsEmptyState';
+import TanStackTable, { TableColumnDef } from 'components/TanStackTableView';
-import awwSnapUrl from '@/assets/Icons/awwSnap.svg';
-import emptyStateUrl from '@/assets/Icons/emptyState.svg';
-
-import RoutingPolicyListItem from './RoutingPolicyListItem';
+import RoutingPoliciesEmptyState from './RoutingPoliciesEmptyState';
+import RoutingPolicyActionsMenu from './RoutingPolicyActionsMenu';
+import styles from './RoutingPolicies.module.scss';
import { RoutingPolicy, RoutingPolicyListProps } from './types';
+import { ROUTING_POLICIES_QUERY_PARAMS } from './useRoutingPoliciesTable';
function RoutingPolicyList({
+ columns,
routingPolicies,
- refetchRoutingPolicies,
- isRoutingPoliciesFetching,
- isRoutingPoliciesLoading,
- isRoutingPoliciesError,
- handlePolicyDetailsModalOpen,
- handleDeleteModalOpen,
+ pagedPolicies,
+ calculatedPageSize,
+ onLimitChange,
+ isFetching,
+ isError,
+ refetch,
+ canEdit,
+ onEdit,
+ onDelete,
+ onCreate,
hasSearchTerm,
+ onClearSearch,
}: RoutingPolicyListProps): JSX.Element {
- const columns: TableProps<RoutingPolicy>['columns'] = [
- {
- title: 'Routing Policy',
- key: 'routingPolicy',
- render: (data: RoutingPolicy): JSX.Element => (
- <RoutingPolicyListItem
- routingPolicy={data}
- handlePolicyDetailsModalOpen={handlePolicyDetailsModalOpen}
- handleDeleteModalOpen={handleDeleteModalOpen}
- />
- ),
- },
- ];
-
- const showLoading = isRoutingPoliciesLoading || isRoutingPoliciesFetching;
- const showError = !showLoading && isRoutingPoliciesError;
+ const columnsWithActions = useMemo((): TableColumnDef<RoutingPolicy>[] => {
+ if (!canEdit) {
+ return columns;
+ }
- const localeEmptyState = useMemo(
- () => (
- <div className="no-routing-policies-message-container">
- {showError ? (
- <img src={awwSnapUrl} alt="aww-snap" className="error-state-svg" />
- ) : (
- <img
- src={emptyStateUrl}
- alt="thinking-emoji"
- className="empty-state-svg"
+ return [
+ ...columns,
+ {
+ id: 'actions',
+ header: (): JSX.Element => (
+ <span className={styles.actionsHeader}>Actions</span>
+ ),
+ accessorKey: 'id',
+ width: { fixed: '96px', ignoreLastColumnFill: true },
+ enableSort: false,
+ enableResize: false,
+ enableRemove: false,
+ enableMove: false,
+ pin: 'right',
+ cell: ({ row }): JSX.Element => (
+ <RoutingPolicyActionsMenu
+ routingPolicy={row}
+ onEdit={onEdit}
+ onDelete={onDelete}
/>
- )}
- {showError ? (
- <div className="error-state">
- <Typography.Text>
- Something went wrong while fetching routing policies.
- </Typography.Text>
- <Button icon={<RotateCw size={14} />} onClick={refetchRoutingPolicies}>
- Retry
- </Button>
- </div>
- ) : hasSearchTerm ? (
- <Typography.Text>No matching routing policies found.</Typography.Text>
- ) : (
- <Typography.Text>
- No routing policies yet,{' '}
- <a
- href="https://signoz.io/docs/alerts-management/routing-policy"
- target="_blank"
- rel="noopener noreferrer"
- >
- Learn more here
- </a>
- </Typography.Text>
- )}
- </div>
- ),
- [showError, hasSearchTerm, refetchRoutingPolicies],
- );
+ ),
+ },
+ ];
+ }, [canEdit, columns, onEdit, onDelete]);
+
+ const isEmpty = !isFetching && routingPolicies.length === 0;
+
+ if (isError) {
+ return (
+ <ErrorEmptyState
+ title="Failed to load routing policies"
+ onRefresh={refetch}
+ />
+ );
+ }
+
+ if (isEmpty && hasSearchTerm) {
+ return (
+ <NoResultsEmptyState
+ title="No matching routing policies"
+ subtitle="No routing policies match your search. Try adjusting your search criteria."
+ onClear={onClearSearch}
+ clearButtonText="Clear Search"
+ />
+ );
+ }
+
+ if (isEmpty) {
+ return <RoutingPoliciesEmptyState canCreate={canEdit} onCreate={onCreate} />;
+ }
return (
- <Table<RoutingPolicy>
- columns={columns}
- className="routing-policies-table"
- bordered={false}
- dataSource={routingPolicies}
- loading={showLoading}
- showHeader={false}
- rowKey="id"
+ <TanStackTable<RoutingPolicy>
+ data={pagedPolicies}
+ columns={columnsWithActions}
+ isLoading={isFetching}
+ getRowKey={(row): string => row.id}
+ getItemKey={(row): string => row.id}
+ getRowTestId={(row): string => `routing-policy-row-${row.id}`}
+ columnStorageKey="routing-policies-columns"
+ enableQueryParams={ROUTING_POLICIES_QUERY_PARAMS}
+ onRowClick={canEdit ? onEdit : undefined}
pagination={{
- pageSize: 5,
- showSizeChanger: false,
- hideOnSinglePage: true,
- }}
- locale={{
- emptyText: showLoading ? null : localeEmptyState,
+ total: routingPolicies.length,
+ calculatedPageSize,
+ onLimitChange,
+ showTotalCount: true,
}}
+ paginationClassname={styles.paginationContainer}
+ enableAlternatingRowColors
+ plainTextCellLineClamp={1}
/>
);
}
diff --git a/frontend/src/container/RoutingPolicies/RoutingPolicyListItem.tsx b/frontend/src/container/RoutingPolicies/RoutingPolicyListItem.tsx
deleted file mode 100644
index 2aa27b12f0..0000000000
--- a/frontend/src/container/RoutingPolicies/RoutingPolicyListItem.tsx
+++ /dev/null
@@ -1,162 +0,0 @@
-import { Color } from '@signozhq/design-tokens';
-import { Button, Collapse, Flex } from 'antd';
-import { Badge } from '@signozhq/ui/badge';
-import { Typography } from '@signozhq/ui/typography';
-import { DATE_TIME_FORMATS } from 'constants/dateTimeFormats';
-import { PenLine, Trash2 } from '@signozhq/icons';
-import { useAppContext } from 'providers/App/App';
-import { useTimezone } from 'providers/Timezone';
-import { USER_ROLES } from 'types/roles';
-
-import {
- PolicyListItemContentProps,
- PolicyListItemHeaderProps,
- RoutingPolicyListItemProps,
-} from './types';
-
-function PolicyListItemHeader({
- name,
- handleEdit,
- handleDelete,
-}: PolicyListItemHeaderProps): JSX.Element {
- const { user } = useAppContext();
-
- const isEditEnabled = user?.role !== USER_ROLES.VIEWER;
-
- return (
- <Flex
- className="policy-list-item-header"
- justify="space-between"
- align="center"
- >
- <Typography.Text className="policy-list-item-header-title" truncate={1}>
- {name}
- </Typography.Text>
- {isEditEnabled && (
- <div className="action-btn">
- <Button
- onClick={(e): void => {
- e.preventDefault();
- e.stopPropagation();
- handleEdit();
- }}
- type="text"
- shape="circle"
- icon={<PenLine size={14} data-testid="edit-routing-policy" />}
- />
- <Button
- onClick={(e): void => {
- e.preventDefault();
- e.stopPropagation();
- handleDelete();
- }}
- type="text"
- shape="circle"
- icon={
- <Trash2
- size={14}
- color={Color.BG_CHERRY_500}
- data-testid="delete-routing-policy"
- />
- }
- />
- </div>
- )}
- </Flex>
- );
-}
-
-function PolicyListItemContent({
- routingPolicy,
-}: PolicyListItemContentProps): JSX.Element {
- const { formatTimezoneAdjustedTimestamp } = useTimezone();
-
- return (
- <div className="policy-list-item-content">
- <div className="policy-list-item-content-row">
- <Typography>Created by</Typography>
- <Typography>{routingPolicy.createdBy}</Typography>
- </div>
- <div className="policy-list-item-content-row">
- <Typography>Created on</Typography>
- <Typography>
- {routingPolicy.createdAt
- ? formatTimezoneAdjustedTimestamp(
- routingPolicy.createdAt,
- DATE_TIME_FORMATS.MONTH_DATETIME,
- )
- : '-'}
- </Typography>
- </div>
- <div className="policy-list-item-content-row">
- <Typography>Updated by</Typography>
- <Typography>{routingPolicy.updatedBy || '-'}</Typography>
- </div>
- <div className="policy-list-item-content-row">
- <Typography>Updated on</Typography>
- <Typography>
- {routingPolicy.updatedAt
- ? formatTimezoneAdjustedTimestamp(
- routingPolicy.updatedAt,
- DATE_TIME_FORMATS.MONTH_DATETIME,
- )
- : '-'}
- </Typography>
- </div>
- <div className="policy-list-item-content-row">
- <Typography>Expression</Typography>
- <Typography.Text truncate={1}>
- {routingPolicy.expression || '-'}
- </Typography.Text>
- </div>
- <div className="policy-list-item-content-row">
- <Typography>Description</Typography>
- <Typography.Text truncate={1}>
- {routingPolicy.description || '-'}
- </Typography.Text>
- </div>
- <div className="policy-list-item-content-row">
- <Typography>Channels</Typography>
- <div>
- {routingPolicy.channels.map((channel) => (
- <Badge
- textTransform="none"
- variant="solid"
- key={channel}
- color="secondary"
- >
- {channel}
- </Badge>
- ))}
- </div>
- </div>
- </div>
- );
-}
-
-function RoutingPolicyListItem({
- routingPolicy,
- handlePolicyDetailsModalOpen,
- handleDeleteModalOpen,
-}: RoutingPolicyListItemProps): JSX.Element {
- return (
- <Collapse accordion className="policy-list-item">
- <Collapse.Panel
- header={
- <PolicyListItemHeader
- name={routingPolicy.name}
- handleEdit={(): void =>
- handlePolicyDetailsModalOpen('edit', routingPolicy)
- }
- handleDelete={(): void => handleDeleteModalOpen(routingPolicy)}
- />
- }
- key={routingPolicy.id}
- >
- <PolicyListItemContent routingPolicy={routingPolicy} />
- </Collapse.Panel>
- </Collapse>
- );
-}
-
-export default RoutingPolicyListItem;
diff --git a/frontend/src/container/RoutingPolicies/__tests__/RoutingPolicies.test.tsx b/frontend/src/container/RoutingPolicies/__tests__/RoutingPolicies.test.tsx
index d8b582b01c..362ec980e7 100644
--- a/frontend/src/container/RoutingPolicies/__tests__/RoutingPolicies.test.tsx
+++ b/frontend/src/container/RoutingPolicies/__tests__/RoutingPolicies.test.tsx
@@ -1,5 +1,5 @@
-import { fireEvent, render, screen } from '@testing-library/react';
import * as appHooks from 'providers/App/App';
+import { fireEvent, render, screen } from 'tests/test-utils';
import RoutingPolicies from '../RoutingPolicies';
import * as routingPoliciesHooks from '../useRoutingPolicies';
@@ -7,34 +7,14 @@ import {
getAppContextMockState,
getUseRoutingPoliciesMockData,
MOCK_ROUTING_POLICY_1,
- mockLocation,
- mockQueryParams,
} from './testUtils';
const ROUTING_POLICY_DETAILS_TEST_ID = 'routing-policy-details';
-const SEARCH_PLACEHOLDER = 'Search for a routing policy...';
+const SEARCH_TEST_ID = 'routing-policies-search';
+const CREATE_TEST_ID = 'routing-policies-create';
jest.spyOn(appHooks, 'useAppContext').mockReturnValue(getAppContextMockState());
-jest.mock('hooks/useUrlQuery', () => ({
- __esModule: true,
- default: (): URLSearchParams => mockQueryParams({}),
-}));
-
-const mockHistoryReplace = jest.fn();
-jest.mock('react-router-dom', () => ({
- ...jest.requireActual('react-router-dom'),
- useHistory: (): any => ({
- replace: mockHistoryReplace,
- }),
- useLocation: (): any => ({
- pathname: '/alerts',
- search: '',
- hash: '',
- state: null,
- }),
-}));
-
jest.mock('../RoutingPolicyList', () => ({
__esModule: true,
default: jest.fn(() => (
@@ -66,20 +46,13 @@ jest.spyOn(routingPoliciesHooks, 'default').mockReturnValue(
describe('RoutingPolicies', () => {
beforeEach(() => {
jest.clearAllMocks();
- mockQueryParams({});
- mockLocation('/alerts');
});
it('should render components properly', () => {
render(<RoutingPolicies />);
expect(screen.getByText('Routing Policies')).toBeInTheDocument();
- expect(
- screen.getByText('Create and manage routing policies.'),
- ).toBeInTheDocument();
- expect(screen.getByPlaceholderText(SEARCH_PLACEHOLDER)).toBeInTheDocument();
- expect(
- screen.getByRole('button', { name: /New routing policy/ }),
- ).toBeInTheDocument();
+ expect(screen.getByTestId(SEARCH_TEST_ID)).toBeInTheDocument();
+ expect(screen.getByTestId(CREATE_TEST_ID)).toBeInTheDocument();
expect(screen.getByTestId('routing-policy-list')).toBeInTheDocument();
expect(
screen.queryByTestId(ROUTING_POLICY_DETAILS_TEST_ID),
@@ -89,9 +62,10 @@ describe('RoutingPolicies', () => {
it('should enable the "New routing policy" button for users with ADMIN role', () => {
render(<RoutingPolicies />);
- expect(
- screen.getByRole('button', { name: /New routing policy/ }),
- ).toBeEnabled();
+ expect(screen.getByTestId(CREATE_TEST_ID)).toHaveAttribute(
+ 'aria-disabled',
+ 'false',
+ );
});
it('should disable the "New routing policy" button for users with VIEWER role', () => {
@@ -99,14 +73,15 @@ describe('RoutingPolicies', () => {
.spyOn(appHooks, 'useAppContext')
.mockReturnValueOnce(getAppContextMockState({ role: 'VIEWER' }));
render(<RoutingPolicies />);
- expect(
- screen.getByRole('button', { name: /New routing policy/ }),
- ).toBeDisabled();
+ expect(screen.getByTestId(CREATE_TEST_ID)).toHaveAttribute(
+ 'aria-disabled',
+ 'true',
+ );
});
it('filters routing policies by search term', () => {
render(<RoutingPolicies />);
- const searchInput = screen.getByPlaceholderText(SEARCH_PLACEHOLDER);
+ const searchInput = screen.getByTestId(SEARCH_TEST_ID);
fireEvent.change(searchInput, {
target: { value: MOCK_ROUTING_POLICY_1.name },
});
@@ -116,10 +91,7 @@ describe('RoutingPolicies', () => {
it('clicking on the "New routing policy" button opens the policy details modal', () => {
render(<RoutingPolicies />);
- const newRoutingPolicyButton = screen.getByRole('button', {
- name: /New routing policy/,
- });
- fireEvent.click(newRoutingPolicyButton);
+ fireEvent.click(screen.getByTestId(CREATE_TEST_ID));
expect(mockHandlePolicyDetailsModalOpen).toHaveBeenCalledWith('create', null);
});
@@ -148,9 +120,8 @@ describe('RoutingPolicies', () => {
expect(screen.getByTestId('delete-routing-policy')).toBeInTheDocument();
});
- it('should load with search term from URL query params', () => {
+ it('should show the current search term', () => {
const searchTerm = 'existing search';
- mockQueryParams({ search: searchTerm });
jest.spyOn(routingPoliciesHooks, 'default').mockReturnValue(
getUseRoutingPoliciesMockData({
searchTerm,
@@ -159,14 +130,11 @@ describe('RoutingPolicies', () => {
render(<RoutingPolicies />);
- const searchInput = screen.getByPlaceholderText(
- SEARCH_PLACEHOLDER,
- ) as HTMLInputElement;
+ const searchInput = screen.getByTestId(SEARCH_TEST_ID) as HTMLInputElement;
expect(searchInput.value).toBe(searchTerm);
});
- it('should initialize with empty search when no search param is in URL', () => {
- mockQueryParams({});
+ it('should show an empty search when there is no search term', () => {
jest.spyOn(routingPoliciesHooks, 'default').mockReturnValue(
getUseRoutingPoliciesMockData({
searchTerm: '',
@@ -175,9 +143,7 @@ describe('RoutingPolicies', () => {
render(<RoutingPolicies />);
- const searchInput = screen.getByPlaceholderText(
- SEARCH_PLACEHOLDER,
- ) as HTMLInputElement;
+ const searchInput = screen.getByTestId(SEARCH_TEST_ID) as HTMLInputElement;
expect(searchInput.value).toBe('');
});
});
diff --git a/frontend/src/container/RoutingPolicies/__tests__/RoutingPoliciesList.test.tsx b/frontend/src/container/RoutingPolicies/__tests__/RoutingPoliciesList.test.tsx
index 1ce521a3a2..9b7c1390b7 100644
--- a/frontend/src/container/RoutingPolicies/__tests__/RoutingPoliciesList.test.tsx
+++ b/frontend/src/container/RoutingPolicies/__tests__/RoutingPoliciesList.test.tsx
@@ -1,126 +1,159 @@
-import { fireEvent, render, screen } from '@testing-library/react';
-
-import RoutingPoliciesList from '../RoutingPolicyList';
-import { RoutingPolicyListItemProps } from '../types';
-import { getUseRoutingPoliciesMockData } from './testUtils';
-
-const useRoutingPolicesMockData = getUseRoutingPoliciesMockData();
-const mockHandlePolicyDetailsModalOpen = jest.fn();
-const mockHandleDeleteModalOpen = jest.fn();
-const mockRefetchRoutingPolicies = jest.fn();
-
-jest.mock('../RoutingPolicyListItem', () => ({
- __esModule: true,
- default: jest.fn(({ routingPolicy }: RoutingPolicyListItemProps) => (
- <div data-testid="routing-policy-list-item">{routingPolicy.name}</div>
- )),
-}));
-
-const ROUTING_POLICY_LIST_ITEM_TEST_ID = 'routing-policy-list-item';
-
-describe('RoutingPoliciesList', () => {
- it('renders base layout with routing policies', () => {
- render(
- <RoutingPoliciesList
- routingPolicies={useRoutingPolicesMockData.routingPoliciesData}
- isRoutingPoliciesLoading={
- useRoutingPolicesMockData.isLoadingRoutingPolicies
- }
- isRoutingPoliciesError={useRoutingPolicesMockData.isErrorRoutingPolicies}
- handlePolicyDetailsModalOpen={mockHandlePolicyDetailsModalOpen}
- handleDeleteModalOpen={mockHandleDeleteModalOpen}
- hasSearchTerm={false}
- refetchRoutingPolicies={mockRefetchRoutingPolicies}
- isRoutingPoliciesFetching={false}
- />,
- );
+import { VirtuosoMockContext } from 'react-virtuoso';
+import { render, screen, userEvent } from 'tests/test-utils';
- const routingPolicyItems = screen.getAllByTestId(
- ROUTING_POLICY_LIST_ITEM_TEST_ID,
- );
- expect(routingPolicyItems).toHaveLength(2);
- expect(routingPolicyItems[0]).toHaveTextContent(
- useRoutingPolicesMockData.routingPoliciesData[0].name,
+import RoutingPolicyList from '../RoutingPolicyList';
+import { getRoutingPolicyColumns } from '../table.config';
+import { RoutingPolicyListProps } from '../types';
+import { MOCK_ROUTING_POLICY_1, MOCK_ROUTING_POLICY_2 } from './testUtils';
+
+const POLICIES = [MOCK_ROUTING_POLICY_1, MOCK_ROUTING_POLICY_2];
+
+function renderList(
+ overrides: Partial<RoutingPolicyListProps> = {},
+): RoutingPolicyListProps {
+ const props: RoutingPolicyListProps = {
+ columns: getRoutingPolicyColumns((date) => date),
+ routingPolicies: POLICIES,
+ pagedPolicies: POLICIES,
+ calculatedPageSize: null,
+ onLimitChange: jest.fn(),
+ isFetching: false,
+ isError: false,
+ refetch: jest.fn(),
+ canEdit: true,
+ onEdit: jest.fn(),
+ onDelete: jest.fn(),
+ onCreate: jest.fn(),
+ hasSearchTerm: false,
+ onClearSearch: jest.fn(),
+ ...overrides,
+ };
+ render(
+ <VirtuosoMockContext.Provider value={{ viewportHeight: 800, itemHeight: 46 }}>
+ <RoutingPolicyList {...props} />
+ </VirtuosoMockContext.Provider>,
+ );
+ return props;
+}
+
+describe('RoutingPolicyList', () => {
+ it('renders the key policy fields and hides audit columns by default', async () => {
+ renderList();
+
+ await expect(
+ screen.findByTestId(`routing-policy-row-${MOCK_ROUTING_POLICY_1.id}-name`),
+ ).resolves.toHaveTextContent(MOCK_ROUTING_POLICY_1.name);
+ expect(
+ screen.getByTestId(`routing-policy-row-${MOCK_ROUTING_POLICY_2.id}-name`),
+ ).toHaveTextContent(MOCK_ROUTING_POLICY_2.name);
+
+ expect(
+ screen.getByText(MOCK_ROUTING_POLICY_1.expression),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByText(MOCK_ROUTING_POLICY_1.description as string),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.getByText(MOCK_ROUTING_POLICY_1.channels?.[0] || ''),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByText(MOCK_ROUTING_POLICY_1.createdBy as string),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByText(MOCK_ROUTING_POLICY_2.updatedBy as string),
+ ).not.toBeInTheDocument();
+ });
+
+ it('lets every data column be resized', async () => {
+ renderList();
+
+ await screen.findByText(MOCK_ROUTING_POLICY_1.name);
+ const resizable = Array.from(document.querySelectorAll('th'))
+ .filter((th) => th.querySelector('[title="Drag to resize column"]'))
+ .map((th) => th.textContent?.trim());
+ expect(resizable).toStrictEqual(['Routing Policy', 'Expression', 'Channels']);
+ });
+
+ it('opens the policy on row click', async () => {
+ const { onEdit } = renderList();
+
+ await userEvent.click(
+ await screen.findByTestId(
+ `routing-policy-row-${MOCK_ROUTING_POLICY_1.id}-name`,
+ ),
);
- expect(routingPolicyItems[1]).toHaveTextContent(
- useRoutingPolicesMockData.routingPoliciesData[1].name,
+
+ expect(onEdit).toHaveBeenCalledWith(
+ MOCK_ROUTING_POLICY_1,
+ MOCK_ROUTING_POLICY_1.id,
+ expect.anything(),
);
});
- it('renders loading state', () => {
- render(
- <RoutingPoliciesList
- routingPolicies={useRoutingPolicesMockData.routingPoliciesData}
- isRoutingPoliciesLoading
- isRoutingPoliciesError={false}
- handlePolicyDetailsModalOpen={mockHandlePolicyDetailsModalOpen}
- handleDeleteModalOpen={mockHandleDeleteModalOpen}
- hasSearchTerm={false}
- refetchRoutingPolicies={mockRefetchRoutingPolicies}
- isRoutingPoliciesFetching={false}
- />,
- );
- // Check for loading spinner by class name
- expect(document.querySelector('.ant-spin-spinning')).toBeInTheDocument();
- // Check that the table is in loading state (blurred)
- expect(document.querySelector('.ant-spin-blur')).toBeInTheDocument();
+ it('edits and deletes from the actions menu', async () => {
+ const { onEdit, onDelete } = renderList();
+ const actions = `routing-policy-actions-${MOCK_ROUTING_POLICY_1.id}`;
+
+ await userEvent.click(await screen.findByTestId(actions));
+ await userEvent.click(await screen.findByText('Edit'));
+ expect(onEdit).toHaveBeenCalledWith(MOCK_ROUTING_POLICY_1);
+
+ await userEvent.click(screen.getByTestId(actions));
+ await userEvent.click(await screen.findByText('Delete'));
+ expect(onDelete).toHaveBeenCalledWith(MOCK_ROUTING_POLICY_1);
});
- it('renders loading state when data is being fetched', () => {
- render(
- <RoutingPoliciesList
- routingPolicies={useRoutingPolicesMockData.routingPoliciesData}
- isRoutingPoliciesLoading={false}
- isRoutingPoliciesError={false}
- handlePolicyDetailsModalOpen={mockHandlePolicyDetailsModalOpen}
- handleDeleteModalOpen={mockHandleDeleteModalOpen}
- hasSearchTerm={false}
- refetchRoutingPolicies={mockRefetchRoutingPolicies}
- isRoutingPoliciesFetching
- />,
+ it('hides actions and row click for viewers', async () => {
+ const { onEdit } = renderList({ canEdit: false });
+
+ await userEvent.click(
+ await screen.findByTestId(
+ `routing-policy-row-${MOCK_ROUTING_POLICY_1.id}-name`,
+ ),
);
- // Check for loading spinner by class name
- expect(document.querySelector('.ant-spin-spinning')).toBeInTheDocument();
- // Check that the table is in loading state (blurred)
- expect(document.querySelector('.ant-spin-blur')).toBeInTheDocument();
+
+ expect(
+ screen.queryByTestId(`routing-policy-actions-${MOCK_ROUTING_POLICY_1.id}`),
+ ).not.toBeInTheDocument();
+ expect(onEdit).not.toHaveBeenCalled();
});
- it('renders error state', () => {
- render(
- <RoutingPoliciesList
- routingPolicies={[]}
- isRoutingPoliciesLoading={false}
- isRoutingPoliciesError
- handlePolicyDetailsModalOpen={mockHandlePolicyDetailsModalOpen}
- handleDeleteModalOpen={mockHandleDeleteModalOpen}
- hasSearchTerm={false}
- refetchRoutingPolicies={mockRefetchRoutingPolicies}
- isRoutingPoliciesFetching={false}
- />,
+ it('renders the error state with a refresh', async () => {
+ const { refetch } = renderList({ isError: true, routingPolicies: [] });
+
+ expect(screen.getByTestId('error-title')).toHaveTextContent(
+ 'Failed to load routing policies',
);
+ await userEvent.click(screen.getByTestId('error-refresh-button'));
+ expect(refetch).toHaveBeenCalled();
+ });
+
+ it('renders the no-results state when a search matches nothing', async () => {
+ const { onClearSearch } = renderList({
+ routingPolicies: [],
+ pagedPolicies: [],
+ hasSearchTerm: true,
+ });
+
+ await userEvent.click(screen.getByTestId('no-results-clear-button'));
+ expect(onClearSearch).toHaveBeenCalled();
+ });
+
+ it('renders the empty state with a create action', async () => {
+ const { onCreate } = renderList({ routingPolicies: [], pagedPolicies: [] });
+
expect(
- screen.getByText('Something went wrong while fetching routing policies.'),
+ screen.getByTestId('routing-policies-empty-state'),
).toBeInTheDocument();
-
- const retryButton = screen.getByRole('button', { name: 'Retry' });
- expect(retryButton).toBeInTheDocument();
- fireEvent.click(retryButton);
- expect(mockRefetchRoutingPolicies).toHaveBeenCalled();
+ await userEvent.click(screen.getByTestId('routing-policies-empty-create'));
+ expect(onCreate).toHaveBeenCalled();
});
- it('renders empty state', () => {
- render(
- <RoutingPoliciesList
- routingPolicies={[]}
- isRoutingPoliciesLoading={false}
- isRoutingPoliciesError={false}
- handlePolicyDetailsModalOpen={mockHandlePolicyDetailsModalOpen}
- handleDeleteModalOpen={mockHandleDeleteModalOpen}
- hasSearchTerm={false}
- refetchRoutingPolicies={mockRefetchRoutingPolicies}
- isRoutingPoliciesFetching={false}
- />,
- );
- expect(screen.getByText('No routing policies yet,')).toBeInTheDocument();
+ it('hides the empty-state create action for viewers', () => {
+ renderList({ routingPolicies: [], pagedPolicies: [], canEdit: false });
+
+ expect(
+ screen.queryByTestId('routing-policies-empty-create'),
+ ).not.toBeInTheDocument();
});
});
diff --git a/frontend/src/container/RoutingPolicies/__tests__/RoutingPolicyListItem.test.tsx b/frontend/src/container/RoutingPolicies/__tests__/RoutingPolicyListItem.test.tsx
deleted file mode 100644
index aaf8a2feab..0000000000
--- a/frontend/src/container/RoutingPolicies/__tests__/RoutingPolicyListItem.test.tsx
+++ /dev/null
@@ -1,126 +0,0 @@
-import { fireEvent, render, screen } from '@testing-library/react';
-import * as appHooks from 'providers/App/App';
-import { ROLES, USER_ROLES } from 'types/roles';
-
-import RoutingPolicyListItem from '../RoutingPolicyListItem';
-import { getAppContextMockState, MOCK_ROUTING_POLICY_1 } from './testUtils';
-
-const mockFormatTimezoneAdjustedTimestamp = jest.fn();
-jest.mock('providers/Timezone', () => ({
- useTimezone: (): any => ({
- formatTimezoneAdjustedTimestamp: mockFormatTimezoneAdjustedTimestamp,
- }),
-}));
-
-jest.spyOn(appHooks, 'useAppContext').mockReturnValue(getAppContextMockState());
-
-const mockRoutingPolicy = MOCK_ROUTING_POLICY_1;
-const mockHandlePolicyDetailsModalOpen = jest.fn();
-const mockHandleDeleteModalOpen = jest.fn();
-
-const EDIT_ROUTING_POLICY_TEST_ID = 'edit-routing-policy';
-const DELETE_ROUTING_POLICY_TEST_ID = 'delete-routing-policy';
-
-describe('RoutingPolicyListItem', () => {
- it('should render properly in collapsed state', () => {
- render(
- <RoutingPolicyListItem
- routingPolicy={mockRoutingPolicy}
- handlePolicyDetailsModalOpen={mockHandlePolicyDetailsModalOpen}
- handleDeleteModalOpen={mockHandleDeleteModalOpen}
- />,
- );
- expect(screen.getByText(mockRoutingPolicy.name)).toBeInTheDocument();
- expect(screen.getByTestId(EDIT_ROUTING_POLICY_TEST_ID)).toBeInTheDocument();
- expect(screen.getByTestId(DELETE_ROUTING_POLICY_TEST_ID)).toBeInTheDocument();
- });
-
- it('should render properly in expanded state', () => {
- render(
- <RoutingPolicyListItem
- routingPolicy={mockRoutingPolicy}
- handlePolicyDetailsModalOpen={mockHandlePolicyDetailsModalOpen}
- handleDeleteModalOpen={mockHandleDeleteModalOpen}
- />,
- );
- expect(screen.getByText(mockRoutingPolicy.name)).toBeInTheDocument();
-
- fireEvent.click(screen.getByText(mockRoutingPolicy.name));
-
- expect(screen.getByText(mockRoutingPolicy.expression)).toBeInTheDocument();
- expect(screen.getByText(mockRoutingPolicy.channels[0])).toBeInTheDocument();
- expect(
- screen.getByText(mockRoutingPolicy.createdBy || '[email protected]'),
- ).toBeInTheDocument();
- expect(
- screen.getByText(mockRoutingPolicy.description || 'description 1'),
- ).toBeInTheDocument();
- });
-
- it('should call handlePolicyDetailsModalOpen when edit button is clicked', () => {
- render(
- <RoutingPolicyListItem
- routingPolicy={mockRoutingPolicy}
- handlePolicyDetailsModalOpen={mockHandlePolicyDetailsModalOpen}
- handleDeleteModalOpen={mockHandleDeleteModalOpen}
- />,
- );
- fireEvent.click(screen.getByTestId(EDIT_ROUTING_POLICY_TEST_ID));
- expect(mockHandlePolicyDetailsModalOpen).toHaveBeenCalledWith(
- 'edit',
- mockRoutingPolicy,
- );
- });
-
- it('should call handleDeleteModalOpen when delete button is clicked', () => {
- render(
- <RoutingPolicyListItem
- routingPolicy={mockRoutingPolicy}
- handlePolicyDetailsModalOpen={mockHandlePolicyDetailsModalOpen}
- handleDeleteModalOpen={mockHandleDeleteModalOpen}
- />,
- );
- fireEvent.click(screen.getByTestId(DELETE_ROUTING_POLICY_TEST_ID));
- expect(mockHandleDeleteModalOpen).toHaveBeenCalledWith(mockRoutingPolicy);
- });
-
- it('edit and delete buttons should not be rendered for viewer role', () => {
- jest
- .spyOn(appHooks, 'useAppContext')
- .mockReturnValue(
- getAppContextMockState({ role: USER_ROLES.VIEWER as ROLES }),
- );
- render(
- <RoutingPolicyListItem
- routingPolicy={mockRoutingPolicy}
- handlePolicyDetailsModalOpen={mockHandlePolicyDetailsModalOpen}
- handleDeleteModalOpen={mockHandleDeleteModalOpen}
- />,
- );
- expect(
- screen.queryByTestId(EDIT_ROUTING_POLICY_TEST_ID),
- ).not.toBeInTheDocument();
- expect(
- screen.queryByTestId(DELETE_ROUTING_POLICY_TEST_ID),
- ).not.toBeInTheDocument();
- });
-
- it('in details panel, show "-" for undefined values', () => {
- render(
- <RoutingPolicyListItem
- routingPolicy={mockRoutingPolicy}
- handlePolicyDetailsModalOpen={mockHandlePolicyDetailsModalOpen}
- handleDeleteModalOpen={mockHandleDeleteModalOpen}
- />,
- );
-
- // Expand the details panel
- fireEvent.click(screen.getByText(mockRoutingPolicy.name));
-
- const updatedByRow = screen.getByText('Updated by').parentElement;
- expect(updatedByRow).toHaveTextContent('-');
-
- const updatedOnRow = screen.getByText('Updated on').parentElement;
- expect(updatedOnRow).toHaveTextContent('-');
- });
-});
diff --git a/frontend/src/container/RoutingPolicies/__tests__/testUtils.ts b/frontend/src/container/RoutingPolicies/__tests__/testUtils.ts
index 3e360afd65..42a7e1af5e 100644
--- a/frontend/src/container/RoutingPolicies/__tests__/testUtils.ts
+++ b/frontend/src/container/RoutingPolicies/__tests__/testUtils.ts
@@ -11,7 +11,7 @@ export const MOCK_ROUTING_POLICY_1: RoutingPolicy = {
description: 'description 1',
channels: ['Channel 1'],
createdAt: '2021-01-04',
- updatedAt: undefined,
+ updatedAt: '2021-01-04',
createdBy: '[email protected]',
updatedBy: undefined,
};
@@ -149,7 +149,7 @@ export function convertRoutingPolicyToApiResponse(
id: routingPolicy.id,
name: routingPolicy.name,
expression: routingPolicy.expression,
- channels: routingPolicy.channels,
+ channels: routingPolicy.channels ?? [],
description: routingPolicy.description || '',
createdAt: routingPolicy.createdAt || '',
updatedAt: routingPolicy.updatedAt || '',
diff --git a/frontend/src/container/RoutingPolicies/styles.scss b/frontend/src/container/RoutingPolicies/styles.scss
index 0df910273e..a277307f0f 100644
--- a/frontend/src/container/RoutingPolicies/styles.scss
+++ b/frontend/src/container/RoutingPolicies/styles.scss
@@ -1,173 +1,3 @@
-.routing-policies-container {
- display: flex;
- justify-content: center;
- width: 100%;
- margin-top: 8px;
-
- .routing-policies-content {
- width: calc(100% - 30px);
- max-width: 736px;
-
- .title {
- color: var(--l1-foreground);
- font-size: var(--font-size-lg);
- font-style: normal;
- font-weight: var(--font-weight-normal);
- line-height: 28px;
- letter-spacing: -0.09px;
- }
-
- .subtitle {
- color: var(--l2-foreground);
- font-size: var(--font-size-sm);
- font-style: normal;
- font-weight: var(--font-weight-normal);
- line-height: 20px;
- letter-spacing: -0.07px;
- }
-
- .ant-input-affix-wrapper {
- margin-top: 16px;
- margin-bottom: 8px;
- }
-
- .toolbar {
- display: flex;
- align-items: center;
- gap: 8px;
- margin-top: 12px;
- }
-
- .routing-policies-table {
- .no-routing-policies-message-container {
- display: flex;
- flex-direction: column;
- justify-content: center;
- align-items: center;
- gap: 16px;
- min-height: 200px;
-
- .error-state {
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- gap: 16px;
-
- .ant-btn {
- display: flex;
- align-items: center;
- }
- }
-
- .empty-state-svg {
- width: 40px;
- height: 40px;
- }
-
- .ant-typography {
- color: var(--l2-foreground);
- }
- }
- }
- }
-}
-
-.routing-policies-table {
- .ant-table {
- background: none !important;
- }
- .ant-table-cell {
- padding: 0 !important;
- border: 0 !important;
- width: 736px;
- }
-
- .ant-table-tbody {
- display: flex;
- flex-direction: column;
- gap: 16px;
-
- .policy-list-item {
- border: 1px solid var(--l1-border);
- background-color: var(--l2-background);
- border-radius: 6px;
-
- .ant-collapse-header {
- height: 56px;
- align-items: center;
- }
-
- .policy-list-item-header {
- .ant-typography {
- color: var(--l2-foreground);
- font-family: Inter;
- font-size: 14px;
- font-weight: 400;
- line-height: 18px;
- }
-
- .policy-list-item-header-title {
- min-width: 0;
- display: block;
- flex: 0 1 500px;
- max-width: 100%;
- overflow: hidden;
- }
-
- .action-btn {
- display: flex;
- align-items: center;
- cursor: pointer;
-
- .ant-btn {
- display: flex;
- align-items: center;
- justify-content: center;
- }
- }
- }
-
- .policy-list-item-content {
- .policy-list-item-content-row {
- display: grid;
- grid-template-columns: 128px 1fr;
- margin-bottom: 13px;
-
- .ant-typography:first-child {
- color: var(--l2-foreground);
- font-family: Inter;
- font-size: 13px;
- font-weight: 400;
- line-height: 20px;
- }
-
- .ant-typography:last-child,
- div .ant-typography {
- color: var(--l1-foreground);
- font-family: Inter;
- font-size: 13px;
- font-weight: 400;
- line-height: 18px;
- }
- }
- }
-
- .ant-collapse-content-box {
- padding: 12px 20px 12px 38px;
- }
-
- .ant-collapse-content-active {
- border-top: none;
- }
-
- .ant-collapse-item {
- border: none;
- }
- }
- }
-}
-
.create-policy-modal {
.ant-modal-content {
padding: 16px;
diff --git a/frontend/src/container/RoutingPolicies/table.config.tsx b/frontend/src/container/RoutingPolicies/table.config.tsx
new file mode 100644
index 0000000000..5fdcc786da
--- /dev/null
+++ b/frontend/src/container/RoutingPolicies/table.config.tsx
@@ -0,0 +1,144 @@
+import { Badge } from '@signozhq/ui/badge';
+import type { TableColumnDef } from 'components/TanStackTableView';
+import TanStackTable from 'components/TanStackTableView';
+import { DATE_TIME_FORMATS } from 'constants/dateTimeFormats';
+import { toRelativeTime } from 'pages/AlertList/NotificationChannels/utils/relativeTime';
+
+import styles from './RoutingPolicies.module.scss';
+import { RoutingPolicy } from './types';
+
+export function getRoutingPolicyColumns(
+ formatTimezoneAdjustedTimestamp: (date: string, format: string) => string,
+): TableColumnDef<RoutingPolicy>[] {
+ const textCell = (value: string | null | undefined): JSX.Element => (
+ <TanStackTable.Text title={value ?? undefined}>
+ {value || '-'}
+ </TanStackTable.Text>
+ );
+
+ const timestampCell = (
+ row: RoutingPolicy,
+ value: string | null | undefined,
+ ): JSX.Element => {
+ if (!value) {
+ return <TanStackTable.Text>-</TanStackTable.Text>;
+ }
+
+ return (
+ <TanStackTable.HoverTooltip
+ rowId={row.id}
+ title={formatTimezoneAdjustedTimestamp(
+ value,
+ DATE_TIME_FORMATS.DASH_DATETIME,
+ )}
+ >
+ <span className={styles.timeText}>{toRelativeTime(value)}</span>
+ </TanStackTable.HoverTooltip>
+ );
+ };
+
+ return [
+ {
+ id: 'name',
+ header: 'Routing Policy',
+ accessorKey: 'name',
+ width: { default: '100%', min: '220px' },
+ enableSort: true,
+ enableResize: true,
+ enableRemove: false,
+ enableMove: false,
+ cell: ({ row }): JSX.Element => (
+ <TanStackTable.Text
+ title={row.name}
+ data-testid={`routing-policy-row-${row.id}-name`}
+ >
+ {row.name}
+ </TanStackTable.Text>
+ ),
+ },
+ {
+ id: 'expression',
+ header: 'Expression',
+ accessorKey: 'expression',
+ width: { default: '260px', min: '160px' },
+ enableSort: false,
+ enableResize: true,
+ enableMove: false,
+ cell: ({ row }): JSX.Element => (
+ <TanStackTable.Text className={styles.expression} title={row.expression}>
+ {row.expression}
+ </TanStackTable.Text>
+ ),
+ },
+ {
+ id: 'channels',
+ header: 'Channels',
+ accessorKey: 'channels',
+ width: { default: '220px', min: '140px' },
+ enableSort: false,
+ enableResize: true,
+ enableMove: false,
+ cell: ({ row }): JSX.Element =>
+ row.channels?.length ? (
+ <div className={styles.badges} title={row.channels.join(', ')}>
+ {row.channels.map((channel) => (
+ <Badge
+ key={channel}
+ textTransform="none"
+ variant="solid"
+ color="secondary"
+ >
+ {channel}
+ </Badge>
+ ))}
+ </div>
+ ) : (
+ <TanStackTable.Text>-</TanStackTable.Text>
+ ),
+ },
+ {
+ id: 'createdBy',
+ header: 'Created By',
+ accessorKey: 'createdBy',
+ width: { default: '180px', min: '120px' },
+ defaultVisibility: false,
+ enableSort: false,
+ enableResize: true,
+ enableMove: false,
+ cell: ({ row }): JSX.Element => textCell(row.createdBy),
+ },
+ {
+ id: 'createdAt',
+ header: 'Created At',
+ accessorKey: 'createdAt',
+ width: { default: '150px', min: '120px' },
+ defaultVisibility: false,
+ enableSort: true,
+ enableResize: true,
+ enableMove: false,
+ cell: ({ row }): JSX.Element => timestampCell(row, row.createdAt),
+ },
+ {
+ id: 'updatedBy',
+ header: 'Updated By',
+ accessorKey: 'updatedBy',
+ width: { default: '180px', min: '120px' },
+ defaultVisibility: false,
+ enableSort: false,
+ enableResize: true,
+ enableMove: false,
+ cell: ({ row }): JSX.Element => textCell(row.updatedBy),
+ },
+ {
+ id: 'updatedAt',
+ header: 'Updated At',
+ accessorKey: 'updatedAt',
+ width: { default: '150px', min: '120px' },
+ defaultVisibility: false,
+ enableSort: true,
+ enableResize: true,
+ enableMove: false,
+ cell: ({ row }): JSX.Element => timestampCell(row, row.updatedAt),
+ },
+ ];
+}
diff --git a/frontend/src/container/RoutingPolicies/types.ts b/frontend/src/container/RoutingPolicies/types.ts
index e2ce61042b..f61e3bcbd2 100644
--- a/frontend/src/container/RoutingPolicies/types.ts
+++ b/frontend/src/container/RoutingPolicies/types.ts
@@ -1,16 +1,8 @@
-import { ChannelOption } from 'hooks/notificationChannels/useChannelOptions';
+import type { AlertmanagertypesGettableRoutePolicyDTO } from 'api/generated/services/sigNoz.schemas';
+import type { TableColumnDef } from 'components/TanStackTableView';
+import type { ChannelOption } from 'hooks/notificationChannels/useChannelOptions';
-export interface RoutingPolicy {
- id: string;
- name: string;
- expression: string;
- channels: string[];
- description: string | undefined;
- createdAt: string | undefined;
- updatedAt: string | undefined;
- createdBy: string | undefined;
- updatedBy: string | undefined;
-}
+export type RoutingPolicy = AlertmanagertypesGettableRoutePolicyDTO;
type HandlePolicyDetailsModalOpen = (
mode: PolicyDetailsModalMode,
@@ -32,30 +24,20 @@ type HandleDeleteModalOpen = (routingPolicy: RoutingPolicy) => void;
export type PolicyDetailsModalMode = 'create' | 'edit' | null;
export interface RoutingPolicyListProps {
+ columns: TableColumnDef<RoutingPolicy>[];
routingPolicies: RoutingPolicy[];
- refetchRoutingPolicies: () => void;
- isRoutingPoliciesLoading: boolean;
- isRoutingPoliciesFetching: boolean;
- isRoutingPoliciesError: boolean;
- handlePolicyDetailsModalOpen: HandlePolicyDetailsModalOpen;
- handleDeleteModalOpen: HandleDeleteModalOpen;
+ pagedPolicies: RoutingPolicy[];
+ calculatedPageSize: number | null;
+ onLimitChange: (limit: number) => void;
+ isFetching: boolean;
+ isError: boolean;
+ refetch: () => void;
+ canEdit: boolean;
+ onEdit: (routingPolicy: RoutingPolicy) => void;
+ onDelete: HandleDeleteModalOpen;
+ onCreate: () => void;
hasSearchTerm: boolean;
-}
-
-export interface RoutingPolicyListItemProps {
- routingPolicy: RoutingPolicy;
- handlePolicyDetailsModalOpen: HandlePolicyDetailsModalOpen;
- handleDeleteModalOpen: HandleDeleteModalOpen;
-}
-
-export interface PolicyListItemHeaderProps {
- name: string;
- handleEdit: () => void;
- handleDelete: () => void;
-}
-
-export interface PolicyListItemContentProps {
- routingPolicy: RoutingPolicy;
+ onClearSearch: () => void;
}
export interface RoutingPolicyDetailsProps {
diff --git a/frontend/src/container/RoutingPolicies/useRoutingPolicies.ts b/frontend/src/container/RoutingPolicies/useRoutingPolicies.ts
index 5cff9400bf..761306a5bc 100644
--- a/frontend/src/container/RoutingPolicies/useRoutingPolicies.ts
+++ b/frontend/src/container/RoutingPolicies/useRoutingPolicies.ts
@@ -1,4 +1,4 @@
-import { useMemo, useState } from 'react';
+import { useCallback, useMemo, useState } from 'react';
import { useQueryClient } from 'react-query';
import { useHistory } from 'react-router-dom';
import { toast } from '@signozhq/ui/sonner';
@@ -88,22 +88,22 @@ function useRoutingPolicies(): UseRoutingPoliciesReturn {
} = useChannelOptions();
const refreshChannels = (): void => {
- refetchChannels();
+ void refetchChannels();
};
// Handlers
- const handlePolicyDetailsModalOpen = (
- mode: PolicyDetailsModalMode,
- routingPolicy: RoutingPolicy | null,
- ): void => {
- if (routingPolicy) {
- setSelectedRoutingPolicy(routingPolicy);
- }
- setPolicyDetailsModalState({
- isOpen: true,
- mode,
- });
- };
+ const handlePolicyDetailsModalOpen = useCallback(
+ (mode: PolicyDetailsModalMode, routingPolicy: RoutingPolicy | null): void => {
+ if (routingPolicy) {
+ setSelectedRoutingPolicy(routingPolicy);
+ }
+ setPolicyDetailsModalState({
+ isOpen: true,
+ mode,
+ });
+ },
+ [],
+ );
const handlePolicyDetailsModalClose = (): void => {
setSelectedRoutingPolicy(null);
@@ -113,10 +113,13 @@ function useRoutingPolicies(): UseRoutingPoliciesReturn {
});
};
- const handleDeleteModalOpen = (routingPolicy: RoutingPolicy): void => {
- setSelectedRoutingPolicy(routingPolicy);
- setIsDeleteModalOpen(true);
- };
+ const handleDeleteModalOpen = useCallback(
+ (routingPolicy: RoutingPolicy): void => {
+ setSelectedRoutingPolicy(routingPolicy);
+ setIsDeleteModalOpen(true);
+ },
+ [],
+ );
const handleDeleteModalClose = (): void => {
setSelectedRoutingPolicy(null);
@@ -154,7 +157,7 @@ function useRoutingPolicies(): UseRoutingPoliciesReturn {
{
onSuccess: () => {
toast.success('Routing policy created successfully');
- queryClient.invalidateQueries(REACT_QUERY_KEY.GET_ROUTING_POLICIES);
+ void queryClient.invalidateQueries(REACT_QUERY_KEY.GET_ROUTING_POLICIES);
handlePolicyDetailsModalClose();
},
onError: (error) => {
@@ -176,7 +179,7 @@ function useRoutingPolicies(): UseRoutingPoliciesReturn {
{
onSuccess: () => {
toast.success('Routing policy updated successfully');
- queryClient.invalidateQueries(REACT_QUERY_KEY.GET_ROUTING_POLICIES);
+ void queryClient.invalidateQueries(REACT_QUERY_KEY.GET_ROUTING_POLICIES);
handlePolicyDetailsModalClose();
},
onError: () => {
@@ -209,7 +212,7 @@ function useRoutingPolicies(): UseRoutingPoliciesReturn {
deleteRoutingPolicy(selectedRoutingPolicy.id, {
onSuccess: () => {
toast.success('Routing policy deleted successfully');
- queryClient.invalidateQueries(REACT_QUERY_KEY.GET_ROUTING_POLICIES);
+ void queryClient.invalidateQueries(REACT_QUERY_KEY.GET_ROUTING_POLICIES);
handleDeleteModalClose();
},
onError: () => {
diff --git a/frontend/src/container/RoutingPolicies/useRoutingPoliciesTable.ts b/frontend/src/container/RoutingPolicies/useRoutingPoliciesTable.ts
new file mode 100644
index 0000000000..7bf53dcc02
--- /dev/null
+++ b/frontend/src/container/RoutingPolicies/useRoutingPoliciesTable.ts
@@ -0,0 +1,74 @@
+import { RefObject, useMemo } from 'react';
+import { sortByColumn } from 'components/Alerts/utils';
+import { useCalculatedPageSize } from 'components/TanStackTableView/useCalculatedPageSize';
+import { useTableParams } from 'components/TanStackTableView/useTableParams';
+
+import { RoutingPolicy } from './types';
+
+export const ROUTING_POLICIES_QUERY_PARAMS = {
+ orderBy: 'orderBy',
+ page: 'page',
+ limit: 'limit',
+} as const;
+
+const DEFAULT_PAGE = 1;
+const DEFAULT_LIMIT = 10;
+
+function getSortValue(
+ policy: RoutingPolicy,
+ columnName: string,
+): string | number {
+ switch (columnName) {
+ case 'name':
+ return policy.name.toLowerCase();
+ case 'createdAt':
+ return policy.createdAt ? new Date(policy.createdAt).getTime() : 0;
+ case 'updatedAt':
+ return policy.updatedAt ? new Date(policy.updatedAt).getTime() : 0;
+ default:
+ return '';
+ }
+}
+
+interface UseRoutingPoliciesTableReturn {
+ containerRef: RefObject<HTMLDivElement>;
+ calculatedPageSize: number | null;
+ pagedPolicies: RoutingPolicy[];
+ setPage: (page: number) => void;
+ setLimit: (limit: number) => void;
+}
+
+function useRoutingPoliciesTable(
+ routingPolicies: RoutingPolicy[],
+): UseRoutingPoliciesTableReturn {
+ const { containerRef, calculatedPageSize } = useCalculatedPageSize({
+ rowHeight: 46,
+ });
+
+ const { orderBy, page, limit, setLimit, setPage } = useTableParams(
+ ROUTING_POLICIES_QUERY_PARAMS,
+ {
+ page: DEFAULT_PAGE,
+ limit: DEFAULT_LIMIT,
+ storageKey: 'routing-policies',
+ calculatedPageSize,
+ cleanupOnUnmount: true,
+ },
+ );
+
+ const pagedPolicies = useMemo(() => {
+ const sorted = sortByColumn(routingPolicies, orderBy, getSortValue);
+ const start = (page - 1) * limit;
+ return sorted.slice(start, start + limit);
+ }, [routingPolicies, orderBy, page, limit]);
+
+ return {
+ containerRef,
+ calculatedPageSize,
+ pagedPolicies,
+ setPage,
+ setLimit,
+ };
+}
+
+export default useRoutingPoliciesTable;
diff --git a/frontend/src/pages/AlertList/PlannedDowntime/stories/PlannedDowntime.stories.mocks.tsx b/frontend/src/pages/AlertList/PlannedDowntime/stories/PlannedDowntime.stories.mocks.tsx
index 28825edcfa..817f008ed8 100644
--- a/frontend/src/pages/AlertList/PlannedDowntime/stories/PlannedDowntime.stories.mocks.tsx
+++ b/frontend/src/pages/AlertList/PlannedDowntime/stories/PlannedDowntime.stories.mocks.tsx
@@ -4,7 +4,7 @@
*/
import { rest } from 'msw';
-import { userEvent, within } from 'storybook/test';
+import { screen, userEvent, within } from 'storybook/test';
import { choiceControl, countControl } from '@/storybook/controls/controls';
import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';
@@ -111,20 +111,14 @@ export const clickFirstRowAction = async (
canvasElement: HTMLElement,
action: 'edit' | 'delete',
): Promise<void> => {
- const icon = (
- await within(canvasElement).findByText(
- FIRST_DOWNTIME_NAME,
- undefined,
+ await userEvent.click(
+ await within(canvasElement).findByRole(
+ 'button',
+ { name: `Actions for ${FIRST_DOWNTIME_NAME}` },
untilLoaded,
- )
- )
- .closest('.header-content')
- // The row action holds edit then delete, neither of them labelled.
- ?.querySelectorAll('.action-btn svg')[action === 'edit' ? 0 : 1];
-
- if (!icon) {
- throw new Error(`Downtime ${action} action did not render`);
- }
-
- await userEvent.click(icon);
+ ),
+ );
+ await userEvent.click(
+ await screen.findByText(action === 'edit' ? 'Edit' : 'Delete'),
+ );
};
diff --git a/frontend/src/pages/AlertList/PlannedDowntime/stories/PlannedDowntime.stories.tsx b/frontend/src/pages/AlertList/PlannedDowntime/stories/PlannedDowntime.stories.tsx
index 7088ab0e35..d79b7c88da 100644
--- a/frontend/src/pages/AlertList/PlannedDowntime/stories/PlannedDowntime.stories.tsx
+++ b/frontend/src/pages/AlertList/PlannedDowntime/stories/PlannedDowntime.stories.tsx
@@ -47,22 +47,22 @@ export const NoDowntimes: Story = {
};
/**
- * A viewer: the edit and delete actions on a row and the New downtime button
- * are gone.
+ * A viewer: the edit and delete actions on a row are gone and New downtime is
+ * disabled.
*/
export const Viewer: Story = {
args: { access: 'viewer' },
};
-/** A downtime opened up: who scheduled it, the window, and what it silences. */
-export const Expanded: Story = {
+/** A downtime opened from its row: the form prefilled with its window and rules. */
+export const OpenFromRow: Story = {
play: async ({ canvasElement }): Promise<void> => {
const canvas = within(canvasElement);
await userEvent.click(
await canvas.findByText(FIRST_DOWNTIME_NAME, undefined, untilLoaded),
);
- await canvas.findByText(/alerts silenced/i);
+ await screen.findByText(/edit planned downtime/i);
},
};
@@ -97,7 +97,9 @@ export const EditDowntime: Story = {
play: async ({ canvasElement }): Promise<void> => {
await clickFirstRowAction(canvasElement, 'edit');
await screen.findByText(/edit planned downtime/i);
- await screen.findByText(/^Postgres connections/);
+ await within(await screen.findByRole('dialog')).findByText(
+ /^Postgres connections/,
+ );
},
};
@@ -118,13 +120,13 @@ export const SearchNoResults: Story = {
play: async ({ canvasElement }): Promise<void> => {
const canvas = within(canvasElement);
const search = await canvas.findByPlaceholderText(
- 'Search for a planned downtime...',
+ 'Search by name',
undefined,
untilLoaded,
);
await userEvent.type(search, 'no matching downtime');
- await canvas.findByRole('table');
+ await canvas.findByText('No matching planned downtime');
},
};
diff --git a/frontend/src/pages/AlertList/RoutingPolicies/stories/RoutingPolicies.stories.mocks.tsx b/frontend/src/pages/AlertList/RoutingPolicies/stories/RoutingPolicies.stories.mocks.tsx
index e3c2af35ad..153fbf7931 100644
--- a/frontend/src/pages/AlertList/RoutingPolicies/stories/RoutingPolicies.stories.mocks.tsx
+++ b/frontend/src/pages/AlertList/RoutingPolicies/stories/RoutingPolicies.stories.mocks.tsx
@@ -10,6 +10,7 @@ import { choiceControl, countControl } from '@/storybook/controls/controls';
import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';
import {
+ FIRST_POLICY_NAME,
ROUTING_POLICY_MAX,
routingPoliciesResponse,
} from './__story_mockdata__/routingPolicies';
@@ -142,7 +143,8 @@ export const fillNewPolicy = async (): Promise<void> => {
'severity = "critical"',
);
await userEvent.click(await screen.findByRole('combobox'));
- await userEvent.click(await screen.findByTitle('ops-slack'));
+ const options = await screen.findAllByTitle('ops-slack');
+ await userEvent.click(options[options.length - 1]);
await userEvent.keyboard('{Escape}');
await userEvent.click(
await screen.findByRole('button', { name: 'Save Routing Policy' }),
@@ -153,13 +155,11 @@ export const openEditPolicy = async (
canvasElement: HTMLElement,
): Promise<void> => {
await userEvent.click(
- (
- await within(canvasElement).findAllByTestId(
- 'edit-routing-policy',
- undefined,
- untilLoaded,
- )
- )[0],
+ await within(canvasElement).findByText(
+ FIRST_POLICY_NAME,
+ undefined,
+ untilLoaded,
+ ),
);
await userEvent.click(
await screen.findByRole('button', { name: 'Save Routing Policy' }),
diff --git a/frontend/src/pages/AlertList/RoutingPolicies/stories/RoutingPolicies.stories.tsx b/frontend/src/pages/AlertList/RoutingPolicies/stories/RoutingPolicies.stories.tsx
index cdfeab6240..64ccf855b2 100644
--- a/frontend/src/pages/AlertList/RoutingPolicies/stories/RoutingPolicies.stories.tsx
+++ b/frontend/src/pages/AlertList/RoutingPolicies/stories/RoutingPolicies.stories.tsx
@@ -47,20 +47,20 @@ export const NoPolicies: Story = {
args: { policies: 0 },
};
-/** A viewer: the row actions and the New routing policy button are gone. */
+/** A viewer: the row actions are gone and New routing policy is disabled. */
export const Viewer: Story = {
args: { access: 'viewer' },
};
-/** A policy opened up: the expression it matches on and where it sends. */
-export const Expanded: Story = {
+/** A policy opened from its row: the form prefilled with its expression and channels. */
+export const EditPolicy: Story = {
play: async ({ canvasElement }): Promise<void> => {
const canvas = within(canvasElement);
await userEvent.click(
await canvas.findByText(FIRST_POLICY_NAME, undefined, untilLoaded),
);
- await canvas.findByText(/expression/i);
+ await screen.findByText(/edit routing policy/i);
},
};
@@ -83,15 +83,13 @@ export const DeletePolicyConfirm: Story = {
play: async ({ canvasElement }): Promise<void> => {
const canvas = within(canvasElement);
- await userEvent.click(
- (
- await canvas.findAllByTestId(
- 'delete-routing-policy',
- undefined,
- untilLoaded,
- )
- )[0],
+ const [firstRowActions] = await canvas.findAllByRole(
+ 'button',
+ { name: /^Actions for / },
+ untilLoaded,
);
+ await userEvent.click(firstRowActions);
+ await userEvent.click(await screen.findByText('Delete'));
// The modal titles itself and its confirm button the same.
await screen.findByRole('button', { name: 'Delete Routing Policy' });
},
@@ -102,13 +100,13 @@ export const SearchNoResults: Story = {
play: async ({ canvasElement }): Promise<void> => {
const canvas = within(canvasElement);
const search = await canvas.findByPlaceholderText(
- 'Search for a routing policy...',
+ 'Search by name or description',
undefined,
untilLoaded,
);
await userEvent.type(search, 'no matching policy');
- await canvas.findByText('No matching routing policies found.');
+ await canvas.findByText('No matching routing policies');
},
};
@@ -140,6 +138,10 @@ export const FormValidationError: Story = {
},
};
+const expectToast = async (text: RegExp): Promise<void> => {
+ await waitFor(() => expect(screen.getByText(text)).toBeVisible());
+};
+
const confirmDelete = async (canvasElement: HTMLElement): Promise<void> => {
await DeletePolicyConfirm.play?.({ canvasElement } as never);
await userEvent.click(
@@ -152,13 +154,11 @@ export const CreatePolicyToast: Story = {
play: async ({ canvasElement, args }): Promise<void> => {
await NewPolicy.play?.({ canvasElement } as never);
await fillNewPolicy();
- if (args.createState === 'success') {
- await waitFor(() =>
- expect(
- screen.getByText(/routing policy created successfully/i),
- ).toBeVisible(),
- );
- }
+ await expectToast(
+ args.createState === 'success'
+ ? /routing policy created successfully/i
+ : /Policy name already exists/i,
+ );
},
};
@@ -173,13 +173,11 @@ export const CreatePolicyErrorToast: Story = {
export const UpdatePolicyToast: Story = {
play: async ({ canvasElement, args }): Promise<void> => {
await openEditPolicy(canvasElement);
- if (args.updateState === 'success') {
- await waitFor(() =>
- expect(
- screen.getByText(/routing policy updated successfully/i),
- ).toBeVisible(),
- );
- }
+ await expectToast(
+ args.updateState === 'success'
+ ? /routing policy updated successfully/i
+ : /failed to update routing policy/i,
+ );
},
};
@@ -194,13 +192,11 @@ export const UpdatePolicyErrorToast: Story = {
export const DeletePolicyToast: Story = {
play: async ({ canvasElement, args }): Promise<void> => {
await confirmDelete(canvasElement);
- if (args.deleteState === 'success') {
- await waitFor(() =>
- expect(
- screen.getByText(/routing policy deleted successfully/i),
- ).toBeVisible(),
- );
- }
+ await expectToast(
+ args.deleteState === 'success'
+ ? /routing policy deleted successfully/i
+ : /failed to delete routing policy/i,
+ );
},
};