row.tsx 14 KB

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