row.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. import {useState} from 'react';
  2. import styled from '@emotion/styled';
  3. import memoize from 'lodash/memoize';
  4. import Access from 'sentry/components/acl/access';
  5. import AlertBadge from 'sentry/components/alertBadge';
  6. import ActorAvatar from 'sentry/components/avatar/actorAvatar';
  7. import TeamAvatar from 'sentry/components/avatar/teamAvatar';
  8. import {openConfirmModal} from 'sentry/components/confirm';
  9. import DropdownAutoComplete from 'sentry/components/dropdownAutoComplete';
  10. import DropdownBubble from 'sentry/components/dropdownBubble';
  11. import {DropdownMenu, MenuItemProps} from 'sentry/components/dropdownMenu';
  12. import ErrorBoundary from 'sentry/components/errorBoundary';
  13. import Highlight from 'sentry/components/highlight';
  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 {Actor, Project} from 'sentry/types';
  31. import type {ColorOrAlias} from 'sentry/utils/theme';
  32. import {getThresholdUnits} from 'sentry/views/alerts/rules/metric/constants';
  33. import {
  34. AlertRuleComparisonType,
  35. AlertRuleThresholdType,
  36. AlertRuleTriggerType,
  37. } from 'sentry/views/alerts/rules/metric/types';
  38. import {CombinedAlertType, CombinedMetricIssueAlerts, IncidentStatus} from '../../types';
  39. import {isIssueAlert} from '../../utils';
  40. type Props = {
  41. hasEditAccess: boolean;
  42. onDelete: (projectId: string, rule: CombinedMetricIssueAlerts) => void;
  43. onOwnerChange: (
  44. projectId: string,
  45. rule: CombinedMetricIssueAlerts,
  46. ownerValue: string
  47. ) => void;
  48. orgId: string;
  49. projects: Project[];
  50. projectsLoaded: boolean;
  51. rule: CombinedMetricIssueAlerts;
  52. // Set of team ids that the user belongs to
  53. userTeams: Set<string>;
  54. };
  55. /**
  56. * Memoized function to find a project from a list of projects
  57. */
  58. const getProject = memoize((slug: string, projects: Project[]) =>
  59. projects.find(project => project.slug === slug)
  60. );
  61. function RuleListRow({
  62. rule,
  63. projectsLoaded,
  64. projects,
  65. orgId,
  66. onDelete,
  67. onOwnerChange,
  68. userTeams,
  69. hasEditAccess,
  70. }: Props) {
  71. const [assignee, setAssignee] = useState<string>('');
  72. const activeIncident =
  73. rule.latestIncident?.status !== undefined &&
  74. [IncidentStatus.CRITICAL, IncidentStatus.WARNING].includes(
  75. rule.latestIncident.status
  76. );
  77. function renderLastIncidentDate(): React.ReactNode {
  78. if (isIssueAlert(rule)) {
  79. if (!rule.lastTriggered) {
  80. return t('Alert not triggered yet');
  81. }
  82. return (
  83. <div>
  84. {t('Triggered ')}
  85. <TimeSince date={rule.lastTriggered} />
  86. </div>
  87. );
  88. }
  89. if (!rule.latestIncident) {
  90. return t('Alert not triggered yet');
  91. }
  92. if (activeIncident) {
  93. return (
  94. <div>
  95. {t('Triggered ')}
  96. <TimeSince date={rule.latestIncident.dateCreated} />
  97. </div>
  98. );
  99. }
  100. return (
  101. <div>
  102. {t('Resolved ')}
  103. <TimeSince date={rule.latestIncident.dateClosed!} />
  104. </div>
  105. );
  106. }
  107. function renderAlertRuleStatus(): React.ReactNode {
  108. if (isIssueAlert(rule)) {
  109. if (rule.status === 'disabled') {
  110. return (
  111. <IssueAlertStatusWrapper>
  112. <IconNot size="sm" color="subText" />
  113. {t('Disabled')}
  114. </IssueAlertStatusWrapper>
  115. );
  116. }
  117. if (rule.snooze) {
  118. return (
  119. <IssueAlertStatusWrapper>
  120. <IconMute size="sm" color="subText" />
  121. {t('Muted')}
  122. </IssueAlertStatusWrapper>
  123. );
  124. }
  125. return null;
  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.has(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 = {
  238. value: '',
  239. label: () => (
  240. <MenuItemWrapper>
  241. <StyledIconUser size="md" />
  242. {t('Unassigned')}
  243. </MenuItemWrapper>
  244. ),
  245. searchKey: 'unassigned',
  246. actor: '',
  247. disabled: false,
  248. };
  249. const projectRow = projects.filter(project => project.slug === slug);
  250. const projectRowTeams = projectRow[0].teams;
  251. const filteredProjectTeams = projectRowTeams?.filter(projTeam => {
  252. return userTeams.has(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. <Tooltip
  295. title={
  296. isIssueAlert(rule)
  297. ? t('Issue Alert')
  298. : tct('Metric Alert Status: [status]', {
  299. status:
  300. IssueStatusText[
  301. rule?.latestIncident?.status ?? IncidentStatus.CLOSED
  302. ],
  303. })
  304. }
  305. >
  306. <AlertBadge
  307. status={rule?.latestIncident?.status}
  308. isIssue={isIssueAlert(rule)}
  309. />
  310. </Tooltip>
  311. </FlexCenter>
  312. <AlertNameAndStatus>
  313. <AlertName>
  314. <Link
  315. to={
  316. isIssueAlert(rule)
  317. ? `/organizations/${orgId}/alerts/rules/${rule.projects[0]}/${rule.id}/details/`
  318. : `/organizations/${orgId}/alerts/rules/details/${rule.id}/`
  319. }
  320. >
  321. {rule.name}
  322. </Link>
  323. </AlertName>
  324. <AlertIncidentDate>{renderLastIncidentDate()}</AlertIncidentDate>
  325. </AlertNameAndStatus>
  326. </AlertNameWrapper>
  327. <FlexCenter>{renderAlertRuleStatus()}</FlexCenter>
  328. <FlexCenter>
  329. <ProjectBadgeContainer>
  330. <ProjectBadge
  331. avatarSize={18}
  332. project={!projectsLoaded ? {slug} : getProject(slug, projects)}
  333. />
  334. </ProjectBadgeContainer>
  335. </FlexCenter>
  336. <FlexCenter>
  337. {teamActor ? (
  338. <ActorAvatar actor={teamActor} size={24} />
  339. ) : (
  340. <AssigneeWrapper>
  341. {!projectsLoaded && (
  342. <LoadingIndicator
  343. mini
  344. style={{height: '24px', margin: 0, marginRight: 11}}
  345. />
  346. )}
  347. {projectsLoaded && (
  348. <DropdownAutoComplete
  349. data-test-id="alert-row-assignee"
  350. maxHeight={400}
  351. onOpen={e => {
  352. e?.stopPropagation();
  353. }}
  354. items={dropdownTeams}
  355. alignMenu="right"
  356. onSelect={handleOwnerChange}
  357. itemSize="small"
  358. searchPlaceholder={t('Filter teams')}
  359. disableLabelPadding
  360. emptyHidesInput
  361. disabled={!hasEditAccess}
  362. >
  363. {({getActorProps, isOpen}) => (
  364. <DropdownButton {...getActorProps({})}>
  365. {avatarElement}
  366. {hasEditAccess && (
  367. <StyledChevron direction={isOpen ? 'up' : 'down'} size="xs" />
  368. )}
  369. </DropdownButton>
  370. )}
  371. </DropdownAutoComplete>
  372. )}
  373. </AssigneeWrapper>
  374. )}
  375. </FlexCenter>
  376. <ActionsColumn>
  377. <Access access={['alerts:write']}>
  378. {({hasAccess}) => (
  379. <DropdownMenu
  380. items={actions}
  381. position="bottom-end"
  382. triggerProps={{
  383. 'aria-label': t('Actions'),
  384. size: 'xs',
  385. icon: <IconEllipsis size="xs" />,
  386. showChevron: false,
  387. }}
  388. disabledKeys={hasAccess && canEdit ? [] : ['delete']}
  389. />
  390. )}
  391. </Access>
  392. </ActionsColumn>
  393. </ErrorBoundary>
  394. );
  395. }
  396. const FlexCenter = styled('div')`
  397. display: flex;
  398. align-items: center;
  399. `;
  400. const IssueAlertStatusWrapper = styled('div')`
  401. display: flex;
  402. align-items: center;
  403. gap: ${space(1)};
  404. line-height: 2;
  405. `;
  406. const AlertNameWrapper = styled('div')<{isIssueAlert?: boolean}>`
  407. display: flex;
  408. align-items: center;
  409. gap: ${space(2)};
  410. position: relative;
  411. ${p => p.isIssueAlert && `padding: ${space(3)} ${space(2)}; line-height: 2.4;`}
  412. `;
  413. const AlertNameAndStatus = styled('div')`
  414. ${p => p.theme.overflowEllipsis}
  415. line-height: 1.35;
  416. `;
  417. const AlertName = styled('div')`
  418. ${p => p.theme.overflowEllipsis}
  419. font-size: ${p => p.theme.fontSizeLarge};
  420. @media (max-width: ${p => p.theme.breakpoints.xlarge}) {
  421. max-width: 300px;
  422. }
  423. @media (max-width: ${p => p.theme.breakpoints.large}) {
  424. max-width: 165px;
  425. }
  426. @media (max-width: ${p => p.theme.breakpoints.medium}) {
  427. max-width: 100px;
  428. }
  429. `;
  430. const AlertIncidentDate = styled('div')`
  431. color: ${p => p.theme.gray300};
  432. `;
  433. const ProjectBadgeContainer = styled('div')`
  434. width: 100%;
  435. `;
  436. const ProjectBadge = styled(IdBadge)`
  437. flex-shrink: 0;
  438. `;
  439. const TriggerText = styled('div')`
  440. margin-left: ${space(1)};
  441. white-space: nowrap;
  442. font-variant-numeric: tabular-nums;
  443. `;
  444. const ActionsColumn = styled('div')`
  445. display: flex;
  446. align-items: center;
  447. justify-content: center;
  448. padding: ${space(1)};
  449. `;
  450. const AssigneeWrapper = styled('div')`
  451. display: flex;
  452. justify-content: flex-end;
  453. /* manually align menu underneath dropdown caret */
  454. ${DropdownBubble} {
  455. right: -14px;
  456. }
  457. `;
  458. const DropdownButton = styled('div')`
  459. display: flex;
  460. align-items: center;
  461. font-size: 20px;
  462. `;
  463. const StyledChevron = styled(IconChevron)`
  464. margin-left: ${space(1)};
  465. `;
  466. const StyledIconUser = styled(IconUser)`
  467. /* We need this to center with Avatar */
  468. margin-right: 2px;
  469. `;
  470. const IconContainer = styled('div')`
  471. display: flex;
  472. align-items: center;
  473. justify-content: center;
  474. width: 24px;
  475. height: 24px;
  476. flex-shrink: 0;
  477. `;
  478. const MenuItemWrapper = styled('div')`
  479. display: flex;
  480. align-items: center;
  481. font-size: 13px;
  482. `;
  483. const Label = styled(TextOverflow)`
  484. margin-left: 6px;
  485. `;
  486. export default RuleListRow;