organizationMembersList.tsx 12 KB

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