organizationMembersList.tsx 12 KB

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