row.tsx 15 KB

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