organizationMembersList.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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. // eslint-disable-next-line react/prop-types
  255. const renderSearch: RenderSearch = ({defaultSearchBar, value, handleChange}) => (
  256. <SearchWrapperWithFilter>
  257. <MembersFilter
  258. roles={currentMember?.roles ?? ORG_ROLES}
  259. query={value}
  260. onChange={(query: string) => handleChange(query)}
  261. />
  262. {defaultSearchBar}
  263. </SearchWrapperWithFilter>
  264. );
  265. return (
  266. <Fragment>
  267. <InviteBanner
  268. onSendInvite={this.fetchMembersList}
  269. onModalClose={this.fetchData}
  270. allowedRoles={currentMember ? currentMember.roles : ORG_ROLES}
  271. />
  272. <ClassNames>
  273. {({css}) =>
  274. this.renderSearchInput({
  275. updateRoute: true,
  276. placeholder: t('Search Members'),
  277. children: renderSearch,
  278. className: css`
  279. font-size: ${theme.fontSizeMedium};
  280. `,
  281. })
  282. }
  283. </ClassNames>
  284. {inviteRequests && inviteRequests.length > 0 && (
  285. <Panel>
  286. <PanelHeader>
  287. <StyledPanelItem>
  288. <div>{t('Pending Members')}</div>
  289. <div>{t('Role')}</div>
  290. <div>{t('Teams')}</div>
  291. </StyledPanelItem>
  292. </PanelHeader>
  293. <PanelBody>
  294. {inviteRequests.map(inviteRequest => (
  295. <InviteRequestRow
  296. key={inviteRequest.id}
  297. organization={organization}
  298. inviteRequest={inviteRequest}
  299. inviteRequestBusy={{}}
  300. allRoles={currentMember?.roles ?? ORG_ROLES}
  301. onApprove={this.handleInviteRequestApprove}
  302. onDeny={this.handleInviteRequestDeny}
  303. onUpdate={data => this.updateInviteRequest(inviteRequest.id, data)}
  304. />
  305. ))}
  306. </PanelBody>
  307. </Panel>
  308. )}
  309. <Panel data-test-id="org-member-list">
  310. <MemberListHeader members={members} organization={organization} />
  311. <PanelBody>
  312. {members.map(member => (
  313. <OrganizationMemberRow
  314. key={member.id}
  315. organization={organization}
  316. member={member}
  317. status={this.state.invited[member.id]}
  318. memberCanLeave={
  319. !(
  320. isOnlyOwner ||
  321. member.flags['idp:provisioned'] ||
  322. member.flags['partnership:restricted']
  323. )
  324. }
  325. currentUser={currentUser}
  326. canRemoveMembers={canRemove}
  327. canAddMembers={canAddMembers}
  328. requireLink={requireLink}
  329. onSendInvite={this.handleSendInvite}
  330. onRemove={this.handleRemove}
  331. onLeave={this.handleLeave}
  332. />
  333. ))}
  334. {members.length === 0 && (
  335. <EmptyMessage>{t('No members found.')}</EmptyMessage>
  336. )}
  337. </PanelBody>
  338. </Panel>
  339. <Pagination pageLinks={membersPageLinks} />
  340. </Fragment>
  341. );
  342. }
  343. }
  344. const SearchWrapperWithFilter = styled(SearchWrapper)`
  345. display: grid;
  346. grid-template-columns: max-content 1fr;
  347. margin-top: 0;
  348. `;
  349. const StyledPanelItem = styled('div')`
  350. display: grid;
  351. grid-template-columns: minmax(150px, auto) minmax(100px, 140px) 420px;
  352. gap: ${space(2)};
  353. align-items: center;
  354. width: 100%;
  355. `;
  356. export default withOrganization(OrganizationMembersList);