row.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  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. tooltip={
  260. <TooltipWrapper>
  261. {tct('Assigned to [name]', {
  262. name: teamName && `#${teamName.name}`,
  263. })}
  264. </TooltipWrapper>
  265. }
  266. />
  267. ) : (
  268. <Tooltip isHoverable skipWrapper title={t('Unassigned')}>
  269. <StyledIconUser size="md" color="gray400" />
  270. </Tooltip>
  271. );
  272. return (
  273. <ErrorBoundary>
  274. <AlertNameWrapper isIssueAlert={isIssueAlert(rule)}>
  275. <FlexCenter>
  276. <Tooltip
  277. title={
  278. isIssueAlert(rule)
  279. ? t('Issue Alert')
  280. : tct('Metric Alert Status: [status]', {
  281. status:
  282. IssueStatusText[
  283. rule?.latestIncident?.status ?? IncidentStatus.CLOSED
  284. ],
  285. })
  286. }
  287. >
  288. <AlertBadge
  289. status={rule?.latestIncident?.status}
  290. isIssue={isIssueAlert(rule)}
  291. />
  292. </Tooltip>
  293. </FlexCenter>
  294. <AlertNameAndStatus>
  295. <AlertName>
  296. <Link
  297. to={
  298. isIssueAlert(rule)
  299. ? `/organizations/${orgId}/alerts/rules/${rule.projects[0]}/${rule.id}/details/`
  300. : `/organizations/${orgId}/alerts/rules/details/${rule.id}/`
  301. }
  302. >
  303. {rule.name}
  304. </Link>
  305. </AlertName>
  306. <AlertIncidentDate>{renderLastIncidentDate()}</AlertIncidentDate>
  307. </AlertNameAndStatus>
  308. </AlertNameWrapper>
  309. <FlexCenter>{renderAlertRuleStatus()}</FlexCenter>
  310. <FlexCenter>
  311. <ProjectBadgeContainer>
  312. <ProjectBadge
  313. avatarSize={18}
  314. project={!projectsLoaded ? {slug} : getProject(slug, projects)}
  315. />
  316. </ProjectBadgeContainer>
  317. </FlexCenter>
  318. <FlexCenter>
  319. {teamActor ? (
  320. <ActorAvatar actor={teamActor} size={24} />
  321. ) : (
  322. <AssigneeWrapper>
  323. {!projectsLoaded && (
  324. <LoadingIndicator
  325. mini
  326. style={{height: '24px', margin: 0, marginRight: 11}}
  327. />
  328. )}
  329. {projectsLoaded && (
  330. <DropdownAutoComplete
  331. data-test-id="alert-row-assignee"
  332. maxHeight={400}
  333. onOpen={e => {
  334. e?.stopPropagation();
  335. }}
  336. items={dropdownTeams}
  337. alignMenu="right"
  338. onSelect={handleOwnerChange}
  339. itemSize="small"
  340. searchPlaceholder={t('Filter teams')}
  341. disableLabelPadding
  342. emptyHidesInput
  343. disabled={!hasEditAccess}
  344. >
  345. {({getActorProps, isOpen}) => (
  346. <DropdownButton {...getActorProps({})}>
  347. {avatarElement}
  348. {hasEditAccess && (
  349. <StyledChevron direction={isOpen ? 'up' : 'down'} size="xs" />
  350. )}
  351. </DropdownButton>
  352. )}
  353. </DropdownAutoComplete>
  354. )}
  355. </AssigneeWrapper>
  356. )}
  357. </FlexCenter>
  358. <ActionsColumn>
  359. <Access access={['alerts:write']}>
  360. {({hasAccess}) => (
  361. <DropdownMenu
  362. items={actions}
  363. position="bottom-end"
  364. triggerProps={{
  365. 'aria-label': t('Actions'),
  366. size: 'xs',
  367. icon: <IconEllipsis size="xs" />,
  368. showChevron: false,
  369. }}
  370. disabledKeys={hasAccess && canEdit ? [] : ['delete']}
  371. />
  372. )}
  373. </Access>
  374. </ActionsColumn>
  375. </ErrorBoundary>
  376. );
  377. }
  378. const FlexCenter = styled('div')`
  379. display: flex;
  380. align-items: center;
  381. `;
  382. const AlertNameWrapper = styled(FlexCenter)<{isIssueAlert?: boolean}>`
  383. gap: ${space(2)};
  384. position: relative;
  385. ${p => p.isIssueAlert && `padding: ${space(3)} ${space(2)}; line-height: 2.4;`}
  386. `;
  387. const AlertNameAndStatus = styled('div')`
  388. ${p => p.theme.overflowEllipsis}
  389. line-height: 1.35;
  390. `;
  391. const AlertName = styled('div')`
  392. ${p => p.theme.overflowEllipsis}
  393. font-size: ${p => p.theme.fontSizeLarge};
  394. @media (max-width: ${p => p.theme.breakpoints.xlarge}) {
  395. max-width: 300px;
  396. }
  397. @media (max-width: ${p => p.theme.breakpoints.large}) {
  398. max-width: 165px;
  399. }
  400. @media (max-width: ${p => p.theme.breakpoints.medium}) {
  401. max-width: 100px;
  402. }
  403. `;
  404. const AlertIncidentDate = styled('div')`
  405. color: ${p => p.theme.gray300};
  406. `;
  407. const ProjectBadgeContainer = styled('div')`
  408. width: 100%;
  409. `;
  410. const ProjectBadge = styled(IdBadge)`
  411. flex-shrink: 0;
  412. `;
  413. const TriggerText = styled('div')`
  414. margin-left: ${space(1)};
  415. white-space: nowrap;
  416. font-variant-numeric: tabular-nums;
  417. `;
  418. const ActionsColumn = styled(FlexCenter)`
  419. justify-content: center;
  420. padding: ${space(1)};
  421. `;
  422. const AssigneeWrapper = styled('div')`
  423. display: flex;
  424. justify-content: flex-end;
  425. /* manually align menu underneath dropdown caret */
  426. ${DropdownBubble} {
  427. right: -14px;
  428. }
  429. `;
  430. const DropdownButton = styled('div')`
  431. display: flex;
  432. align-items: center;
  433. font-size: 20px;
  434. `;
  435. const StyledChevron = styled(IconChevron)`
  436. margin-left: ${space(1)};
  437. `;
  438. const TooltipWrapper = styled('div')`
  439. text-align: left;
  440. `;
  441. const StyledIconUser = styled(IconUser)`
  442. /* We need this to center with Avatar */
  443. margin-right: 2px;
  444. `;
  445. const IconContainer = styled('div')`
  446. display: flex;
  447. align-items: center;
  448. justify-content: center;
  449. width: 24px;
  450. height: 24px;
  451. flex-shrink: 0;
  452. `;
  453. const MenuItemWrapper = styled('div')`
  454. display: flex;
  455. align-items: center;
  456. font-size: 13px;
  457. `;
  458. const Label = styled(TextOverflow)`
  459. margin-left: 6px;
  460. `;
  461. export default RuleListRow;