organizationMembersList.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. import {Fragment} from 'react';
  2. import type {RouteComponentProps} from 'react-router';
  3. import {ClassNames} from '@emotion/react';
  4. import styled from '@emotion/styled';
  5. import {addErrorMessage, addSuccessMessage} from 'sentry/actionCreators/indicator';
  6. import {resendMemberInvite} from 'sentry/actionCreators/members';
  7. import {redirectToRemainingOrganization} from 'sentry/actionCreators/organizations';
  8. import type {AsyncComponentState} from 'sentry/components/deprecatedAsyncComponent';
  9. import EmptyMessage from 'sentry/components/emptyMessage';
  10. import HookOrDefault from 'sentry/components/hookOrDefault';
  11. import Pagination from 'sentry/components/pagination';
  12. import Panel from 'sentry/components/panels/panel';
  13. import PanelBody from 'sentry/components/panels/panelBody';
  14. import PanelHeader from 'sentry/components/panels/panelHeader';
  15. import {ORG_ROLES} from 'sentry/constants';
  16. import {t, tct} from 'sentry/locale';
  17. import ConfigStore from 'sentry/stores/configStore';
  18. import {space} from 'sentry/styles/space';
  19. import type {
  20. Member,
  21. MemberRole,
  22. MissingMember,
  23. Organization,
  24. OrganizationAuthProvider,
  25. } from 'sentry/types';
  26. import {trackAnalytics} from 'sentry/utils/analytics';
  27. import routeTitleGen from 'sentry/utils/routeTitle';
  28. import theme from 'sentry/utils/theme';
  29. import withOrganization from 'sentry/utils/withOrganization';
  30. import DeprecatedAsyncView from 'sentry/views/deprecatedAsyncView';
  31. import type {RenderSearch} from 'sentry/views/settings/components/defaultSearchBar';
  32. import {SearchWrapper} from 'sentry/views/settings/components/defaultSearchBar';
  33. import InviteBanner from 'sentry/views/settings/organizationMembers/inviteBanner';
  34. import MembersFilter from './components/membersFilter';
  35. import InviteRequestRow from './inviteRequestRow';
  36. import OrganizationMemberRow from './organizationMemberRow';
  37. interface Props extends RouteComponentProps<{}, {}> {
  38. organization: Organization;
  39. }
  40. interface State extends AsyncComponentState {
  41. authProvider: OrganizationAuthProvider | null;
  42. inviteRequests: Member[];
  43. invited: {[key: string]: 'loading' | 'success' | null};
  44. member: (Member & {roles: MemberRole[]}) | null;
  45. members: Member[];
  46. missingMembers: {integration: string; users: MissingMember[]}[];
  47. }
  48. const MemberListHeader = HookOrDefault({
  49. hookName: 'component:member-list-header',
  50. defaultComponent: () => <PanelHeader>{t('Active Members')}</PanelHeader>,
  51. });
  52. class OrganizationMembersList extends DeprecatedAsyncView<Props, State> {
  53. getDefaultState() {
  54. return {
  55. ...super.getDefaultState(),
  56. members: [],
  57. missingMembers: [],
  58. invited: {},
  59. };
  60. }
  61. onLoadAllEndpointsSuccess() {
  62. const {organization} = this.props;
  63. const {inviteRequests, members} = this.state;
  64. trackAnalytics('member_settings_page.loaded', {
  65. organization,
  66. num_members: members?.length,
  67. num_invite_requests: inviteRequests?.length,
  68. });
  69. }
  70. getEndpoints(): ReturnType<DeprecatedAsyncView['getEndpoints']> {
  71. const {organization} = this.props;
  72. return [
  73. ['members', `/organizations/${organization.slug}/members/`, {}, {paginate: true}],
  74. [
  75. 'member',
  76. `/organizations/${organization.slug}/members/me/`,
  77. {},
  78. {allowError: error => error.status === 404},
  79. ],
  80. [
  81. 'authProvider',
  82. `/organizations/${organization.slug}/auth-provider/`,
  83. {},
  84. {allowError: error => error.status === 403},
  85. ],
  86. ['inviteRequests', `/organizations/${organization.slug}/invite-requests/`],
  87. // [
  88. // 'missingMembers',
  89. // `/organizations/${organization.slug}/missing-members/`,
  90. // {},
  91. // {allowError: error => error.status === 403},
  92. // ],
  93. ];
  94. }
  95. getTitle() {
  96. const orgId = this.props.organization.slug;
  97. return routeTitleGen(t('Members'), orgId, false);
  98. }
  99. removeMember = async (id: string) => {
  100. const {organization} = this.props;
  101. await this.api.requestPromise(`/organizations/${organization.slug}/members/${id}/`, {
  102. method: 'DELETE',
  103. data: {},
  104. });
  105. this.setState(state => ({
  106. members: state.members.filter(({id: existingId}) => existingId !== id),
  107. }));
  108. };
  109. handleRemove = async ({id, name}: Member) => {
  110. const {organization} = this.props;
  111. const {slug: orgName} = organization;
  112. try {
  113. await this.removeMember(id);
  114. } catch {
  115. addErrorMessage(tct('Error removing [name] from [orgName]', {name, orgName}));
  116. return;
  117. }
  118. addSuccessMessage(tct('Removed [name] from [orgName]', {name, orgName}));
  119. };
  120. handleLeave = async ({id}: Member) => {
  121. const {organization} = this.props;
  122. const {slug: orgName} = organization;
  123. try {
  124. await this.removeMember(id);
  125. } catch {
  126. addErrorMessage(tct('Error leaving [orgName]', {orgName}));
  127. return;
  128. }
  129. redirectToRemainingOrganization({orgId: orgName, removeOrg: true});
  130. addSuccessMessage(tct('You left [orgName]', {orgName}));
  131. };
  132. handleSendInvite = async ({id, expired}) => {
  133. this.setState(state => ({
  134. invited: {...state.invited, [id]: 'loading'},
  135. }));
  136. const {organization} = this.props;
  137. try {
  138. await resendMemberInvite(this.api, {
  139. orgId: organization.slug,
  140. memberId: id,
  141. regenerate: expired,
  142. });
  143. } catch {
  144. this.setState(state => ({invited: {...state.invited, [id]: null}}));
  145. addErrorMessage(t('Error sending invite'));
  146. return;
  147. }
  148. this.setState(state => ({invited: {...state.invited, [id]: 'success'}}));
  149. };
  150. fetchMembersList = async () => {
  151. const {organization} = this.props;
  152. try {
  153. const data = await this.api.requestPromise(
  154. `/organizations/${organization.slug}/members/`,
  155. {
  156. method: 'GET',
  157. data: {paginate: true},
  158. }
  159. );
  160. this.setState({members: data});
  161. } catch {
  162. addErrorMessage(t('Error fetching members'));
  163. }
  164. };
  165. updateInviteRequest = (id: string, data: Partial<Member>) =>
  166. this.setState(state => {
  167. const inviteRequests = [...state.inviteRequests];
  168. const inviteIndex = inviteRequests.findIndex(request => request.id === id);
  169. inviteRequests[inviteIndex] = {...inviteRequests[inviteIndex], ...data};
  170. return {inviteRequests};
  171. });
  172. removeInviteRequest = (id: string) =>
  173. this.setState(state => ({
  174. inviteRequests: state.inviteRequests.filter(request => request.id !== id),
  175. }));
  176. handleInviteRequestAction = async ({
  177. inviteRequest,
  178. method,
  179. data,
  180. successMessage,
  181. errorMessage,
  182. eventKey,
  183. }) => {
  184. const {organization} = this.props;
  185. this.setState(state => ({
  186. inviteRequestBusy: {...state.inviteRequestBusy, [inviteRequest.id]: true},
  187. }));
  188. try {
  189. await this.api.requestPromise(
  190. `/organizations/${organization.slug}/invite-requests/${inviteRequest.id}/`,
  191. {
  192. method,
  193. data,
  194. }
  195. );
  196. this.removeInviteRequest(inviteRequest.id);
  197. addSuccessMessage(successMessage);
  198. trackAnalytics(eventKey, {
  199. member_id: parseInt(inviteRequest.id, 10),
  200. invite_status: inviteRequest.inviteStatus,
  201. organization,
  202. });
  203. } catch {
  204. addErrorMessage(errorMessage);
  205. }
  206. this.setState(state => ({
  207. inviteRequestBusy: {...state.inviteRequestBusy, [inviteRequest.id]: false},
  208. }));
  209. };
  210. handleInviteRequestApprove = (inviteRequest: Member) => {
  211. this.handleInviteRequestAction({
  212. inviteRequest,
  213. method: 'PUT',
  214. data: {
  215. role: inviteRequest.role,
  216. teams: inviteRequest.teams,
  217. approve: 1,
  218. },
  219. successMessage: tct('[email] has been invited', {email: inviteRequest.email}),
  220. errorMessage: tct('Error inviting [email]', {email: inviteRequest.email}),
  221. eventKey: 'invite_request.approved',
  222. });
  223. };
  224. handleInviteRequestDeny = (inviteRequest: Member) => {
  225. this.handleInviteRequestAction({
  226. inviteRequest,
  227. method: 'DELETE',
  228. data: {},
  229. successMessage: tct('Invite request for [email] denied', {
  230. email: inviteRequest.email,
  231. }),
  232. errorMessage: tct('Error denying invite request for [email]', {
  233. email: inviteRequest.email,
  234. }),
  235. eventKey: 'invite_request.denied',
  236. });
  237. };
  238. renderBody() {
  239. const {organization} = this.props;
  240. const {membersPageLinks, members, member: currentMember, inviteRequests} = this.state;
  241. const {access} = organization;
  242. const canAddMembers = access.includes('member:write');
  243. const canRemove = access.includes('member:admin');
  244. const currentUser = ConfigStore.get('user');
  245. // Find out if current user is the only owner
  246. const isOnlyOwner = !members.find(
  247. ({role, email, pending}) =>
  248. role === 'owner' && email !== currentUser.email && !pending
  249. );
  250. // Only admins/owners can remove members
  251. const requireLink = !!this.state.authProvider && this.state.authProvider.require_link;
  252. const renderSearch: RenderSearch = ({defaultSearchBar, value, handleChange}) => (
  253. <SearchWrapperWithFilter>
  254. <MembersFilter
  255. roles={currentMember?.roles ?? ORG_ROLES}
  256. query={value}
  257. onChange={(query: string) => handleChange(query)}
  258. />
  259. {defaultSearchBar}
  260. </SearchWrapperWithFilter>
  261. );
  262. return (
  263. <Fragment>
  264. <InviteBanner
  265. onSendInvite={this.fetchMembersList}
  266. onModalClose={this.fetchData}
  267. allowedRoles={currentMember ? currentMember.roles : ORG_ROLES}
  268. />
  269. <ClassNames>
  270. {({css}) =>
  271. this.renderSearchInput({
  272. updateRoute: true,
  273. placeholder: t('Search Members'),
  274. children: renderSearch,
  275. className: css`
  276. font-size: ${theme.fontSizeMedium};
  277. `,
  278. })
  279. }
  280. </ClassNames>
  281. {inviteRequests && inviteRequests.length > 0 && (
  282. <Panel>
  283. <PanelHeader>
  284. <StyledPanelItem>
  285. <div>{t('Pending Members')}</div>
  286. <div>{t('Role')}</div>
  287. <div>{t('Teams')}</div>
  288. </StyledPanelItem>
  289. </PanelHeader>
  290. <PanelBody>
  291. {inviteRequests.map(inviteRequest => (
  292. <InviteRequestRow
  293. key={inviteRequest.id}
  294. organization={organization}
  295. inviteRequest={inviteRequest}
  296. inviteRequestBusy={{}}
  297. allRoles={currentMember?.roles ?? ORG_ROLES}
  298. onApprove={this.handleInviteRequestApprove}
  299. onDeny={this.handleInviteRequestDeny}
  300. onUpdate={data => this.updateInviteRequest(inviteRequest.id, data)}
  301. />
  302. ))}
  303. </PanelBody>
  304. </Panel>
  305. )}
  306. <Panel data-test-id="org-member-list">
  307. <MemberListHeader members={members} organization={organization} />
  308. <PanelBody>
  309. {members.map(member => (
  310. <OrganizationMemberRow
  311. key={member.id}
  312. organization={organization}
  313. member={member}
  314. status={this.state.invited[member.id]}
  315. memberCanLeave={
  316. !(
  317. isOnlyOwner ||
  318. member.flags['idp:provisioned'] ||
  319. member.flags['partnership:restricted']
  320. )
  321. }
  322. currentUser={currentUser}
  323. canRemoveMembers={canRemove}
  324. canAddMembers={canAddMembers}
  325. requireLink={requireLink}
  326. onSendInvite={this.handleSendInvite}
  327. onRemove={this.handleRemove}
  328. onLeave={this.handleLeave}
  329. />
  330. ))}
  331. {members.length === 0 && (
  332. <EmptyMessage>{t('No members found.')}</EmptyMessage>
  333. )}
  334. </PanelBody>
  335. </Panel>
  336. <Pagination pageLinks={membersPageLinks} />
  337. </Fragment>
  338. );
  339. }
  340. }
  341. const SearchWrapperWithFilter = styled(SearchWrapper)`
  342. display: grid;
  343. grid-template-columns: max-content 1fr;
  344. margin-top: 0;
  345. `;
  346. const StyledPanelItem = styled('div')`
  347. display: grid;
  348. grid-template-columns: minmax(150px, auto) minmax(100px, 140px) 420px;
  349. gap: ${space(2)};
  350. align-items: center;
  351. width: 100%;
  352. `;
  353. export default withOrganization(OrganizationMembersList);