teamMembers.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. import {Fragment} from 'react';
  2. import type {RouteComponentProps} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import debounce from 'lodash/debounce';
  5. import {addErrorMessage, addSuccessMessage} from 'sentry/actionCreators/indicator';
  6. import {
  7. openInviteMembersModal,
  8. openTeamAccessRequestModal,
  9. } from 'sentry/actionCreators/modal';
  10. import {joinTeam, leaveTeam} from 'sentry/actionCreators/teams';
  11. import type {Client} from 'sentry/api';
  12. import {hasEveryAccess} from 'sentry/components/acl/access';
  13. import UserAvatar from 'sentry/components/avatar/userAvatar';
  14. import DropdownAutoComplete from 'sentry/components/dropdownAutoComplete';
  15. import type {Item} from 'sentry/components/dropdownAutoComplete/types';
  16. import DropdownButton from 'sentry/components/dropdownButton';
  17. import EmptyMessage from 'sentry/components/emptyMessage';
  18. import Link from 'sentry/components/links/link';
  19. import LoadingError from 'sentry/components/loadingError';
  20. import LoadingIndicator from 'sentry/components/loadingIndicator';
  21. import Pagination from 'sentry/components/pagination';
  22. import Panel from 'sentry/components/panels/panel';
  23. import PanelHeader from 'sentry/components/panels/panelHeader';
  24. import {TeamRoleColumnLabel} from 'sentry/components/teamRoleUtils';
  25. import {IconUser} from 'sentry/icons';
  26. import {t} from 'sentry/locale';
  27. import {space} from 'sentry/styles/space';
  28. import type {Member, Organization, Team, TeamMember} from 'sentry/types/organization';
  29. import type {Config} from 'sentry/types/system';
  30. import withApi from 'sentry/utils/withApi';
  31. import withConfig from 'sentry/utils/withConfig';
  32. import withOrganization from 'sentry/utils/withOrganization';
  33. import type {AsyncViewState} from 'sentry/views/deprecatedAsyncView';
  34. import DeprecatedAsyncView from 'sentry/views/deprecatedAsyncView';
  35. import TextBlock from 'sentry/views/settings/components/text/textBlock';
  36. import TeamMembersRow, {
  37. GRID_TEMPLATE,
  38. } from 'sentry/views/settings/organizationTeams/teamMembersRow';
  39. import PermissionAlert from 'sentry/views/settings/project/permissionAlert';
  40. import {getButtonHelpText} from './utils';
  41. type RouteParams = {
  42. teamId: string;
  43. };
  44. interface Props extends RouteComponentProps<RouteParams, {}> {
  45. api: Client;
  46. config: Config;
  47. organization: Organization;
  48. team: Team;
  49. }
  50. interface State extends AsyncViewState {
  51. dropdownBusy: boolean;
  52. error: boolean;
  53. orgMembers: Member[];
  54. teamMembers: TeamMember[];
  55. }
  56. class TeamMembers extends DeprecatedAsyncView<Props, State> {
  57. getDefaultState() {
  58. return {
  59. ...super.getDefaultState(),
  60. error: false,
  61. dropdownBusy: false,
  62. teamMembers: [],
  63. orgMembers: [],
  64. };
  65. }
  66. componentDidMount() {
  67. super.componentDidMount();
  68. // Initialize "add member" dropdown with data
  69. this.fetchMembersRequest('');
  70. }
  71. debouncedFetchMembersRequest = debounce(
  72. (query: string) =>
  73. this.setState({dropdownBusy: true}, () => this.fetchMembersRequest(query)),
  74. 200
  75. );
  76. fetchMembersRequest = async (query: string) => {
  77. const {organization, api} = this.props;
  78. try {
  79. const data = await api.requestPromise(
  80. `/organizations/${organization.slug}/members/`,
  81. {
  82. query: {query},
  83. }
  84. );
  85. this.setState({
  86. orgMembers: data,
  87. dropdownBusy: false,
  88. });
  89. } catch (_err) {
  90. addErrorMessage(t('Unable to load organization members.'), {
  91. duration: 2000,
  92. });
  93. this.setState({
  94. dropdownBusy: false,
  95. });
  96. }
  97. };
  98. getEndpoints(): ReturnType<DeprecatedAsyncView['getEndpoints']> {
  99. const {organization, params} = this.props;
  100. return [
  101. [
  102. 'teamMembers',
  103. `/teams/${organization.slug}/${params.teamId}/members/`,
  104. {},
  105. {paginate: true},
  106. ],
  107. ];
  108. }
  109. addTeamMember = (selection: Item) => {
  110. const {organization, params} = this.props;
  111. const {orgMembers, teamMembers} = this.state;
  112. // Reset members list after adding member to team
  113. this.debouncedFetchMembersRequest('');
  114. joinTeam(
  115. this.props.api,
  116. {
  117. orgId: organization.slug,
  118. teamId: params.teamId,
  119. memberId: selection.value,
  120. },
  121. {
  122. success: () => {
  123. const orgMember = orgMembers.find(member => member.id === selection.value);
  124. if (orgMember === undefined) {
  125. return;
  126. }
  127. this.setState({
  128. error: false,
  129. teamMembers: teamMembers.concat([orgMember as TeamMember]),
  130. });
  131. addSuccessMessage(t('Successfully added member to team.'));
  132. },
  133. error: resp => {
  134. const errorMessage =
  135. resp?.responseJSON?.detail || t('Unable to add team member.');
  136. addErrorMessage(errorMessage);
  137. },
  138. }
  139. );
  140. };
  141. removeTeamMember = (member: Member) => {
  142. const {organization, params} = this.props;
  143. const {teamMembers} = this.state;
  144. leaveTeam(
  145. this.props.api,
  146. {
  147. orgId: organization.slug,
  148. teamId: params.teamId,
  149. memberId: member.id,
  150. },
  151. {
  152. success: () => {
  153. this.setState({
  154. teamMembers: teamMembers.filter(m => m.id !== member.id),
  155. });
  156. addSuccessMessage(t('Successfully removed member from team.'));
  157. },
  158. error: () =>
  159. addErrorMessage(
  160. t('There was an error while trying to remove a member from the team.')
  161. ),
  162. }
  163. );
  164. };
  165. updateTeamMemberRole = (member: Member, newRole: string) => {
  166. const {organization} = this.props;
  167. const {teamId} = this.props.params;
  168. const endpoint = `/organizations/${organization.slug}/members/${member.id}/teams/${teamId}/`;
  169. this.props.api.request(endpoint, {
  170. method: 'PUT',
  171. data: {teamRole: newRole},
  172. success: data => {
  173. const teamMembers: any = [...this.state.teamMembers];
  174. const i = teamMembers.findIndex(m => m.id === member.id);
  175. teamMembers[i] = {
  176. ...member,
  177. teamRole: data.teamRole,
  178. };
  179. this.setState({teamMembers});
  180. addSuccessMessage(t('Successfully changed role for team member.'));
  181. },
  182. error: () => {
  183. addErrorMessage(
  184. t('There was an error while trying to change the roles for a team member.')
  185. );
  186. },
  187. });
  188. };
  189. /**
  190. * We perform an API request to support orgs with > 100 members (since that's the max API returns)
  191. *
  192. * @param {Event} e React Event when member filter input changes
  193. */
  194. handleMemberFilterChange = (e: React.ChangeEvent<HTMLInputElement>) => {
  195. this.setState({dropdownBusy: true});
  196. this.debouncedFetchMembersRequest(e.target.value);
  197. };
  198. renderDropdown(isTeamAdmin: boolean) {
  199. const {organization, params, team} = this.props;
  200. const {orgMembers} = this.state;
  201. const existingMembers = new Set(this.state.teamMembers.map(member => member.id));
  202. // members can add other members to a team if the `Open Membership` setting is enabled
  203. // otherwise, `org:write` or `team:admin` permissions are required
  204. const hasOpenMembership = !!organization?.openMembership;
  205. const canAddMembers = hasOpenMembership || isTeamAdmin;
  206. const isDropdownDisabled = team.flags['idp:provisioned'];
  207. const items = (orgMembers || [])
  208. .filter(m => !existingMembers.has(m.id))
  209. .map(m => ({
  210. searchKey: `${m.name} ${m.email}`,
  211. value: m.id,
  212. label: (
  213. <StyledUserListElement>
  214. <StyledAvatar user={m} size={24} className="avatar" />
  215. <StyledNameOrEmail>{m.name || m.email}</StyledNameOrEmail>
  216. </StyledUserListElement>
  217. ),
  218. }));
  219. const menuHeader = (
  220. <StyledMembersLabel>
  221. {t('Members')}
  222. <StyledCreateMemberLink
  223. to=""
  224. onClick={() => openInviteMembersModal({source: 'teams'})}
  225. data-test-id="invite-member"
  226. >
  227. {t('Invite Member')}
  228. </StyledCreateMemberLink>
  229. </StyledMembersLabel>
  230. );
  231. return (
  232. <DropdownAutoComplete
  233. closeOnSelect={false}
  234. items={items}
  235. alignMenu="right"
  236. onSelect={
  237. canAddMembers
  238. ? this.addTeamMember
  239. : selection =>
  240. openTeamAccessRequestModal({
  241. teamId: params.teamId,
  242. orgId: organization.slug,
  243. memberId: selection.value,
  244. })
  245. }
  246. menuHeader={menuHeader}
  247. emptyMessage={t('No members')}
  248. onChange={this.handleMemberFilterChange}
  249. busy={this.state.dropdownBusy}
  250. onClose={() => this.debouncedFetchMembersRequest('')}
  251. disabled={isDropdownDisabled}
  252. data-test-id="add-member-menu"
  253. >
  254. {({isOpen}) => (
  255. <DropdownButton
  256. isOpen={isOpen}
  257. size="xs"
  258. data-test-id="add-member"
  259. disabled={isDropdownDisabled}
  260. >
  261. {t('Add Member')}
  262. </DropdownButton>
  263. )}
  264. </DropdownAutoComplete>
  265. );
  266. }
  267. renderPageTextBlock() {
  268. const {organization, team} = this.props;
  269. const {openMembership} = organization;
  270. const isIdpProvisioned = team.flags['idp:provisioned'];
  271. if (isIdpProvisioned) {
  272. return getButtonHelpText(isIdpProvisioned);
  273. }
  274. return openMembership
  275. ? t(
  276. '"Open Membership" is enabled for the organization. Anyone can add members for this team.'
  277. )
  278. : t(
  279. '"Open Membership" is disabled for the organization. Org Owner/Manager/Admin, or Team Admins can add members for this team.'
  280. );
  281. }
  282. renderMembers(isTeamAdmin: boolean) {
  283. const {config, organization, team} = this.props;
  284. const {teamMembers, loading} = this.state;
  285. if (loading) {
  286. return <LoadingIndicator />;
  287. }
  288. if (teamMembers.length) {
  289. return teamMembers.map(member => {
  290. return (
  291. <TeamMembersRow
  292. key={member.id}
  293. hasWriteAccess={isTeamAdmin}
  294. organization={organization}
  295. team={team}
  296. member={member}
  297. user={config.user}
  298. removeMember={this.removeTeamMember}
  299. updateMemberRole={this.updateTeamMemberRole}
  300. />
  301. );
  302. });
  303. }
  304. return (
  305. <EmptyMessage icon={<IconUser size="xl" />} size="large">
  306. {t('This team has no members')}
  307. </EmptyMessage>
  308. );
  309. }
  310. render() {
  311. if (this.state.error) {
  312. return <LoadingError onRetry={this.fetchData} />;
  313. }
  314. const {organization, team} = this.props;
  315. const {teamMembersPageLinks} = this.state;
  316. const {openMembership} = organization;
  317. const hasOrgWriteAccess = hasEveryAccess(['org:write'], {organization, team});
  318. const hasTeamAdminAccess = hasEveryAccess(['team:admin'], {organization, team});
  319. const isTeamAdmin = hasOrgWriteAccess || hasTeamAdminAccess;
  320. return (
  321. <Fragment>
  322. <TextBlock>{this.renderPageTextBlock()}</TextBlock>
  323. <PermissionAlert
  324. access={openMembership ? ['org:read'] : ['team:write']}
  325. team={team}
  326. />
  327. <Panel>
  328. <StyledPanelHeader hasButtons>
  329. <div>{t('Members')}</div>
  330. <div>
  331. <TeamRoleColumnLabel />
  332. </div>
  333. <div style={{textTransform: 'none'}}>{this.renderDropdown(isTeamAdmin)}</div>
  334. </StyledPanelHeader>
  335. {this.renderMembers(isTeamAdmin)}
  336. </Panel>
  337. <Pagination pageLinks={teamMembersPageLinks} />
  338. </Fragment>
  339. );
  340. }
  341. }
  342. const StyledUserListElement = styled('div')`
  343. display: grid;
  344. grid-template-columns: max-content 1fr;
  345. gap: ${space(0.5)};
  346. align-items: center;
  347. `;
  348. const StyledNameOrEmail = styled('div')`
  349. font-size: ${p => p.theme.fontSizeSmall};
  350. ${p => p.theme.overflowEllipsis};
  351. `;
  352. const StyledAvatar = styled(props => <UserAvatar {...props} />)`
  353. min-width: 1.75em;
  354. min-height: 1.75em;
  355. width: 1.5em;
  356. height: 1.5em;
  357. `;
  358. const StyledMembersLabel = styled('div')`
  359. display: grid;
  360. grid-template-columns: 1fr max-content;
  361. padding: ${space(1)} 0;
  362. font-size: ${p => p.theme.fontSizeExtraSmall};
  363. text-transform: uppercase;
  364. `;
  365. const StyledCreateMemberLink = styled(Link)`
  366. text-transform: none;
  367. `;
  368. const StyledPanelHeader = styled(PanelHeader)`
  369. ${GRID_TEMPLATE}
  370. `;
  371. export default withConfig(withApi(withOrganization(TeamMembers)));