row.tsx 15 KB

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