accountNotificationFineTuning.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. import {Fragment} from 'react';
  2. import type {RouteComponentProps} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import EmptyMessage from 'sentry/components/emptyMessage';
  5. import SelectField from 'sentry/components/forms/fields/selectField';
  6. import Form from 'sentry/components/forms/form';
  7. import ProjectBadge from 'sentry/components/idBadge/projectBadge';
  8. import Pagination from 'sentry/components/pagination';
  9. import Panel from 'sentry/components/panels/panel';
  10. import PanelBody from 'sentry/components/panels/panelBody';
  11. import PanelHeader from 'sentry/components/panels/panelHeader';
  12. import {t} from 'sentry/locale';
  13. import ConfigStore from 'sentry/stores/configStore';
  14. import OrganizationsStore from 'sentry/stores/organizationsStore';
  15. import {useLegacyStore} from 'sentry/stores/useLegacyStore';
  16. import {space} from 'sentry/styles/space';
  17. import type {Organization} from 'sentry/types/organization';
  18. import type {Project} from 'sentry/types/project';
  19. import type {UserEmail} from 'sentry/types/user';
  20. import parseLinkHeader from 'sentry/utils/parseLinkHeader';
  21. import withOrganizations from 'sentry/utils/withOrganizations';
  22. import DeprecatedAsyncView from 'sentry/views/deprecatedAsyncView';
  23. import type {FineTuneField} from 'sentry/views/settings/account/notifications/fields';
  24. import {ACCOUNT_NOTIFICATION_FIELDS} from 'sentry/views/settings/account/notifications/fields';
  25. import NotificationSettingsByType from 'sentry/views/settings/account/notifications/notificationSettingsByType';
  26. import {OrganizationSelectHeader} from 'sentry/views/settings/account/notifications/organizationSelectHeader';
  27. import {
  28. getNotificationTypeFromPathname,
  29. groupByOrganization,
  30. isGroupedByProject,
  31. } from 'sentry/views/settings/account/notifications/utils';
  32. import SettingsPageHeader from 'sentry/views/settings/components/settingsPageHeader';
  33. import TextBlock from 'sentry/views/settings/components/text/textBlock';
  34. const PanelBodyLineItem = styled(PanelBody)`
  35. font-size: 1rem;
  36. &:not(:last-child) {
  37. border-bottom: 1px solid ${p => p.theme.innerBorder};
  38. }
  39. `;
  40. const accountNotifications = [
  41. 'alerts',
  42. 'deploy',
  43. 'workflow',
  44. 'approval',
  45. 'quota',
  46. 'spikeProtection',
  47. 'reports',
  48. 'brokenMonitors',
  49. ];
  50. type ANBPProps = {
  51. field: FineTuneField;
  52. projects: Project[];
  53. };
  54. function AccountNotificationsByProject({projects, field}: ANBPProps) {
  55. const projectsByOrg = groupByOrganization(projects);
  56. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  57. const {title, description, ...fieldConfig} = field;
  58. // Display as select box in this view regardless of the type specified in the config
  59. const data = Object.values(projectsByOrg).map(org => ({
  60. name: org.organization.name,
  61. projects: org.projects.map(project => ({
  62. ...fieldConfig,
  63. // `name` key refers to field name
  64. // we use project.id because slugs are not unique across orgs
  65. name: project.id,
  66. label: (
  67. <ProjectBadge
  68. project={project}
  69. avatarSize={20}
  70. avatarProps={{consistentWidth: true}}
  71. disableLink
  72. />
  73. ),
  74. })),
  75. }));
  76. return (
  77. <Fragment>
  78. {data.map(({name, projects: projectFields}) => (
  79. <div key={name}>
  80. {projectFields.map(f => (
  81. <PanelBodyLineItem key={f.name}>
  82. <SelectField
  83. defaultValue={f.defaultValue}
  84. name={f.name}
  85. options={f.options}
  86. label={f.label}
  87. />
  88. </PanelBodyLineItem>
  89. ))}
  90. </div>
  91. ))}
  92. </Fragment>
  93. );
  94. }
  95. type ANBOProps = {
  96. field: FineTuneField;
  97. };
  98. function AccountNotificationsByOrganization({field}: ANBOProps) {
  99. const {organizations} = useLegacyStore(OrganizationsStore);
  100. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  101. const {title, description, ...fieldConfig} = field;
  102. // Display as select box in this view regardless of the type specified in the config
  103. const data = organizations.map(org => ({
  104. ...fieldConfig,
  105. // `name` key refers to field name
  106. // we use org.id to remain consistent project.id use (which is required because slugs are not unique across orgs)
  107. name: org.id,
  108. label: org.slug,
  109. }));
  110. return (
  111. <Fragment>
  112. {data.map(f => (
  113. <PanelBodyLineItem key={f.name}>
  114. <SelectField
  115. defaultValue={f.defaultValue}
  116. name={f.name}
  117. options={f.options}
  118. label={f.label}
  119. />
  120. </PanelBodyLineItem>
  121. ))}
  122. </Fragment>
  123. );
  124. }
  125. type Props = DeprecatedAsyncView['props'] &
  126. RouteComponentProps<{fineTuneType: string}, {}> & {
  127. organizations: Organization[];
  128. };
  129. type State = DeprecatedAsyncView['state'] & {
  130. emails: UserEmail[] | null;
  131. emailsByProject: Record<string, any> | null;
  132. notifications: Record<string, any> | null;
  133. projects: Project[] | null;
  134. };
  135. class AccountNotificationFineTuning extends DeprecatedAsyncView<Props, State> {
  136. getEndpoints(): ReturnType<DeprecatedAsyncView['getEndpoints']> {
  137. const {fineTuneType: pathnameType} = this.props.params;
  138. const fineTuneType = getNotificationTypeFromPathname(pathnameType);
  139. const endpoints: ReturnType<DeprecatedAsyncView['getEndpoints']> = [
  140. ['notifications', '/users/me/notifications/'],
  141. ];
  142. if (isGroupedByProject(fineTuneType)) {
  143. const organizationId = this.getOrganizationId();
  144. endpoints.push(['projects', `/projects/`, {query: {organizationId}}]);
  145. }
  146. // special logic for email
  147. if (fineTuneType === 'email') {
  148. endpoints.push(['emails', '/users/me/emails/']);
  149. endpoints.push(['emailsByProject', `/users/me/notifications/email/`]);
  150. }
  151. return endpoints;
  152. }
  153. // Return a sorted list of user's verified emails
  154. get emailChoices() {
  155. return (
  156. this.state.emails
  157. ?.filter(({isVerified}) => isVerified)
  158. ?.sort((a, b) => {
  159. // Sort by primary -> email
  160. if (a.isPrimary) {
  161. return -1;
  162. }
  163. if (b.isPrimary) {
  164. return 1;
  165. }
  166. return a.email < b.email ? -1 : 1;
  167. }) ?? []
  168. );
  169. }
  170. handleOrgChange = (organizationId: string) => {
  171. this.props.router.replace({
  172. ...this.props.location,
  173. query: {organizationId},
  174. });
  175. };
  176. getOrganizationId(): string | undefined {
  177. const {location, organizations} = this.props;
  178. const customerDomain = ConfigStore.get('customerDomain');
  179. const orgFromSubdomain = organizations.find(
  180. ({slug}) => slug === customerDomain?.subdomain
  181. )?.id;
  182. return location?.query?.organizationId ?? orgFromSubdomain ?? organizations[0]?.id;
  183. }
  184. renderBody() {
  185. const {params, organizations} = this.props;
  186. const {fineTuneType: pathnameType} = params;
  187. const fineTuneType = getNotificationTypeFromPathname(pathnameType);
  188. if (accountNotifications.includes(fineTuneType)) {
  189. return <NotificationSettingsByType notificationType={fineTuneType} />;
  190. }
  191. const {notifications, projects, emailsByProject, projectsPageLinks} = this.state;
  192. const isProject = isGroupedByProject(fineTuneType) && organizations.length > 0;
  193. const field = ACCOUNT_NOTIFICATION_FIELDS[fineTuneType];
  194. // TODO(isabella): once GA, remove this
  195. if (
  196. fineTuneType === 'quota' &&
  197. organizations.some(org => org.features?.includes('spend-visibility-notifications'))
  198. ) {
  199. field.title = t('Spend Notifications');
  200. field.description = t(
  201. 'Control the notifications you receive for organization spend.'
  202. );
  203. }
  204. const {title, description} = field;
  205. const [stateKey] = isProject ? this.getEndpoints()[2] : [];
  206. const hasProjects = !!projects?.length;
  207. if (fineTuneType === 'email') {
  208. // Fetch verified email addresses
  209. field.options = this.emailChoices.map(({email}) => ({value: email, label: email}));
  210. }
  211. if (!notifications || (!emailsByProject && fineTuneType === 'email')) {
  212. return null;
  213. }
  214. const orgId = this.getOrganizationId();
  215. const paginationObject = parseLinkHeader(projectsPageLinks ?? '');
  216. const hasMore = paginationObject?.next?.results;
  217. const hasPrevious = paginationObject?.previous?.results;
  218. const mainContent = (
  219. <Fragment>
  220. {isProject && hasProjects && (
  221. <AccountNotificationsByProject projects={projects!} field={field} />
  222. )}
  223. {isProject && !hasProjects && (
  224. <EmptyMessage>{t('No projects found')}</EmptyMessage>
  225. )}
  226. {!isProject && <AccountNotificationsByOrganization field={field} />}
  227. </Fragment>
  228. );
  229. return (
  230. <div>
  231. <SettingsPageHeader title={title} />
  232. {description && <TextBlock>{description}</TextBlock>}
  233. <Panel>
  234. <StyledPanelHeader hasButtons={isProject}>
  235. {isProject ? (
  236. <Fragment>
  237. <OrganizationSelectHeader
  238. organizations={organizations}
  239. organizationId={orgId}
  240. handleOrgChange={this.handleOrgChange}
  241. />
  242. {this.renderSearchInput({
  243. placeholder: t('Search Projects'),
  244. url: `/projects/?organizationId=${orgId}`,
  245. stateKey,
  246. })}
  247. </Fragment>
  248. ) : (
  249. <Heading>{t('Organizations')}</Heading>
  250. )}
  251. </StyledPanelHeader>
  252. <PanelBody>
  253. {/* Only email needs the form to change the emmail */}
  254. {fineTuneType === 'email' && emailsByProject ? (
  255. <Form
  256. saveOnBlur
  257. apiMethod="PUT"
  258. apiEndpoint="/users/me/notifications/email/"
  259. initialData={emailsByProject}
  260. >
  261. {mainContent}
  262. </Form>
  263. ) : (
  264. mainContent
  265. )}
  266. </PanelBody>
  267. </Panel>
  268. {projects && (hasMore || hasPrevious) && (
  269. <Pagination pageLinks={projectsPageLinks} />
  270. )}
  271. </div>
  272. );
  273. }
  274. }
  275. const Heading = styled('div')`
  276. flex: 1;
  277. `;
  278. const StyledPanelHeader = styled(PanelHeader)`
  279. flex-wrap: wrap;
  280. gap: ${space(1)};
  281. & > form:last-child {
  282. flex-grow: 1;
  283. }
  284. `;
  285. export default withOrganizations(AccountNotificationFineTuning);