row.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  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 type {ItemsBeforeFilter} from 'sentry/components/dropdownAutoComplete/types';
  10. import DropdownBubble from 'sentry/components/dropdownBubble';
  11. import type {MenuItemProps} from 'sentry/components/dropdownMenu';
  12. import {DropdownMenu} from 'sentry/components/dropdownMenu';
  13. import ErrorBoundary from 'sentry/components/errorBoundary';
  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: ItemsBeforeFilter[number] = {
  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<ItemsBeforeFilter[number]>((team, idx) => ({
  255. value: team.id,
  256. searchKey: team.slug,
  257. label: (
  258. <MenuItemWrapper data-test-id="assignee-option" key={idx}>
  259. <IconContainer>
  260. <TeamAvatar team={team} size={24} />
  261. </IconContainer>
  262. <Label>#{team.slug}</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. <PaddedIconUser size="lg" 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 PaddedIconUser = styled(IconUser)`
  455. padding: ${space(0.25)};
  456. `;
  457. const IconContainer = styled('div')`
  458. display: flex;
  459. align-items: center;
  460. justify-content: center;
  461. width: 24px;
  462. height: 24px;
  463. flex-shrink: 0;
  464. `;
  465. const MenuItemWrapper = styled('div')`
  466. display: flex;
  467. align-items: center;
  468. font-size: 13px;
  469. `;
  470. const Label = styled(TextOverflow)`
  471. margin-left: 6px;
  472. `;
  473. export default RuleListRow;