row.tsx 14 KB

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