row.tsx 14 KB

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