activatedRuleRow.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. import {useMemo, useState} from 'react';
  2. import styled from '@emotion/styled';
  3. import Access from 'sentry/components/acl/access';
  4. import ActorAvatar from 'sentry/components/avatar/actorAvatar';
  5. import TeamAvatar from 'sentry/components/avatar/teamAvatar';
  6. import AlertBadge from 'sentry/components/badge/alertBadge';
  7. import {openConfirmModal} from 'sentry/components/confirm';
  8. import DropdownAutoComplete from 'sentry/components/dropdownAutoComplete';
  9. import type {ItemsBeforeFilter} from 'sentry/components/dropdownAutoComplete/types';
  10. import DropdownBubble from 'sentry/components/dropdownBubble';
  11. import type {MenuItemProps} from 'sentry/components/dropdownMenu';
  12. import {DropdownMenu} from 'sentry/components/dropdownMenu';
  13. import ErrorBoundary from 'sentry/components/errorBoundary';
  14. import IdBadge from 'sentry/components/idBadge';
  15. import Link from 'sentry/components/links/link';
  16. import LoadingIndicator from 'sentry/components/loadingIndicator';
  17. import TextOverflow from 'sentry/components/textOverflow';
  18. import TimeSince from 'sentry/components/timeSince';
  19. import {Tooltip} from 'sentry/components/tooltip';
  20. import {IconArrow, IconChevron, IconEllipsis, IconMute, IconUser} from 'sentry/icons';
  21. import {t, tct} from 'sentry/locale';
  22. import {space} from 'sentry/styles/space';
  23. import type {Actor, Project} from 'sentry/types';
  24. import type {ColorOrAlias} from 'sentry/utils/theme';
  25. import {useUserTeams} from 'sentry/utils/useUserTeams';
  26. import {getThresholdUnits} from 'sentry/views/alerts/rules/metric/constants';
  27. import {
  28. AlertRuleComparisonType,
  29. AlertRuleThresholdType,
  30. AlertRuleTriggerType,
  31. } from 'sentry/views/alerts/rules/metric/types';
  32. import type {CombinedMetricIssueAlerts, MetricAlert} from '../../types';
  33. import {ActivationStatus, CombinedAlertType, IncidentStatus} from '../../types';
  34. type Props = {
  35. hasEditAccess: boolean;
  36. onDelete: (projectId: string, rule: CombinedMetricIssueAlerts) => void;
  37. onOwnerChange: (
  38. projectId: string,
  39. rule: CombinedMetricIssueAlerts,
  40. ownerValue: string
  41. ) => void;
  42. orgId: string;
  43. projects: Project[];
  44. projectsLoaded: boolean;
  45. rule: MetricAlert;
  46. };
  47. function ActivatedRuleListRow({
  48. rule,
  49. projectsLoaded,
  50. projects,
  51. orgId,
  52. onDelete,
  53. onOwnerChange,
  54. hasEditAccess,
  55. }: Props) {
  56. const {teams: userTeams} = useUserTeams();
  57. const [assignee, setAssignee] = useState<string>('');
  58. const isWaiting = useMemo(
  59. () =>
  60. !rule.activations?.length ||
  61. (rule.activations?.length && rule.activations[0].isComplete),
  62. [rule]
  63. );
  64. function renderLatestActivation(): React.ReactNode {
  65. if (!rule.activations?.length) {
  66. return t('Alert has not been activated yet');
  67. }
  68. return (
  69. <div>
  70. {t('Last activated ')}
  71. <TimeSince date={rule.activations[0].dateCreated} />
  72. </div>
  73. );
  74. }
  75. function renderSnoozeStatus(): React.ReactNode {
  76. return (
  77. <IssueAlertStatusWrapper>
  78. <IconMute size="sm" color="subText" />
  79. {t('Muted')}
  80. </IssueAlertStatusWrapper>
  81. );
  82. }
  83. function renderAlertRuleStatus(): React.ReactNode {
  84. if (rule.snooze) {
  85. return renderSnoozeStatus();
  86. }
  87. const isUnhealthy =
  88. rule.latestIncident?.status !== undefined &&
  89. [IncidentStatus.CRITICAL, IncidentStatus.WARNING].includes(
  90. rule.latestIncident.status
  91. );
  92. let iconColor: ColorOrAlias = 'successText';
  93. let iconDirection: 'up' | 'down' =
  94. rule.thresholdType === AlertRuleThresholdType.ABOVE ? 'down' : 'up';
  95. let thresholdTypeText =
  96. rule.thresholdType === AlertRuleThresholdType.ABOVE ? t('Below') : t('Above');
  97. if (isUnhealthy) {
  98. iconColor =
  99. rule.latestIncident?.status === IncidentStatus.CRITICAL
  100. ? 'errorText'
  101. : 'warningText';
  102. // if unhealthy, swap icon direction
  103. iconDirection = rule.thresholdType === AlertRuleThresholdType.ABOVE ? 'up' : 'down';
  104. thresholdTypeText =
  105. rule.thresholdType === AlertRuleThresholdType.ABOVE ? t('Above') : t('Below');
  106. }
  107. let threshold = rule.triggers.find(
  108. ({label}) => label === AlertRuleTriggerType.CRITICAL
  109. )?.alertThreshold;
  110. if (isUnhealthy && rule.latestIncident?.status === IncidentStatus.WARNING) {
  111. threshold = rule.triggers.find(
  112. ({label}) => label === AlertRuleTriggerType.WARNING
  113. )?.alertThreshold;
  114. } else if (!isUnhealthy && rule.latestIncident && rule.resolveThreshold) {
  115. threshold = rule.resolveThreshold;
  116. }
  117. return (
  118. <FlexCenter>
  119. <IconArrow color={iconColor} direction={iconDirection} />
  120. <TriggerText>
  121. {`${thresholdTypeText} ${threshold}`}
  122. {getThresholdUnits(
  123. rule.aggregate,
  124. rule.comparisonDelta
  125. ? AlertRuleComparisonType.CHANGE
  126. : AlertRuleComparisonType.COUNT
  127. )}
  128. </TriggerText>
  129. </FlexCenter>
  130. );
  131. }
  132. const slug = rule.projects[0];
  133. const editLink = `/organizations/${orgId}/alerts/metric-rules/${slug}/${rule.id}/`;
  134. const duplicateLink = {
  135. pathname: `/organizations/${orgId}/alerts/new/${
  136. rule.type === CombinedAlertType.METRIC ? 'metric' : 'issue'
  137. }/`,
  138. query: {
  139. project: slug,
  140. duplicateRuleId: rule.id,
  141. createFromDuplicate: true,
  142. referrer: 'alert_stream',
  143. },
  144. };
  145. const ownerId = rule.owner?.split(':')[1];
  146. const teamActor = ownerId
  147. ? {type: 'team' as Actor['type'], id: ownerId, name: ''}
  148. : null;
  149. const canEdit = ownerId ? userTeams.some(team => team.id === ownerId) : true;
  150. const actions: MenuItemProps[] = [
  151. {
  152. key: 'edit',
  153. label: t('Edit'),
  154. to: editLink,
  155. },
  156. {
  157. key: 'duplicate',
  158. label: t('Duplicate'),
  159. to: duplicateLink,
  160. },
  161. {
  162. key: 'delete',
  163. label: t('Delete'),
  164. priority: 'danger',
  165. onAction: () => {
  166. openConfirmModal({
  167. onConfirm: () => onDelete(slug, rule),
  168. header: <h5>{t('Delete Alert Rule?')}</h5>,
  169. message: t(
  170. 'Are you sure you want to delete "%s"? You won\'t be able to view the history of this alert once it\'s deleted.',
  171. rule.name
  172. ),
  173. confirmText: t('Delete Rule'),
  174. priority: 'danger',
  175. });
  176. },
  177. },
  178. ];
  179. function handleOwnerChange({value}: {value: string}) {
  180. const ownerValue = value && `team:${value}`;
  181. setAssignee(ownerValue);
  182. onOwnerChange(slug, rule, ownerValue);
  183. }
  184. const unassignedOption: ItemsBeforeFilter[number] = {
  185. value: '',
  186. label: (
  187. <MenuItemWrapper>
  188. <PaddedIconUser size="lg" />
  189. <Label>{t('Unassigned')}</Label>
  190. </MenuItemWrapper>
  191. ),
  192. searchKey: 'unassigned',
  193. actor: '',
  194. disabled: false,
  195. };
  196. const project = projects.find(p => p.slug === slug);
  197. const filteredProjectTeams = (project?.teams ?? []).filter(projTeam => {
  198. return userTeams.some(team => team.id === projTeam.id);
  199. });
  200. const dropdownTeams = filteredProjectTeams
  201. .map<ItemsBeforeFilter[number]>((team, idx) => ({
  202. value: team.id,
  203. searchKey: team.slug,
  204. label: (
  205. <MenuItemWrapper data-test-id="assignee-option" key={idx}>
  206. <IconContainer>
  207. <TeamAvatar team={team} size={24} />
  208. </IconContainer>
  209. <Label>#{team.slug}</Label>
  210. </MenuItemWrapper>
  211. ),
  212. }))
  213. .concat(unassignedOption);
  214. const teamId = assignee?.split(':')[1];
  215. const teamName = filteredProjectTeams.find(team => team.id === teamId);
  216. const assigneeTeamActor = assignee && {
  217. type: 'team' as Actor['type'],
  218. id: teamId,
  219. name: '',
  220. };
  221. const avatarElement = assigneeTeamActor ? (
  222. <ActorAvatar
  223. actor={assigneeTeamActor}
  224. className="avatar"
  225. size={24}
  226. tooltipOptions={{overlayStyle: {textAlign: 'left'}}}
  227. tooltip={tct('Assigned to [name]', {name: teamName && `#${teamName.name}`})}
  228. />
  229. ) : (
  230. <Tooltip isHoverable skipWrapper title={t('Unassigned')}>
  231. <PaddedIconUser size="lg" color="gray400" />
  232. </Tooltip>
  233. );
  234. return (
  235. <ErrorBoundary>
  236. <AlertNameWrapper>
  237. <AlertNameAndStatus>
  238. <AlertName>
  239. <Link to={`/organizations/${orgId}/alerts/rules/details/${rule.id}/`}>
  240. {rule.name}
  241. </Link>
  242. </AlertName>
  243. <AlertActivationDate>{renderLatestActivation()}</AlertActivationDate>
  244. </AlertNameAndStatus>
  245. </AlertNameWrapper>
  246. <FlexCenter>
  247. <FlexCenter>
  248. <Tooltip
  249. title={tct('Metric Alert Status: [status]', {
  250. status: isWaiting ? 'Ready to monitor' : 'Monitoring',
  251. })}
  252. >
  253. <AlertBadge
  254. status={rule?.latestIncident?.status}
  255. activationStatus={
  256. isWaiting ? ActivationStatus.WAITING : ActivationStatus.MONITORING
  257. }
  258. />
  259. </Tooltip>
  260. </FlexCenter>
  261. <MarginLeft>{renderAlertRuleStatus()}</MarginLeft>
  262. </FlexCenter>
  263. <FlexCenter>
  264. <ProjectBadgeContainer>
  265. <ProjectBadge
  266. avatarSize={18}
  267. project={projectsLoaded && project ? project : {slug}}
  268. />
  269. </ProjectBadgeContainer>
  270. </FlexCenter>
  271. <FlexCenter>
  272. {teamActor ? (
  273. <ActorAvatar actor={teamActor} size={24} />
  274. ) : (
  275. <AssigneeWrapper>
  276. {!projectsLoaded && <StyledLoadingIndicator mini />}
  277. {projectsLoaded && (
  278. <DropdownAutoComplete
  279. data-test-id="alert-row-assignee"
  280. maxHeight={400}
  281. onOpen={e => {
  282. e?.stopPropagation();
  283. }}
  284. items={dropdownTeams}
  285. alignMenu="right"
  286. onSelect={handleOwnerChange}
  287. itemSize="small"
  288. searchPlaceholder={t('Filter teams')}
  289. disableLabelPadding
  290. emptyHidesInput
  291. disabled={!hasEditAccess}
  292. >
  293. {({getActorProps, isOpen}) => (
  294. <DropdownButton {...getActorProps({})}>
  295. {avatarElement}
  296. {hasEditAccess && (
  297. <StyledChevron direction={isOpen ? 'up' : 'down'} size="xs" />
  298. )}
  299. </DropdownButton>
  300. )}
  301. </DropdownAutoComplete>
  302. )}
  303. </AssigneeWrapper>
  304. )}
  305. </FlexCenter>
  306. <ActionsColumn>
  307. <Access access={['alerts:write']}>
  308. {({hasAccess}) => (
  309. <DropdownMenu
  310. items={actions}
  311. position="bottom-end"
  312. triggerProps={{
  313. 'aria-label': t('Actions'),
  314. size: 'xs',
  315. icon: <IconEllipsis />,
  316. showChevron: false,
  317. }}
  318. disabledKeys={hasAccess && canEdit ? [] : ['delete']}
  319. />
  320. )}
  321. </Access>
  322. </ActionsColumn>
  323. </ErrorBoundary>
  324. );
  325. }
  326. // TODO: see static/app/components/profiling/flex.tsx and utilize the FlexContainer styled component
  327. const FlexCenter = styled('div')`
  328. display: flex;
  329. align-items: center;
  330. `;
  331. const IssueAlertStatusWrapper = styled('div')`
  332. display: flex;
  333. align-items: center;
  334. gap: ${space(1)};
  335. line-height: 2;
  336. `;
  337. const AlertNameWrapper = styled('div')<{isIssueAlert?: boolean}>`
  338. ${p => p.theme.overflowEllipsis}
  339. display: flex;
  340. align-items: center;
  341. gap: ${space(2)};
  342. ${p => p.isIssueAlert && `padding: ${space(3)} ${space(2)}; line-height: 2.4;`}
  343. `;
  344. const AlertNameAndStatus = styled('div')`
  345. ${p => p.theme.overflowEllipsis}
  346. line-height: 1.35;
  347. `;
  348. const AlertName = styled('div')`
  349. ${p => p.theme.overflowEllipsis}
  350. font-size: ${p => p.theme.fontSizeLarge};
  351. `;
  352. const AlertActivationDate = styled('div')`
  353. color: ${p => p.theme.gray300};
  354. `;
  355. const ProjectBadgeContainer = styled('div')`
  356. width: 100%;
  357. `;
  358. const ProjectBadge = styled(IdBadge)`
  359. flex-shrink: 0;
  360. `;
  361. const TriggerText = styled('div')`
  362. margin-left: ${space(1)};
  363. white-space: nowrap;
  364. font-variant-numeric: tabular-nums;
  365. `;
  366. const ActionsColumn = styled('div')`
  367. display: flex;
  368. align-items: center;
  369. justify-content: center;
  370. padding: ${space(1)};
  371. `;
  372. const AssigneeWrapper = styled('div')`
  373. display: flex;
  374. justify-content: flex-end;
  375. /* manually align menu underneath dropdown caret */
  376. ${DropdownBubble} {
  377. right: -14px;
  378. }
  379. `;
  380. const DropdownButton = styled('div')`
  381. display: flex;
  382. align-items: center;
  383. font-size: 20px;
  384. `;
  385. const StyledChevron = styled(IconChevron)`
  386. margin-left: ${space(1)};
  387. `;
  388. const PaddedIconUser = styled(IconUser)`
  389. padding: ${space(0.25)};
  390. `;
  391. const IconContainer = styled('div')`
  392. display: flex;
  393. align-items: center;
  394. justify-content: center;
  395. width: ${p => p.theme.iconSizes.lg};
  396. height: ${p => p.theme.iconSizes.lg};
  397. flex-shrink: 0;
  398. `;
  399. const MenuItemWrapper = styled('div')`
  400. display: flex;
  401. align-items: center;
  402. font-size: ${p => p.theme.fontSizeSmall};
  403. `;
  404. const Label = styled(TextOverflow)`
  405. margin-left: ${space(0.75)};
  406. `;
  407. const MarginLeft = styled('div')`
  408. margin-left: ${space(1)};
  409. `;
  410. const StyledLoadingIndicator = styled(LoadingIndicator)`
  411. height: 24px;
  412. margin: 0;
  413. margin-right: ${space(1.5)};
  414. `;
  415. export default ActivatedRuleListRow;