row.tsx 15 KB

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