row.tsx 14 KB

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