index.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  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 send a request to your organization owner and manager for review.`
  282. )}
  283. </Subtext>
  284. {headerInfo}
  285. <InviteeHeadings>
  286. <div>{t('Email addresses')}</div>
  287. <div>{t('Role')}</div>
  288. <div>{t('Add to team')}</div>
  289. </InviteeHeadings>
  290. {pendingInvites.map(({emails, role, teams}, i) => (
  291. <StyledInviteRow
  292. key={i}
  293. disabled={disableInputs}
  294. emails={[...emails]}
  295. role={role}
  296. teams={[...teams]}
  297. roleOptions={member ? member.roles : MEMBER_ROLES}
  298. roleDisabledUnallowed={this.willInvite}
  299. teamOptions={allTeams}
  300. inviteStatus={inviteStatus}
  301. onRemove={() => this.removeInviteRow(i)}
  302. onChangeEmails={opts => this.setEmails(opts?.map(v => v.value) ?? [], i)}
  303. onChangeRole={value => this.setRole(value?.value, i)}
  304. onChangeTeams={opts => this.setTeams(opts ? opts.map(v => v.value) : [], i)}
  305. disableRemove={disableInputs || pendingInvites.length === 1}
  306. />
  307. ))}
  308. <AddButton
  309. disabled={disableInputs}
  310. priority="link"
  311. onClick={this.addInviteRow}
  312. icon={<IconAdd size="xs" isCircled />}
  313. >
  314. {t('Add another')}
  315. </AddButton>
  316. <Footer>
  317. <FooterContent>
  318. <div>{this.statusMessage}</div>
  319. {complete ? (
  320. <React.Fragment>
  321. <Button data-test-id="send-more" size="small" onClick={this.reset}>
  322. {t('Send more invites')}
  323. </Button>
  324. <Button
  325. data-test-id="close"
  326. priority="primary"
  327. size="small"
  328. onClick={() => {
  329. trackAnalyticsEvent({
  330. eventKey: 'invite_modal.closed',
  331. eventName: 'Invite Modal: Closed',
  332. organization_id: this.props.organization.id,
  333. modal_session: this.sessionId,
  334. });
  335. closeModal();
  336. }}
  337. >
  338. {t('Close')}
  339. </Button>
  340. </React.Fragment>
  341. ) : (
  342. <React.Fragment>
  343. <Button
  344. data-test-id="cancel"
  345. size="small"
  346. onClick={closeModal}
  347. disabled={disableInputs}
  348. >
  349. {t('Cancel')}
  350. </Button>
  351. <Button
  352. size="small"
  353. data-test-id="send-invites"
  354. priority="primary"
  355. disabled={!canSend || !this.isValidInvites || disableInputs}
  356. onClick={sendInvites}
  357. >
  358. {this.inviteButtonLabel}
  359. </Button>
  360. </React.Fragment>
  361. )}
  362. </FooterContent>
  363. </Footer>
  364. </React.Fragment>
  365. );
  366. return (
  367. <InviteModalHook
  368. organization={organization}
  369. willInvite={this.willInvite}
  370. onSendInvites={this.sendInvites}
  371. >
  372. {hookRenderer}
  373. </InviteModalHook>
  374. );
  375. }
  376. }
  377. const Heading = styled('h1')`
  378. display: inline-grid;
  379. grid-gap: ${space(1.5)};
  380. grid-auto-flow: column;
  381. align-items: center;
  382. font-weight: 400;
  383. font-size: ${p => p.theme.headerFontSize};
  384. margin-top: 0;
  385. margin-bottom: ${space(0.75)};
  386. `;
  387. const Subtext = styled('p')`
  388. color: ${p => p.theme.subText};
  389. margin-bottom: ${space(3)};
  390. `;
  391. const inviteRowGrid = css`
  392. display: grid;
  393. grid-gap: ${space(1.5)};
  394. grid-template-columns: 3fr 180px 2fr max-content;
  395. `;
  396. const InviteeHeadings = styled('div')`
  397. ${inviteRowGrid};
  398. margin-bottom: ${space(1)};
  399. font-weight: 600;
  400. text-transform: uppercase;
  401. font-size: ${p => p.theme.fontSizeSmall};
  402. `;
  403. const StyledInviteRow = styled(InviteRowControl)`
  404. ${inviteRowGrid};
  405. margin-bottom: ${space(1.5)};
  406. `;
  407. const AddButton = styled(Button)`
  408. margin-top: ${space(3)};
  409. `;
  410. const FooterContent = styled('div')`
  411. width: 100%;
  412. display: grid;
  413. grid-template-columns: 1fr max-content max-content;
  414. grid-gap: ${space(1)};
  415. `;
  416. const StatusMessage = styled('div')<{status?: 'success' | 'error'}>`
  417. display: grid;
  418. grid-template-columns: max-content max-content;
  419. grid-gap: ${space(1)};
  420. align-items: center;
  421. font-size: ${p => p.theme.fontSizeMedium};
  422. color: ${p => (p.status === 'error' ? p.theme.red300 : p.theme.gray400)};
  423. > :first-child {
  424. ${p => p.status === 'success' && `color: ${p.theme.green300}`};
  425. }
  426. `;
  427. export const modalCss = css`
  428. width: 100%;
  429. max-width: 800px;
  430. margin: 50px auto;
  431. `;
  432. export default withLatestContext(withTeams(InviteMembersModal));