index.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. import * as React from 'react';
  2. import {css} from '@emotion/react';
  3. import styled from '@emotion/styled';
  4. import {ModalRenderProps} from 'app/actionCreators/modal';
  5. import AsyncComponent from 'app/components/asyncComponent';
  6. import Button from 'app/components/button';
  7. import HookOrDefault from 'app/components/hookOrDefault';
  8. import LoadingIndicator from 'app/components/loadingIndicator';
  9. import QuestionTooltip from 'app/components/questionTooltip';
  10. import {MEMBER_ROLES} from 'app/constants';
  11. import {IconAdd, IconCheckmark, IconWarning} from 'app/icons';
  12. import {t, tct, tn} from 'app/locale';
  13. import space from 'app/styles/space';
  14. import {Organization, Team} from 'app/types';
  15. import {trackAnalyticsEvent} from 'app/utils/analytics';
  16. import {uniqueId} from 'app/utils/guid';
  17. import withLatestContext from 'app/utils/withLatestContext';
  18. import withTeams from 'app/utils/withTeams';
  19. import InviteRowControl from './inviteRowControl';
  20. import {InviteRow, InviteStatus, NormalizedInvite} from './types';
  21. type Props = AsyncComponent['props'] &
  22. ModalRenderProps & {
  23. organization: Organization;
  24. teams: Team[];
  25. source?: string;
  26. initialData?: Partial<InviteRow>[];
  27. };
  28. type State = AsyncComponent['state'] & {
  29. pendingInvites: InviteRow[];
  30. sendingInvites: boolean;
  31. complete: boolean;
  32. inviteStatus: InviteStatus;
  33. };
  34. const DEFAULT_ROLE = 'member';
  35. const InviteModalHook = HookOrDefault({
  36. hookName: 'member-invite-modal:customization',
  37. defaultComponent: ({onSendInvites, children}) =>
  38. children({sendInvites: onSendInvites, canSend: true}),
  39. });
  40. type InviteModalRenderFunc = React.ComponentProps<typeof InviteModalHook>['children'];
  41. class InviteMembersModal extends AsyncComponent<Props, State> {
  42. get inviteTemplate(): InviteRow {
  43. return {
  44. emails: new Set(),
  45. teams: new Set(),
  46. role: DEFAULT_ROLE,
  47. };
  48. }
  49. /**
  50. * Used for analytics tracking of the modals usage.
  51. */
  52. sessionId = '';
  53. componentDidMount() {
  54. this.sessionId = uniqueId();
  55. const {organization, source} = this.props;
  56. trackAnalyticsEvent({
  57. eventKey: 'invite_modal.opened',
  58. eventName: 'Invite Modal: Opened',
  59. organization_id: organization.id,
  60. modal_session: this.sessionId,
  61. can_invite: this.willInvite,
  62. source,
  63. });
  64. }
  65. getEndpoints(): ReturnType<AsyncComponent['getEndpoints']> {
  66. const orgId = this.props.organization.slug;
  67. return [['member', `/organizations/${orgId}/members/me/`]];
  68. }
  69. getDefaultState() {
  70. const state = super.getDefaultState();
  71. const {initialData} = this.props;
  72. const pendingInvites = initialData
  73. ? initialData.map(initial => ({
  74. ...this.inviteTemplate,
  75. ...initial,
  76. }))
  77. : [this.inviteTemplate];
  78. return {
  79. ...state,
  80. pendingInvites,
  81. inviteStatus: {},
  82. complete: false,
  83. sendingInvites: false,
  84. };
  85. }
  86. reset = () => {
  87. this.setState({
  88. pendingInvites: [this.inviteTemplate],
  89. inviteStatus: {},
  90. complete: false,
  91. sendingInvites: false,
  92. });
  93. trackAnalyticsEvent({
  94. eventKey: 'invite_modal.add_more',
  95. eventName: 'Invite Modal: Add More',
  96. organization_id: this.props.organization.id,
  97. modal_session: this.sessionId,
  98. });
  99. };
  100. sendInvite = async (invite: NormalizedInvite) => {
  101. const {slug} = this.props.organization;
  102. const data = {
  103. email: invite.email,
  104. teams: [...invite.teams],
  105. role: invite.role,
  106. };
  107. this.setState(state => ({
  108. inviteStatus: {...state.inviteStatus, [invite.email]: {sent: false}},
  109. }));
  110. const endpoint = this.willInvite
  111. ? `/organizations/${slug}/members/`
  112. : `/organizations/${slug}/invite-requests/`;
  113. try {
  114. await this.api.requestPromise(endpoint, {method: 'POST', data});
  115. } catch (err) {
  116. const errorResponse = err.responseJSON;
  117. // Use the email error message if available. This inconsistently is
  118. // returned as either a list of errors for the field, or a single error.
  119. const emailError =
  120. !errorResponse || !errorResponse.email
  121. ? false
  122. : Array.isArray(errorResponse.email)
  123. ? errorResponse.email[0]
  124. : errorResponse.email;
  125. const error = emailError || t('Could not invite user');
  126. this.setState(state => ({
  127. inviteStatus: {...state.inviteStatus, [invite.email]: {sent: false, error}},
  128. }));
  129. return;
  130. }
  131. this.setState(state => ({
  132. inviteStatus: {...state.inviteStatus, [invite.email]: {sent: true}},
  133. }));
  134. };
  135. sendInvites = async () => {
  136. this.setState({sendingInvites: true});
  137. await Promise.all(this.invites.map(this.sendInvite));
  138. this.setState({sendingInvites: false, complete: true});
  139. trackAnalyticsEvent({
  140. eventKey: this.willInvite
  141. ? 'invite_modal.invites_sent'
  142. : 'invite_modal.requests_sent',
  143. eventName: this.willInvite
  144. ? 'Invite Modal: Invites Sent'
  145. : 'Invite Modal: Requests Sent',
  146. organization_id: this.props.organization.id,
  147. modal_session: this.sessionId,
  148. });
  149. };
  150. addInviteRow = () =>
  151. this.setState(state => ({
  152. pendingInvites: [...state.pendingInvites, this.inviteTemplate],
  153. }));
  154. setEmails(emails: string[], index: number) {
  155. this.setState(state => {
  156. const pendingInvites = [...state.pendingInvites];
  157. pendingInvites[index] = {...pendingInvites[index], emails: new Set(emails)};
  158. return {pendingInvites};
  159. });
  160. }
  161. setTeams(teams: string[], index: number) {
  162. this.setState(state => {
  163. const pendingInvites = [...state.pendingInvites];
  164. pendingInvites[index] = {...pendingInvites[index], teams: new Set(teams)};
  165. return {pendingInvites};
  166. });
  167. }
  168. setRole(role: string, index: number) {
  169. this.setState(state => {
  170. const pendingInvites = [...state.pendingInvites];
  171. pendingInvites[index] = {...pendingInvites[index], role};
  172. return {pendingInvites};
  173. });
  174. }
  175. removeInviteRow(index: number) {
  176. this.setState(state => {
  177. const pendingInvites = [...state.pendingInvites];
  178. pendingInvites.splice(index, 1);
  179. return {pendingInvites};
  180. });
  181. }
  182. get invites(): NormalizedInvite[] {
  183. return this.state.pendingInvites.reduce<NormalizedInvite[]>(
  184. (acc, row) => [
  185. ...acc,
  186. ...[...row.emails].map(email => ({email, teams: row.teams, role: row.role})),
  187. ],
  188. []
  189. );
  190. }
  191. get hasDuplicateEmails() {
  192. const emails = this.invites.map(inv => inv.email);
  193. return emails.length !== new Set(emails).size;
  194. }
  195. get isValidInvites() {
  196. return this.invites.length > 0 && !this.hasDuplicateEmails;
  197. }
  198. get statusMessage() {
  199. const {sendingInvites, complete, inviteStatus} = this.state;
  200. if (sendingInvites) {
  201. return (
  202. <StatusMessage>
  203. <LoadingIndicator mini relative hideMessage size={16} />
  204. {this.willInvite
  205. ? t('Sending organization invitations...')
  206. : t('Sending invite requests...')}
  207. </StatusMessage>
  208. );
  209. }
  210. if (complete) {
  211. const statuses = Object.values(inviteStatus);
  212. const sentCount = statuses.filter(i => i.sent).length;
  213. const errorCount = statuses.filter(i => i.error).length;
  214. const invites = <strong>{tn('%s invite', '%s invites', sentCount)}</strong>;
  215. const tctComponents = {
  216. invites,
  217. failed: errorCount,
  218. };
  219. return (
  220. <StatusMessage status="success">
  221. <IconCheckmark size="sm" />
  222. {errorCount > 0
  223. ? tct('Sent [invites], [failed] failed to send.', tctComponents)
  224. : tct('Sent [invites]', tctComponents)}
  225. </StatusMessage>
  226. );
  227. }
  228. if (this.hasDuplicateEmails) {
  229. return (
  230. <StatusMessage status="error">
  231. <IconWarning size="sm" />
  232. {t('Duplicate emails between invite rows.')}
  233. </StatusMessage>
  234. );
  235. }
  236. return null;
  237. }
  238. get willInvite() {
  239. return this.props.organization.access?.includes('member:write');
  240. }
  241. get inviteButtonLabel() {
  242. if (this.invites.length > 0) {
  243. const numberInvites = this.invites.length;
  244. // Note we use `t()` here because `tn()` expects the same # of string formatters
  245. const inviteText =
  246. numberInvites === 1 ? t('Send invite') : t('Send invites (%s)', numberInvites);
  247. const requestText =
  248. numberInvites === 1
  249. ? t('Send invite request')
  250. : t('Send invite requests (%s)', numberInvites);
  251. return this.willInvite ? inviteText : requestText;
  252. }
  253. return this.willInvite ? t('Send invite') : t('Send invite request');
  254. }
  255. render() {
  256. const {Footer, closeModal, organization, teams: allTeams} = this.props;
  257. const {pendingInvites, sendingInvites, complete, inviteStatus, member} = this.state;
  258. const disableInputs = sendingInvites || complete;
  259. // eslint-disable-next-line react/prop-types
  260. const hookRenderer: InviteModalRenderFunc = ({sendInvites, canSend, headerInfo}) => (
  261. <React.Fragment>
  262. <Heading>
  263. {t('Invite New Members')}
  264. {!this.willInvite && (
  265. <QuestionTooltip
  266. title={t(
  267. `You do not have permission to directly invite members. Email
  268. addresses entered here will be forwarded to organization
  269. managers and owners; they will be prompted to approve the
  270. invitation.`
  271. )}
  272. size="sm"
  273. position="bottom"
  274. />
  275. )}
  276. </Heading>
  277. <Subtext>
  278. {this.willInvite
  279. ? t('Invite new members by email to join your organization.')
  280. : t(
  281. `You don’t have permission to directly invite users, but we’ll
  282. send a request on your behalf.`
  283. )}
  284. </Subtext>
  285. {headerInfo}
  286. <InviteeHeadings>
  287. <div>{t('Email addresses')}</div>
  288. <div>{t('Role')}</div>
  289. <div>{t('Add to team')}</div>
  290. </InviteeHeadings>
  291. {pendingInvites.map(({emails, role, teams}, i) => (
  292. <StyledInviteRow
  293. key={i}
  294. disabled={disableInputs}
  295. emails={[...emails]}
  296. role={role}
  297. teams={[...teams]}
  298. roleOptions={member ? member.roles : MEMBER_ROLES}
  299. roleDisabledUnallowed={this.willInvite}
  300. teamOptions={allTeams}
  301. inviteStatus={inviteStatus}
  302. onRemove={() => this.removeInviteRow(i)}
  303. onChangeEmails={opts => this.setEmails(opts?.map(v => v.value) ?? [], i)}
  304. onChangeRole={value => this.setRole(value?.value, i)}
  305. onChangeTeams={opts => this.setTeams(opts ? opts.map(v => v.value) : [], i)}
  306. disableRemove={disableInputs || pendingInvites.length === 1}
  307. />
  308. ))}
  309. <AddButton
  310. disabled={disableInputs}
  311. priority="link"
  312. onClick={this.addInviteRow}
  313. icon={<IconAdd size="xs" isCircled />}
  314. >
  315. {t('Add another')}
  316. </AddButton>
  317. <Footer>
  318. <FooterContent>
  319. <div>{this.statusMessage}</div>
  320. {complete ? (
  321. <React.Fragment>
  322. <Button data-test-id="send-more" size="small" onClick={this.reset}>
  323. {t('Send more invites')}
  324. </Button>
  325. <Button
  326. data-test-id="close"
  327. priority="primary"
  328. size="small"
  329. onClick={() => {
  330. trackAnalyticsEvent({
  331. eventKey: 'invite_modal.closed',
  332. eventName: 'Invite Modal: Closed',
  333. organization_id: this.props.organization.id,
  334. modal_session: this.sessionId,
  335. });
  336. closeModal();
  337. }}
  338. >
  339. {t('Close')}
  340. </Button>
  341. </React.Fragment>
  342. ) : (
  343. <React.Fragment>
  344. <Button
  345. data-test-id="cancel"
  346. size="small"
  347. onClick={closeModal}
  348. disabled={disableInputs}
  349. >
  350. {t('Cancel')}
  351. </Button>
  352. <Button
  353. size="small"
  354. data-test-id="send-invites"
  355. priority="primary"
  356. disabled={!canSend || !this.isValidInvites || disableInputs}
  357. onClick={sendInvites}
  358. >
  359. {this.inviteButtonLabel}
  360. </Button>
  361. </React.Fragment>
  362. )}
  363. </FooterContent>
  364. </Footer>
  365. </React.Fragment>
  366. );
  367. return (
  368. <InviteModalHook
  369. organization={organization}
  370. willInvite={this.willInvite}
  371. onSendInvites={this.sendInvites}
  372. >
  373. {hookRenderer}
  374. </InviteModalHook>
  375. );
  376. }
  377. }
  378. const Heading = styled('h1')`
  379. display: inline-grid;
  380. grid-gap: ${space(1.5)};
  381. grid-auto-flow: column;
  382. align-items: center;
  383. font-weight: 400;
  384. font-size: ${p => p.theme.headerFontSize};
  385. margin-top: 0;
  386. margin-bottom: ${space(0.75)};
  387. `;
  388. const Subtext = styled('p')`
  389. color: ${p => p.theme.subText};
  390. margin-bottom: ${space(3)};
  391. `;
  392. const inviteRowGrid = css`
  393. display: grid;
  394. grid-gap: ${space(1.5)};
  395. grid-template-columns: 3fr 180px 2fr max-content;
  396. `;
  397. const InviteeHeadings = styled('div')`
  398. ${inviteRowGrid};
  399. margin-bottom: ${space(1)};
  400. font-weight: 600;
  401. text-transform: uppercase;
  402. font-size: ${p => p.theme.fontSizeSmall};
  403. `;
  404. const StyledInviteRow = styled(InviteRowControl)`
  405. ${inviteRowGrid};
  406. margin-bottom: ${space(1.5)};
  407. `;
  408. const AddButton = styled(Button)`
  409. margin-top: ${space(3)};
  410. `;
  411. const FooterContent = styled('div')`
  412. width: 100%;
  413. display: grid;
  414. grid-template-columns: 1fr max-content max-content;
  415. grid-gap: ${space(1)};
  416. `;
  417. const StatusMessage = styled('div')<{status?: 'success' | 'error'}>`
  418. display: grid;
  419. grid-template-columns: max-content max-content;
  420. grid-gap: ${space(1)};
  421. align-items: center;
  422. font-size: ${p => p.theme.fontSizeMedium};
  423. color: ${p => (p.status === 'error' ? p.theme.red300 : p.theme.gray400)};
  424. > :first-child {
  425. ${p => p.status === 'success' && `color: ${p.theme.green300}`};
  426. }
  427. `;
  428. export const modalCss = css`
  429. width: 100%;
  430. max-width: 800px;
  431. margin: 50px auto;
  432. `;
  433. export default withLatestContext(withTeams(InviteMembersModal));