teamMembers.tsx 12 KB

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