organizationMembersList.tsx 13 KB

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