teamMembers.tsx 12 KB

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