organizationMembersList.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  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. handleInviteMissingMember = async (email: string) => {
  153. const {organization} = this.props;
  154. try {
  155. await this.api.requestPromise(`/organizations/${organization.slug}/members/`, {
  156. method: 'POST',
  157. data: {email},
  158. });
  159. addSuccessMessage(tct('Sent invite to [email]', {email}));
  160. this.fetchMembersList();
  161. this.setState(state => ({
  162. missingMembers: state.missingMembers.map(integrationMissingMembers => ({
  163. ...integrationMissingMembers,
  164. users: integrationMissingMembers.users.filter(member => member.email !== email),
  165. })),
  166. }));
  167. } catch {
  168. addErrorMessage(t('Error sending invite'));
  169. }
  170. };
  171. fetchMembersList = async () => {
  172. const {organization} = this.props;
  173. try {
  174. const data = await this.api.requestPromise(
  175. `/organizations/${organization.slug}/members/`,
  176. {
  177. method: 'GET',
  178. data: {paginate: true},
  179. }
  180. );
  181. this.setState({members: data});
  182. } catch {
  183. addErrorMessage(t('Error fetching members'));
  184. }
  185. };
  186. updateInviteRequest = (id: string, data: Partial<Member>) =>
  187. this.setState(state => {
  188. const inviteRequests = [...state.inviteRequests];
  189. const inviteIndex = inviteRequests.findIndex(request => request.id === id);
  190. inviteRequests[inviteIndex] = {...inviteRequests[inviteIndex], ...data};
  191. return {inviteRequests};
  192. });
  193. removeInviteRequest = (id: string) =>
  194. this.setState(state => ({
  195. inviteRequests: state.inviteRequests.filter(request => request.id !== id),
  196. }));
  197. handleInviteRequestAction = async ({
  198. inviteRequest,
  199. method,
  200. data,
  201. successMessage,
  202. errorMessage,
  203. eventKey,
  204. }) => {
  205. const {organization} = this.props;
  206. this.setState(state => ({
  207. inviteRequestBusy: {...state.inviteRequestBusy, [inviteRequest.id]: true},
  208. }));
  209. try {
  210. await this.api.requestPromise(
  211. `/organizations/${organization.slug}/invite-requests/${inviteRequest.id}/`,
  212. {
  213. method,
  214. data,
  215. }
  216. );
  217. this.removeInviteRequest(inviteRequest.id);
  218. addSuccessMessage(successMessage);
  219. trackAnalytics(eventKey, {
  220. member_id: parseInt(inviteRequest.id, 10),
  221. invite_status: inviteRequest.inviteStatus,
  222. organization,
  223. });
  224. } catch {
  225. addErrorMessage(errorMessage);
  226. }
  227. this.setState(state => ({
  228. inviteRequestBusy: {...state.inviteRequestBusy, [inviteRequest.id]: false},
  229. }));
  230. };
  231. handleInviteRequestApprove = (inviteRequest: Member) => {
  232. this.handleInviteRequestAction({
  233. inviteRequest,
  234. method: 'PUT',
  235. data: {
  236. role: inviteRequest.role,
  237. teams: inviteRequest.teams,
  238. approve: 1,
  239. },
  240. successMessage: tct('[email] has been invited', {email: inviteRequest.email}),
  241. errorMessage: tct('Error inviting [email]', {email: inviteRequest.email}),
  242. eventKey: 'invite_request.approved',
  243. });
  244. };
  245. handleInviteRequestDeny = (inviteRequest: Member) => {
  246. this.handleInviteRequestAction({
  247. inviteRequest,
  248. method: 'DELETE',
  249. data: {},
  250. successMessage: tct('Invite request for [email] denied', {
  251. email: inviteRequest.email,
  252. }),
  253. errorMessage: tct('Error denying invite request for [email]', {
  254. email: inviteRequest.email,
  255. }),
  256. eventKey: 'invite_request.denied',
  257. });
  258. };
  259. renderBody() {
  260. const {organization} = this.props;
  261. const {
  262. membersPageLinks,
  263. members,
  264. member: currentMember,
  265. inviteRequests,
  266. missingMembers,
  267. } = this.state;
  268. const {access} = organization;
  269. const canAddMembers = access.includes('member:write');
  270. const canRemove = access.includes('member:admin');
  271. const currentUser = ConfigStore.get('user');
  272. // Find out if current user is the only owner
  273. const isOnlyOwner = !members.find(
  274. ({role, email, pending}) =>
  275. role === 'owner' && email !== currentUser.email && !pending
  276. );
  277. // Only admins/owners can remove members
  278. const requireLink = !!this.state.authProvider && this.state.authProvider.require_link;
  279. // eslint-disable-next-line react/prop-types
  280. const renderSearch: RenderSearch = ({defaultSearchBar, value, handleChange}) => (
  281. <SearchWrapperWithFilter>
  282. <MembersFilter
  283. roles={currentMember?.roles ?? ORG_ROLES}
  284. query={value}
  285. onChange={(query: string) => handleChange(query)}
  286. />
  287. {defaultSearchBar}
  288. </SearchWrapperWithFilter>
  289. );
  290. const githubMissingMembers = missingMembers?.filter(
  291. integrationMissingMembers => integrationMissingMembers.integration === 'github'
  292. )[0];
  293. return (
  294. <Fragment>
  295. <InviteBanner
  296. missingMembers={githubMissingMembers}
  297. onSendInvite={this.handleInviteMissingMember}
  298. onModalClose={this.fetchMembersList}
  299. allowedRoles={currentMember ? currentMember.roles : ORG_ROLES}
  300. />
  301. <ClassNames>
  302. {({css}) =>
  303. this.renderSearchInput({
  304. updateRoute: true,
  305. placeholder: t('Search Members'),
  306. children: renderSearch,
  307. className: css`
  308. font-size: ${theme.fontSizeMedium};
  309. `,
  310. })
  311. }
  312. </ClassNames>
  313. {inviteRequests && inviteRequests.length > 0 && (
  314. <Panel>
  315. <PanelHeader>
  316. <StyledPanelItem>
  317. <div>{t('Pending Members')}</div>
  318. <div>{t('Role')}</div>
  319. <div>{t('Teams')}</div>
  320. </StyledPanelItem>
  321. </PanelHeader>
  322. <PanelBody>
  323. {inviteRequests.map(inviteRequest => (
  324. <InviteRequestRow
  325. key={inviteRequest.id}
  326. organization={organization}
  327. inviteRequest={inviteRequest}
  328. inviteRequestBusy={{}}
  329. allRoles={currentMember?.roles ?? ORG_ROLES}
  330. onApprove={this.handleInviteRequestApprove}
  331. onDeny={this.handleInviteRequestDeny}
  332. onUpdate={data => this.updateInviteRequest(inviteRequest.id, data)}
  333. />
  334. ))}
  335. </PanelBody>
  336. </Panel>
  337. )}
  338. <Panel data-test-id="org-member-list">
  339. <MemberListHeader members={members} organization={organization} />
  340. <PanelBody>
  341. {members.map(member => (
  342. <OrganizationMemberRow
  343. key={member.id}
  344. organization={organization}
  345. member={member}
  346. status={this.state.invited[member.id]}
  347. memberCanLeave={!isOnlyOwner && !member.flags['idp:provisioned']}
  348. currentUser={currentUser}
  349. canRemoveMembers={canRemove}
  350. canAddMembers={canAddMembers}
  351. requireLink={requireLink}
  352. onSendInvite={this.handleSendInvite}
  353. onRemove={this.handleRemove}
  354. onLeave={this.handleLeave}
  355. />
  356. ))}
  357. {members.length === 0 && (
  358. <EmptyMessage>{t('No members found.')}</EmptyMessage>
  359. )}
  360. </PanelBody>
  361. </Panel>
  362. <Pagination pageLinks={membersPageLinks} />
  363. </Fragment>
  364. );
  365. }
  366. }
  367. const SearchWrapperWithFilter = styled(SearchWrapper)`
  368. display: grid;
  369. grid-template-columns: max-content 1fr;
  370. margin-top: 0;
  371. `;
  372. const StyledPanelItem = styled('div')`
  373. display: grid;
  374. grid-template-columns: minmax(150px, auto) minmax(100px, 140px) 420px;
  375. gap: ${space(2)};
  376. align-items: center;
  377. width: 100%;
  378. `;
  379. export default withOrganization(OrganizationMembersList);