row.tsx 15 KB

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