row.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  1. import {useState} from 'react';
  2. import styled from '@emotion/styled';
  3. import Access from 'sentry/components/acl/access';
  4. import AlertBadge from 'sentry/components/alertBadge';
  5. import ActorAvatar from 'sentry/components/avatar/actorAvatar';
  6. import TeamAvatar from 'sentry/components/avatar/teamAvatar';
  7. import {openConfirmModal} from 'sentry/components/confirm';
  8. import DropdownAutoComplete from 'sentry/components/dropdownAutoComplete';
  9. import DropdownBubble from 'sentry/components/dropdownBubble';
  10. import type {MenuItemProps} from 'sentry/components/dropdownMenu';
  11. import {DropdownMenu} 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 type {Actor, Project} from 'sentry/types';
  31. import type {ColorOrAlias} from 'sentry/utils/theme';
  32. import {useUserTeams} from 'sentry/utils/useUserTeams';
  33. import {getThresholdUnits} from 'sentry/views/alerts/rules/metric/constants';
  34. import {
  35. AlertRuleComparisonType,
  36. AlertRuleThresholdType,
  37. AlertRuleTriggerType,
  38. } from 'sentry/views/alerts/rules/metric/types';
  39. import type {CombinedMetricIssueAlerts} from '../../types';
  40. import {CombinedAlertType, IncidentStatus} from '../../types';
  41. import {isIssueAlert} from '../../utils';
  42. type Props = {
  43. hasEditAccess: boolean;
  44. onDelete: (projectId: string, rule: CombinedMetricIssueAlerts) => void;
  45. onOwnerChange: (
  46. projectId: string,
  47. rule: CombinedMetricIssueAlerts,
  48. ownerValue: string
  49. ) => void;
  50. orgId: string;
  51. projects: Project[];
  52. projectsLoaded: boolean;
  53. rule: CombinedMetricIssueAlerts;
  54. };
  55. function RuleListRow({
  56. rule,
  57. projectsLoaded,
  58. projects,
  59. orgId,
  60. onDelete,
  61. onOwnerChange,
  62. hasEditAccess,
  63. }: Props) {
  64. const {teams: userTeams} = useUserTeams();
  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('Alert 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('Alert 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 renderSnoozeStatus(): React.ReactNode {
  102. return (
  103. <IssueAlertStatusWrapper>
  104. <IconMute size="sm" color="subText" />
  105. {t('Muted')}
  106. </IssueAlertStatusWrapper>
  107. );
  108. }
  109. function renderAlertRuleStatus(): React.ReactNode {
  110. if (isIssueAlert(rule)) {
  111. if (rule.status === 'disabled') {
  112. return (
  113. <IssueAlertStatusWrapper>
  114. <IconNot size="sm" color="subText" />
  115. {t('Disabled')}
  116. </IssueAlertStatusWrapper>
  117. );
  118. }
  119. if (rule.snooze) {
  120. return renderSnoozeStatus();
  121. }
  122. return null;
  123. }
  124. if (rule.snooze) {
  125. return renderSnoozeStatus();
  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.some(team => team.id === 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. <PaddedIconUser size="lg" />
  242. <Label>{t('Unassigned')}</Label>
  243. </MenuItemWrapper>
  244. ),
  245. searchKey: 'unassigned',
  246. actor: '',
  247. disabled: false,
  248. };
  249. const project = projects.find(p => p.slug === slug);
  250. const filteredProjectTeams = (project?.teams ?? []).filter(projTeam => {
  251. return userTeams.some(team => team.id === projTeam.id);
  252. });
  253. const dropdownTeams = filteredProjectTeams
  254. .map((team, idx) => ({
  255. value: team.id,
  256. searchKey: team.slug,
  257. label: ({inputValue}) => (
  258. <MenuItemWrapper data-test-id="assignee-option" key={idx}>
  259. <IconContainer>
  260. <TeamAvatar team={team} size={24} />
  261. </IconContainer>
  262. <Label>
  263. <Highlight text={inputValue}>{`#${team.slug}`}</Highlight>
  264. </Label>
  265. </MenuItemWrapper>
  266. ),
  267. }))
  268. .concat(unassignedOption);
  269. const teamId = assignee?.split(':')[1];
  270. const teamName = filteredProjectTeams.find(team => team.id === teamId);
  271. const assigneeTeamActor = assignee && {
  272. type: 'team' as Actor['type'],
  273. id: teamId,
  274. name: '',
  275. };
  276. const avatarElement = assigneeTeamActor ? (
  277. <ActorAvatar
  278. actor={assigneeTeamActor}
  279. className="avatar"
  280. size={24}
  281. tooltipOptions={{overlayStyle: {textAlign: 'left'}}}
  282. tooltip={tct('Assigned to [name]', {name: teamName && `#${teamName.name}`})}
  283. />
  284. ) : (
  285. <Tooltip isHoverable skipWrapper title={t('Unassigned')}>
  286. <PaddedIconUser size="lg" color="gray400" />
  287. </Tooltip>
  288. );
  289. return (
  290. <ErrorBoundary>
  291. <AlertNameWrapper isIssueAlert={isIssueAlert(rule)}>
  292. <FlexCenter>
  293. <Tooltip
  294. title={
  295. isIssueAlert(rule)
  296. ? t('Issue Alert')
  297. : tct('Metric Alert Status: [status]', {
  298. status:
  299. IssueStatusText[
  300. rule?.latestIncident?.status ?? IncidentStatus.CLOSED
  301. ],
  302. })
  303. }
  304. >
  305. <AlertBadge
  306. status={rule?.latestIncident?.status}
  307. isIssue={isIssueAlert(rule)}
  308. />
  309. </Tooltip>
  310. </FlexCenter>
  311. <AlertNameAndStatus>
  312. <AlertName>
  313. <Link
  314. to={
  315. isIssueAlert(rule)
  316. ? `/organizations/${orgId}/alerts/rules/${rule.projects[0]}/${rule.id}/details/`
  317. : `/organizations/${orgId}/alerts/rules/details/${rule.id}/`
  318. }
  319. >
  320. {rule.name}
  321. </Link>
  322. </AlertName>
  323. <AlertIncidentDate>{renderLastIncidentDate()}</AlertIncidentDate>
  324. </AlertNameAndStatus>
  325. </AlertNameWrapper>
  326. <FlexCenter>{renderAlertRuleStatus()}</FlexCenter>
  327. <FlexCenter>
  328. <ProjectBadgeContainer>
  329. <ProjectBadge
  330. avatarSize={18}
  331. project={projectsLoaded && project ? project : {slug}}
  332. />
  333. </ProjectBadgeContainer>
  334. </FlexCenter>
  335. <FlexCenter>
  336. {teamActor ? (
  337. <ActorAvatar actor={teamActor} size={24} />
  338. ) : (
  339. <AssigneeWrapper>
  340. {!projectsLoaded && (
  341. <LoadingIndicator
  342. mini
  343. style={{height: '24px', margin: 0, marginRight: 11}}
  344. />
  345. )}
  346. {projectsLoaded && (
  347. <DropdownAutoComplete
  348. data-test-id="alert-row-assignee"
  349. maxHeight={400}
  350. onOpen={e => {
  351. e?.stopPropagation();
  352. }}
  353. items={dropdownTeams}
  354. alignMenu="right"
  355. onSelect={handleOwnerChange}
  356. itemSize="small"
  357. searchPlaceholder={t('Filter teams')}
  358. disableLabelPadding
  359. emptyHidesInput
  360. disabled={!hasEditAccess}
  361. >
  362. {({getActorProps, isOpen}) => (
  363. <DropdownButton {...getActorProps({})}>
  364. {avatarElement}
  365. {hasEditAccess && (
  366. <StyledChevron direction={isOpen ? 'up' : 'down'} size="xs" />
  367. )}
  368. </DropdownButton>
  369. )}
  370. </DropdownAutoComplete>
  371. )}
  372. </AssigneeWrapper>
  373. )}
  374. </FlexCenter>
  375. <ActionsColumn>
  376. <Access access={['alerts:write']}>
  377. {({hasAccess}) => (
  378. <DropdownMenu
  379. items={actions}
  380. position="bottom-end"
  381. triggerProps={{
  382. 'aria-label': t('Actions'),
  383. size: 'xs',
  384. icon: <IconEllipsis />,
  385. showChevron: false,
  386. }}
  387. disabledKeys={hasAccess && canEdit ? [] : ['delete']}
  388. />
  389. )}
  390. </Access>
  391. </ActionsColumn>
  392. </ErrorBoundary>
  393. );
  394. }
  395. const FlexCenter = styled('div')`
  396. display: flex;
  397. align-items: center;
  398. `;
  399. const IssueAlertStatusWrapper = styled('div')`
  400. display: flex;
  401. align-items: center;
  402. gap: ${space(1)};
  403. line-height: 2;
  404. `;
  405. const AlertNameWrapper = styled('div')<{isIssueAlert?: boolean}>`
  406. ${p => p.theme.overflowEllipsis}
  407. display: flex;
  408. align-items: center;
  409. gap: ${space(2)};
  410. ${p => p.isIssueAlert && `padding: ${space(3)} ${space(2)}; line-height: 2.4;`}
  411. `;
  412. const AlertNameAndStatus = styled('div')`
  413. ${p => p.theme.overflowEllipsis}
  414. line-height: 1.35;
  415. `;
  416. const AlertName = styled('div')`
  417. ${p => p.theme.overflowEllipsis}
  418. font-size: ${p => p.theme.fontSizeLarge};
  419. `;
  420. const AlertIncidentDate = styled('div')`
  421. color: ${p => p.theme.gray300};
  422. `;
  423. const ProjectBadgeContainer = styled('div')`
  424. width: 100%;
  425. `;
  426. const ProjectBadge = styled(IdBadge)`
  427. flex-shrink: 0;
  428. `;
  429. const TriggerText = styled('div')`
  430. margin-left: ${space(1)};
  431. white-space: nowrap;
  432. font-variant-numeric: tabular-nums;
  433. `;
  434. const ActionsColumn = styled('div')`
  435. display: flex;
  436. align-items: center;
  437. justify-content: center;
  438. padding: ${space(1)};
  439. `;
  440. const AssigneeWrapper = styled('div')`
  441. display: flex;
  442. justify-content: flex-end;
  443. /* manually align menu underneath dropdown caret */
  444. ${DropdownBubble} {
  445. right: -14px;
  446. }
  447. `;
  448. const DropdownButton = styled('div')`
  449. display: flex;
  450. align-items: center;
  451. font-size: 20px;
  452. `;
  453. const StyledChevron = styled(IconChevron)`
  454. margin-left: ${space(1)};
  455. `;
  456. const PaddedIconUser = styled(IconUser)`
  457. padding: ${space(0.25)};
  458. `;
  459. const IconContainer = styled('div')`
  460. display: flex;
  461. align-items: center;
  462. justify-content: center;
  463. width: 24px;
  464. height: 24px;
  465. flex-shrink: 0;
  466. `;
  467. const MenuItemWrapper = styled('div')`
  468. display: flex;
  469. align-items: center;
  470. font-size: 13px;
  471. `;
  472. const Label = styled(TextOverflow)`
  473. margin-left: 6px;
  474. `;
  475. export default RuleListRow;