activatedRuleRow.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. import {useState} from 'react';
  2. import styled from '@emotion/styled';
  3. import Access from 'sentry/components/acl/access';
  4. import ActorAvatar from 'sentry/components/avatar/actorAvatar';
  5. import TeamAvatar from 'sentry/components/avatar/teamAvatar';
  6. import AlertBadge from 'sentry/components/badge/alertBadge';
  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 {IconChevron, IconEllipsis, IconUser} from 'sentry/icons';
  21. import {t, tct} from 'sentry/locale';
  22. import {space} from 'sentry/styles/space';
  23. import type {Actor, Project} from 'sentry/types';
  24. import {useUserTeams} from 'sentry/utils/useUserTeams';
  25. import ActivatedMetricAlertRuleStatus from 'sentry/views/alerts/list/rules/activatedMetricAlertRuleStatus';
  26. import type {CombinedMetricIssueAlerts, MetricAlert} from '../../types';
  27. import {ActivationStatus, CombinedAlertType} from '../../types';
  28. type Props = {
  29. hasEditAccess: boolean;
  30. onDelete: (projectId: string, rule: CombinedMetricIssueAlerts) => void;
  31. onOwnerChange: (
  32. projectId: string,
  33. rule: CombinedMetricIssueAlerts,
  34. ownerValue: string
  35. ) => void;
  36. orgId: string;
  37. projects: Project[];
  38. projectsLoaded: boolean;
  39. rule: MetricAlert;
  40. };
  41. function ActivatedRuleListRow({
  42. rule,
  43. projectsLoaded,
  44. projects,
  45. orgId,
  46. onDelete,
  47. onOwnerChange,
  48. hasEditAccess,
  49. }: Props) {
  50. const {teams: userTeams} = useUserTeams();
  51. const [assignee, setAssignee] = useState<string>('');
  52. const isWaiting =
  53. !rule.activations?.length ||
  54. (rule.activations?.length && rule.activations[0].isComplete);
  55. function renderLatestActivation(): React.ReactNode {
  56. if (!rule.activations?.length) {
  57. return t('Alert has not been activated yet');
  58. }
  59. return (
  60. <div>
  61. {t('Last activated ')}
  62. <TimeSince date={rule.activations[0].dateCreated} />
  63. </div>
  64. );
  65. }
  66. const slug = rule.projects[0];
  67. const editLink = `/organizations/${orgId}/alerts/metric-rules/${slug}/${rule.id}/`;
  68. const duplicateLink = {
  69. pathname: `/organizations/${orgId}/alerts/new/${
  70. rule.type === CombinedAlertType.METRIC ? 'metric' : 'issue'
  71. }/`,
  72. query: {
  73. project: slug,
  74. duplicateRuleId: rule.id,
  75. createFromDuplicate: true,
  76. referrer: 'alert_stream',
  77. },
  78. };
  79. const ownerId = rule.owner?.split(':')[1];
  80. const teamActor = ownerId
  81. ? {type: 'team' as Actor['type'], id: ownerId, name: ''}
  82. : null;
  83. const canEdit = ownerId ? userTeams.some(team => team.id === ownerId) : true;
  84. const actions: MenuItemProps[] = [
  85. {
  86. key: 'edit',
  87. label: t('Edit'),
  88. to: editLink,
  89. },
  90. {
  91. key: 'duplicate',
  92. label: t('Duplicate'),
  93. to: duplicateLink,
  94. },
  95. {
  96. key: 'delete',
  97. label: t('Delete'),
  98. priority: 'danger',
  99. onAction: () => {
  100. openConfirmModal({
  101. onConfirm: () => onDelete(slug, rule),
  102. header: <h5>{t('Delete Alert Rule?')}</h5>,
  103. message: t(
  104. 'Are you sure you want to delete "%s"? You won\'t be able to view the history of this alert once it\'s deleted.',
  105. rule.name
  106. ),
  107. confirmText: t('Delete Rule'),
  108. priority: 'danger',
  109. });
  110. },
  111. },
  112. ];
  113. function handleOwnerChange({value}: {value: string}) {
  114. const ownerValue = value && `team:${value}`;
  115. setAssignee(ownerValue);
  116. onOwnerChange(slug, rule, ownerValue);
  117. }
  118. const unassignedOption: ItemsBeforeFilter[number] = {
  119. value: '',
  120. label: (
  121. <MenuItemWrapper>
  122. <PaddedIconUser size="lg" />
  123. <Label>{t('Unassigned')}</Label>
  124. </MenuItemWrapper>
  125. ),
  126. searchKey: 'unassigned',
  127. actor: '',
  128. disabled: false,
  129. };
  130. const project = projects.find(p => p.slug === slug);
  131. const filteredProjectTeams = (project?.teams ?? []).filter(projTeam => {
  132. return userTeams.some(team => team.id === projTeam.id);
  133. });
  134. const dropdownTeams = filteredProjectTeams
  135. .map<ItemsBeforeFilter[number]>((team, idx) => ({
  136. value: team.id,
  137. searchKey: team.slug,
  138. label: (
  139. <MenuItemWrapper data-test-id="assignee-option" key={idx}>
  140. <IconContainer>
  141. <TeamAvatar team={team} size={24} />
  142. </IconContainer>
  143. <Label>#{team.slug}</Label>
  144. </MenuItemWrapper>
  145. ),
  146. }))
  147. .concat(unassignedOption);
  148. const teamId = assignee?.split(':')[1];
  149. const teamName = filteredProjectTeams.find(team => team.id === teamId);
  150. const assigneeTeamActor = assignee && {
  151. type: 'team' as Actor['type'],
  152. id: teamId,
  153. name: '',
  154. };
  155. const avatarElement = assigneeTeamActor ? (
  156. <ActorAvatar
  157. actor={assigneeTeamActor}
  158. className="avatar"
  159. size={24}
  160. tooltipOptions={{overlayStyle: {textAlign: 'left'}}}
  161. tooltip={tct('Assigned to [name]', {name: teamName && `#${teamName.name}`})}
  162. />
  163. ) : (
  164. <Tooltip isHoverable skipWrapper title={t('Unassigned')}>
  165. <PaddedIconUser size="lg" color="gray400" />
  166. </Tooltip>
  167. );
  168. return (
  169. <ErrorBoundary>
  170. <AlertNameWrapper>
  171. <AlertNameAndStatus>
  172. <AlertName>
  173. <Link to={`/organizations/${orgId}/alerts/rules/details/${rule.id}/`}>
  174. {rule.name}
  175. </Link>
  176. </AlertName>
  177. <AlertActivationDate>{renderLatestActivation()}</AlertActivationDate>
  178. </AlertNameAndStatus>
  179. </AlertNameWrapper>
  180. <FlexCenter>
  181. <FlexCenter>
  182. <Tooltip
  183. title={tct('Metric Alert Status: [status]', {
  184. status: isWaiting ? 'Ready to monitor' : 'Monitoring',
  185. })}
  186. >
  187. <AlertBadge
  188. status={rule?.latestIncident?.status}
  189. activationStatus={
  190. isWaiting ? ActivationStatus.WAITING : ActivationStatus.MONITORING
  191. }
  192. />
  193. </Tooltip>
  194. </FlexCenter>
  195. <MarginLeft>
  196. <ActivatedMetricAlertRuleStatus rule={rule} />
  197. </MarginLeft>
  198. </FlexCenter>
  199. <FlexCenter>
  200. <ProjectBadgeContainer>
  201. <ProjectBadge
  202. avatarSize={18}
  203. project={projectsLoaded && project ? project : {slug}}
  204. />
  205. </ProjectBadgeContainer>
  206. </FlexCenter>
  207. <FlexCenter>
  208. {teamActor ? (
  209. <ActorAvatar actor={teamActor} size={24} />
  210. ) : (
  211. <AssigneeWrapper>
  212. {!projectsLoaded && <StyledLoadingIndicator mini />}
  213. {projectsLoaded && (
  214. <DropdownAutoComplete
  215. data-test-id="alert-row-assignee"
  216. maxHeight={400}
  217. onOpen={e => {
  218. e?.stopPropagation();
  219. }}
  220. items={dropdownTeams}
  221. alignMenu="right"
  222. onSelect={handleOwnerChange}
  223. itemSize="small"
  224. searchPlaceholder={t('Filter teams')}
  225. disableLabelPadding
  226. emptyHidesInput
  227. disabled={!hasEditAccess}
  228. >
  229. {({getActorProps, isOpen}) => (
  230. <DropdownButton {...getActorProps({})}>
  231. {avatarElement}
  232. {hasEditAccess && (
  233. <StyledChevron direction={isOpen ? 'up' : 'down'} size="xs" />
  234. )}
  235. </DropdownButton>
  236. )}
  237. </DropdownAutoComplete>
  238. )}
  239. </AssigneeWrapper>
  240. )}
  241. </FlexCenter>
  242. <ActionsColumn>
  243. <Access access={['alerts:write']}>
  244. {({hasAccess}) => (
  245. <DropdownMenu
  246. items={actions}
  247. position="bottom-end"
  248. triggerProps={{
  249. 'aria-label': t('Actions'),
  250. size: 'xs',
  251. icon: <IconEllipsis />,
  252. showChevron: false,
  253. }}
  254. disabledKeys={hasAccess && canEdit ? [] : ['delete']}
  255. />
  256. )}
  257. </Access>
  258. </ActionsColumn>
  259. </ErrorBoundary>
  260. );
  261. }
  262. // TODO: see static/app/components/profiling/flex.tsx and utilize the FlexContainer styled component
  263. const FlexCenter = styled('div')`
  264. display: flex;
  265. align-items: center;
  266. `;
  267. const AlertNameWrapper = styled('div')<{isIssueAlert?: boolean}>`
  268. ${p => p.theme.overflowEllipsis}
  269. display: flex;
  270. align-items: center;
  271. gap: ${space(2)};
  272. ${p => p.isIssueAlert && `padding: ${space(3)} ${space(2)}; line-height: 2.4;`}
  273. `;
  274. const AlertNameAndStatus = styled('div')`
  275. ${p => p.theme.overflowEllipsis}
  276. line-height: 1.35;
  277. `;
  278. const AlertName = styled('div')`
  279. ${p => p.theme.overflowEllipsis}
  280. font-size: ${p => p.theme.fontSizeLarge};
  281. `;
  282. const AlertActivationDate = styled('div')`
  283. color: ${p => p.theme.gray300};
  284. `;
  285. const ProjectBadgeContainer = styled('div')`
  286. width: 100%;
  287. `;
  288. const ProjectBadge = styled(IdBadge)`
  289. flex-shrink: 0;
  290. `;
  291. const ActionsColumn = styled('div')`
  292. display: flex;
  293. align-items: center;
  294. justify-content: center;
  295. padding: ${space(1)};
  296. `;
  297. const AssigneeWrapper = styled('div')`
  298. display: flex;
  299. justify-content: flex-end;
  300. /* manually align menu underneath dropdown caret */
  301. ${DropdownBubble} {
  302. right: -14px;
  303. }
  304. `;
  305. const DropdownButton = styled('div')`
  306. display: flex;
  307. align-items: center;
  308. font-size: 20px;
  309. `;
  310. const StyledChevron = styled(IconChevron)`
  311. margin-left: ${space(1)};
  312. `;
  313. const PaddedIconUser = styled(IconUser)`
  314. padding: ${space(0.25)};
  315. `;
  316. const IconContainer = styled('div')`
  317. display: flex;
  318. align-items: center;
  319. justify-content: center;
  320. width: ${p => p.theme.iconSizes.lg};
  321. height: ${p => p.theme.iconSizes.lg};
  322. flex-shrink: 0;
  323. `;
  324. const MenuItemWrapper = styled('div')`
  325. display: flex;
  326. align-items: center;
  327. font-size: ${p => p.theme.fontSizeSmall};
  328. `;
  329. const Label = styled(TextOverflow)`
  330. margin-left: ${space(0.75)};
  331. `;
  332. const MarginLeft = styled('div')`
  333. margin-left: ${space(1)};
  334. `;
  335. const StyledLoadingIndicator = styled(LoadingIndicator)`
  336. height: 24px;
  337. margin: 0;
  338. margin-right: ${space(1.5)};
  339. `;
  340. export default ActivatedRuleListRow;