accountNotificationFineTuning.tsx 9.7 KB

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