organizationMembersList.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. import {Fragment, useState} from 'react';
  2. import styled from '@emotion/styled';
  3. import {addErrorMessage, addSuccessMessage} from 'sentry/actionCreators/indicator';
  4. import {resendMemberInvite} from 'sentry/actionCreators/members';
  5. import {openInviteMembersModal} from 'sentry/actionCreators/modal';
  6. import {redirectToRemainingOrganization} from 'sentry/actionCreators/organizations';
  7. import FeatureDisabled from 'sentry/components/acl/featureDisabled';
  8. import {Button} from 'sentry/components/button';
  9. import EmptyMessage from 'sentry/components/emptyMessage';
  10. import HookOrDefault from 'sentry/components/hookOrDefault';
  11. import {Hovercard} from 'sentry/components/hovercard';
  12. import LoadingIndicator from 'sentry/components/loadingIndicator';
  13. import Pagination from 'sentry/components/pagination';
  14. import Panel from 'sentry/components/panels/panel';
  15. import PanelBody from 'sentry/components/panels/panelBody';
  16. import PanelHeader from 'sentry/components/panels/panelHeader';
  17. import SearchBar from 'sentry/components/searchBar';
  18. import {Tooltip} from 'sentry/components/tooltip';
  19. import {ORG_ROLES} from 'sentry/constants';
  20. import {IconMail} from 'sentry/icons';
  21. import {t, tct} from 'sentry/locale';
  22. import ConfigStore from 'sentry/stores/configStore';
  23. import {space} from 'sentry/styles/space';
  24. import type {OrganizationAuthProvider} from 'sentry/types/auth';
  25. import type {Member} from 'sentry/types/organization';
  26. import {trackAnalytics} from 'sentry/utils/analytics';
  27. import {
  28. type ApiQueryKey,
  29. setApiQueryData,
  30. useApiQuery,
  31. useQueryClient,
  32. } from 'sentry/utils/queryClient';
  33. import useApi from 'sentry/utils/useApi';
  34. import {useLocation} from 'sentry/utils/useLocation';
  35. import {useNavigate} from 'sentry/utils/useNavigate';
  36. import useOrganization from 'sentry/utils/useOrganization';
  37. import SettingsPageHeader from 'sentry/views/settings/components/settingsPageHeader';
  38. import InviteBanner from 'sentry/views/settings/organizationMembers/inviteBanner';
  39. import MembersFilter from './components/membersFilter';
  40. import InviteRequestRow from './inviteRequestRow';
  41. import OrganizationMemberRow from './organizationMemberRow';
  42. const MemberListHeader = HookOrDefault({
  43. hookName: 'component:member-list-header',
  44. defaultComponent: () => <PanelHeader>{t('Active Members')}</PanelHeader>,
  45. });
  46. const InviteMembersButtonHook = HookOrDefault({
  47. hookName: 'member-invite-button:customization',
  48. defaultComponent: ({children, organization, onTriggerModal}) => {
  49. const isSsoRequired = organization.requiresSso;
  50. const disabled = isSsoRequired || !organization.features.includes('invite-members');
  51. return children({disabled, isSsoRequired, onTriggerModal});
  52. },
  53. });
  54. const getMembersQueryKey = ({
  55. orgSlug,
  56. query,
  57. }: {
  58. orgSlug: string;
  59. query: Record<string, string>;
  60. }): ApiQueryKey => [`/organizations/${orgSlug}/members/`, {query}];
  61. const getInviteRequestsQueryKey = ({organization}): ApiQueryKey => [
  62. `/organizations/${organization.slug}/invite-requests/`,
  63. ];
  64. function OrganizationMembersList() {
  65. const queryClient = useQueryClient();
  66. const api = useApi({persistInFlight: true});
  67. const organization = useOrganization();
  68. const navigate = useNavigate();
  69. const location = useLocation();
  70. const {data: inviteRequests = [], refetch: refetchInviteRequests} = useApiQuery<
  71. Member[]
  72. >(getInviteRequestsQueryKey({organization}), {staleTime: 0});
  73. const {data: authProvider} = useApiQuery<OrganizationAuthProvider>(
  74. [`/organizations/${organization.slug}/auth-provider/`],
  75. {staleTime: 0}
  76. );
  77. const {data: currentMember} = useApiQuery<Member>(
  78. [`/organizations/${organization.slug}/members/me/`],
  79. {staleTime: 0}
  80. );
  81. const {
  82. data: members = [],
  83. isLoading: isLoadingMembers,
  84. refetch: refetchMembers,
  85. getResponseHeader,
  86. } = useApiQuery<Member[]>(
  87. getMembersQueryKey({
  88. orgSlug: organization.slug,
  89. query: {
  90. query: location.query.query as string,
  91. cursor: location.query.cursor as string,
  92. },
  93. }),
  94. {staleTime: 0}
  95. );
  96. const [invited, setInvited] = useState<{
  97. [memberId: string]: 'loading' | 'success' | null;
  98. }>({});
  99. const removeMember = async (id: string) => {
  100. await api.requestPromise(`/organizations/${organization.slug}/members/${id}/`, {
  101. method: 'DELETE',
  102. data: {},
  103. });
  104. setApiQueryData<Member[]>(
  105. queryClient,
  106. getMembersQueryKey({
  107. orgSlug: organization.slug,
  108. query: {
  109. query: location.query.query as string,
  110. cursor: location.query.cursor as string,
  111. },
  112. }),
  113. currentMembers => currentMembers?.filter(member => member.id !== id)
  114. );
  115. };
  116. const handleRemove = async ({id, name}: Member) => {
  117. const {slug: orgName} = organization;
  118. try {
  119. await removeMember(id);
  120. } catch {
  121. addErrorMessage(tct('Error removing [name] from [orgName]', {name, orgName}));
  122. return;
  123. }
  124. addSuccessMessage(tct('Removed [name] from [orgName]', {name, orgName}));
  125. };
  126. const handleLeave = async ({id}: Member) => {
  127. try {
  128. await removeMember(id);
  129. } catch {
  130. addErrorMessage(tct('Error leaving [orgName]', {orgName: organization.slug}));
  131. return;
  132. }
  133. redirectToRemainingOrganization({
  134. orgId: organization.slug,
  135. removeOrg: true,
  136. });
  137. addSuccessMessage(tct('You left [orgName]', {orgName: organization.slug}));
  138. };
  139. const handleSendInvite = async ({id, expired}) => {
  140. setInvited(state => ({...state, [id]: 'loading'}));
  141. try {
  142. await resendMemberInvite(api, {
  143. orgId: organization.slug,
  144. memberId: id,
  145. regenerate: expired,
  146. });
  147. } catch {
  148. setInvited(state => ({...state, [id]: null}));
  149. addErrorMessage(t('Error sending invite'));
  150. return;
  151. }
  152. setInvited(state => ({...state, [id]: 'success'}));
  153. };
  154. const updateInviteRequest = (id: string, data: Partial<Member>) => {
  155. setApiQueryData<Member[]>(
  156. queryClient,
  157. getInviteRequestsQueryKey({organization}),
  158. curentInviteRequests => {
  159. const newInviteRequests = curentInviteRequests.map(request => {
  160. if (request.id === id) {
  161. return {...request, ...data};
  162. }
  163. return request;
  164. });
  165. return newInviteRequests;
  166. }
  167. );
  168. };
  169. const removeInviteRequest = (id: string) => {
  170. setApiQueryData<Member[]>(
  171. queryClient,
  172. getInviteRequestsQueryKey({organization}),
  173. curentInviteRequests => curentInviteRequests?.filter(request => request.id !== id)
  174. );
  175. };
  176. const handleInviteRequestAction = async ({
  177. inviteRequest,
  178. method,
  179. data,
  180. successMessage,
  181. errorMessage,
  182. eventKey,
  183. }) => {
  184. try {
  185. await api.requestPromise(
  186. `/organizations/${organization.slug}/invite-requests/${inviteRequest.id}/`,
  187. {
  188. method,
  189. data,
  190. }
  191. );
  192. removeInviteRequest(inviteRequest.id);
  193. addSuccessMessage(successMessage);
  194. trackAnalytics(eventKey, {
  195. member_id: parseInt(inviteRequest.id, 10),
  196. invite_status: inviteRequest.inviteStatus,
  197. organization,
  198. });
  199. } catch {
  200. addErrorMessage(errorMessage);
  201. }
  202. };
  203. const handleInviteRequestApprove = (inviteRequest: Member) => {
  204. handleInviteRequestAction({
  205. inviteRequest,
  206. method: 'PUT',
  207. data: {
  208. role: inviteRequest.role,
  209. teams: inviteRequest.teams,
  210. approve: 1,
  211. },
  212. successMessage: tct('[email] has been invited', {email: inviteRequest.email}),
  213. errorMessage: tct('Error inviting [email]', {email: inviteRequest.email}),
  214. eventKey: 'invite_request.approved',
  215. });
  216. };
  217. const handleInviteRequestDeny = (inviteRequest: Member) => {
  218. handleInviteRequestAction({
  219. inviteRequest,
  220. method: 'DELETE',
  221. data: {},
  222. successMessage: tct('Invite request for [email] denied', {
  223. email: inviteRequest.email,
  224. }),
  225. errorMessage: tct('Error denying invite request for [email]', {
  226. email: inviteRequest.email,
  227. }),
  228. eventKey: 'invite_request.denied',
  229. });
  230. };
  231. const handleQueryChange = (query: string) => {
  232. navigate({
  233. pathname: location.pathname,
  234. query: {...location.query, query, cursor: undefined},
  235. });
  236. };
  237. const canAddMembers = organization.access.includes('member:write');
  238. const canRemove = organization.access.includes('member:admin');
  239. const currentUser = ConfigStore.get('user');
  240. // Find out if current user is the only owner
  241. const isOnlyOwner = !members.find(
  242. ({role, email, pending}) =>
  243. role === 'owner' && email !== currentUser.email && !pending
  244. );
  245. // Only admins/owners can remove members
  246. const requireLink = !!authProvider && authProvider.require_link;
  247. const searchQuery = (location.query.query as string) || '';
  248. const membersPageLinks = getResponseHeader?.('Link');
  249. const action = (
  250. <InviteMembersButtonHook
  251. organization={organization}
  252. onTriggerModal={() => {
  253. openInviteMembersModal({
  254. onClose: () => {
  255. refetchInviteRequests();
  256. refetchMembers();
  257. },
  258. source: 'members_settings',
  259. });
  260. }}
  261. >
  262. {({disabled, isSsoRequired, onTriggerModal}) => (
  263. <InviteMembersButton
  264. disabled={disabled}
  265. isSsoRequired={isSsoRequired}
  266. onTriggerModal={onTriggerModal}
  267. />
  268. )}
  269. </InviteMembersButtonHook>
  270. );
  271. return (
  272. <Fragment>
  273. <SettingsPageHeader title="Members" action={action} />
  274. <InviteBanner
  275. onSendInvite={() => {
  276. refetchMembers();
  277. }}
  278. onModalClose={() => {
  279. refetchInviteRequests();
  280. refetchMembers();
  281. }}
  282. allowedRoles={currentMember ? currentMember.roles : ORG_ROLES}
  283. />
  284. {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={handleInviteRequestApprove}
  302. onDeny={handleInviteRequestDeny}
  303. onUpdate={data => updateInviteRequest(inviteRequest.id, data)}
  304. />
  305. ))}
  306. </PanelBody>
  307. </Panel>
  308. )}
  309. <SearchWrapperWithFilter>
  310. <MembersFilter
  311. roles={currentMember?.roles ?? ORG_ROLES}
  312. query={searchQuery}
  313. onChange={handleQueryChange}
  314. />
  315. <SearchBar
  316. placeholder={t('Search Members')}
  317. query={searchQuery}
  318. onSearch={handleQueryChange}
  319. />
  320. </SearchWrapperWithFilter>
  321. <Panel data-test-id="org-member-list">
  322. <MemberListHeader members={members} organization={organization} />
  323. <PanelBody>
  324. {isLoadingMembers ? (
  325. <LoadingIndicator />
  326. ) : (
  327. <Fragment>
  328. {members.map(member => (
  329. <OrganizationMemberRow
  330. key={member.id}
  331. organization={organization}
  332. member={member}
  333. status={invited[member.id]}
  334. memberCanLeave={
  335. !(
  336. isOnlyOwner ||
  337. member.flags['idp:provisioned'] ||
  338. member.flags['partnership:restricted']
  339. )
  340. }
  341. currentUser={currentUser}
  342. canRemoveMembers={canRemove}
  343. canAddMembers={canAddMembers}
  344. requireLink={requireLink}
  345. onSendInvite={handleSendInvite}
  346. onRemove={handleRemove}
  347. onLeave={handleLeave}
  348. />
  349. ))}
  350. {members.length === 0 && (
  351. <EmptyMessage>{t('No members found.')}</EmptyMessage>
  352. )}
  353. </Fragment>
  354. )}
  355. </PanelBody>
  356. </Panel>
  357. <Pagination pageLinks={membersPageLinks} />
  358. </Fragment>
  359. );
  360. }
  361. const SearchWrapperWithFilter = styled('div')`
  362. position: relative;
  363. display: grid;
  364. grid-template-columns: max-content 1fr;
  365. gap: ${space(1.5)};
  366. margin-bottom: ${space(1.5)};
  367. `;
  368. const StyledPanelItem = styled('div')`
  369. display: grid;
  370. grid-template-columns: minmax(150px, auto) minmax(100px, 140px) 420px;
  371. gap: ${space(2)};
  372. align-items: center;
  373. width: 100%;
  374. `;
  375. export default OrganizationMembersList;
  376. function InviteMembersButton({
  377. disabled,
  378. isSsoRequired,
  379. onTriggerModal,
  380. }: {
  381. onTriggerModal: () => void;
  382. disabled?: boolean;
  383. isSsoRequired?: boolean;
  384. }) {
  385. const action = (
  386. <Button
  387. priority="primary"
  388. size="sm"
  389. onClick={onTriggerModal}
  390. data-test-id="email-invite"
  391. icon={<IconMail />}
  392. disabled={disabled}
  393. >
  394. {t('Invite Members')}
  395. </Button>
  396. );
  397. return disabled ? (
  398. isSsoRequired ? (
  399. <Tooltip
  400. skipWrapper
  401. title={t(
  402. `Your organization must use its single sign-on provider to register new members.`
  403. )}
  404. >
  405. {action}
  406. </Tooltip>
  407. ) : (
  408. <Hovercard
  409. body={
  410. <FeatureDisabled
  411. featureName={t('Invite Members')}
  412. features="organizations:invite-members"
  413. hideHelpToggle
  414. />
  415. }
  416. >
  417. {action}
  418. </Hovercard>
  419. )
  420. ) : (
  421. action
  422. );
  423. }