accountNotificationFineTuning.tsx 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. import {Fragment} from 'react';
  2. import {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 {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 {
  22. ACCOUNT_NOTIFICATION_FIELDS,
  23. FineTuneField,
  24. } 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. ];
  49. type ANBPProps = {
  50. field: FineTuneField;
  51. projects: Project[];
  52. };
  53. function AccountNotificationsByProject({projects, field}: ANBPProps) {
  54. const projectsByOrg = groupByOrganization(projects);
  55. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  56. const {title, description, ...fieldConfig} = field;
  57. // Display as select box in this view regardless of the type specified in the config
  58. const data = Object.values(projectsByOrg).map(org => ({
  59. name: org.organization.name,
  60. projects: org.projects.map(project => ({
  61. ...fieldConfig,
  62. // `name` key refers to field name
  63. // we use project.id because slugs are not unique across orgs
  64. name: project.id,
  65. label: (
  66. <ProjectBadge
  67. project={project}
  68. avatarSize={20}
  69. displayName={project.slug}
  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. const {title, description} = field;
  195. const [stateKey] = isProject ? this.getEndpoints()[2] : [];
  196. const hasProjects = !!projects?.length;
  197. if (fineTuneType === 'email') {
  198. // Fetch verified email addresses
  199. field.options = this.emailChoices.map(({email}) => ({value: email, label: email}));
  200. }
  201. if (!notifications || (!emailsByProject && fineTuneType === 'email')) {
  202. return null;
  203. }
  204. const orgId = this.getOrganizationId();
  205. const paginationObject = parseLinkHeader(projectsPageLinks ?? '');
  206. const hasMore = paginationObject?.next?.results;
  207. const hasPrevious = paginationObject?.previous?.results;
  208. const mainContent = (
  209. <Fragment>
  210. {isProject && hasProjects && (
  211. <AccountNotificationsByProject projects={projects!} field={field} />
  212. )}
  213. {isProject && !hasProjects && (
  214. <EmptyMessage>{t('No projects found')}</EmptyMessage>
  215. )}
  216. {!isProject && <AccountNotificationsByOrganization field={field} />}
  217. </Fragment>
  218. );
  219. return (
  220. <div>
  221. <SettingsPageHeader title={title} />
  222. {description && <TextBlock>{description}</TextBlock>}
  223. <Panel>
  224. <StyledPanelHeader hasButtons={isProject}>
  225. {isProject ? (
  226. <Fragment>
  227. <OrganizationSelectHeader
  228. organizations={organizations}
  229. organizationId={orgId}
  230. handleOrgChange={this.handleOrgChange}
  231. />
  232. {this.renderSearchInput({
  233. placeholder: t('Search Projects'),
  234. url: `/projects/?organizationId=${orgId}`,
  235. stateKey,
  236. })}
  237. </Fragment>
  238. ) : (
  239. <Heading>{t('Organizations')}</Heading>
  240. )}
  241. </StyledPanelHeader>
  242. <PanelBody>
  243. {/* Only email needs the form to change the emmail */}
  244. {fineTuneType === 'email' && emailsByProject ? (
  245. <Form
  246. saveOnBlur
  247. apiMethod="PUT"
  248. apiEndpoint="/users/me/notifications/email/"
  249. initialData={emailsByProject}
  250. >
  251. {mainContent}
  252. </Form>
  253. ) : (
  254. mainContent
  255. )}
  256. </PanelBody>
  257. </Panel>
  258. {projects && (hasMore || hasPrevious) && (
  259. <Pagination pageLinks={projectsPageLinks} />
  260. )}
  261. </div>
  262. );
  263. }
  264. }
  265. const Heading = styled('div')`
  266. flex: 1;
  267. `;
  268. const StyledPanelHeader = styled(PanelHeader)`
  269. flex-wrap: wrap;
  270. gap: ${space(1)};
  271. & > form:last-child {
  272. flex-grow: 1;
  273. }
  274. `;
  275. export default withOrganizations(AccountNotificationFineTuning);