row.tsx 15 KB

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