activatedRuleRow.tsx 13 KB

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