accountNotificationFineTuning.tsx 9.7 KB

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