organizationMembersList.tsx 11 KB

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