organizationMembersList.tsx 11 KB

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