Compare commits
54 Commits
open-relea
...
open-relea
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a6e84bf56c | ||
|
|
9cf76fec74 | ||
|
|
0e22884a34 | ||
|
|
1c0f1d6db9 | ||
|
|
c5a2070b6e | ||
|
|
6ac242aa0a | ||
|
|
0130b5279f | ||
|
|
d40450dabf | ||
|
|
61245d4423 | ||
|
|
aec96cd652 | ||
|
|
2c146b516f | ||
|
|
70d5c0e112 | ||
|
|
15325f0eb1 | ||
|
|
25bb72b53b | ||
|
|
0ef0cee7dc | ||
|
|
8e2cdb1b25 | ||
|
|
f8212c24c3 | ||
|
|
fcad43c485 | ||
|
|
bc64c9e278 | ||
|
|
64d532aad5 | ||
|
|
d05ed5ba26 | ||
|
|
44e122142c | ||
|
|
937f7a17c6 | ||
|
|
905dd98d28 | ||
|
|
2927f938eb | ||
|
|
156dd0e47b | ||
|
|
dcf69d693f | ||
|
|
c905ede6fe | ||
|
|
eea663675b | ||
|
|
9c6644c1b9 | ||
|
|
8205ff64f8 | ||
|
|
c0f41874bb | ||
|
|
339f9b303f | ||
|
|
aec97816fb | ||
|
|
b62a92c4d2 | ||
|
|
c950864afa | ||
|
|
31669aa1f2 | ||
|
|
deae6c9654 | ||
|
|
1ede234b31 | ||
|
|
3deaeece2c | ||
|
|
b7275c1491 | ||
|
|
f6058c9bbe | ||
|
|
5a20359856 | ||
|
|
99b9a51598 | ||
|
|
5d88b19c07 | ||
|
|
9e29c54ac6 | ||
|
|
298f573113 | ||
|
|
6dd09451a3 | ||
|
|
ffa0361c22 | ||
|
|
e09bb55544 | ||
|
|
5ce9ab00c8 | ||
|
|
200f19dd9a | ||
|
|
a37d63a4a3 | ||
|
|
d67348929d |
1
.env
1
.env
@@ -18,3 +18,4 @@ REFRESH_ACCESS_TOKEN_ENDPOINT=''
|
||||
SEGMENT_KEY=''
|
||||
SITE_NAME=''
|
||||
USER_INFO_COOKIE_NAME=''
|
||||
SCHEDULE_EMAIL_SECTION=''
|
||||
|
||||
@@ -19,3 +19,4 @@ REFRESH_ACCESS_TOKEN_ENDPOINT='http://localhost:18000/login_refresh'
|
||||
SEGMENT_KEY=''
|
||||
SITE_NAME=localhost
|
||||
USER_INFO_COOKIE_NAME='edx-user-info'
|
||||
SCHEDULE_EMAIL_SECTION='true'
|
||||
|
||||
@@ -17,3 +17,4 @@ REFRESH_ACCESS_TOKEN_ENDPOINT='http://localhost:18000/login_refresh'
|
||||
SEGMENT_KEY=''
|
||||
SITE_NAME=localhost
|
||||
USER_INFO_COOKIE_NAME='edx-user-info'
|
||||
SCHEDULE_EMAIL_SECTION='true'
|
||||
|
||||
2
.github/workflows/ci.yml
vendored
2
.github/workflows/ci.yml
vendored
@@ -11,7 +11,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
node: [12, 14, 16]
|
||||
node: [16]
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v2
|
||||
|
||||
2
.github/workflows/commitlint.yml
vendored
2
.github/workflows/commitlint.yml
vendored
@@ -7,4 +7,4 @@ on:
|
||||
|
||||
jobs:
|
||||
commitlint:
|
||||
uses: edx/.github/.github/workflows/commitlint.yml@master
|
||||
uses: openedx/.github/.github/workflows/commitlint.yml@master
|
||||
|
||||
13
.github/workflows/lockfileversion-check.yml
vendored
Normal file
13
.github/workflows/lockfileversion-check.yml
vendored
Normal file
@@ -0,0 +1,13 @@
|
||||
#check package-lock file version
|
||||
|
||||
name: Lockfile Version check
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
version-check:
|
||||
uses: openedx/.github/.github/workflows/lockfileversion-check.yml@master
|
||||
2
Makefile
2
Makefile
@@ -46,7 +46,7 @@ push_translations:
|
||||
|
||||
# Pulls translations from Transifex.
|
||||
pull_translations:
|
||||
tx pull -f --mode reviewed --language=$(transifex_langs)
|
||||
tx pull -f --mode reviewed --languages=$(transifex_langs)
|
||||
|
||||
# This target is used by Travis.
|
||||
validate-no-uncommitted-package-lock-changes:
|
||||
|
||||
24695
package-lock.json
generated
24695
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
47
package.json
47
package.json
@@ -18,7 +18,7 @@
|
||||
"lint:fix": "fedx-scripts eslint --fix --ext .js --ext .jsx .",
|
||||
"snapshot": "fedx-scripts jest --updateSnapshot",
|
||||
"start": "fedx-scripts webpack-dev-server --progress",
|
||||
"test": "fedx-scripts jest --coverage --passWithNoTests"
|
||||
"test": "TZ=UTC fedx-scripts jest --coverage --passWithNoTests"
|
||||
},
|
||||
"husky": {
|
||||
"hooks": {
|
||||
@@ -36,41 +36,44 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@edx/brand": "npm:@edx/brand-openedx@1.1.0",
|
||||
"@edx/frontend-component-footer": "10.1.6",
|
||||
"@edx/frontend-component-header": "^2.4.2",
|
||||
"@edx/frontend-platform": "1.12.7",
|
||||
"@edx/paragon": "16.3.2",
|
||||
"@edx/tinymce-language-selector": "^1.1.0",
|
||||
"@edx/frontend-component-footer": "11.2.1",
|
||||
"@edx/frontend-component-header": "3.2.1",
|
||||
"@edx/frontend-platform": "2.6.2",
|
||||
"@edx/paragon": "19.25.3",
|
||||
"@edx/tinymce-language-selector": "1.1.0",
|
||||
"@fortawesome/fontawesome-svg-core": "1.2.36",
|
||||
"@fortawesome/free-brands-svg-icons": "5.15.4",
|
||||
"@fortawesome/free-regular-svg-icons": "5.15.4",
|
||||
"@fortawesome/free-solid-svg-icons": "5.15.4",
|
||||
"@fortawesome/react-fontawesome": "0.1.16",
|
||||
"@tinymce/tinymce-react": "^3.13.0",
|
||||
"classnames": "^2.3.1",
|
||||
"core-js": "3.15.2",
|
||||
"prop-types": "15.7.2",
|
||||
"@fortawesome/react-fontawesome": "0.2.0",
|
||||
"@tinymce/tinymce-react": "3.14.0",
|
||||
"axios": "0.27.2",
|
||||
"classnames": "2.3.2",
|
||||
"core-js": "3.25.5",
|
||||
"jquery": "3.6.1",
|
||||
"popper.js": "1.16.1",
|
||||
"prop-types": "15.8.1",
|
||||
"react": "16.14.0",
|
||||
"react-dom": "16.14.0",
|
||||
"react-redux": "7.2.6",
|
||||
"react-redux": "7.2.9",
|
||||
"react-router": "5.2.1",
|
||||
"react-router-dom": "5.3.0",
|
||||
"redux": "4.1.2",
|
||||
"regenerator-runtime": "0.13.9",
|
||||
"tinymce": "^5.10.2"
|
||||
"tinymce": "5.10.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@edx/frontend-build": "8.1.6",
|
||||
"axios-mock-adapter": "^1.20.0",
|
||||
"@edx/frontend-build": "9.2.2",
|
||||
"@testing-library/jest-dom": "5.16.5",
|
||||
"@testing-library/react": "12.1.5",
|
||||
"axios-mock-adapter": "1.21.2",
|
||||
"codecov": "3.8.3",
|
||||
"es-check": "6.1.1",
|
||||
"glob": "7.2.0",
|
||||
"es-check": "6.2.1",
|
||||
"glob": "7.2.3",
|
||||
"husky": "7.0.4",
|
||||
"jest": "27.3.1",
|
||||
"prettier": "^2.5.1",
|
||||
"jest": "27.5.1",
|
||||
"prettier": "2.7.1",
|
||||
"reactifex": "1.1.1",
|
||||
"rosie": "^2.1.0",
|
||||
"@testing-library/jest-dom": "^5.16.1",
|
||||
"@testing-library/react": "^12.1.2"
|
||||
"rosie": "2.1.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,41 +1,46 @@
|
||||
import React, { useRef } from 'react';
|
||||
import classnames from 'classnames';
|
||||
import React from 'react';
|
||||
|
||||
import { useParams } from 'react-router-dom';
|
||||
|
||||
import { ErrorPage } from '@edx/frontend-platform/react';
|
||||
import { Container } from '@edx/paragon';
|
||||
import { FormattedMessage } from '@edx/frontend-platform/i18n';
|
||||
import BulkEmailTaskManager from './bulk-email-task-manager/BulkEmailTaskManager';
|
||||
import NavigationTabs from '../navigation-tabs/NavigationTabs';
|
||||
import useMobileResponsive from '../../utils/useMobileResponsive';
|
||||
import BulkEmailForm from './bulk-email-form';
|
||||
import { CourseMetadataContext } from '../page-container/PageContainer';
|
||||
import { BulkEmailProvider } from './bulk-email-context';
|
||||
import BackToInstructor from '../navigation-tabs/BackToInstructor';
|
||||
|
||||
export default function BulkEmailTool() {
|
||||
const { courseId } = useParams();
|
||||
|
||||
const isMobile = useMobileResponsive();
|
||||
const textEditorRef = useRef();
|
||||
|
||||
const copyTextToEditor = (body) => {
|
||||
if (textEditorRef?.current) {
|
||||
textEditorRef.current.setContent(body);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<CourseMetadataContext.Consumer>
|
||||
{(courseMetadata) => (courseMetadata.isStaff ? (
|
||||
<div>
|
||||
{(courseMetadata) => (courseMetadata.originalUserIsStaff ? (
|
||||
<>
|
||||
<NavigationTabs courseId={courseId} tabData={courseMetadata.tabs} />
|
||||
<div className={classnames({ 'border border-primary-200': !isMobile })}>
|
||||
<div className="row">
|
||||
<BulkEmailForm courseId={courseId} cohorts={courseMetadata.cohorts} editorRef={textEditorRef} />
|
||||
</div>
|
||||
<div className="row">
|
||||
<BulkEmailTaskManager courseId={courseId} copyTextToEditor={copyTextToEditor} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<BulkEmailProvider>
|
||||
<Container size="md">
|
||||
<BackToInstructor />
|
||||
<div className="row pb-4.5">
|
||||
<h1 className="text-primary-500" id="main-content">
|
||||
<FormattedMessage
|
||||
id="bulk.email.send.email.header"
|
||||
defaultMessage="Send an email"
|
||||
description="A label for email form"
|
||||
/>
|
||||
</h1>
|
||||
</div>
|
||||
<div className="row">
|
||||
<BulkEmailForm courseId={courseId} cohorts={courseMetadata.cohorts} />
|
||||
</div>
|
||||
<div className="row py-5">
|
||||
<BulkEmailTaskManager courseId={courseId} />
|
||||
</div>
|
||||
</Container>
|
||||
</BulkEmailProvider>
|
||||
</>
|
||||
) : (
|
||||
<ErrorPage />
|
||||
))}
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import React from 'react';
|
||||
import PropTypes from 'prop-types';
|
||||
import useAsyncReducer, { combineReducers } from '../../../utils/useAsyncReducer';
|
||||
import editor, { editorInitialState } from '../bulk-email-form/data/reducer';
|
||||
import scheduledEmailsTable, {
|
||||
scheduledEmailsTableInitialState,
|
||||
} from '../bulk-email-task-manager/bulk-email-scheduled-emails-table/data/reducer';
|
||||
|
||||
export const BulkEmailContext = React.createContext();
|
||||
|
||||
export default function BulkEmailProvider({ children }) {
|
||||
const initialState = {
|
||||
editor: editorInitialState,
|
||||
scheduledEmailsTable: scheduledEmailsTableInitialState,
|
||||
};
|
||||
const [state, dispatch] = useAsyncReducer(
|
||||
combineReducers({ editor, scheduledEmailsTable }),
|
||||
initialState,
|
||||
);
|
||||
return <BulkEmailContext.Provider value={[state, dispatch]}>{children}</BulkEmailContext.Provider>;
|
||||
}
|
||||
|
||||
BulkEmailProvider.propTypes = {
|
||||
children: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.node), PropTypes.node]).isRequired,
|
||||
};
|
||||
@@ -0,0 +1 @@
|
||||
export { default as BulkEmailProvider, BulkEmailContext } from './BulkEmailProvider';
|
||||
@@ -1,112 +1,262 @@
|
||||
import React, { useState } from 'react';
|
||||
import React, { useContext, useEffect, useState } from 'react';
|
||||
import PropTypes from 'prop-types';
|
||||
import {
|
||||
Form, Icon, StatefulButton, useCheckboxSetValues, useToggle,
|
||||
Button,
|
||||
Form, Icon, StatefulButton, Toast, useToggle,
|
||||
} from '@edx/paragon';
|
||||
import { SpinnerSimple, CheckCircle, Cancel } from '@edx/paragon/icons';
|
||||
import { FormattedMessage } from '@edx/frontend-platform/i18n';
|
||||
import {
|
||||
SpinnerSimple, Cancel, Send, Event, Check,
|
||||
} from '@edx/paragon/icons';
|
||||
import { injectIntl, intlShape } from '@edx/frontend-platform/i18n';
|
||||
import classNames from 'classnames';
|
||||
import { getConfig } from '@edx/frontend-platform';
|
||||
import TextEditor from '../text-editor/TextEditor';
|
||||
import { postBulkEmail } from './api';
|
||||
import BulkEmailRecipient from './bulk-email-recipient';
|
||||
import TaskAlertModal from './TaskAlertModal';
|
||||
import TaskAlertModal from '../task-alert-modal';
|
||||
import useTimeout from '../../../utils/useTimeout';
|
||||
import useMobileResponsive from '../../../utils/useMobileResponsive';
|
||||
import ScheduleEmailForm from './ScheduleEmailForm';
|
||||
import messages from './messages';
|
||||
import { BulkEmailContext } from '../bulk-email-context';
|
||||
import {
|
||||
addRecipient,
|
||||
clearEditor,
|
||||
clearErrorState,
|
||||
handleEditorChange,
|
||||
removeRecipient,
|
||||
} from './data/actions';
|
||||
import { editScheduledEmailThunk, postBulkEmailThunk } from './data/thunks';
|
||||
import { getScheduledBulkEmailThunk } from '../bulk-email-task-manager/bulk-email-scheduled-emails-table/data/thunks';
|
||||
|
||||
import './bulkEmailForm.scss';
|
||||
|
||||
export const FORM_SUBMIT_STATES = {
|
||||
DEFAULT: 'default',
|
||||
PENDING: 'pending',
|
||||
COMPLETE: 'complete',
|
||||
COMPLETED_DEFAULT: 'completed_default',
|
||||
COMPLETE_SCHEDULE: 'completed_schedule',
|
||||
SCHEDULE: 'schedule',
|
||||
RESCHEDULE: 'reschedule',
|
||||
ERROR: 'error',
|
||||
};
|
||||
|
||||
export default function BulkEmailForm(props) {
|
||||
const { courseId, cohorts, editorRef } = props;
|
||||
const [subject, setSubject] = useState('');
|
||||
const FORM_ACTIONS = {
|
||||
POST: 'POST',
|
||||
PATCH: 'PATCH',
|
||||
};
|
||||
|
||||
function BulkEmailForm(props) {
|
||||
const { courseId, cohorts, intl } = props;
|
||||
const [{ editor }, dispatch] = useContext(BulkEmailContext);
|
||||
const [emailFormStatus, setEmailFormStatus] = useState(FORM_SUBMIT_STATES.DEFAULT);
|
||||
const [emailFormValidation, setEmailFormValidation] = useState({
|
||||
// set these as true on initialization, to prevent invalid messages from prematurely showing
|
||||
subject: true,
|
||||
body: true,
|
||||
recipients: true,
|
||||
schedule: true,
|
||||
});
|
||||
const [selectedRecipients, { add, remove }] = useCheckboxSetValues([]);
|
||||
const [isTaskAlertOpen, openTaskAlert, closeTaskAlert] = useToggle(false);
|
||||
const resetEmailForm = useTimeout(() => {
|
||||
setEmailFormStatus(FORM_SUBMIT_STATES.COMPLETED_DEFAULT);
|
||||
}, 3000);
|
||||
const [isScheduled, toggleScheduled] = useState(false);
|
||||
const isMobile = useMobileResponsive();
|
||||
|
||||
/**
|
||||
* Since we are working with both an old and new API endpoint, the body for the POST
|
||||
* and the PATCH have different signatures. Therefore, based on the action required, we need to
|
||||
* format the data properly to be accepted on the back end.
|
||||
* @param {*} action "POST" or "PATCH" of the FORM_ACTIONS constant
|
||||
* @returns formatted Data
|
||||
*/
|
||||
const formatDataForFormAction = (action) => {
|
||||
if (action === FORM_ACTIONS.POST) {
|
||||
const emailData = new FormData();
|
||||
emailData.append('action', 'send');
|
||||
emailData.append('send_to', JSON.stringify(editor.emailRecipients));
|
||||
emailData.append('subject', editor.emailSubject);
|
||||
emailData.append('message', editor.emailBody);
|
||||
if (isScheduled) {
|
||||
emailData.append('schedule', new Date(`${editor.scheduleDate} ${editor.scheduleTime}`).toISOString());
|
||||
}
|
||||
return emailData;
|
||||
}
|
||||
if (action === FORM_ACTIONS.PATCH) {
|
||||
return {
|
||||
email: {
|
||||
targets: editor.emailRecipients,
|
||||
subject: editor.emailSubject,
|
||||
message: editor.emailBody,
|
||||
id: editor.emailId,
|
||||
},
|
||||
schedule: isScheduled ? new Date(`${editor.scheduleDate} ${editor.scheduleTime}`).toISOString() : null,
|
||||
};
|
||||
}
|
||||
return {};
|
||||
};
|
||||
|
||||
/**
|
||||
* This function resets the form based on what state the form is currently in. Used after
|
||||
* successfully sending or scheduling and email, or on error.
|
||||
*
|
||||
* @param {Boolean} error If true, resets just the state of the form, and not the editor.
|
||||
* if false, reset the form completely, and wipe all email data form the form.
|
||||
*/
|
||||
const resetEmailForm = (error) => {
|
||||
if (error) {
|
||||
dispatch(clearErrorState());
|
||||
} else {
|
||||
dispatch(clearEditor());
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Allows for a delayed form reset, to give the user time to process completion and error
|
||||
* states before reseting the form.
|
||||
*/
|
||||
const delayedEmailFormReset = useTimeout(
|
||||
() => resetEmailForm(editor.errorRetrievingData),
|
||||
3000,
|
||||
);
|
||||
|
||||
const onFormChange = (event) => dispatch(handleEditorChange(event.target.name, event.target.value));
|
||||
|
||||
const onRecipientChange = (event) => {
|
||||
if (event.target.checked) {
|
||||
add(event.target.value);
|
||||
dispatch(addRecipient(event.target.value));
|
||||
// if "All Learners" is checked then we want to remove any cohorts, verified learners, and audit learners
|
||||
if (event.target.value === 'learners') {
|
||||
editor.emailRecipients.forEach(recipient => {
|
||||
if (/^cohort/.test(recipient) || /^track/.test(recipient)) {
|
||||
dispatch(removeRecipient(recipient));
|
||||
}
|
||||
});
|
||||
}
|
||||
} else {
|
||||
remove(event.target.value);
|
||||
dispatch(removeRecipient(event.target.value));
|
||||
}
|
||||
};
|
||||
const onInit = (event, editor) => {
|
||||
editorRef.current = editor;
|
||||
|
||||
const validateDateTime = (date, time) => {
|
||||
if (isScheduled) {
|
||||
const now = new Date();
|
||||
const newSchedule = new Date(`${editor.scheduleDate} ${editor.scheduleTime}`);
|
||||
return !!date && !!time && newSchedule > now;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
const onSubjectChange = (event) => setSubject(event.target.value);
|
||||
|
||||
const validateEmailForm = () => {
|
||||
const subjectValid = subject.length !== 0;
|
||||
const bodyValid = editorRef.current.getContent().length !== 0;
|
||||
const recipientsValid = selectedRecipients.length !== 0;
|
||||
|
||||
const subjectValid = editor.emailSubject.length !== 0;
|
||||
const bodyValid = editor.emailBody.length !== 0;
|
||||
const recipientsValid = editor.emailRecipients.length !== 0;
|
||||
const scheduleValid = validateDateTime(editor.scheduleDate, editor.scheduleTime);
|
||||
setEmailFormValidation({
|
||||
subject: subjectValid,
|
||||
recipients: recipientsValid,
|
||||
body: bodyValid,
|
||||
schedule: scheduleValid,
|
||||
});
|
||||
|
||||
return subjectValid && bodyValid && recipientsValid;
|
||||
return subjectValid && bodyValid && recipientsValid && scheduleValid;
|
||||
};
|
||||
|
||||
const createEmailTask = async () => {
|
||||
const emailData = new FormData();
|
||||
if (validateEmailForm()) {
|
||||
setEmailFormStatus(() => FORM_SUBMIT_STATES.PENDING);
|
||||
emailData.append('action', 'send');
|
||||
emailData.append('send_to', JSON.stringify(selectedRecipients));
|
||||
emailData.append('subject', subject);
|
||||
emailData.append('message', editorRef.current.getContent());
|
||||
let data;
|
||||
try {
|
||||
data = await postBulkEmail(emailData, courseId);
|
||||
} catch (e) {
|
||||
setEmailFormStatus(FORM_SUBMIT_STATES.ERROR);
|
||||
return;
|
||||
}
|
||||
if (data.status === 200) {
|
||||
setEmailFormStatus(FORM_SUBMIT_STATES.COMPLETE);
|
||||
resetEmailForm();
|
||||
if (editor.editMode) {
|
||||
const editedEmail = formatDataForFormAction(FORM_ACTIONS.PATCH);
|
||||
await dispatch(editScheduledEmailThunk(editedEmail, courseId, editor.schedulingId));
|
||||
} else {
|
||||
const emailData = formatDataForFormAction(FORM_ACTIONS.POST);
|
||||
await dispatch(postBulkEmailThunk(emailData, courseId));
|
||||
}
|
||||
dispatch(getScheduledBulkEmailThunk(courseId, 1));
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* State manager for the various states the form can be in at any given time.
|
||||
* The states of the form are based off various pieces of the editor store, and
|
||||
* calculates what state and whether to reset the form based on these booleans.
|
||||
* Any time the form needs to change state, the conditions for that state change should
|
||||
* placed here to prevent unecessary rerenders and implicit/flakey state update batching.
|
||||
*/
|
||||
useEffect(() => {
|
||||
if (editor.isLoading) {
|
||||
setEmailFormStatus(FORM_SUBMIT_STATES.PENDING);
|
||||
return;
|
||||
}
|
||||
if (editor.errorRetrievingData) {
|
||||
setEmailFormStatus(FORM_SUBMIT_STATES.ERROR);
|
||||
delayedEmailFormReset();
|
||||
return;
|
||||
}
|
||||
if (editor.formComplete) {
|
||||
if (isScheduled) {
|
||||
setEmailFormStatus(FORM_SUBMIT_STATES.COMPLETE_SCHEDULE);
|
||||
} else {
|
||||
setEmailFormStatus(FORM_SUBMIT_STATES.COMPLETE);
|
||||
}
|
||||
delayedEmailFormReset();
|
||||
return;
|
||||
}
|
||||
if (editor.editMode === true) {
|
||||
toggleScheduled(true);
|
||||
setEmailFormStatus(FORM_SUBMIT_STATES.RESCHEDULE);
|
||||
} else if (isScheduled) {
|
||||
setEmailFormStatus(FORM_SUBMIT_STATES.SCHEDULE);
|
||||
} else {
|
||||
setEmailFormStatus(FORM_SUBMIT_STATES.DEFAULT);
|
||||
}
|
||||
}, [isScheduled, editor.editMode, editor.isLoading, editor.errorRetrievingData, editor.formComplete]);
|
||||
|
||||
const AlertMessage = () => (
|
||||
<>
|
||||
<p>{intl.formatMessage(messages.bulkEmailTaskAlertRecipients, { subject: editor.emailSubject })}</p>
|
||||
<ul className="list-unstyled">
|
||||
{editor.emailRecipients.map((group) => (
|
||||
<li key={group}>{group}</li>
|
||||
))}
|
||||
</ul>
|
||||
{!isScheduled && (
|
||||
<p>
|
||||
<strong>{intl.formatMessage(messages.bulkEmailInstructionsCaution)}</strong>
|
||||
{intl.formatMessage(messages.bulkEmailInstructionsCautionMessage)}
|
||||
</p>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
|
||||
const EditMessage = () => (
|
||||
<>
|
||||
<p>
|
||||
{intl.formatMessage(messages.bulkEmailTaskAlertEditingDate, {
|
||||
dateTime: new Date(`${editor.scheduleDate} ${editor.scheduleTime}`).toLocaleString(),
|
||||
})}
|
||||
</p>
|
||||
<p>
|
||||
{intl.formatMessage(messages.bulkEmailTaskAlertEditingSubject, {
|
||||
subject: editor.emailSubject,
|
||||
})}
|
||||
</p>
|
||||
<p>{intl.formatMessage(messages.bulkEmailTaskAlertEditingTo)}</p>
|
||||
<ul className="list-unstyled">
|
||||
{editor.emailRecipients.map((group) => (
|
||||
<li key={group}>{group}</li>
|
||||
))}
|
||||
</ul>
|
||||
<p>{intl.formatMessage(messages.bulkEmailTaskAlertEditingWarning)}</p>
|
||||
{!isScheduled && (
|
||||
<p>
|
||||
<strong>{intl.formatMessage(messages.bulkEmailInstructionsCaution)}</strong>
|
||||
{intl.formatMessage(messages.bulkEmailInstructionsCautionMessage)}
|
||||
</p>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="w-100 m-auto p-lg-4 py-2.5 px-5">
|
||||
<div className={classNames('w-100 m-auto', !isMobile && 'p-4 border border-primary-200')}>
|
||||
<TaskAlertModal
|
||||
isOpen={isTaskAlertOpen}
|
||||
alertMessage={(
|
||||
<>
|
||||
<p>
|
||||
<FormattedMessage
|
||||
id="bulk.email.task.alert.recipients"
|
||||
defaultMessage="You are sending an email message with the subject {subject} to the following recipients:"
|
||||
description="A warning shown to the user after submitting the email, to confirm the email recipients."
|
||||
values={{
|
||||
subject,
|
||||
}}
|
||||
/>
|
||||
</p>
|
||||
<ul className="list-unstyled">
|
||||
{selectedRecipients.map((group) => (
|
||||
<li key={group}>{group}</li>
|
||||
))}
|
||||
</ul>
|
||||
</>
|
||||
)}
|
||||
alertMessage={editor.editMode ? EditMessage() : AlertMessage()}
|
||||
close={(event) => {
|
||||
closeTaskAlert();
|
||||
if (event.target.name === 'continue') {
|
||||
@@ -115,127 +265,109 @@ export default function BulkEmailForm(props) {
|
||||
}}
|
||||
/>
|
||||
<Form>
|
||||
<p className="h2">
|
||||
<FormattedMessage
|
||||
id="bulk.email.tool.label"
|
||||
defaultMessage="Email"
|
||||
description="Tool label. Describes the function of the tool (to send email)."
|
||||
/>
|
||||
</p>
|
||||
<BulkEmailRecipient
|
||||
selectedGroups={selectedRecipients}
|
||||
selectedGroups={editor.emailRecipients}
|
||||
handleCheckboxes={onRecipientChange}
|
||||
additionalCohorts={cohorts}
|
||||
isValid={emailFormValidation.recipients}
|
||||
/>
|
||||
<Form.Group controlId="emailSubject">
|
||||
<Form.Label>
|
||||
<FormattedMessage
|
||||
id="bulk.email.subject.label"
|
||||
defaultMessage="Subject:"
|
||||
description="Email subject line input label. Meant to have colon or equivilant punctuation."
|
||||
/>
|
||||
</Form.Label>
|
||||
<Form.Control name="subject" className="w-lg-50" onChange={onSubjectChange} />
|
||||
<Form.Label className="h3 text-primary-500">{intl.formatMessage(messages.bulkEmailSubjectLabel)}</Form.Label>
|
||||
<Form.Control name="emailSubject" className="w-lg-50" onChange={onFormChange} value={editor.emailSubject} />
|
||||
{!emailFormValidation.subject && (
|
||||
<Form.Control.Feedback className="px-3" hasIcon type="invalid">
|
||||
<FormattedMessage
|
||||
id="bulk.email.form.subject.error"
|
||||
defaultMessage="A subject is required"
|
||||
description="An Error message located under the subject line. Visible only on failure."
|
||||
/>
|
||||
{intl.formatMessage(messages.bulkEmailFormSubjectError)}
|
||||
</Form.Control.Feedback>
|
||||
)}
|
||||
</Form.Group>
|
||||
<Form.Group controlId="emailBody">
|
||||
<Form.Label>
|
||||
<FormattedMessage
|
||||
id="bulk.email.body.label"
|
||||
defaultMessage="Body:"
|
||||
description="Email Body label. Meant to have colon or equivilant punctuation."
|
||||
/>
|
||||
</Form.Label>
|
||||
<TextEditor onInit={onInit} />
|
||||
<Form.Label className="h3 text-primary-500">{intl.formatMessage(messages.bulkEmailBodyLabel)}</Form.Label>
|
||||
<TextEditor onChange={(value) => dispatch(handleEditorChange('emailBody', value))} value={editor.emailBody} />
|
||||
{!emailFormValidation.body && (
|
||||
<Form.Control.Feedback className="px-3" hasIcon type="invalid">
|
||||
<FormattedMessage
|
||||
id="bulk.email.form.body.error"
|
||||
defaultMessage="The message cannot be blank"
|
||||
description="An error message located under the body editor. Visible only on failure."
|
||||
/>
|
||||
{intl.formatMessage(messages.bulkEmailFormBodyError)}
|
||||
</Form.Control.Feedback>
|
||||
)}
|
||||
</Form.Group>
|
||||
<div>
|
||||
<p>
|
||||
<FormattedMessage
|
||||
id="bulk.email.instructions.proofreading"
|
||||
defaultMessage="We recommend sending learners no more than one email message per week. Before you send your email, review
|
||||
the text carefully and send it to yourself first, so that you can preview the formatting and make sure
|
||||
embedded images and links work correctly."
|
||||
description="A set of instructions to give users a heads up about the formatting of the email they are about to send"
|
||||
/>
|
||||
</p>
|
||||
<p>
|
||||
<strong>
|
||||
<FormattedMessage id="bulk.email.instructions.caution" defaultMessage="Caution!" />
|
||||
</strong>
|
||||
<FormattedMessage
|
||||
id="bulk.email.instructions.caution.message"
|
||||
defaultMessage=" When you select Send Email, your email message is added to the queue for sending,
|
||||
and cannot be cancelled."
|
||||
description="A warning about how emails are sent out to users"
|
||||
/>
|
||||
</p>
|
||||
<p>{intl.formatMessage(messages.bulkEmailInstructionsProofreading)}</p>
|
||||
</div>
|
||||
<Form.Group className="d-flex flex-row">
|
||||
<StatefulButton
|
||||
variant="primary"
|
||||
type="submit"
|
||||
onClick={(event) => {
|
||||
event.preventDefault();
|
||||
openTaskAlert();
|
||||
}}
|
||||
state={emailFormStatus}
|
||||
icons={{
|
||||
default: <Icon className="icon-download" />,
|
||||
pending: <Icon src={SpinnerSimple} className="icon-spin" />,
|
||||
complete: <Icon src={CheckCircle} />,
|
||||
error: <Icon src={Cancel} />,
|
||||
}}
|
||||
labels={{
|
||||
default: 'Submit',
|
||||
pending: 'Submitting',
|
||||
complete: 'Task Created',
|
||||
error: 'Error',
|
||||
}}
|
||||
disabledStates={['pending', 'complete']}
|
||||
>
|
||||
<FormattedMessage
|
||||
id="bulk.email.submit.button"
|
||||
defaultMessage="Submit"
|
||||
description="Submit/Send email button"
|
||||
<Form.Group>
|
||||
{getConfig().SCHEDULE_EMAIL_SECTION && (
|
||||
<div className="mb-3">
|
||||
<Form.Checkbox
|
||||
name="scheduleEmailBox"
|
||||
checked={isScheduled}
|
||||
onChange={() => toggleScheduled((prev) => !prev)}
|
||||
disabled={emailFormStatus === FORM_SUBMIT_STATES.PENDING}
|
||||
>
|
||||
{intl.formatMessage(messages.bulkEmailFormScheduleBox)}
|
||||
</Form.Checkbox>
|
||||
</div>
|
||||
)}
|
||||
{isScheduled && (
|
||||
<ScheduleEmailForm
|
||||
isValid={emailFormValidation.schedule}
|
||||
onDateTimeChange={onFormChange}
|
||||
dateTime={{ date: editor.scheduleDate, time: editor.scheduleTime }}
|
||||
/>
|
||||
</StatefulButton>
|
||||
{emailFormStatus === FORM_SUBMIT_STATES.ERROR && (
|
||||
<Form.Control.Feedback className="px-3" hasIcon={false} type="invalid">
|
||||
<FormattedMessage
|
||||
id="bulk.email.form.error"
|
||||
defaultMessage="An error occured while attempting to send the email."
|
||||
description="An Error message located under the submit button for the email form. Visible only on a failure."
|
||||
/>
|
||||
</Form.Control.Feedback>
|
||||
)}
|
||||
{(emailFormStatus === FORM_SUBMIT_STATES.COMPLETED_DEFAULT
|
||||
|| emailFormStatus === FORM_SUBMIT_STATES.COMPLETE) && (
|
||||
<Form.Control.Feedback className="px-3" hasIcon={false} type="valid">
|
||||
<FormattedMessage
|
||||
id="bulk.email.form.complete"
|
||||
defaultMessage="A task to send the emails has been successfully created!"
|
||||
description="A success message displays under the submit button when successfully completing the form."
|
||||
/>
|
||||
</Form.Control.Feedback>
|
||||
)}
|
||||
<div
|
||||
className={classNames('d-flex', {
|
||||
'mt-n4.5': !isScheduled && !isMobile,
|
||||
'flex-row-reverse align-items-end': !isMobile,
|
||||
'border-top pt-2': isScheduled,
|
||||
})}
|
||||
>
|
||||
{editor.editMode && <Button className="ml-2" variant="outline-brand" onClick={() => dispatch(clearEditor())}>Cancel</Button>}
|
||||
<StatefulButton
|
||||
className="send-email-btn"
|
||||
variant="primary"
|
||||
onClick={(event) => {
|
||||
event.preventDefault();
|
||||
openTaskAlert();
|
||||
}}
|
||||
state={emailFormStatus}
|
||||
icons={{
|
||||
[FORM_SUBMIT_STATES.DEFAULT]: <Icon src={Send} />,
|
||||
[FORM_SUBMIT_STATES.SCHEDULE]: <Icon src={Event} />,
|
||||
[FORM_SUBMIT_STATES.RESCHEDULE]: <Icon src={Event} />,
|
||||
[FORM_SUBMIT_STATES.PENDING]: <Icon src={SpinnerSimple} className="icon-spin" />,
|
||||
[FORM_SUBMIT_STATES.COMPLETE]: <Icon src={Check} />,
|
||||
[FORM_SUBMIT_STATES.COMPLETE_SCHEDULE]: <Icon src={Check} />,
|
||||
[FORM_SUBMIT_STATES.ERROR]: <Icon src={Cancel} />,
|
||||
}}
|
||||
labels={{
|
||||
[FORM_SUBMIT_STATES.DEFAULT]: intl.formatMessage(messages.bulkEmailSubmitButtonDefault),
|
||||
[FORM_SUBMIT_STATES.SCHEDULE]: intl.formatMessage(messages.bulkEmailSubmitButtonSchedule),
|
||||
[FORM_SUBMIT_STATES.RESCHEDULE]: intl.formatMessage(messages.bulkEmailSubmitButtonReschedule),
|
||||
[FORM_SUBMIT_STATES.PENDING]: intl.formatMessage(messages.bulkEmailSubmitButtonPending),
|
||||
[FORM_SUBMIT_STATES.COMPLETE]: intl.formatMessage(messages.bulkEmailSubmitButtonComplete),
|
||||
[FORM_SUBMIT_STATES.COMPLETE_SCHEDULE]: intl.formatMessage(
|
||||
messages.bulkEmailSubmitButtonCompleteSchedule,
|
||||
),
|
||||
[FORM_SUBMIT_STATES.ERROR]: intl.formatMessage(messages.bulkEmailSubmitButtonError),
|
||||
}}
|
||||
disabledStates={[
|
||||
FORM_SUBMIT_STATES.PENDING,
|
||||
FORM_SUBMIT_STATES.COMPLETE,
|
||||
FORM_SUBMIT_STATES.COMPLETE_SCHEDULE,
|
||||
]}
|
||||
/>
|
||||
<Toast
|
||||
show={
|
||||
emailFormStatus === FORM_SUBMIT_STATES.ERROR
|
||||
|| emailFormStatus === FORM_SUBMIT_STATES.COMPLETE
|
||||
|| emailFormStatus === FORM_SUBMIT_STATES.COMPLETE_SCHEDULE
|
||||
}
|
||||
onClose={() => resetEmailForm(emailFormStatus === FORM_SUBMIT_STATES.ERROR)}
|
||||
>
|
||||
{emailFormStatus === FORM_SUBMIT_STATES.ERROR && intl.formatMessage(messages.bulkEmailFormError)}
|
||||
{emailFormStatus === FORM_SUBMIT_STATES.COMPLETE && intl.formatMessage(messages.bulkEmailFormSuccess)}
|
||||
{emailFormStatus === FORM_SUBMIT_STATES.COMPLETE_SCHEDULE
|
||||
&& intl.formatMessage(messages.bulkEmailFormScheduledSuccess)}
|
||||
</Toast>
|
||||
</div>
|
||||
</Form.Group>
|
||||
</Form>
|
||||
</div>
|
||||
@@ -249,6 +381,7 @@ BulkEmailForm.defaultProps = {
|
||||
BulkEmailForm.propTypes = {
|
||||
courseId: PropTypes.string.isRequired,
|
||||
cohorts: PropTypes.arrayOf(PropTypes.string),
|
||||
editorRef: PropTypes.oneOfType([PropTypes.func, PropTypes.shape({ current: PropTypes.instanceOf(Element) })])
|
||||
.isRequired,
|
||||
intl: intlShape.isRequired,
|
||||
};
|
||||
|
||||
export default injectIntl(BulkEmailForm);
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
import React from 'react';
|
||||
import PropTypes from 'prop-types';
|
||||
import classNames from 'classnames';
|
||||
import { FormattedMessage } from '@edx/frontend-platform/i18n';
|
||||
import { Form } from '@edx/paragon';
|
||||
import useMobileResponsive from '../../../utils/useMobileResponsive';
|
||||
|
||||
function ScheduleEmailForm(props) {
|
||||
const isMobile = useMobileResponsive();
|
||||
const { isValid, onDateTimeChange, dateTime } = props;
|
||||
const { date, time } = dateTime;
|
||||
return (
|
||||
<Form.Group>
|
||||
<div className={classNames('d-flex', isMobile ? 'flex-column' : 'flex-row', 'my-3')}>
|
||||
<div className="w-md-50 mx-2">
|
||||
<Form.Control
|
||||
type="date"
|
||||
name="scheduleDate"
|
||||
data-testid="scheduleDate"
|
||||
onChange={onDateTimeChange}
|
||||
value={date}
|
||||
floatingLabel={(
|
||||
<FormattedMessage
|
||||
id="bulk.email.form.schedule.date"
|
||||
defaultMessage="Send date"
|
||||
description="Label for the date portion of the email schedule form"
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<small className="text-gray-500 x-small">
|
||||
<FormattedMessage
|
||||
id="bulk.email.form.schedule.date.description"
|
||||
defaultMessage="Enter a start date, e.g. 11/27/2023"
|
||||
/>
|
||||
</small>
|
||||
</div>
|
||||
<div className="w-md-50 mx-2">
|
||||
<Form.Control
|
||||
type="time"
|
||||
name="scheduleTime"
|
||||
data-testid="scheduleTime"
|
||||
onChange={onDateTimeChange}
|
||||
value={time}
|
||||
floatingLabel={(
|
||||
<FormattedMessage
|
||||
id="bulk.email.form.schedule.time"
|
||||
defaultMessage="Send time"
|
||||
description="Label for the time portion of the email schedule form"
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<small className="text-gray-500 x-small">
|
||||
<FormattedMessage
|
||||
id="bulk.email.form.schedule.time.description"
|
||||
defaultMessage="Enter a start time, e.g. 09:00 AM"
|
||||
/>
|
||||
</small>
|
||||
</div>
|
||||
</div>
|
||||
{!isValid && (
|
||||
<Form.Control.Feedback className="pb-2" hasIcon type="invalid">
|
||||
<FormattedMessage
|
||||
id="bulk.email.form.dateTime.error"
|
||||
defaultMessage="Date and time cannot be blank, and must be a date in the future"
|
||||
description="An error message located under the date-time selector. Visible only on failure."
|
||||
/>
|
||||
</Form.Control.Feedback>
|
||||
)}
|
||||
</Form.Group>
|
||||
);
|
||||
}
|
||||
|
||||
ScheduleEmailForm.defaultProps = {
|
||||
dateTime: {
|
||||
date: '',
|
||||
time: '',
|
||||
},
|
||||
};
|
||||
|
||||
ScheduleEmailForm.propTypes = {
|
||||
isValid: PropTypes.bool.isRequired,
|
||||
onDateTimeChange: PropTypes.func.isRequired,
|
||||
dateTime: PropTypes.shape({
|
||||
date: PropTypes.string,
|
||||
time: PropTypes.string,
|
||||
}),
|
||||
};
|
||||
|
||||
export default ScheduleEmailForm;
|
||||
@@ -1,8 +0,0 @@
|
||||
/* eslint-disable import/prefer-default-export */
|
||||
import { getConfig } from '@edx/frontend-platform';
|
||||
import { getAuthenticatedHttpClient } from '@edx/frontend-platform/auth';
|
||||
|
||||
export async function postBulkEmail(email, courseId) {
|
||||
const url = `${getConfig().LMS_BASE_URL}/courses/${courseId}/instructor/api/send_email`;
|
||||
return getAuthenticatedHttpClient().post(url, email);
|
||||
}
|
||||
@@ -18,36 +18,73 @@ export default function BulkEmailRecipient(props) {
|
||||
return (
|
||||
<Form.Group>
|
||||
<Form.Label>
|
||||
<FormattedMessage
|
||||
id="bulk.email.form.recipients.sendLabel"
|
||||
defaultMessage="Send To:"
|
||||
description="A label before the list of potential recipients"
|
||||
/>
|
||||
<span className="h3 text-primary-500">
|
||||
<FormattedMessage
|
||||
id="bulk.email.form.recipients.sendLabel"
|
||||
defaultMessage="Send to"
|
||||
description="A label before the list of potential recipients"
|
||||
/>
|
||||
</span>
|
||||
</Form.Label>
|
||||
<Form.CheckboxSet
|
||||
name="recipientGroups"
|
||||
className="flex-wrap flex-row recipient-groups w-75"
|
||||
className="flex-wrap flex-row recipient-groups w-100"
|
||||
onChange={handleCheckboxes}
|
||||
value={selectedGroups}
|
||||
>
|
||||
<Form.Checkbox key="myself" value="myself" className="mt-2.5">
|
||||
<Form.Checkbox key="myself" value="myself" className="mt-2.5 col col-lg-4 col-sm-6 col-12">
|
||||
<FormattedMessage
|
||||
id="bulk.email.form.recipients.myself"
|
||||
defaultMessage="Myself"
|
||||
description="A selectable choice from a list of potential email recipients"
|
||||
/>
|
||||
</Form.Checkbox>
|
||||
<Form.Checkbox key="staff" value="staff">
|
||||
<Form.Checkbox
|
||||
key="staff"
|
||||
value="staff"
|
||||
className="col col-lg-4 col-sm-6 col-12"
|
||||
>
|
||||
<FormattedMessage
|
||||
id="bulk.email.form.recipients.staff"
|
||||
defaultMessage="Staff/Administrators"
|
||||
description="A selectable choice from a list of potential email recipients"
|
||||
/>
|
||||
</Form.Checkbox>
|
||||
<Form.Checkbox
|
||||
key="track:verified"
|
||||
value="track:verified"
|
||||
disabled={selectedGroups.find((group) => group === DEFAULT_GROUPS.ALL_LEARNERS)}
|
||||
className="col col-lg-4 col-sm-6 col-12"
|
||||
>
|
||||
<FormattedMessage
|
||||
id="bulk.email.form.recipients.verified"
|
||||
defaultMessage="Learners in the verified certificate track"
|
||||
description="A selectable choice from a list of potential email recipients"
|
||||
/>
|
||||
</Form.Checkbox>
|
||||
{
|
||||
// additional cohorts
|
||||
additionalCohorts
|
||||
&& additionalCohorts.map((cohort) => (
|
||||
<Form.Checkbox
|
||||
key={cohort}
|
||||
value={`cohort:${cohort}`}
|
||||
disabled={selectedGroups.find((group) => group === DEFAULT_GROUPS.ALL_LEARNERS)}
|
||||
className="col col-lg-4 col-sm-6 col-12"
|
||||
>
|
||||
<FormattedMessage
|
||||
id="bulk.email.form.cohort.label"
|
||||
defaultMessage="Cohort: {cohort}"
|
||||
values={{ cohort }}
|
||||
/>
|
||||
</Form.Checkbox>
|
||||
))
|
||||
}
|
||||
<Form.Checkbox
|
||||
key="track:audit"
|
||||
value="track:audit"
|
||||
disabled={selectedGroups.find((group) => group === DEFAULT_GROUPS.ALL_LEARNERS)}
|
||||
className="col col-lg-4 col-sm-6 col-12"
|
||||
>
|
||||
<FormattedMessage
|
||||
id="bulk.email.form.recipients.audit"
|
||||
@@ -55,21 +92,10 @@ export default function BulkEmailRecipient(props) {
|
||||
description="A selectable choice from a list of potential email recipients"
|
||||
/>
|
||||
</Form.Checkbox>
|
||||
<Form.Checkbox
|
||||
key="track:verified"
|
||||
value="track:verified"
|
||||
disabled={selectedGroups.find((group) => group === DEFAULT_GROUPS.ALL_LEARNERS)}
|
||||
>
|
||||
<FormattedMessage
|
||||
id="bulk.email.form.recipients.verified"
|
||||
defaultMessage="Learners in the verified certificate track"
|
||||
description="A selectable choice from a list of potential email recipients"
|
||||
/>
|
||||
</Form.Checkbox>
|
||||
<Form.Checkbox
|
||||
key="learners"
|
||||
value="learners"
|
||||
disabled={selectedGroups.find((group) => group === (DEFAULT_GROUPS.AUDIT || DEFAULT_GROUPS.VERIFIED))}
|
||||
className="col col-lg-4 col-sm-6 col-12"
|
||||
>
|
||||
<FormattedMessage
|
||||
id="bulk.email.form.recipients.learners"
|
||||
@@ -77,22 +103,6 @@ export default function BulkEmailRecipient(props) {
|
||||
description="A selectable choice from a list of potential email recipients"
|
||||
/>
|
||||
</Form.Checkbox>
|
||||
{
|
||||
// additional cohorts
|
||||
additionalCohorts
|
||||
&& additionalCohorts.map((cohort) => (
|
||||
<Form.Checkbox
|
||||
key={cohort}
|
||||
value={`cohort:${cohort}`}
|
||||
>
|
||||
<FormattedMessage
|
||||
id="bulk.email.form.cohort.label"
|
||||
defaultMessage="Cohort: {cohort}"
|
||||
values={{ cohort }}
|
||||
/>
|
||||
</Form.Checkbox>
|
||||
))
|
||||
}
|
||||
</Form.CheckboxSet>
|
||||
{!props.isValid && (
|
||||
<Form.Control.Feedback className="px-3" hasIcon type="invalid">
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
.recipient-groups {
|
||||
> div {
|
||||
min-width: 50%;
|
||||
padding-right: 0.5rem;
|
||||
input {
|
||||
padding: 0.5rem !important;
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
// Flip a leading icon to be a trailing icon
|
||||
.send-email-btn {
|
||||
> span {
|
||||
flex-direction: row-reverse;
|
||||
gap: 0.5rem;
|
||||
> span {
|
||||
margin: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { Factory } from 'rosie'; // eslint-disable-line import/no-extraneous-dependencies
|
||||
|
||||
export default Factory.define('')
|
||||
.attr('cohorts', [
|
||||
'Gnarly',
|
||||
'Righteous',
|
||||
]);
|
||||
@@ -0,0 +1,74 @@
|
||||
export const handleEditorChange = (fieldName, fieldValue) => ({
|
||||
type: 'EDITOR_ON_CHANGE',
|
||||
payload: {
|
||||
[fieldName]: fieldValue,
|
||||
},
|
||||
});
|
||||
|
||||
export const clearEditor = () => ({
|
||||
type: 'CLEAR_EDITOR',
|
||||
});
|
||||
|
||||
export const clearErrorState = () => ({
|
||||
type: 'CLEAR_ERROR',
|
||||
});
|
||||
|
||||
export const copyToEditor = (payload) => ({
|
||||
type: 'COPY_TO_EDITOR',
|
||||
payload,
|
||||
});
|
||||
|
||||
export const addRecipient = (payload) => ({
|
||||
type: 'ADD_RECIPIENT',
|
||||
payload,
|
||||
});
|
||||
|
||||
export const removeRecipient = (payload) => ({
|
||||
type: 'REMOVE_RECIPIENT',
|
||||
payload,
|
||||
});
|
||||
|
||||
export const clearRecipients = () => ({
|
||||
type: 'CLEAR_RECIPIENTS',
|
||||
});
|
||||
|
||||
export const clearDateTime = () => ({
|
||||
type: 'CLEAR_DATE_TIME',
|
||||
});
|
||||
|
||||
export const setEditMode = (editMode = false) => ({
|
||||
type: 'SET_EDIT_MODE',
|
||||
payload: editMode,
|
||||
});
|
||||
|
||||
export const patchScheduledEmail = () => ({
|
||||
type: 'PATCH_SCHEDULED_EMAIL',
|
||||
});
|
||||
|
||||
export const patchScheduledEmailStart = () => ({
|
||||
type: 'PATCH_START',
|
||||
});
|
||||
|
||||
export const patchScheduledEmailComplete = () => ({
|
||||
type: 'PATCH_COMPLETE',
|
||||
});
|
||||
|
||||
export const patchScheduledEmailError = () => ({
|
||||
type: 'PATCH_FAILURE',
|
||||
});
|
||||
|
||||
export const postBulkEmail = () => ({
|
||||
type: 'POST_BULK_EMAIL',
|
||||
});
|
||||
|
||||
export const postBulkEmailStart = () => ({
|
||||
type: 'POST_START',
|
||||
});
|
||||
|
||||
export const postBulkEmailComplete = () => ({
|
||||
type: 'POST_COMPLETE',
|
||||
});
|
||||
|
||||
export const postBulkEmailError = () => ({
|
||||
type: 'POST_FAILURE',
|
||||
});
|
||||
26
src/components/bulk-email-tool/bulk-email-form/data/api.js
Normal file
26
src/components/bulk-email-tool/bulk-email-form/data/api.js
Normal file
@@ -0,0 +1,26 @@
|
||||
/* eslint-disable import/prefer-default-export */
|
||||
import { getConfig } from '@edx/frontend-platform';
|
||||
import { getAuthenticatedHttpClient } from '@edx/frontend-platform/auth';
|
||||
import { logError } from '@edx/frontend-platform/logging';
|
||||
|
||||
export async function postBulkEmailInstructorTask(email, courseId) {
|
||||
try {
|
||||
const url = `${getConfig().LMS_BASE_URL}/courses/${courseId}/instructor/api/send_email`;
|
||||
const response = await getAuthenticatedHttpClient().post(url, email);
|
||||
return response;
|
||||
} catch (error) {
|
||||
logError(error);
|
||||
throw new Error(error);
|
||||
}
|
||||
}
|
||||
|
||||
export async function patchScheduledBulkEmailInstructorTask(emailData, courseId, scheduleId) {
|
||||
const endpointUrl = `${getConfig().LMS_BASE_URL}/api/instructor_task/v1/schedules/${courseId}/bulk_email/${scheduleId}`;
|
||||
try {
|
||||
const response = await getAuthenticatedHttpClient().patch(endpointUrl, emailData);
|
||||
return response;
|
||||
} catch (error) {
|
||||
logError(error);
|
||||
throw new Error(error);
|
||||
}
|
||||
}
|
||||
130
src/components/bulk-email-tool/bulk-email-form/data/reducer.js
Normal file
130
src/components/bulk-email-tool/bulk-email-form/data/reducer.js
Normal file
@@ -0,0 +1,130 @@
|
||||
export function editorReducer(state, action) {
|
||||
switch (action.type) {
|
||||
case 'EDITOR_ON_CHANGE':
|
||||
return {
|
||||
...state,
|
||||
...action.payload,
|
||||
};
|
||||
case 'COPY_TO_EDITOR':
|
||||
return {
|
||||
...state,
|
||||
emailBody: action.payload.emailBody || '',
|
||||
emailSubject: action.payload.emailSubject || '',
|
||||
emailRecipients: action.payload.emailRecipients || [],
|
||||
scheduleDate: action.payload.scheduleDate || '',
|
||||
scheduleTime: action.payload.scheduleTime || '',
|
||||
schedulingId: action.payload.schedulingId || '',
|
||||
emailId: action.payload.emailId || null,
|
||||
editMode: action.payload.editMode || false,
|
||||
};
|
||||
case 'ADD_RECIPIENT':
|
||||
return {
|
||||
...state,
|
||||
emailRecipients: [...state.emailRecipients, action.payload],
|
||||
};
|
||||
case 'REMOVE_RECIPIENT':
|
||||
return {
|
||||
...state,
|
||||
emailRecipients: state.emailRecipients.filter((value) => value !== action.payload),
|
||||
};
|
||||
case 'CLEAR_RECIPIENTS':
|
||||
return {
|
||||
...state,
|
||||
emailRecipients: [],
|
||||
};
|
||||
case 'CLEAR_DATE_TIME':
|
||||
return {
|
||||
...state,
|
||||
scheduleDate: '',
|
||||
scheduleTime: '',
|
||||
editMode: false,
|
||||
};
|
||||
case 'CLEAR_EDITOR':
|
||||
return {
|
||||
...state,
|
||||
emailBody: '',
|
||||
emailSubject: '',
|
||||
scheduleDate: '',
|
||||
scheduleTime: '',
|
||||
emailRecipients: [],
|
||||
editMode: false,
|
||||
schedulingId: '',
|
||||
emailId: null,
|
||||
errorRetrievingData: false,
|
||||
formComplete: false,
|
||||
};
|
||||
case 'CLEAR_ERROR':
|
||||
return {
|
||||
...state,
|
||||
errorRetrievingData: false,
|
||||
formComplete: false,
|
||||
};
|
||||
case 'SET_EDIT_MODE':
|
||||
return {
|
||||
...state,
|
||||
editMode: action.payload,
|
||||
};
|
||||
case 'PATCH_SCHEDULED_EMAIL':
|
||||
return state;
|
||||
case 'PATCH_START':
|
||||
return {
|
||||
...state,
|
||||
isLoading: true,
|
||||
};
|
||||
case 'PATCH_COMPLETE':
|
||||
return {
|
||||
...state,
|
||||
isLoading: false,
|
||||
errorRetrievingData: false,
|
||||
formComplete: true,
|
||||
...action.payload,
|
||||
};
|
||||
case 'PATCH_FAILURE':
|
||||
return {
|
||||
...state,
|
||||
isLoading: false,
|
||||
errorRetrievingData: true,
|
||||
formComplete: false,
|
||||
};
|
||||
case 'POST_BULK_EMAIL':
|
||||
return state;
|
||||
case 'POST_START':
|
||||
return {
|
||||
...state,
|
||||
isLoading: true,
|
||||
};
|
||||
case 'POST_COMPLETE':
|
||||
return {
|
||||
...state,
|
||||
isLoading: false,
|
||||
errorRetrievingData: false,
|
||||
formComplete: true,
|
||||
...action.payload,
|
||||
};
|
||||
case 'POST_FAILURE':
|
||||
return {
|
||||
...state,
|
||||
isLoading: false,
|
||||
errorRetrievingData: true,
|
||||
formComplete: false,
|
||||
};
|
||||
default:
|
||||
return state;
|
||||
}
|
||||
}
|
||||
|
||||
export const editorInitialState = {
|
||||
emailBody: '',
|
||||
emailSubject: '',
|
||||
scheduleDate: '',
|
||||
scheduleTime: '',
|
||||
emailRecipients: [],
|
||||
editMode: false,
|
||||
schedulingId: '',
|
||||
emailId: null,
|
||||
isLoading: false,
|
||||
errorRetrievingData: false,
|
||||
formComplete: false,
|
||||
};
|
||||
|
||||
export default editorReducer;
|
||||
@@ -0,0 +1,35 @@
|
||||
import { initializeMockApp } from '../../../../../setupTest';
|
||||
import { editorInitialState, editorReducer } from '../reducer';
|
||||
|
||||
describe('editorReducer', () => {
|
||||
const testState = editorInitialState;
|
||||
beforeAll(async () => {
|
||||
await initializeMockApp();
|
||||
});
|
||||
|
||||
it('does not remove present data from slice when EDITOR_ON_CHANGE action dispatched', () => {
|
||||
const newEditorState = {
|
||||
emailBody: 'test',
|
||||
};
|
||||
const returnedState = editorReducer(testState, { type: 'EDITOR_ON_CHANGE', payload: newEditorState });
|
||||
const finalState = {
|
||||
...testState,
|
||||
emailBody: 'test',
|
||||
};
|
||||
expect(returnedState).toEqual(finalState);
|
||||
});
|
||||
|
||||
it('it copies full editor state when COPY_TO_EDITOR action dispatched', () => {
|
||||
const newEditorState = {
|
||||
emailBody: 'test',
|
||||
emailSubject: 'test',
|
||||
emailRecipients: ['test'],
|
||||
};
|
||||
const finalState = {
|
||||
...testState,
|
||||
...newEditorState,
|
||||
};
|
||||
const returnedState = editorReducer(testState, { type: 'COPY_TO_EDITOR', payload: newEditorState });
|
||||
expect(returnedState).toEqual(finalState);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,53 @@
|
||||
import {
|
||||
patchScheduledEmail,
|
||||
patchScheduledEmailComplete,
|
||||
patchScheduledEmailError,
|
||||
patchScheduledEmailStart,
|
||||
postBulkEmail,
|
||||
postBulkEmailComplete,
|
||||
postBulkEmailError,
|
||||
postBulkEmailStart,
|
||||
} from './actions';
|
||||
import { patchScheduledBulkEmailInstructorTask, postBulkEmailInstructorTask } from './api';
|
||||
|
||||
export function postBulkEmailThunk(emailData, courseId) {
|
||||
return async (dispatch) => {
|
||||
dispatch(postBulkEmail());
|
||||
dispatch(postBulkEmailStart());
|
||||
function onComplete(data) {
|
||||
dispatch(postBulkEmailComplete());
|
||||
return data;
|
||||
}
|
||||
function onError(error) {
|
||||
dispatch(postBulkEmailError());
|
||||
return error;
|
||||
}
|
||||
try {
|
||||
const data = await postBulkEmailInstructorTask(emailData, courseId);
|
||||
return onComplete(data);
|
||||
} catch (error) {
|
||||
return onError(error);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function editScheduledEmailThunk(emailData, courseId, schedulingId) {
|
||||
return async (dispatch) => {
|
||||
dispatch(patchScheduledEmail());
|
||||
dispatch(patchScheduledEmailStart());
|
||||
function onComplete(data) {
|
||||
dispatch(patchScheduledEmailComplete());
|
||||
return data;
|
||||
}
|
||||
function onError(error) {
|
||||
dispatch(patchScheduledEmailError());
|
||||
return error;
|
||||
}
|
||||
try {
|
||||
const data = await patchScheduledBulkEmailInstructorTask(emailData, courseId, schedulingId);
|
||||
return onComplete(data);
|
||||
} catch (error) {
|
||||
return onError(error);
|
||||
}
|
||||
};
|
||||
}
|
||||
119
src/components/bulk-email-tool/bulk-email-form/messages.js
Normal file
119
src/components/bulk-email-tool/bulk-email-form/messages.js
Normal file
@@ -0,0 +1,119 @@
|
||||
import { defineMessages } from '@edx/frontend-platform/i18n';
|
||||
|
||||
const messages = defineMessages({
|
||||
/* BulkEmailForm.jsx Messages */
|
||||
bulkEmailSubmitButtonDefault: {
|
||||
id: 'bulk.email.submit.button.default',
|
||||
defaultMessage: 'Send email',
|
||||
},
|
||||
bulkEmailSubmitButtonSchedule: {
|
||||
id: 'bulk.email.submit.button.schedule',
|
||||
defaultMessage: 'Schedule Email',
|
||||
},
|
||||
bulkEmailSubmitButtonPending: {
|
||||
id: 'bulk.email.submit.button.pending',
|
||||
defaultMessage: 'Submitting',
|
||||
},
|
||||
bulkEmailSubmitButtonComplete: {
|
||||
id: 'bulk.email.submit.button.send.complete',
|
||||
defaultMessage: 'Email Created',
|
||||
},
|
||||
bulkEmailSubmitButtonError: {
|
||||
id: 'bulk.email.submit.button.error',
|
||||
defaultMessage: 'Error',
|
||||
},
|
||||
bulkEmailSubmitButtonCompleteSchedule: {
|
||||
id: 'bulk.email.submit.button.schedule.complete',
|
||||
defaultMessage: 'Scheduling Done',
|
||||
},
|
||||
bulkEmailTaskAlertRecipients: {
|
||||
id: 'bulk.email.task.alert.recipients',
|
||||
defaultMessage: 'You are sending an email message with the subject {subject} to the following recipients:',
|
||||
description: 'A warning shown to the user after submitting the email, to confirm the email recipients.',
|
||||
},
|
||||
bulkEmailToolLabel: {
|
||||
id: 'bulk.email.tool.label',
|
||||
defaultMessage: 'Email',
|
||||
description: 'Tool label. Describes the function of the tool (to send email).',
|
||||
},
|
||||
bulkEmailSubjectLabel: {
|
||||
id: 'bulk.email.subject.label',
|
||||
defaultMessage: 'Subject',
|
||||
description: 'Email subject line input label. Meant to have colon or equivilant punctuation.',
|
||||
},
|
||||
bulkEmailFormSubjectError: {
|
||||
id: 'bulk.email.form.subject.error',
|
||||
defaultMessage: 'A subject is required',
|
||||
description: 'An Error message located under the subject line. Visible only on failure.',
|
||||
},
|
||||
bulkEmailBodyLabel: {
|
||||
id: 'bulk.email.body.label',
|
||||
defaultMessage: 'Body',
|
||||
description: 'Email Body label. Meant to have colon or equivilant punctuation.',
|
||||
},
|
||||
bulkEmailFormBodyError: {
|
||||
id: 'bulk.email.form.body.error',
|
||||
defaultMessage: 'The message cannot be blank',
|
||||
description: 'An error message located under the body editor. Visible only on failure.',
|
||||
},
|
||||
bulkEmailInstructionsProofreading: {
|
||||
id: 'bulk.email.instructions.proofreading',
|
||||
defaultMessage: 'We recommend sending learners no more than one email message per week. Before you send your email, review the text carefully and send it to yourself first, so that you can preview the formatting and make sure embedded images and links work correctly.',
|
||||
description: 'A set of instructions to give users a heads up about the formatting of the email they are about to send',
|
||||
},
|
||||
bulkEmailInstructionsCaution: { id: 'bulk.email.instructions.caution', defaultMessage: 'Caution!' },
|
||||
|
||||
bulkEmailInstructionsCautionMessage: {
|
||||
id: 'bulk.email.instructions.caution.message.new.email',
|
||||
defaultMessage:
|
||||
' When you select Send Email, you are creating a new email message that is added to the queue for sending, and cannot be cancelled.',
|
||||
description: 'A warning about how emails are sent out to users',
|
||||
},
|
||||
bulkEmailFormScheduleBox: {
|
||||
id: 'bulk.email.form.scheduleBox',
|
||||
defaultMessage: 'Schedule this email for a future date',
|
||||
description: 'Checkbox to schedule sending the email at a later date',
|
||||
},
|
||||
bulkEmailSendEmailButton: {
|
||||
id: 'bulk.email.send.email.button',
|
||||
defaultMessage: 'Send Email',
|
||||
description: 'Schedule/Send email button',
|
||||
},
|
||||
bulkEmailFormError: {
|
||||
id: 'bulk.email.form.error',
|
||||
defaultMessage: 'An error occured while attempting to send the email.',
|
||||
description: 'An Error message located under the submit button for the email form. Visible only on a failure.',
|
||||
},
|
||||
bulkEmailFormSuccess: {
|
||||
id: 'bilk.email.form.success',
|
||||
defaultMessage: 'Email successfully created',
|
||||
},
|
||||
bulkEmailFormScheduledSuccess: {
|
||||
id: 'bulk.email.form.scheduled.success',
|
||||
defaultMessage: 'Email successfully scheduled',
|
||||
},
|
||||
bulkEmailSubmitButtonReschedule: {
|
||||
id: 'bulk.email.submit.button.reschedule',
|
||||
defaultMessage: 'Reschedule Email',
|
||||
},
|
||||
bulkEmailTaskAlertEditingDate: {
|
||||
id: 'bulk.email.task.alert.editing',
|
||||
defaultMessage: 'You are editing a scheduled email to be sent on: {dateTime}',
|
||||
description: 'This alert pops up before submitting when editing an email that has already been scheduled',
|
||||
},
|
||||
bulkEmailTaskAlertEditingSubject: {
|
||||
id: 'bulk.email.task.alert.subject',
|
||||
defaultMessage: 'with the subject: {subject}',
|
||||
},
|
||||
bulkEmailTaskAlertEditingTo: {
|
||||
id: 'bulk.email.task.alert.to',
|
||||
defaultMessage: 'to recipients:',
|
||||
},
|
||||
bulkEmailTaskAlertEditingWarning: {
|
||||
id: 'bulk.email.task.alert.warning',
|
||||
defaultMessage: 'This will not create a new scheduled email task and instead overwrite the one currently selected. Do you want to overwrite this scheduled email?',
|
||||
description: 'This alert pops up before submitting when editing an email that has already been scheduled',
|
||||
},
|
||||
});
|
||||
|
||||
export default messages;
|
||||
@@ -2,64 +2,172 @@
|
||||
* @jest-environment jsdom
|
||||
*/
|
||||
import React from 'react';
|
||||
import { getAuthenticatedHttpClient } from '@edx/frontend-platform/auth';
|
||||
import MockAdapter from 'axios-mock-adapter';
|
||||
import {
|
||||
render, screen, cleanup, act, fireEvent,
|
||||
render, screen, cleanup, fireEvent, initializeMockApp, getConfig,
|
||||
} from '../../../../setupTest';
|
||||
import BulkEmailForm from '..';
|
||||
import { postBulkEmail } from '../api';
|
||||
import * as bulkEmailFormApi from '../data/api';
|
||||
import { BulkEmailContext, BulkEmailProvider } from '../../bulk-email-context';
|
||||
import { formatDate } from '../../../../utils/formatDateAndTime';
|
||||
import cohortFactory from '../data/__factories__/bulkEmailFormCohort.factory';
|
||||
|
||||
jest.mock('../../text-editor/TextEditor');
|
||||
jest.mock('../api', () => ({
|
||||
__esModule: true,
|
||||
postBulkEmail: jest.fn(() => ({ status: 200 })),
|
||||
}));
|
||||
|
||||
const appendMock = jest.spyOn(FormData.prototype, 'append');
|
||||
const dispatchMock = jest.fn();
|
||||
|
||||
const tomorrow = new Date();
|
||||
tomorrow.setDate(new Date().getDate() + 1);
|
||||
|
||||
function renderBulkEmailForm() {
|
||||
const { cohorts } = cohortFactory.build();
|
||||
return (
|
||||
<BulkEmailProvider>
|
||||
<BulkEmailForm courseId="test" cohorts={cohorts} />
|
||||
</BulkEmailProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function renderBulkEmailFormContext(value) {
|
||||
return (
|
||||
<BulkEmailContext.Provider value={[value, dispatchMock]}>
|
||||
<BulkEmailForm courseId="test" />
|
||||
</BulkEmailContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
describe('bulk-email-form', () => {
|
||||
beforeAll(async () => {
|
||||
await initializeMockApp();
|
||||
});
|
||||
beforeEach(() => jest.resetModules());
|
||||
afterEach(cleanup);
|
||||
afterEach(() => cleanup());
|
||||
test('it renders', () => {
|
||||
render(<BulkEmailForm courseId="test-course-id" editorRef={jest.fn()} />);
|
||||
expect(screen.getByText('Submit')).toBeTruthy();
|
||||
render(renderBulkEmailForm());
|
||||
expect(screen.getByText('Send email')).toBeTruthy();
|
||||
});
|
||||
test('it shows a warning when clicking submit', async () => {
|
||||
render(<BulkEmailForm courseId="test-course-id" editorRef={jest.fn()} />);
|
||||
fireEvent.click(screen.getByText('Submit'));
|
||||
render(renderBulkEmailForm());
|
||||
fireEvent.click(screen.getByText('Send email'));
|
||||
const warning = await screen.findByText('CAUTION!', { exact: false });
|
||||
expect(warning).toBeTruthy();
|
||||
});
|
||||
test('Prevent form POST if invalid', async () => {
|
||||
render(<BulkEmailForm courseId="test-course-id" editorRef={jest.fn()} />);
|
||||
fireEvent.click(screen.getByText('Submit'));
|
||||
render(renderBulkEmailForm());
|
||||
fireEvent.click(screen.getByText('Send email'));
|
||||
expect(await screen.findByRole('button', { name: /continue/i })).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole('button', { name: /continue/i }));
|
||||
expect(await screen.findByText('At least one recipient is required', { exact: false })).toBeInTheDocument();
|
||||
expect(await screen.findByText('A subject is required')).toBeInTheDocument();
|
||||
});
|
||||
test('Shows complete message on completed POST', async () => {
|
||||
render(<BulkEmailForm courseId="test-course-id" editorRef={jest.fn()} />);
|
||||
const axiosMock = new MockAdapter(getAuthenticatedHttpClient());
|
||||
axiosMock.onPost().reply(200, {
|
||||
course_id: 'test',
|
||||
success: true,
|
||||
});
|
||||
render(renderBulkEmailForm());
|
||||
fireEvent.click(screen.getByRole('checkbox', { name: 'Myself' }));
|
||||
expect(screen.getByRole('checkbox', { name: 'Myself' })).toBeChecked();
|
||||
fireEvent.change(screen.getByRole('textbox', { name: 'Subject:' }), { target: { value: 'test subject' } });
|
||||
fireEvent.click(screen.getByText('Submit'));
|
||||
fireEvent.change(screen.getByRole('textbox', { name: 'Subject' }), { target: { value: 'test subject' } });
|
||||
fireEvent.change(screen.getByTestId('textEditor'), { target: { value: 'test body' } });
|
||||
fireEvent.click(screen.getByText('Send email'));
|
||||
expect(await screen.findByRole('button', { name: /continue/i })).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole('button', { name: /continue/i }));
|
||||
expect(await screen.findByText('Submitting')).toBeInTheDocument();
|
||||
expect(await screen.findByText('A task to send the emails has been successfully created!')).toBeInTheDocument();
|
||||
expect(await screen.findByText('Email Created')).toBeInTheDocument();
|
||||
});
|
||||
test('Shows Error on failed POST', async () => {
|
||||
postBulkEmail.mockImplementation(() => {
|
||||
throw Error('api-response-error');
|
||||
});
|
||||
await act(async () => {
|
||||
render(<BulkEmailForm courseId="test-course-id" editorRef={jest.fn()} />);
|
||||
const subjectLine = screen.getByRole('textbox', { name: 'Subject:' });
|
||||
const recipient = screen.getByRole('checkbox', { name: 'Myself' });
|
||||
fireEvent.click(recipient);
|
||||
fireEvent.change(subjectLine, { target: { value: 'test subject' } });
|
||||
fireEvent.click(screen.getByText('Submit'));
|
||||
expect(await screen.findByRole('button', { name: /continue/i })).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole('button', { name: /continue/i }));
|
||||
expect(await screen.findByText('Error')).toBeInTheDocument();
|
||||
});
|
||||
const axiosMock = new MockAdapter(getAuthenticatedHttpClient());
|
||||
axiosMock.onPost(`${getConfig().LMS_BASE_URL}/courses/test/instructor/api/send_email`).reply(500);
|
||||
render(renderBulkEmailForm());
|
||||
const subjectLine = screen.getByRole('textbox', { name: 'Subject' });
|
||||
const recipient = screen.getByRole('checkbox', { name: 'Myself' });
|
||||
fireEvent.click(recipient);
|
||||
fireEvent.change(subjectLine, { target: { value: 'test subject' } });
|
||||
fireEvent.change(screen.getByTestId('textEditor'), { target: { value: 'test body' } });
|
||||
fireEvent.click(screen.getByText('Send email'));
|
||||
expect(await screen.findByRole('button', { name: /continue/i })).toBeInTheDocument();
|
||||
fireEvent.click(await screen.findByRole('button', { name: /continue/i }));
|
||||
expect(await screen.findByText('An error occured while attempting to send the email.')).toBeInTheDocument();
|
||||
});
|
||||
test('Checking "All Learners" disables each learner group', async () => {
|
||||
render(renderBulkEmailForm());
|
||||
fireEvent.click(screen.getByRole('checkbox', { name: 'All Learners' }));
|
||||
const verifiedLearners = screen.getByRole('checkbox', { name: 'Learners in the verified certificate track' });
|
||||
const auditLearners = screen.getByRole('checkbox', { name: 'Learners in the audit track' });
|
||||
const { cohorts } = cohortFactory.build();
|
||||
cohorts.forEach(cohort => expect(screen.getByRole('checkbox', { name: `Cohort: ${cohort}` })).toBeDisabled());
|
||||
expect(verifiedLearners).toBeDisabled();
|
||||
expect(auditLearners).toBeDisabled();
|
||||
});
|
||||
test('Shows scheduling form when checkbox is checked and submit is changed', async () => {
|
||||
render(renderBulkEmailForm());
|
||||
const scheduleCheckbox = screen.getByText('Schedule this email for a future date');
|
||||
fireEvent.click(scheduleCheckbox);
|
||||
expect(screen.getByText('Send time'));
|
||||
expect(screen.getByText('Send date'));
|
||||
expect(screen.getByText('Schedule Email'));
|
||||
});
|
||||
test('Prevents sending email when scheduling inputs are empty', async () => {
|
||||
render(renderBulkEmailForm());
|
||||
const scheduleCheckbox = screen.getByText('Schedule this email for a future date');
|
||||
fireEvent.click(scheduleCheckbox);
|
||||
const submitButton = await screen.findByText('Schedule Email');
|
||||
fireEvent.click(submitButton);
|
||||
const continueButton = await screen.findByRole('button', { name: /continue/i });
|
||||
fireEvent.click(continueButton);
|
||||
expect(screen.getByText('Date and time cannot be blank, and must be a date in the future'));
|
||||
});
|
||||
test('Adds scheduling data to POST requests when schedule is selected', async () => {
|
||||
const postBulkEmailInstructorTask = jest.spyOn(bulkEmailFormApi, 'postBulkEmailInstructorTask');
|
||||
render(renderBulkEmailForm());
|
||||
fireEvent.click(screen.getByRole('checkbox', { name: 'Myself' }));
|
||||
fireEvent.change(screen.getByRole('textbox', { name: 'Subject' }), { target: { value: 'test subject' } });
|
||||
fireEvent.change(screen.getByTestId('textEditor'), { target: { value: 'test body' } });
|
||||
const scheduleCheckbox = screen.getByText('Schedule this email for a future date');
|
||||
fireEvent.click(scheduleCheckbox);
|
||||
const submitButton = screen.getByText('Schedule Email');
|
||||
const scheduleDate = screen.getByTestId('scheduleDate');
|
||||
const scheduleTime = screen.getByTestId('scheduleTime');
|
||||
fireEvent.change(scheduleDate, { target: { value: formatDate(tomorrow) } });
|
||||
fireEvent.change(scheduleTime, { target: { value: '10:00' } });
|
||||
fireEvent.click(submitButton);
|
||||
const continueButton = await screen.findByRole('button', { name: /continue/i });
|
||||
fireEvent.click(continueButton);
|
||||
expect(appendMock).toHaveBeenCalledWith('schedule', expect.stringContaining(formatDate(tomorrow)));
|
||||
expect(postBulkEmailInstructorTask).toHaveBeenCalledWith(expect.any(FormData), expect.stringContaining('test'));
|
||||
});
|
||||
test('will PATCH instead of POST when in edit mode', async () => {
|
||||
const axiosMock = new MockAdapter(getAuthenticatedHttpClient());
|
||||
axiosMock.onPatch().reply(200);
|
||||
render(
|
||||
renderBulkEmailFormContext({
|
||||
editor: {
|
||||
editMode: true,
|
||||
emailBody: 'test',
|
||||
emailSubject: 'test',
|
||||
emailRecipients: ['test'],
|
||||
scheduleDate: formatDate(tomorrow),
|
||||
scheduleTime: '10:00',
|
||||
schedulingId: 1,
|
||||
emailId: 1,
|
||||
isLoading: false,
|
||||
errorRetrievingData: false,
|
||||
},
|
||||
}),
|
||||
);
|
||||
const submitButton = screen.getByText('Reschedule Email');
|
||||
fireEvent.click(submitButton);
|
||||
expect(
|
||||
await screen.findByText(
|
||||
'This will not create a new scheduled email task and instead overwrite the one currently selected. Do you want to overwrite this scheduled email?',
|
||||
),
|
||||
).toBeInTheDocument();
|
||||
const continueButton = await screen.findByRole('button', { name: /continue/i });
|
||||
fireEvent.click(continueButton);
|
||||
expect(dispatchMock).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,29 +1,24 @@
|
||||
import React, { useState } from 'react';
|
||||
import PropTypes from 'prop-types';
|
||||
import { useParams } from 'react-router-dom';
|
||||
import { FormattedMessage, injectIntl, intlShape } from '@edx/frontend-platform/i18n';
|
||||
import { injectIntl, intlShape } from '@edx/frontend-platform/i18n';
|
||||
|
||||
import {
|
||||
Button, Icon, Modal, StatefulButton,
|
||||
Button, Collapsible, Icon,
|
||||
} from '@edx/paragon';
|
||||
import { SpinnerSimple } from '@edx/paragon/icons';
|
||||
import messages from './messages';
|
||||
import { getSentEmailHistory } from './data/api';
|
||||
import BulkEmailTaskManagerTable from './BulkEmailHistoryTable';
|
||||
import ViewEmailModal from './ViewEmailModal';
|
||||
|
||||
export function BulkEmailContentHistory({ intl, copyTextToEditor }) {
|
||||
function BulkEmailContentHistory({ intl }) {
|
||||
const { courseId } = useParams();
|
||||
const BUTTON_STATE = {
|
||||
DEFAULT: 'default',
|
||||
PENDING: 'pending',
|
||||
COMPLETE: 'complete',
|
||||
};
|
||||
const [emailHistoryData, setEmailHistoryData] = useState();
|
||||
const [errorRetrievingData, setErrorRetrievingData] = useState(false);
|
||||
const [showHistoricalEmailContentTable, setShowHistoricalEmailContentTable] = useState(false);
|
||||
const [isMessageModalOpen, setIsMessageModalOpen] = useState(false);
|
||||
const [messageContent, setMessageContent] = useState();
|
||||
const [buttonState, setButtonState] = useState(BUTTON_STATE.DEFAULT);
|
||||
|
||||
/**
|
||||
* Async function that makes a REST API call to retrieve historical email message data sent by the bulk course email
|
||||
@@ -32,7 +27,6 @@ export function BulkEmailContentHistory({ intl, copyTextToEditor }) {
|
||||
async function fetchSentEmailHistoryData() {
|
||||
setErrorRetrievingData(false);
|
||||
setShowHistoricalEmailContentTable(false);
|
||||
setButtonState(BUTTON_STATE.PENDING);
|
||||
|
||||
let data = null;
|
||||
try {
|
||||
@@ -47,7 +41,6 @@ export function BulkEmailContentHistory({ intl, copyTextToEditor }) {
|
||||
}
|
||||
|
||||
setShowHistoricalEmailContentTable(true);
|
||||
setButtonState(BUTTON_STATE.COMPLETE);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -57,7 +50,7 @@ export function BulkEmailContentHistory({ intl, copyTextToEditor }) {
|
||||
* display bug in the table.
|
||||
*/
|
||||
function transformDataForTable() {
|
||||
let tableData = {};
|
||||
let tableData = [];
|
||||
if (emailHistoryData) {
|
||||
tableData = emailHistoryData.map((item) => ({
|
||||
...item,
|
||||
@@ -78,58 +71,6 @@ export function BulkEmailContentHistory({ intl, copyTextToEditor }) {
|
||||
setIsMessageModalOpen(true);
|
||||
};
|
||||
|
||||
/**
|
||||
* Renders a modal that will display the contents of a single historical email message sent via the bulk course email
|
||||
* tool to a user.
|
||||
*/
|
||||
const renderMessageModal = () => (
|
||||
<div>
|
||||
<Modal
|
||||
open={isMessageModalOpen}
|
||||
title=""
|
||||
body={(
|
||||
<div>
|
||||
<div className="d-flex flex-row">
|
||||
<p>{intl.formatMessage(messages.modalMessageSubject)}</p>
|
||||
<p className="pl-2">{messageContent.subject}</p>
|
||||
</div>
|
||||
<div className="d-flex flex-row">
|
||||
<p>{intl.formatMessage(messages.modalMessageSentBy)}</p>
|
||||
<p className="pl-2">{messageContent.requester}</p>
|
||||
</div>
|
||||
<div className="d-flex flex-row">
|
||||
<p>{intl.formatMessage(messages.modalMessageTimeSent)}</p>
|
||||
<p className="pl-2">{messageContent.created}</p>
|
||||
</div>
|
||||
<div className="d-flex flex-row">
|
||||
<p>{intl.formatMessage(messages.modalMessageSentTo)}</p>
|
||||
<p className="pl-2">{messageContent.sent_to}</p>
|
||||
</div>
|
||||
<hr className="py-2" />
|
||||
<div>
|
||||
<p>{intl.formatMessage(messages.modalMessageBody)}</p>
|
||||
{/* eslint-disable-next-line react/no-danger */}
|
||||
<div dangerouslySetInnerHTML={{ __html: messageContent.email.html_message }} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
onClose={() => setIsMessageModalOpen(false)}
|
||||
buttons={[
|
||||
<Button onClick={() => {
|
||||
copyTextToEditor(messageContent.email.html_message);
|
||||
setIsMessageModalOpen(false);
|
||||
}}
|
||||
>
|
||||
<FormattedMessage
|
||||
id="bulk.email.tool.copy.message.button"
|
||||
defaultMessage="Copy to editor"
|
||||
/>
|
||||
</Button>,
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
const tableColumns = [
|
||||
{
|
||||
Header: `${intl.formatMessage(messages.emailHistoryTableColumnHeaderSubject)}`,
|
||||
@@ -168,6 +109,7 @@ export function BulkEmailContentHistory({ intl, copyTextToEditor }) {
|
||||
Cell: ({ row }) => (
|
||||
<Button variant="link" className="px-1" onClick={() => onViewMessageClick(tableData[row.index])}>
|
||||
{intl.formatMessage(messages.buttonViewMessage)}
|
||||
<span className="sr-only"> {row.index}</span>
|
||||
</Button>
|
||||
),
|
||||
},
|
||||
@@ -176,40 +118,35 @@ export function BulkEmailContentHistory({ intl, copyTextToEditor }) {
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div>{messageContent && renderMessageModal()}</div>
|
||||
{messageContent && (
|
||||
<ViewEmailModal
|
||||
messageContent={messageContent}
|
||||
isOpen={isMessageModalOpen}
|
||||
setModalOpen={setIsMessageModalOpen}
|
||||
/>
|
||||
)}
|
||||
<div>
|
||||
<p>{intl.formatMessage(messages.emailHistoryTableSectionButtonHeader)}</p>
|
||||
<StatefulButton
|
||||
className="btn btn-outline-primary mb-2"
|
||||
variant="outline-primary"
|
||||
type="submit"
|
||||
onClick={async () => {
|
||||
await fetchSentEmailHistoryData();
|
||||
}}
|
||||
labels={{
|
||||
default: `${intl.formatMessage(messages.emailHistoryTableSectionButton)}`,
|
||||
pending: `${intl.formatMessage(messages.emailHistoryTableSectionButton)}`,
|
||||
complete: `${intl.formatMessage(messages.emailHistoryTableSectionButton)}`,
|
||||
}}
|
||||
icons={{
|
||||
pending: <Icon src={SpinnerSimple} className="icon-spin" />,
|
||||
}}
|
||||
disabledStates={['error']}
|
||||
state={buttonState}
|
||||
<Collapsible
|
||||
styling="card"
|
||||
title={intl.formatMessage(messages.emailHistoryTableSectionButton)}
|
||||
className="mb-3"
|
||||
onOpen={fetchSentEmailHistoryData}
|
||||
>
|
||||
{intl.formatMessage(messages.emailHistoryTableSectionButton)}
|
||||
</StatefulButton>
|
||||
{showHistoricalEmailContentTable && (
|
||||
<BulkEmailTaskManagerTable
|
||||
errorRetrievingData={errorRetrievingData}
|
||||
tableData={transformDataForTable()}
|
||||
tableDescription={intl.formatMessage(messages.emailHistoryTableViewMessageInstructions)}
|
||||
alertWarningMessage={intl.formatMessage(messages.noEmailData)}
|
||||
alertErrorMessage={intl.formatMessage(messages.errorFetchingEmailHistoryData)}
|
||||
columns={tableColumns}
|
||||
additionalColumns={additionalColumns()}
|
||||
/>
|
||||
)}
|
||||
{showHistoricalEmailContentTable ? (
|
||||
<BulkEmailTaskManagerTable
|
||||
errorRetrievingData={errorRetrievingData}
|
||||
tableData={transformDataForTable()}
|
||||
tableDescription={intl.formatMessage(messages.emailHistoryTableViewMessageInstructions)}
|
||||
alertWarningMessage={intl.formatMessage(messages.noEmailData)}
|
||||
alertErrorMessage={intl.formatMessage(messages.errorFetchingEmailHistoryData)}
|
||||
columns={tableColumns}
|
||||
additionalColumns={additionalColumns()}
|
||||
/>
|
||||
) : (
|
||||
<Icon src={SpinnerSimple} className="icon-spin mx-auto" />
|
||||
)}
|
||||
</Collapsible>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
@@ -220,7 +157,6 @@ BulkEmailContentHistory.propTypes = {
|
||||
row: PropTypes.shape({
|
||||
index: PropTypes.number,
|
||||
}),
|
||||
copyTextToEditor: PropTypes.func.isRequired,
|
||||
};
|
||||
|
||||
BulkEmailContentHistory.defaultProps = {
|
||||
|
||||
@@ -7,7 +7,7 @@ import messages from './messages';
|
||||
import useInterval from '../../../utils/useInterval';
|
||||
import BulkEmailTaskManagerTable from './BulkEmailHistoryTable';
|
||||
|
||||
export function BulkEmailPendingTasks({ intl }) {
|
||||
function BulkEmailPendingTasks({ intl }) {
|
||||
const { courseId } = useParams();
|
||||
|
||||
const [instructorTaskData, setInstructorTaskData] = useState();
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import React from 'react';
|
||||
|
||||
import { getConfig } from '@edx/frontend-platform';
|
||||
import { Hyperlink, Alert } from '@edx/paragon';
|
||||
import { WarningFilled } from '@edx/paragon/icons';
|
||||
import { FormattedMessage } from '@edx/frontend-platform/i18n';
|
||||
|
||||
export default function BulkEmailPendingTasksAlert() {
|
||||
return (
|
||||
<>
|
||||
<Alert variant="warning" icon={WarningFilled}>
|
||||
<FormattedMessage
|
||||
id="bulk.email.pending.tasks.description.one"
|
||||
defaultMessage="To view all pending tasks, including email, visit "
|
||||
/>
|
||||
<Hyperlink
|
||||
destination={`${getConfig().LMS_BASE_URL}/courses/${window.location.pathname.split('/')[2]}/instructor#view-course-info`}
|
||||
target="_blank"
|
||||
isInline
|
||||
showLaunchIcon={false}
|
||||
>
|
||||
<FormattedMessage
|
||||
id="bulk.email.pending.tasks.link"
|
||||
defaultMessage="Course Info"
|
||||
/>
|
||||
</Hyperlink>
|
||||
<FormattedMessage
|
||||
id="bulk.email.pending.tasks.description.two"
|
||||
defaultMessage=" in the Instructor Dashboard."
|
||||
/>
|
||||
</Alert>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -2,25 +2,21 @@ import React, { useState } from 'react';
|
||||
import { useParams } from 'react-router-dom';
|
||||
import { injectIntl, intlShape } from '@edx/frontend-platform/i18n';
|
||||
|
||||
import { Icon, StatefulButton } from '@edx/paragon';
|
||||
import { Icon, Collapsible } from '@edx/paragon';
|
||||
import { SpinnerSimple } from '@edx/paragon/icons';
|
||||
import { getEmailTaskHistory } from './data/api';
|
||||
import messages from './messages';
|
||||
|
||||
import BulkEmailTaskManagerTable from './BulkEmailHistoryTable';
|
||||
|
||||
export function BulkEmailTaskHistory({ intl }) {
|
||||
const { courseId } = useParams();
|
||||
const BUTTON_STATE = {
|
||||
DEFAULT: 'default',
|
||||
PENDING: 'pending',
|
||||
COMPLETE: 'complete',
|
||||
};
|
||||
import './bulkEmailTaskHistory.scss';
|
||||
|
||||
const [emailTaskHistoryData, setEmailTaskHistoryData] = useState();
|
||||
function BulkEmailTaskHistory({ intl }) {
|
||||
const { courseId } = useParams();
|
||||
|
||||
const [emailTaskHistoryData, setEmailTaskHistoryData] = useState([]);
|
||||
const [showHistoricalTaskContentTable, setShowHistoricalTaskContentTable] = useState(false);
|
||||
const [errorRetrievingData, setErrorRetrievingData] = useState(false);
|
||||
const [buttonState, setButtonState] = useState(BUTTON_STATE.DEFAULT);
|
||||
|
||||
/**
|
||||
* Async function that makes a REST API call to retrieve historical bulk email (Instructor) task data for display
|
||||
@@ -29,7 +25,6 @@ export function BulkEmailTaskHistory({ intl }) {
|
||||
async function fetchEmailTaskHistoryData() {
|
||||
setErrorRetrievingData(false);
|
||||
setShowHistoricalTaskContentTable(false);
|
||||
setButtonState(BUTTON_STATE.PENDING);
|
||||
|
||||
let data = null;
|
||||
try {
|
||||
@@ -44,7 +39,6 @@ export function BulkEmailTaskHistory({ intl }) {
|
||||
}
|
||||
|
||||
setShowHistoricalTaskContentTable(true);
|
||||
setButtonState(BUTTON_STATE.COMPLETE);
|
||||
}
|
||||
|
||||
const tableColumns = [
|
||||
@@ -87,38 +81,28 @@ export function BulkEmailTaskHistory({ intl }) {
|
||||
];
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="pb-4.5">
|
||||
<div>
|
||||
<p>
|
||||
{intl.formatMessage(messages.emailTaskHistoryTableSectionButtonHeader)}
|
||||
</p>
|
||||
<StatefulButton
|
||||
className="btn btn-outline-primary mb-2"
|
||||
variant="outline-primary"
|
||||
type="submit"
|
||||
onClick={async () => { await fetchEmailTaskHistoryData(); }}
|
||||
labels={{
|
||||
default: `${intl.formatMessage(messages.emailTaskHistoryTableSectionButton)}`,
|
||||
pending: `${intl.formatMessage(messages.emailTaskHistoryTableSectionButton)}`,
|
||||
complete: `${intl.formatMessage(messages.emailTaskHistoryTableSectionButton)}`,
|
||||
}}
|
||||
icons={{
|
||||
pending: <Icon src={SpinnerSimple} className="icon-spin" />,
|
||||
}}
|
||||
disabledStates={['error']}
|
||||
state={buttonState}
|
||||
<Collapsible
|
||||
styling="card"
|
||||
title={intl.formatMessage(messages.emailTaskHistoryTableSectionButton)}
|
||||
onOpen={fetchEmailTaskHistoryData}
|
||||
>
|
||||
{intl.formatMessage(messages.emailHistoryTableSectionButton)}
|
||||
</StatefulButton>
|
||||
{showHistoricalTaskContentTable && (
|
||||
<BulkEmailTaskManagerTable
|
||||
errorRetrievingData={errorRetrievingData}
|
||||
tableData={emailTaskHistoryData}
|
||||
alertWarningMessage={intl.formatMessage(messages.noTaskHistoryData)}
|
||||
alertErrorMessage={intl.formatMessage(messages.errorFetchingTaskHistoryData)}
|
||||
columns={tableColumns}
|
||||
/>
|
||||
)}
|
||||
{showHistoricalTaskContentTable ? (
|
||||
<BulkEmailTaskManagerTable
|
||||
errorRetrievingData={errorRetrievingData}
|
||||
tableData={emailTaskHistoryData}
|
||||
alertWarningMessage={intl.formatMessage(messages.noTaskHistoryData)}
|
||||
alertErrorMessage={intl.formatMessage(messages.errorFetchingTaskHistoryData)}
|
||||
columns={tableColumns}
|
||||
/>
|
||||
) : (
|
||||
<Icon src={SpinnerSimple} className="icon-spin mx-auto" />
|
||||
)}
|
||||
</Collapsible>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,37 +1,39 @@
|
||||
import React from 'react';
|
||||
|
||||
import { injectIntl, intlShape } from '@edx/frontend-platform/i18n';
|
||||
import PropTypes from 'prop-types';
|
||||
import { getConfig } from '@edx/frontend-platform';
|
||||
import BulkEmailContentHistory from './BulkEmailContentHistory';
|
||||
import BulkEmailPendingTasks from './BulkEmailPendingTasks';
|
||||
import BulkEmailTaskHistory from './BulkEmailTaskHistory';
|
||||
import messages from './messages';
|
||||
import BulkEmailScheduledEmailsTable from './bulk-email-scheduled-emails-table';
|
||||
import BulkEmailPendingTasksAlert from './BulkEmailPendingTasksAlert';
|
||||
|
||||
export function BulkEmailTaskManager({ intl, copyTextToEditor }) {
|
||||
function BulkEmailTaskManager({ intl }) {
|
||||
return (
|
||||
<div className="px-5">
|
||||
<div className="w-100">
|
||||
{getConfig().SCHEDULE_EMAIL_SECTION && (
|
||||
<div>
|
||||
<h2 className="h3 text-primary-500">{intl.formatMessage(messages.scheduledEmailsTableHeader)}</h2>
|
||||
<BulkEmailScheduledEmailsTable />
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
<h2 className="h3">
|
||||
{intl.formatMessage(messages.pendingTasksHeader)}
|
||||
</h2>
|
||||
<BulkEmailPendingTasks />
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="h3">
|
||||
{intl.formatMessage(messages.emailTaskHistoryHeader)}
|
||||
</h2>
|
||||
<BulkEmailContentHistory copyTextToEditor={copyTextToEditor} />
|
||||
<h2 className="h3 text-primary-500">{intl.formatMessage(messages.emailTaskHistoryHeader)}</h2>
|
||||
<BulkEmailContentHistory />
|
||||
</div>
|
||||
<div>
|
||||
<BulkEmailTaskHistory />
|
||||
</div>
|
||||
<div className="border-top border-primary-500 pt-4.5">
|
||||
<h2 className="h3 mb-4 text-primary-500">{intl.formatMessage(messages.pendingTasksHeader)}</h2>
|
||||
<BulkEmailPendingTasksAlert />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
BulkEmailTaskManager.propTypes = {
|
||||
intl: intlShape.isRequired,
|
||||
copyTextToEditor: PropTypes.func.isRequired,
|
||||
};
|
||||
|
||||
export default injectIntl(BulkEmailTaskManager);
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import React, { useContext } from 'react';
|
||||
import PropTypes from 'prop-types';
|
||||
import { Button, Modal } from '@edx/paragon';
|
||||
import { FormattedMessage, injectIntl, intlShape } from '@edx/frontend-platform/i18n';
|
||||
import messages from './messages';
|
||||
import { BulkEmailContext } from '../bulk-email-context';
|
||||
import { copyToEditor } from '../bulk-email-form/data/actions';
|
||||
|
||||
function ViewEmailModal({
|
||||
intl, messageContent, isOpen, setModalOpen,
|
||||
}) {
|
||||
const [, dispatch] = useContext(BulkEmailContext);
|
||||
return (
|
||||
<div>
|
||||
<Modal
|
||||
open={isOpen}
|
||||
title=""
|
||||
body={(
|
||||
<div>
|
||||
<div className="d-flex flex-row">
|
||||
<p>{intl.formatMessage(messages.modalMessageSubject)}</p>
|
||||
<p className="pl-2">{messageContent.subject}</p>
|
||||
</div>
|
||||
<div className="d-flex flex-row">
|
||||
<p>{intl.formatMessage(messages.modalMessageSentBy)}</p>
|
||||
<p className="pl-2">{messageContent.requester}</p>
|
||||
</div>
|
||||
<div className="d-flex flex-row">
|
||||
<p>{intl.formatMessage(messages.modalMessageTimeSent)}</p>
|
||||
<p className="pl-2">{messageContent.created}</p>
|
||||
</div>
|
||||
<div className="d-flex flex-row">
|
||||
<p>{intl.formatMessage(messages.modalMessageSentTo)}</p>
|
||||
<p className="pl-2">{messageContent.sent_to}</p>
|
||||
</div>
|
||||
<hr className="py-2" />
|
||||
<div>
|
||||
<p>{intl.formatMessage(messages.modalMessageBody)}</p>
|
||||
{/* eslint-disable-next-line react/no-danger */}
|
||||
<div dangerouslySetInnerHTML={{ __html: messageContent.email.html_message }} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
onClose={() => setModalOpen(false)}
|
||||
buttons={[
|
||||
<Button
|
||||
onClick={() => {
|
||||
dispatch(
|
||||
copyToEditor({
|
||||
emailBody: messageContent.email.html_message,
|
||||
emailSubject: messageContent.subject,
|
||||
}),
|
||||
);
|
||||
setModalOpen(false);
|
||||
}}
|
||||
>
|
||||
<FormattedMessage id="bulk.email.tool.copy.message.button" defaultMessage="Copy to editor" />
|
||||
</Button>,
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
ViewEmailModal.propTypes = {
|
||||
intl: intlShape.isRequired,
|
||||
messageContent: PropTypes.shape({
|
||||
subject: PropTypes.string,
|
||||
requester: PropTypes.string,
|
||||
created: PropTypes.string,
|
||||
email: PropTypes.shape({
|
||||
html_message: PropTypes.string,
|
||||
}).isRequired,
|
||||
sent_to: PropTypes.string,
|
||||
}).isRequired,
|
||||
isOpen: PropTypes.bool.isRequired,
|
||||
setModalOpen: PropTypes.func.isRequired,
|
||||
};
|
||||
|
||||
export default injectIntl(ViewEmailModal);
|
||||
@@ -0,0 +1,199 @@
|
||||
/* eslint-disable react/prop-types */
|
||||
import React, {
|
||||
useCallback, useContext, useState, useEffect,
|
||||
} from 'react';
|
||||
import { injectIntl, intlShape } from '@edx/frontend-platform/i18n';
|
||||
import {
|
||||
Alert, DataTable, Icon, IconButton, useToggle,
|
||||
} from '@edx/paragon';
|
||||
import {
|
||||
Delete, Info, Visibility, Edit,
|
||||
} from '@edx/paragon/icons';
|
||||
import { useParams } from 'react-router-dom';
|
||||
import { BulkEmailContext } from '../../bulk-email-context';
|
||||
import { deleteScheduledEmailThunk, getScheduledBulkEmailThunk } from './data/thunks';
|
||||
import messages from './messages';
|
||||
import ViewEmailModal from '../ViewEmailModal';
|
||||
import { copyToEditor } from '../../bulk-email-form/data/actions';
|
||||
import TaskAlertModal from '../../task-alert-modal';
|
||||
import { formatDate, formatTime } from '../../../../utils/formatDateAndTime';
|
||||
|
||||
function flattenScheduledEmailsArray(emails) {
|
||||
return emails.map((email) => ({
|
||||
schedulingId: email.id,
|
||||
emailId: email.courseEmail.id,
|
||||
task: email.task,
|
||||
taskDue: new Date(email.taskDue).toLocaleString(),
|
||||
...email.courseEmail,
|
||||
targets: email.courseEmail.targets.join(', '),
|
||||
}));
|
||||
}
|
||||
|
||||
function BulkEmailScheduledEmailsTable({ intl }) {
|
||||
const { courseId } = useParams();
|
||||
const [{ scheduledEmailsTable }, dispatch] = useContext(BulkEmailContext);
|
||||
const [tableData, setTableData] = useState([]);
|
||||
const [viewModal, setViewModal] = useState({
|
||||
isOpen: false,
|
||||
messageContent: {},
|
||||
});
|
||||
const [isConfirmModalOpen, openConfirmModal, closeConfirmModal] = useToggle();
|
||||
const [currentTask, setCurrentTask] = useState({});
|
||||
|
||||
useEffect(() => {
|
||||
setTableData(flattenScheduledEmailsArray(scheduledEmailsTable.results));
|
||||
}, [scheduledEmailsTable.results]);
|
||||
|
||||
const fetchTableData = useCallback((args) => {
|
||||
dispatch(getScheduledBulkEmailThunk(courseId, args.pageIndex + 1));
|
||||
}, []);
|
||||
|
||||
const handleViewEmail = (row) => {
|
||||
setViewModal({
|
||||
isOpen: true,
|
||||
messageContent: {
|
||||
subject: row.original.subject,
|
||||
requester: row.original.sender,
|
||||
created: row.original.taskDue,
|
||||
email: {
|
||||
html_message: row.original.htmlMessage,
|
||||
},
|
||||
sent_to: row.original.targets,
|
||||
},
|
||||
});
|
||||
};
|
||||
if (scheduledEmailsTable.errorRetrievingData) {
|
||||
return (
|
||||
<div className="pb-4">
|
||||
<Alert variant="danger" icon={Info}>
|
||||
<Alert.Heading>{intl.formatMessage(messages.bulkEmailScheduledEmailsTableErrorHeader)}</Alert.Heading>
|
||||
<p>{intl.formatMessage(messages.bulkEmailScheduledEmailsTableError)}</p>
|
||||
</Alert>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const handleDeleteEmail = async () => {
|
||||
const {
|
||||
row, pageIndex, page, previousPage,
|
||||
} = currentTask;
|
||||
await dispatch(deleteScheduledEmailThunk(courseId, row.original.schedulingId));
|
||||
if (page.length === 1 && pageIndex !== 0) {
|
||||
previousPage();
|
||||
} else {
|
||||
dispatch(getScheduledBulkEmailThunk(courseId, pageIndex + 1));
|
||||
}
|
||||
};
|
||||
|
||||
const handleEditEmail = (row) => {
|
||||
const {
|
||||
original: {
|
||||
htmlMessage: emailBody, subject: emailSubject, taskDue, targets, schedulingId, emailId,
|
||||
},
|
||||
} = row;
|
||||
const dateTime = new Date(taskDue);
|
||||
const emailRecipients = targets.replaceAll('-', ':').split(', ');
|
||||
const scheduleDate = formatDate(dateTime);
|
||||
const scheduleTime = formatTime(dateTime);
|
||||
dispatch(
|
||||
copyToEditor({
|
||||
emailId,
|
||||
emailBody,
|
||||
emailSubject,
|
||||
emailRecipients,
|
||||
scheduleDate,
|
||||
scheduleTime,
|
||||
schedulingId,
|
||||
editMode: true,
|
||||
}),
|
||||
);
|
||||
};
|
||||
return (
|
||||
<>
|
||||
<TaskAlertModal
|
||||
isOpen={isConfirmModalOpen}
|
||||
close={(event) => {
|
||||
closeConfirmModal();
|
||||
if (event.target.name === 'continue') {
|
||||
handleDeleteEmail();
|
||||
}
|
||||
}}
|
||||
alertMessage={intl.formatMessage(
|
||||
messages.bulkEmailScheduledEmailsTableConfirmDelete,
|
||||
{ date: currentTask?.row?.original?.taskDue ?? '' },
|
||||
)}
|
||||
/>
|
||||
{viewModal.isOpen && (
|
||||
<ViewEmailModal
|
||||
isOpen={viewModal.isOpen}
|
||||
setModalOpen={(open) => setViewModal({ isOpen: open })}
|
||||
messageContent={viewModal.messageContent}
|
||||
/>
|
||||
)}
|
||||
<div className="pb-4">
|
||||
<DataTable
|
||||
isLoading={scheduledEmailsTable.isLoading}
|
||||
itemCount={scheduledEmailsTable.count}
|
||||
pageCount={scheduledEmailsTable.numPages}
|
||||
data={tableData}
|
||||
isPaginated
|
||||
manualPagination
|
||||
fetchData={fetchTableData}
|
||||
initialState={{
|
||||
pageSize: 10,
|
||||
pageIndex: 0,
|
||||
}}
|
||||
columns={[
|
||||
{
|
||||
Header: intl.formatMessage(messages.bulkEmailScheduledEmailsTableSendDate),
|
||||
accessor: 'taskDue',
|
||||
},
|
||||
{
|
||||
Header: intl.formatMessage(messages.bulkEmailScheduledEmailsTableSendTo),
|
||||
accessor: 'targets',
|
||||
},
|
||||
{
|
||||
Header: intl.formatMessage(messages.bulkEmailScheduledEmailsTableSubject),
|
||||
accessor: 'subject',
|
||||
},
|
||||
{
|
||||
Header: intl.formatMessage(messages.bulkEmailScheduledEmailsTableAuthor),
|
||||
accessor: 'sender',
|
||||
},
|
||||
]}
|
||||
additionalColumns={[
|
||||
{
|
||||
id: 'action',
|
||||
Header: 'Action',
|
||||
Cell: ({
|
||||
row, state, page, previousPage,
|
||||
}) => (
|
||||
<>
|
||||
<IconButton src={Visibility} iconAs={Icon} alt="View" onClick={() => handleViewEmail(row)} />
|
||||
<IconButton
|
||||
src={Delete}
|
||||
iconAs={Icon}
|
||||
alt="Delete"
|
||||
onClick={() => {
|
||||
setCurrentTask({
|
||||
row, pageIndex: state.pageIndex, page, previousPage,
|
||||
});
|
||||
openConfirmModal();
|
||||
}}
|
||||
/>
|
||||
<IconButton src={Edit} iconAs={Icon} alt="Edit" onClick={() => handleEditEmail(row)} />
|
||||
</>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
BulkEmailScheduledEmailsTable.propTypes = {
|
||||
intl: intlShape.isRequired,
|
||||
};
|
||||
|
||||
export default injectIntl(BulkEmailScheduledEmailsTable);
|
||||
@@ -0,0 +1,31 @@
|
||||
export const fetchScheduledEmails = () => ({
|
||||
type: 'FETCH_SCHEDULED_EMAILS',
|
||||
});
|
||||
|
||||
export const fetchScheduledEmailsStart = () => ({
|
||||
type: 'FETCH_START',
|
||||
});
|
||||
|
||||
export const fetchScheduledEmailsComplete = (payload) => ({
|
||||
type: 'FETCH_COMPLETE',
|
||||
payload,
|
||||
});
|
||||
|
||||
export const fetchScheduledEmailsError = () => ({
|
||||
type: 'FETCH_FAILURE',
|
||||
});
|
||||
|
||||
export const deleteScheduledEmail = () => ({
|
||||
type: 'DELETE_SCHEDULED_EMAIL',
|
||||
});
|
||||
export const deleteScheduledEmailStart = () => ({
|
||||
type: 'DELETE_START',
|
||||
});
|
||||
|
||||
export const deleteScheduledEmailComplete = () => ({
|
||||
type: 'DELETE_COMPLETE',
|
||||
});
|
||||
|
||||
export const deleteScheduledEmailError = () => ({
|
||||
type: 'DELETE_FAILURE',
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
import { camelCaseObject, getConfig } from '@edx/frontend-platform';
|
||||
import { getAuthenticatedHttpClient } from '@edx/frontend-platform/auth';
|
||||
import { logError } from '@edx/frontend-platform/logging';
|
||||
|
||||
// eslint-disable-next-line import/prefer-default-export
|
||||
export async function getScheduledBulkEmailIntructorTaskData(courseId, page = 1) {
|
||||
const endpointUrl = `${
|
||||
getConfig().LMS_BASE_URL
|
||||
}/api/instructor_task/v1/schedules/${courseId}/bulk_email/?page=${page}`;
|
||||
try {
|
||||
const { data } = await getAuthenticatedHttpClient().get(endpointUrl);
|
||||
return camelCaseObject(data);
|
||||
} catch (error) {
|
||||
logError(error);
|
||||
throw new Error(error);
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteScheduledBulkEmailInstructorTask(courseId, scheduleId) {
|
||||
const endpointUrl = `${getConfig().LMS_BASE_URL}/api/instructor_task/v1/schedules/${courseId}/bulk_email/${scheduleId}`;
|
||||
try {
|
||||
const { status } = await getAuthenticatedHttpClient().delete(endpointUrl);
|
||||
return status;
|
||||
} catch (error) {
|
||||
logError(error);
|
||||
throw new Error(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
export function scheduledEmailsTableReducer(state, action) {
|
||||
switch (action.type) {
|
||||
case 'FETCH_SCHEDULED_EMAILS':
|
||||
return state;
|
||||
case 'FETCH_START':
|
||||
return {
|
||||
...state,
|
||||
isLoading: true,
|
||||
};
|
||||
case 'FETCH_COMPLETE':
|
||||
return {
|
||||
...state,
|
||||
isLoading: false,
|
||||
errorRetrievingData: false,
|
||||
...action.payload,
|
||||
};
|
||||
case 'FETCH_FAILURE':
|
||||
return {
|
||||
...state,
|
||||
isLoading: false,
|
||||
errorRetrievingData: true,
|
||||
};
|
||||
case 'DELETE_SCHEDULED_EMAIL':
|
||||
return state;
|
||||
case 'DELETE_START':
|
||||
return {
|
||||
...state,
|
||||
isLoading: true,
|
||||
};
|
||||
case 'DELETE_COMPLETE':
|
||||
return {
|
||||
...state,
|
||||
isLoading: false,
|
||||
errorRetrievingData: false,
|
||||
...action.payload,
|
||||
};
|
||||
case 'DELETE_FAILURE':
|
||||
return {
|
||||
...state,
|
||||
isLoading: false,
|
||||
errorRetrievingData: true,
|
||||
};
|
||||
default:
|
||||
return state;
|
||||
}
|
||||
}
|
||||
|
||||
export const scheduledEmailsTableInitialState = {
|
||||
results: [],
|
||||
isLoading: false,
|
||||
errorRetrievingData: false,
|
||||
count: 0,
|
||||
numPages: 0,
|
||||
currentPage: 0,
|
||||
start: 0,
|
||||
previous: null,
|
||||
next: null,
|
||||
};
|
||||
|
||||
export default scheduledEmailsTableReducer;
|
||||
@@ -0,0 +1,63 @@
|
||||
import { initializeMockApp } from '../../../../../../setupTest';
|
||||
import { scheduledEmailsTableReducer } from '../reducer';
|
||||
|
||||
describe('scheduledEmailsTableReducer', () => {
|
||||
const testState = {
|
||||
scheduledEmails: [],
|
||||
isLoading: false,
|
||||
errorRetrievingData: false,
|
||||
};
|
||||
beforeAll(async () => {
|
||||
await initializeMockApp();
|
||||
});
|
||||
|
||||
it('does not change state on FETCH_SCHEDULED_EMAILS', () => {
|
||||
expect(scheduledEmailsTableReducer(testState, { type: 'FETCH_SCHEDULED_EMAILS' })).toEqual(testState);
|
||||
});
|
||||
it('sets loading state on FETCH_START', () => {
|
||||
const finalState = {
|
||||
...testState,
|
||||
isLoading: true,
|
||||
};
|
||||
const returnedState = scheduledEmailsTableReducer(testState, { type: 'FETCH_START' });
|
||||
expect(returnedState).toEqual(finalState);
|
||||
});
|
||||
it('adds payload on FETCH_COMPLETE', () => {
|
||||
const finalState = {
|
||||
...testState,
|
||||
additionalField: true,
|
||||
isLoading: false,
|
||||
};
|
||||
const returnedState = scheduledEmailsTableReducer(testState, { type: 'FETCH_COMPLETE', payload: { additionalField: true } });
|
||||
expect(returnedState).toEqual(finalState);
|
||||
expect(returnedState.isLoading).toEqual(false);
|
||||
expect(returnedState.errorRetrievingData).toEqual(false);
|
||||
});
|
||||
it('sets Error to true when FETCH_FAILURE action dispatched', () => {
|
||||
const finalState = {
|
||||
...testState,
|
||||
isLoading: false,
|
||||
errorRetrievingData: true,
|
||||
};
|
||||
const returnedState = scheduledEmailsTableReducer(testState, { type: 'FETCH_FAILURE' });
|
||||
expect(returnedState).toEqual(finalState);
|
||||
});
|
||||
it('properly sets state on DELETE_COMPLETE', () => {
|
||||
const finalState = {
|
||||
...testState,
|
||||
};
|
||||
const returnedState = scheduledEmailsTableReducer(testState, { type: 'DELETE_COMPLETE' });
|
||||
expect(returnedState).toEqual(finalState);
|
||||
expect(returnedState.isLoading).toEqual(false);
|
||||
expect(returnedState.errorRetrievingData).toEqual(false);
|
||||
});
|
||||
it('sets Error when DELETE_FAILURE action dispatched', () => {
|
||||
const finalState = {
|
||||
...testState,
|
||||
isLoading: false,
|
||||
errorRetrievingData: true,
|
||||
};
|
||||
const returnedState = scheduledEmailsTableReducer(testState, { type: 'DELETE_FAILURE' });
|
||||
expect(returnedState).toEqual(finalState);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,53 @@
|
||||
import {
|
||||
deleteScheduledEmail,
|
||||
deleteScheduledEmailComplete,
|
||||
deleteScheduledEmailError,
|
||||
deleteScheduledEmailStart,
|
||||
fetchScheduledEmails,
|
||||
fetchScheduledEmailsComplete,
|
||||
fetchScheduledEmailsError,
|
||||
fetchScheduledEmailsStart,
|
||||
} from './actions';
|
||||
import { deleteScheduledBulkEmailInstructorTask, getScheduledBulkEmailIntructorTaskData } from './api';
|
||||
|
||||
export function getScheduledBulkEmailThunk(courseId, page) {
|
||||
return async (dispatch) => {
|
||||
dispatch(fetchScheduledEmails());
|
||||
dispatch(fetchScheduledEmailsStart());
|
||||
function onComplete(data) {
|
||||
dispatch(fetchScheduledEmailsComplete(data));
|
||||
return data;
|
||||
}
|
||||
function onError(error) {
|
||||
dispatch(fetchScheduledEmailsError());
|
||||
return error;
|
||||
}
|
||||
try {
|
||||
const data = await getScheduledBulkEmailIntructorTaskData(courseId, page);
|
||||
return onComplete(data);
|
||||
} catch (error) {
|
||||
return onError(error);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function deleteScheduledEmailThunk(courseId, emailIndex) {
|
||||
return async (dispatch) => {
|
||||
dispatch(deleteScheduledEmail());
|
||||
dispatch(deleteScheduledEmailStart());
|
||||
function onComplete(data) {
|
||||
dispatch(deleteScheduledEmailComplete(data));
|
||||
return data;
|
||||
}
|
||||
function onError(error) {
|
||||
dispatch(deleteScheduledEmailError());
|
||||
return error;
|
||||
}
|
||||
try {
|
||||
const status = await deleteScheduledBulkEmailInstructorTask(courseId, emailIndex);
|
||||
return onComplete(status);
|
||||
} catch (error) {
|
||||
return onError(error);
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { default } from './BulkEmailScheduledEmailsTable';
|
||||
@@ -0,0 +1,37 @@
|
||||
import { defineMessages } from '@edx/frontend-platform/i18n';
|
||||
|
||||
const messages = defineMessages({
|
||||
/* BulkEmailScheduledEmailsTable.jsx Messages */
|
||||
bulkEmailScheduledEmailsTableErrorHeader: {
|
||||
id: 'bulk.email.scheduled.emails.table.error.header',
|
||||
defaultMessage: 'Error',
|
||||
},
|
||||
|
||||
bulkEmailScheduledEmailsTableError: {
|
||||
id: 'bulk.email.scheduled.emails.table.error',
|
||||
defaultMessage: 'An error occured while retrieving scheduled email information. Please try again later.',
|
||||
description: 'An error message that shows if the app is unable to display scheduled emails in the table',
|
||||
},
|
||||
bulkEmailScheduledEmailsTableSendDate: {
|
||||
id: 'bulk.email.scheduled.emails.table.sendDate',
|
||||
defaultMessage: 'Send date',
|
||||
},
|
||||
bulkEmailScheduledEmailsTableSendTo: {
|
||||
id: 'bulk.email.scheduled.emails.table.sendTo',
|
||||
defaultMessage: 'Send to',
|
||||
},
|
||||
bulkEmailScheduledEmailsTableSubject: {
|
||||
id: 'bulk.email.scheduled.emails.table.subject',
|
||||
defaultMessage: 'Subject',
|
||||
},
|
||||
bulkEmailScheduledEmailsTableAuthor: {
|
||||
id: 'bulk.email.scheduled.emails.table.Author',
|
||||
defaultMessage: 'Author',
|
||||
},
|
||||
bulkEmailScheduledEmailsTableConfirmDelete: {
|
||||
id: 'bulk.email.scheduled.emails.table.confirm.delete',
|
||||
defaultMessage: 'You are deleting an email scheduled to be sent on {date}. The email will not be sent and the scheduling canceled. Are you sure?',
|
||||
},
|
||||
});
|
||||
|
||||
export default messages;
|
||||
@@ -0,0 +1,141 @@
|
||||
/**
|
||||
* @jest-environment jsdom
|
||||
*/
|
||||
import React from 'react';
|
||||
import MockAdapter from 'axios-mock-adapter';
|
||||
import { Factory } from 'rosie';
|
||||
import { getAuthenticatedHttpClient } from '@edx/frontend-platform/auth';
|
||||
import { getConfig } from '@edx/frontend-platform';
|
||||
import {
|
||||
render, screen, cleanup, fireEvent, initializeMockApp,
|
||||
} from '../../../../../setupTest';
|
||||
import { BulkEmailProvider } from '../../../bulk-email-context';
|
||||
import BulkEmailScheduledEmailsTable from '..';
|
||||
import scheduledEmailsFactory from './__factories__/scheduledEmails.factory';
|
||||
import * as actions from '../../../bulk-email-form/data/actions';
|
||||
|
||||
jest.mock('react-router-dom', () => ({
|
||||
...jest.requireActual('react-router-dom'),
|
||||
useParams: jest.fn().mockReturnValue({ courseId: 'test-id' }),
|
||||
}));
|
||||
|
||||
function renderBulkEmailScheduledEmailsTable() {
|
||||
return (
|
||||
<BulkEmailProvider>
|
||||
<BulkEmailScheduledEmailsTable />
|
||||
</BulkEmailProvider>
|
||||
);
|
||||
}
|
||||
|
||||
describe('BulkEmailScheduledEmailsTable', () => {
|
||||
beforeAll(async () => {
|
||||
await initializeMockApp();
|
||||
});
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
Factory.resetAll();
|
||||
});
|
||||
|
||||
it('properly renders scheduled emails', async () => {
|
||||
const axiosMock = new MockAdapter(getAuthenticatedHttpClient());
|
||||
axiosMock
|
||||
.onGet(`${getConfig().LMS_BASE_URL}/api/instructor_task/v1/schedules/test-id/bulk_email/?page=1`)
|
||||
.reply(200, scheduledEmailsFactory.build(1));
|
||||
render(renderBulkEmailScheduledEmailsTable());
|
||||
expect(await screen.findByText('learners')).toBeTruthy();
|
||||
expect(await screen.findByText('subject')).toBeTruthy();
|
||||
expect(await screen.findByText('edx')).toBeTruthy();
|
||||
expect(await screen.findByLabelText('View')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('shows an error when the fetch fails', async () => {
|
||||
const axiosMock = new MockAdapter(getAuthenticatedHttpClient());
|
||||
axiosMock
|
||||
.onGet(`${getConfig().LMS_BASE_URL}/api/instructor_task/v1/schedules/test-id/bulk_email/?page=1`)
|
||||
.reply(500, { response: 500 });
|
||||
render(renderBulkEmailScheduledEmailsTable());
|
||||
expect(
|
||||
await screen.findByText('An error occured while retrieving scheduled email information. Please try again later.'),
|
||||
).toBeTruthy();
|
||||
});
|
||||
|
||||
it('pops up the modal when viewing an email', async () => {
|
||||
const axiosMock = new MockAdapter(getAuthenticatedHttpClient());
|
||||
axiosMock
|
||||
.onGet(`${getConfig().LMS_BASE_URL}/api/instructor_task/v1/schedules/test-id/bulk_email/?page=1`)
|
||||
.reply(200, scheduledEmailsFactory.build(1));
|
||||
render(renderBulkEmailScheduledEmailsTable());
|
||||
fireEvent.click(await screen.findByLabelText('View'));
|
||||
expect(await screen.findByText('Subject:')).toBeTruthy();
|
||||
expect(await screen.findByText('Sent by:')).toBeTruthy();
|
||||
expect(await screen.findByText('Time sent:')).toBeTruthy();
|
||||
expect(await screen.findByText('Sent to:')).toBeTruthy();
|
||||
expect(await screen.findByText('Message:')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('properly formats data for editing mode', async () => {
|
||||
const editorObj = {
|
||||
editMode: true,
|
||||
emailId: 1,
|
||||
emailBody: '<p>body</p>',
|
||||
emailSubject: 'subject',
|
||||
emailRecipients: ['learners'],
|
||||
scheduleDate: '2022-04-27',
|
||||
scheduleTime: '00:00',
|
||||
schedulingId: 1,
|
||||
};
|
||||
jest.spyOn(actions, 'copyToEditor');
|
||||
jest.spyOn(actions, 'setEditMode');
|
||||
const axiosMock = new MockAdapter(getAuthenticatedHttpClient());
|
||||
axiosMock
|
||||
.onGet(`${getConfig().LMS_BASE_URL}/api/instructor_task/v1/schedules/test-id/bulk_email/?page=1`)
|
||||
.reply(200, scheduledEmailsFactory.build(1));
|
||||
render(renderBulkEmailScheduledEmailsTable());
|
||||
fireEvent.click(await screen.findByLabelText('Edit'));
|
||||
expect(actions.copyToEditor).toHaveBeenCalledWith(editorObj);
|
||||
});
|
||||
it('pops up alert on delete pressed', async () => {
|
||||
const axiosMock = new MockAdapter(getAuthenticatedHttpClient());
|
||||
axiosMock
|
||||
.onGet(`${getConfig().LMS_BASE_URL}/api/instructor_task/v1/schedules/test-id/bulk_email/?page=1`)
|
||||
.replyOnce(200, scheduledEmailsFactory.build(1))
|
||||
.onGet(`${getConfig().LMS_BASE_URL}/api/instructor_task/v1/schedules/test-id/bulk_email/?page=1`)
|
||||
.replyOnce(200, {
|
||||
next: null,
|
||||
previous: null,
|
||||
count: 0,
|
||||
num_pages: 1,
|
||||
current_page: 1,
|
||||
start: 0,
|
||||
results: [],
|
||||
})
|
||||
.onDelete(`${getConfig().LMS_BASE_URL}/api/instructor_task/v1/schedules/test-id/bulk_email/1`)
|
||||
.reply(204, []);
|
||||
render(renderBulkEmailScheduledEmailsTable());
|
||||
fireEvent.click(await screen.findByLabelText('Delete'));
|
||||
expect(await screen.findByText('Caution')).toBeInTheDocument();
|
||||
});
|
||||
it('Deletes an email when clicking continue on warning', async () => {
|
||||
const axiosMock = new MockAdapter(getAuthenticatedHttpClient());
|
||||
axiosMock
|
||||
.onGet(`${getConfig().LMS_BASE_URL}/api/instructor_task/v1/schedules/test-id/bulk_email/?page=1`)
|
||||
.replyOnce(200, scheduledEmailsFactory.build(1))
|
||||
.onGet(`${getConfig().LMS_BASE_URL}/api/instructor_task/v1/schedules/test-id/bulk_email/?page=1`)
|
||||
.replyOnce(200, {
|
||||
next: null,
|
||||
previous: null,
|
||||
count: 0,
|
||||
num_pages: 1,
|
||||
current_page: 1,
|
||||
start: 0,
|
||||
results: [],
|
||||
})
|
||||
.onDelete(`${getConfig().LMS_BASE_URL}/api/instructor_task/v1/schedules/test-id/bulk_email/1`)
|
||||
.reply(204, []);
|
||||
render(renderBulkEmailScheduledEmailsTable());
|
||||
fireEvent.click(await screen.findByLabelText('Delete'));
|
||||
expect(await screen.findByText('Caution')).toBeInTheDocument();
|
||||
fireEvent.click(await screen.findByText('Continue'));
|
||||
expect(await screen.findByText('No results found')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
import { Factory } from 'rosie'; // eslint-disable-line import/no-extraneous-dependencies
|
||||
|
||||
Factory.define('emailDataFactory')
|
||||
.sequence('id')
|
||||
.attrs({
|
||||
subject: 'subject',
|
||||
html_message: '<p>body</p>',
|
||||
text_message: 'body',
|
||||
course_id: 'course-v1:edX+DemoX+Demo_Course',
|
||||
to_option: '',
|
||||
sender: 'edx',
|
||||
targets: ['learners'],
|
||||
});
|
||||
|
||||
export default Factory.define('courseEmailFactory')
|
||||
.sequence('id')
|
||||
.attr('course_email', Factory.build('emailDataFactory'))
|
||||
.sequence('task')
|
||||
.attr('task_due', '2022-04-27T00:00:00Z');
|
||||
@@ -0,0 +1,19 @@
|
||||
import { Factory } from 'rosie'; // eslint-disable-line import/no-extraneous-dependencies
|
||||
import './courseEmail.factory';
|
||||
|
||||
export default Factory.define('scheduledEmailFactory')
|
||||
.attr(
|
||||
'next',
|
||||
'http://localhost:18000/api/instructor_task/v1/schedules/course-v1:edX+DemoX+Demo_Course/bulk_email/?page=$2',
|
||||
)
|
||||
.attr('previous', 'null')
|
||||
.option('count', '1')
|
||||
.attr('current_page', 1)
|
||||
.attr('start', 0)
|
||||
.attr('results', ['count'], (count) => {
|
||||
const emails = [];
|
||||
for (let i = 1; i <= count; i++) {
|
||||
emails.push(Factory.build('courseEmailFactory'));
|
||||
}
|
||||
return emails;
|
||||
});
|
||||
@@ -0,0 +1,4 @@
|
||||
// Apply side scroll for table that overflows
|
||||
div.collapsible-body {
|
||||
overflow: auto;
|
||||
}
|
||||
@@ -60,7 +60,7 @@ const messages = defineMessages({
|
||||
},
|
||||
emailHistoryTableSectionButtonHeader: {
|
||||
id: 'bulk.email.content.history.table.button.header',
|
||||
defaultMessage: 'To see the content of previously sent emails, click this button:',
|
||||
defaultMessage: 'View the content of previously sent emails',
|
||||
},
|
||||
emailHistoryTableSectionButton: {
|
||||
id: 'bulk.email.content.history.table.button',
|
||||
@@ -69,7 +69,7 @@ const messages = defineMessages({
|
||||
/* BulkEmailTaskManager.jsx messages */
|
||||
pendingTasksHeader: {
|
||||
id: 'bulk.email.pending.tasks.header',
|
||||
defaultMessage: 'Pending Tasks',
|
||||
defaultMessage: 'Pending tasks has moved',
|
||||
},
|
||||
emailTaskHistoryHeader: {
|
||||
id: 'bulk.email.email.task.history.header',
|
||||
@@ -91,7 +91,7 @@ const messages = defineMessages({
|
||||
/* BulkEmailTaskHistory.jsx messages */
|
||||
emailTaskHistoryTableSectionButtonHeader: {
|
||||
id: 'bulk.email.task.history.table.button.header',
|
||||
defaultMessage: 'To see the status for all email tasks submitted for this course, click this button:',
|
||||
defaultMessage: 'View the status for all email tasks created for this course',
|
||||
},
|
||||
emailTaskHistoryTableSectionButton: {
|
||||
id: 'bulk.email.task.history.table.button',
|
||||
@@ -142,6 +142,10 @@ const messages = defineMessages({
|
||||
id: 'bulk.email.task.history.table.column.header.taskProgress',
|
||||
defaultMessage: 'Task Progress',
|
||||
},
|
||||
scheduledEmailsTableHeader: {
|
||||
id: 'bulk.email.scheduled.emails.table.header',
|
||||
defaultMessage: 'Scheduled emails',
|
||||
},
|
||||
});
|
||||
|
||||
export default messages;
|
||||
|
||||
@@ -3,8 +3,9 @@
|
||||
*/
|
||||
import React from 'react';
|
||||
import {
|
||||
render, screen, fireEvent, cleanup, act,
|
||||
render, screen, fireEvent, cleanup, act, initializeMockApp,
|
||||
} from '../../../../setupTest';
|
||||
import { BulkEmailProvider } from '../../bulk-email-context';
|
||||
import BulkEmailContentHistory from '../BulkEmailContentHistory';
|
||||
import { getSentEmailHistory } from '../data/api';
|
||||
import buildEmailContentHistoryData from '../data/__factories__/emailContentHistory.factory';
|
||||
@@ -14,14 +15,25 @@ jest.mock('../data/api', () => ({
|
||||
getSentEmailHistory: jest.fn(() => {}),
|
||||
}));
|
||||
|
||||
function renderBulkEmailContentHistory() {
|
||||
return (
|
||||
<BulkEmailProvider>
|
||||
<BulkEmailContentHistory courseId="test-course-id" />
|
||||
</BulkEmailProvider>
|
||||
);
|
||||
}
|
||||
|
||||
describe('BulkEmailContentHistory component', () => {
|
||||
beforeEach(() => jest.resetModules());
|
||||
beforeAll(async () => {
|
||||
await initializeMockApp();
|
||||
});
|
||||
afterEach(cleanup);
|
||||
|
||||
test('renders correctly', async () => {
|
||||
render(<BulkEmailContentHistory copyTextToEditor={jest.fn()} />);
|
||||
render(renderBulkEmailContentHistory());
|
||||
const tableDescription = await screen.findByText(
|
||||
'To see the content of previously sent emails, click this button:',
|
||||
'View the content of previously sent emails',
|
||||
);
|
||||
expect(tableDescription).toBeTruthy();
|
||||
const showEmailContentHistoryButton = await screen.findByText('Show Sent Email History');
|
||||
@@ -33,7 +45,7 @@ describe('BulkEmailContentHistory component', () => {
|
||||
const emailHistoryData = buildEmailContentHistoryData(1);
|
||||
getSentEmailHistory.mockImplementation(() => emailHistoryData);
|
||||
|
||||
render(<BulkEmailContentHistory copyTextToEditor={jest.fn()} />);
|
||||
render(renderBulkEmailContentHistory());
|
||||
|
||||
const showEmailContentHistoryButton = await screen.findByText('Show Sent Email History');
|
||||
fireEvent.click(showEmailContentHistoryButton);
|
||||
@@ -59,6 +71,8 @@ describe('BulkEmailContentHistory component', () => {
|
||||
expect(await screen.findByText(email.requester)).toBeTruthy();
|
||||
expect(await screen.findByText(email.sent_to.join(', '))).toBeTruthy();
|
||||
expect(await screen.findByText(email.email.subject)).toBeTruthy();
|
||||
// verify screen reader only <span />
|
||||
expect(await screen.findByText('0')).toHaveClass('sr-only');
|
||||
expect(await screen.findAllByText('View Message')).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -68,7 +82,7 @@ describe('BulkEmailContentHistory component', () => {
|
||||
const emailHistoryData = buildEmailContentHistoryData(1);
|
||||
getSentEmailHistory.mockImplementation(() => emailHistoryData);
|
||||
|
||||
render(<BulkEmailContentHistory copyTextToEditor={jest.fn()} />);
|
||||
render(renderBulkEmailContentHistory());
|
||||
|
||||
const showEmailContentHistoryButton = await screen.findByText('Show Sent Email History');
|
||||
fireEvent.click(showEmailContentHistoryButton);
|
||||
@@ -101,7 +115,7 @@ describe('BulkEmailContentHistory component', () => {
|
||||
const emailHistoryData = buildEmailContentHistoryData(0);
|
||||
getSentEmailHistory.mockImplementation(() => emailHistoryData);
|
||||
// render the component
|
||||
render(<BulkEmailContentHistory copyTextToEditor={jest.fn()} />);
|
||||
render(renderBulkEmailContentHistory());
|
||||
// press the `show sent email history` button to initiate data retrieval
|
||||
const showEmailContentHistoryButton = await screen.findByText('Show Sent Email History');
|
||||
fireEvent.click(showEmailContentHistoryButton);
|
||||
@@ -117,7 +131,7 @@ describe('BulkEmailContentHistory component', () => {
|
||||
throw new Error();
|
||||
});
|
||||
// render the component
|
||||
render(<BulkEmailContentHistory copyTextToEditor={jest.fn()} />);
|
||||
render(renderBulkEmailContentHistory());
|
||||
// press the `show sent email history` button to initiate data retrieval
|
||||
const showEmailContentHistoryButton = await screen.findByText('Show Sent Email History');
|
||||
fireEvent.click(showEmailContentHistoryButton);
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
*/
|
||||
import React from 'react';
|
||||
import {
|
||||
render, screen, cleanup, act,
|
||||
render, screen, cleanup, act, initializeMockApp,
|
||||
} from '../../../../setupTest';
|
||||
import BulkEmailPendingTasks from '../BulkEmailPendingTasks';
|
||||
import { getInstructorTasks } from '../data/api';
|
||||
@@ -16,6 +16,9 @@ jest.mock('../data/api', () => ({
|
||||
|
||||
describe('BulkEmailPendingTasks component', () => {
|
||||
beforeEach(() => jest.resetModules());
|
||||
beforeAll(async () => {
|
||||
await initializeMockApp();
|
||||
});
|
||||
afterEach(cleanup);
|
||||
|
||||
test('renders correctly', async () => {
|
||||
@@ -27,68 +30,72 @@ describe('BulkEmailPendingTasks component', () => {
|
||||
});
|
||||
|
||||
test('renders a table when running Instructor Task data is returned', async () => {
|
||||
await act(async () => {
|
||||
jest.useFakeTimers();
|
||||
jest.useFakeTimers();
|
||||
|
||||
const pendingInstructorTaskData = buildPendingInstructorTaskData(1);
|
||||
getInstructorTasks.mockImplementation(() => pendingInstructorTaskData);
|
||||
const pendingInstructorTaskData = buildPendingInstructorTaskData(1);
|
||||
getInstructorTasks.mockImplementation(() => pendingInstructorTaskData);
|
||||
|
||||
act(() => {
|
||||
render(<BulkEmailPendingTasks />);
|
||||
});
|
||||
|
||||
act(() => {
|
||||
// fast forward time by 31 seconds for the API call to be made to retrieve pending tasks
|
||||
jest.advanceTimersByTime(31000);
|
||||
|
||||
// verify component structure
|
||||
const tableDescription = await screen.findByText(
|
||||
'Email actions run in the background. The status for any active tasks - including email tasks - appears in '
|
||||
+ 'the table below.',
|
||||
);
|
||||
expect(tableDescription).toBeTruthy();
|
||||
|
||||
// verify table structure
|
||||
expect(await screen.findByText('Task Type')).toBeTruthy();
|
||||
expect(await screen.findByText('Task Inputs')).toBeTruthy();
|
||||
expect(await screen.findByText('Task Id')).toBeTruthy();
|
||||
expect(await screen.findByText('Requester')).toBeTruthy();
|
||||
expect(await screen.findByText('Submitted')).toBeTruthy();
|
||||
expect(await screen.findByText('Duration (seconds)')).toBeTruthy();
|
||||
expect(await screen.findByText('State')).toBeTruthy();
|
||||
expect(await screen.findByText('Status')).toBeTruthy();
|
||||
expect(await screen.findByText('Task Progress')).toBeTruthy();
|
||||
expect(await screen.findAllByText('Showing 1 of 1')).toBeTruthy();
|
||||
|
||||
// verification of table contents
|
||||
const { tasks } = pendingInstructorTaskData;
|
||||
const task = tasks[0];
|
||||
expect(await screen.findByText(task.created)).toBeTruthy();
|
||||
expect(await screen.findByText(task.duration_sec)).toBeTruthy();
|
||||
expect(await screen.findByText(task.requester)).toBeTruthy();
|
||||
expect(await screen.findByText(task.status)).toBeTruthy();
|
||||
expect(await screen.findByText(task.task_id)).toBeTruthy();
|
||||
expect(await screen.findByText(task.task_input)).toBeTruthy();
|
||||
expect(await screen.findByText(task.task_message)).toBeTruthy();
|
||||
expect(await screen.findByText(task.task_state)).toBeTruthy();
|
||||
expect(await screen.findByText(task.task_type)).toBeTruthy();
|
||||
});
|
||||
|
||||
// verify component structure
|
||||
const tableDescription = await screen.findByText(
|
||||
'Email actions run in the background. The status for any active tasks - including email tasks - appears in '
|
||||
+ 'the table below.',
|
||||
);
|
||||
expect(tableDescription).toBeTruthy();
|
||||
|
||||
// verify table structure
|
||||
expect(await screen.findByText('Task Type')).toBeTruthy();
|
||||
expect(await screen.findByText('Task Inputs')).toBeTruthy();
|
||||
expect(await screen.findByText('Task Id')).toBeTruthy();
|
||||
expect(await screen.findByText('Requester')).toBeTruthy();
|
||||
expect(await screen.findByText('Submitted')).toBeTruthy();
|
||||
expect(await screen.findByText('Duration (seconds)')).toBeTruthy();
|
||||
expect(await screen.findByText('State')).toBeTruthy();
|
||||
expect(await screen.findByText('Status')).toBeTruthy();
|
||||
expect(await screen.findByText('Task Progress')).toBeTruthy();
|
||||
expect(await screen.findAllByText('Showing 1 of 1.')).toBeTruthy();
|
||||
|
||||
// verification of table contents
|
||||
const { tasks } = pendingInstructorTaskData;
|
||||
const task = tasks[0];
|
||||
expect(await screen.findByText(task.created)).toBeTruthy();
|
||||
expect(await screen.findByText(task.duration_sec)).toBeTruthy();
|
||||
expect(await screen.findByText(task.requester)).toBeTruthy();
|
||||
expect(await screen.findByText(task.status)).toBeTruthy();
|
||||
expect(await screen.findByText(task.task_id)).toBeTruthy();
|
||||
expect(await screen.findByText(task.task_input)).toBeTruthy();
|
||||
expect(await screen.findByText(task.task_message)).toBeTruthy();
|
||||
expect(await screen.findByText(task.task_state)).toBeTruthy();
|
||||
expect(await screen.findByText(task.task_type)).toBeTruthy();
|
||||
});
|
||||
|
||||
test('renders an error Alert if an error occurs retrieving data', async () => {
|
||||
await act(async () => {
|
||||
jest.useFakeTimers();
|
||||
jest.useFakeTimers();
|
||||
|
||||
getInstructorTasks.mockImplementation(() => {
|
||||
throw new Error();
|
||||
});
|
||||
getInstructorTasks.mockImplementation(() => {
|
||||
throw new Error();
|
||||
});
|
||||
|
||||
act(() => {
|
||||
render(<BulkEmailPendingTasks />);
|
||||
});
|
||||
|
||||
act(() => {
|
||||
// fast forward time by 31 seconds for the API call to be made to retrieve pending tasks
|
||||
jest.advanceTimersByTime(31000);
|
||||
|
||||
const alertMessage = await screen.findByText(
|
||||
'Error fetching running task data. This request will be retried automatically.',
|
||||
);
|
||||
expect(alertMessage).toBeTruthy();
|
||||
});
|
||||
|
||||
const alertMessage = await screen.findByText(
|
||||
'Error fetching running task data. This request will be retried automatically.',
|
||||
);
|
||||
expect(alertMessage).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
*/
|
||||
import React from 'react';
|
||||
import {
|
||||
render, screen, fireEvent, cleanup, act,
|
||||
render, screen, fireEvent, cleanup, act, initializeMockApp,
|
||||
} from '../../../../setupTest';
|
||||
import BulkEmailTaskHistory from '../BulkEmailTaskHistory';
|
||||
import { getEmailTaskHistory } from '../data/api';
|
||||
@@ -16,12 +16,15 @@ jest.mock('../data/api', () => ({
|
||||
|
||||
describe('BulkEmailTaskHistory component', () => {
|
||||
beforeEach(() => jest.resetModules());
|
||||
beforeAll(async () => {
|
||||
await initializeMockApp();
|
||||
});
|
||||
afterEach(cleanup);
|
||||
|
||||
test('renders correctly ', async () => {
|
||||
render(<BulkEmailTaskHistory />);
|
||||
const tableDescription = await screen.findByText(
|
||||
'To see the status for all email tasks submitted for this course, click this button:',
|
||||
'View the status for all email tasks created for this course',
|
||||
);
|
||||
expect(tableDescription).toBeTruthy();
|
||||
const showEmailTaskHistoryButton = await screen.findByText('Show Email Task History');
|
||||
@@ -48,7 +51,7 @@ describe('BulkEmailTaskHistory component', () => {
|
||||
expect(await screen.findByText('State')).toBeTruthy();
|
||||
expect(await screen.findByText('Status')).toBeTruthy();
|
||||
expect(await screen.findByText('Task Progress')).toBeTruthy();
|
||||
expect(await screen.findAllByText('Showing 1 of 1')).toBeTruthy();
|
||||
expect(await screen.findAllByText('Showing 1 of 1.')).toBeTruthy();
|
||||
// verification of row contents
|
||||
const { tasks } = taskHistoryData;
|
||||
const task = tasks[0];
|
||||
|
||||
@@ -35,7 +35,14 @@ function TaskAlertModal(props) {
|
||||
id="bulk.email.form.recipients.Contine"
|
||||
defaultMessage="Continue"
|
||||
description="Continue button for the task alert"
|
||||
/>
|
||||
>
|
||||
{ // FormattedMessage wraps the translated string in a <span/> by default. This was
|
||||
// causing strange click event target issues in safari. To solve this, we want to
|
||||
// wrap the string in a fragment instead of a span, so that the whole button considered
|
||||
// a "button" target, and not a "span inside a button"
|
||||
msg => <>{msg}</>
|
||||
}
|
||||
</FormattedMessage>
|
||||
</Button>
|
||||
</ActionRow>
|
||||
)}
|
||||
1
src/components/bulk-email-tool/task-alert-modal/index.js
Normal file
1
src/components/bulk-email-tool/task-alert-modal/index.js
Normal file
@@ -0,0 +1 @@
|
||||
export { default } from './TaskAlertModal';
|
||||
@@ -3,7 +3,10 @@
|
||||
*/
|
||||
import React from 'react';
|
||||
import { Factory } from 'rosie';
|
||||
import { render, screen, cleanup } from '../../../setupTest';
|
||||
import { camelCaseObject } from '@edx/frontend-platform';
|
||||
import {
|
||||
render, screen, cleanup, initializeMockApp,
|
||||
} from '../../../setupTest';
|
||||
import BulkEmailTool from '../BulkEmailTool';
|
||||
import { CourseMetadataContext } from '../../page-container/PageContainer';
|
||||
import '../../page-container/data/__factories__/cohort.factory';
|
||||
@@ -23,6 +26,9 @@ jest.mock('react-router-dom', () => ({
|
||||
|
||||
describe('BulkEmailTool', () => {
|
||||
beforeEach(() => jest.resetModules());
|
||||
beforeAll(async () => {
|
||||
await initializeMockApp();
|
||||
});
|
||||
afterEach(cleanup);
|
||||
|
||||
/**
|
||||
@@ -31,15 +37,15 @@ describe('BulkEmailTool', () => {
|
||||
*/
|
||||
function buildCourseMetadata(cohortData, courseData) {
|
||||
const {
|
||||
org, number, title, tabs, is_staff: isStaff,
|
||||
} = courseData;
|
||||
org, number, title, tabs, originalUserIsStaff,
|
||||
} = camelCaseObject(courseData);
|
||||
const { cohorts } = cohortData;
|
||||
|
||||
return {
|
||||
org,
|
||||
number,
|
||||
title,
|
||||
isStaff,
|
||||
originalUserIsStaff,
|
||||
tabs: [...tabs],
|
||||
cohorts: cohorts.map(({ name }) => name),
|
||||
};
|
||||
@@ -73,7 +79,7 @@ describe('BulkEmailTool', () => {
|
||||
|
||||
test('BulkEmailTool renders error page on no staff user', async () => {
|
||||
const cohorts = { cohorts: [] };
|
||||
const courseInfo = Factory.build('courseMetadata', { is_staff: false });
|
||||
const courseInfo = Factory.build('courseMetadata', { original_user_is_staff: false });
|
||||
const courseMetadata = buildCourseMetadata(cohorts, courseInfo);
|
||||
renderBulkEmailTool(courseMetadata);
|
||||
// verify error page is displayed for user without staff permissions
|
||||
|
||||
@@ -22,7 +22,7 @@ import contentCss from 'tinymce/skins/content/default/content.css';
|
||||
|
||||
export default function TextEditor(props) {
|
||||
const {
|
||||
onChange, onKeyUp, onInit, disabled,
|
||||
onChange, onKeyUp, onInit, disabled, value,
|
||||
} = props;
|
||||
|
||||
return (
|
||||
@@ -33,17 +33,19 @@ export default function TextEditor(props) {
|
||||
height: 600,
|
||||
branding: false,
|
||||
menubar: 'edit view insert format table tools',
|
||||
plugins: 'advlist code link lists table image language codesample',
|
||||
plugins: 'advlist code link lists table image codesample',
|
||||
toolbar:
|
||||
'formatselect fontselect bold italic underline forecolor | codesample bullist numlist alignleft aligncenter alignright alignjustify indent | blockquote link image code | language',
|
||||
'formatselect fontselect bold italic underline forecolor | codesample bullist numlist alignleft aligncenter alignright alignjustify indent | blockquote link image code ',
|
||||
skin: false,
|
||||
content_css: false,
|
||||
content_style: `${contentUiCss.toString()}\n${contentCss.toString()}`,
|
||||
extended_valid_elements: 'span[lang|id] -span',
|
||||
block_unsupported_drop: false,
|
||||
image_advtab: true,
|
||||
name: 'emailBody',
|
||||
}}
|
||||
onChange={onChange}
|
||||
onEditorChange={onChange}
|
||||
value={value}
|
||||
onKeyUp={onKeyUp}
|
||||
onInit={onInit}
|
||||
disabled={disabled}
|
||||
@@ -56,6 +58,7 @@ TextEditor.defaultProps = {
|
||||
onKeyUp: () => {},
|
||||
onInit: () => {},
|
||||
disabled: false,
|
||||
value: '',
|
||||
};
|
||||
|
||||
TextEditor.propTypes = {
|
||||
@@ -63,4 +66,5 @@ TextEditor.propTypes = {
|
||||
onKeyUp: PropTypes.func,
|
||||
onInit: PropTypes.func,
|
||||
disabled: PropTypes.bool,
|
||||
value: PropTypes.string,
|
||||
};
|
||||
|
||||
@@ -1,23 +1,23 @@
|
||||
import React from 'react';
|
||||
import PropTypes from 'prop-types';
|
||||
|
||||
function MockTinyMCE({ onInit }) {
|
||||
const mockedEditor = {
|
||||
getContent: () => 'test body',
|
||||
};
|
||||
onInit({}, mockedEditor);
|
||||
|
||||
return <div />;
|
||||
/**
|
||||
* We represent tinyMCE here as a textarea, because tinyMCE has no support for testing
|
||||
* with jest, so we need to mock it out. This is not ideal, but since the TextEditor
|
||||
* component is really just a wrapper, we're not too concerned about unit testing.
|
||||
*/
|
||||
function MockTinyMCE({ onChange }) {
|
||||
return <textarea data-testid="textEditor" onChange={onChange} />;
|
||||
}
|
||||
|
||||
MockTinyMCE.propTypes = {
|
||||
onInit: PropTypes.func.isRequired,
|
||||
onChange: PropTypes.func.isRequired,
|
||||
};
|
||||
|
||||
export default function TextEditor({ onInit }) {
|
||||
return <MockTinyMCE onInit={onInit} />;
|
||||
export default function TextEditor({ onChange }) {
|
||||
return <MockTinyMCE onChange={onChange} />;
|
||||
}
|
||||
|
||||
TextEditor.propTypes = {
|
||||
onInit: PropTypes.func.isRequired,
|
||||
onChange: PropTypes.func.isRequired,
|
||||
};
|
||||
|
||||
26
src/components/navigation-tabs/BackToInstructor.jsx
Normal file
26
src/components/navigation-tabs/BackToInstructor.jsx
Normal file
@@ -0,0 +1,26 @@
|
||||
import React from 'react';
|
||||
|
||||
import { getConfig } from '@edx/frontend-platform';
|
||||
import { FormattedMessage } from '@edx/frontend-platform/i18n';
|
||||
import { Button, Icon } from '@edx/paragon';
|
||||
import { ArrowBack } from '@edx/paragon/icons';
|
||||
|
||||
export default function BackToInstructor() {
|
||||
return (
|
||||
<Button
|
||||
variant="tertiary"
|
||||
className="mb-4.5 ml-n4.5 text-primary-500"
|
||||
href={`${getConfig().LMS_BASE_URL}/courses/${window.location.pathname.split('/')[2]}/instructor#view-course-info`}
|
||||
>
|
||||
<Icon
|
||||
src={ArrowBack}
|
||||
className="mr-2"
|
||||
/>
|
||||
<FormattedMessage
|
||||
id="bulk.email.back.to.instructorDashboard"
|
||||
defaultMessage="Back to Instructor Dashboard"
|
||||
description="A link to take the user back to the instructor dashboard"
|
||||
/>
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
@@ -8,10 +8,12 @@ export default function NavigationTabs(props) {
|
||||
|
||||
return (
|
||||
<div className="py-4">
|
||||
<Nav>
|
||||
<Nav variant="tabs" defaultActiveKey="Instructor">
|
||||
{tabData && tabData.map(tab => (
|
||||
<Nav.Item key={tab.tab_id}>
|
||||
<Nav.Link eventKey={tab.url} href={tab.url} className="mx-3 py-2">{tab.title}</Nav.Link>
|
||||
<Nav.Link eventKey={tab.title} href={tab.url}>
|
||||
{tab.title}
|
||||
</Nav.Link>
|
||||
</Nav.Item>
|
||||
))}
|
||||
</Nav>
|
||||
|
||||
@@ -31,7 +31,7 @@ export default function PageContainer(props) {
|
||||
org: '',
|
||||
number: '',
|
||||
title: '',
|
||||
isStaff: false,
|
||||
originalUserIsStaff: false,
|
||||
tabs: [],
|
||||
cohorts: [],
|
||||
});
|
||||
@@ -39,7 +39,7 @@ export default function PageContainer(props) {
|
||||
}
|
||||
|
||||
const {
|
||||
org, number, title, tabs, is_staff: isStaff,
|
||||
org, number, title, tabs, originalUserIsStaff,
|
||||
} = metadataResponse;
|
||||
const { cohorts } = cohortsResponse;
|
||||
|
||||
@@ -47,7 +47,7 @@ export default function PageContainer(props) {
|
||||
org,
|
||||
number,
|
||||
title,
|
||||
isStaff,
|
||||
originalUserIsStaff,
|
||||
tabs: [...tabs],
|
||||
cohorts: cohorts.map(({ name }) => name),
|
||||
});
|
||||
@@ -65,7 +65,9 @@ export default function PageContainer(props) {
|
||||
courseNumber={courseMetadata.number}
|
||||
courseTitle={courseMetadata.title}
|
||||
/>
|
||||
{children}
|
||||
<main>
|
||||
{children}
|
||||
</main>
|
||||
<Footer />
|
||||
</>
|
||||
</CourseMetadataContext.Provider>
|
||||
|
||||
@@ -6,7 +6,7 @@ export default Factory.define('courseMetadata')
|
||||
.option('host', 'http://localhost:18000')
|
||||
.attrs({
|
||||
is_staff: true,
|
||||
original_user_is_staff: false,
|
||||
original_user_is_staff: true,
|
||||
number: 'DemoX',
|
||||
org: 'edX',
|
||||
title: 'Demonstration Course',
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { getConfig } from '@edx/frontend-platform';
|
||||
import { camelCaseObject, getConfig } from '@edx/frontend-platform';
|
||||
import { getAuthenticatedHttpClient } from '@edx/frontend-platform/auth';
|
||||
|
||||
const courseHomeBaseUrl = `${getConfig().LMS_BASE_URL}/api/course_home/v1/course_metadata`;
|
||||
@@ -6,7 +6,7 @@ const courseHomeBaseUrl = `${getConfig().LMS_BASE_URL}/api/course_home/v1/course
|
||||
export async function getCourseHomeCourseMetadata(courseId) {
|
||||
const courseHomeMetadataUrl = `${courseHomeBaseUrl}/${courseId}`;
|
||||
const { data } = await getAuthenticatedHttpClient().get(courseHomeMetadataUrl);
|
||||
return data;
|
||||
return camelCaseObject(data);
|
||||
}
|
||||
|
||||
export async function getCohorts(courseId) {
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
import React from 'react';
|
||||
import { Factory } from 'rosie';
|
||||
import {
|
||||
act, cleanup, render, screen,
|
||||
act, cleanup, initializeMockApp, render, screen,
|
||||
} from '../../../setupTest';
|
||||
|
||||
import PageContainer from '../PageContainer';
|
||||
@@ -26,6 +26,9 @@ jest.mock('react-router-dom', () => ({
|
||||
|
||||
describe('PageContainer', () => {
|
||||
beforeEach(() => jest.resetModules());
|
||||
beforeAll(async () => {
|
||||
await initializeMockApp();
|
||||
});
|
||||
afterEach(cleanup);
|
||||
|
||||
test('PageContainer renders properly when given course metadata', async () => {
|
||||
|
||||
@@ -39,13 +39,16 @@ subscribe(APP_INIT_ERROR, (error) => {
|
||||
});
|
||||
|
||||
initialize({
|
||||
config: () => {
|
||||
mergeConfig({
|
||||
}, 'CommuncationsAppConfig');
|
||||
handlers: {
|
||||
config: () => {
|
||||
mergeConfig(
|
||||
{
|
||||
// MICROBA-1505: Remove this when we remove the flag from config
|
||||
SCHEDULE_EMAIL_SECTION: process.env.SCHEDULE_EMAIL_SECTION || null,
|
||||
},
|
||||
'CommunicationsAppConfig',
|
||||
);
|
||||
},
|
||||
},
|
||||
messages: [
|
||||
appMessages,
|
||||
headerMessages,
|
||||
footerMessages,
|
||||
],
|
||||
messages: [appMessages, headerMessages, footerMessages],
|
||||
});
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
@import "@edx/brand/paragon/fonts.scss";
|
||||
@import "@edx/brand/paragon/variables.scss";
|
||||
@import "@edx/paragon/scss/core/core.scss";
|
||||
@import "@edx/brand/paragon/overrides.scss";
|
||||
|
||||
@import "~@edx/brand/paragon/fonts";
|
||||
@import "~@edx/brand/paragon/variables";
|
||||
@import "~@edx/paragon/scss/core/core";
|
||||
@import "~@edx/brand/paragon/overrides";
|
||||
|
||||
@import "~@edx/frontend-component-header/dist/index";
|
||||
@import "~@edx/frontend-component-footer/dist/footer";
|
||||
|
||||
@@ -2,17 +2,17 @@ import 'core-js/stable';
|
||||
import 'regenerator-runtime/runtime';
|
||||
import '@testing-library/jest-dom';
|
||||
import React from 'react';
|
||||
import PropTypes from 'prop-types';
|
||||
import { render } from '@testing-library/react';
|
||||
import { render as rtlRender } from '@testing-library/react';
|
||||
import AppProvider from '@edx/frontend-platform/react/AppProvider';
|
||||
import { configure as configureI18n } from '@edx/frontend-platform/i18n';
|
||||
import { configure as configureLogging } from '@edx/frontend-platform/logging';
|
||||
import { getConfig } from '@edx/frontend-platform';
|
||||
import { configure as configureI18n, IntlProvider } from '@edx/frontend-platform/i18n';
|
||||
import { configure as configureLogging, MockLoggingService } from '@edx/frontend-platform/logging';
|
||||
import { getConfig, mergeConfig } from '@edx/frontend-platform';
|
||||
import { configure as configureAuth, MockAuthService } from '@edx/frontend-platform/auth';
|
||||
import appMessages from './i18n';
|
||||
|
||||
Object.defineProperty(window, 'matchMedia', {
|
||||
writable: true,
|
||||
value: jest.fn().mockImplementation(query => ({
|
||||
value: jest.fn().mockImplementation((query) => ({
|
||||
matches: false,
|
||||
media: query,
|
||||
onchange: null,
|
||||
@@ -24,46 +24,47 @@ Object.defineProperty(window, 'matchMedia', {
|
||||
})),
|
||||
});
|
||||
|
||||
jest.mock('@edx/frontend-platform/auth', () => ({
|
||||
getAuthenticatedUser: jest.fn(() => ({
|
||||
userId: 'abc123',
|
||||
username: 'MockUser',
|
||||
roles: [],
|
||||
administrator: false,
|
||||
})),
|
||||
}));
|
||||
class MockLoggingService {
|
||||
logInfo = jest.fn();
|
||||
export function initializeMockApp() {
|
||||
mergeConfig({
|
||||
// MICROBA-1505: Remove this when we remove the flag from config
|
||||
SCHEDULE_EMAIL_SECTION: true,
|
||||
authenticatedUser: {
|
||||
userId: 'abc123',
|
||||
username: 'Mock User',
|
||||
roles: [],
|
||||
administrator: false,
|
||||
},
|
||||
});
|
||||
|
||||
logError = jest.fn();
|
||||
const loggingService = configureLogging(MockLoggingService, {
|
||||
config: getConfig(),
|
||||
});
|
||||
|
||||
const i18nService = configureI18n({
|
||||
config: getConfig(),
|
||||
loggingService,
|
||||
messages: [appMessages],
|
||||
});
|
||||
|
||||
const authService = configureAuth(MockAuthService, { config: getConfig(), loggingService });
|
||||
return { loggingService, i18nService, authService };
|
||||
}
|
||||
|
||||
const loggingService = configureLogging(MockLoggingService, {
|
||||
config: getConfig(),
|
||||
});
|
||||
|
||||
configureI18n({
|
||||
config: getConfig(),
|
||||
loggingService,
|
||||
messages: [appMessages],
|
||||
});
|
||||
|
||||
function Wrapper({ children }) {
|
||||
return (
|
||||
// eslint-disable-next-line react/jsx-filename-extension
|
||||
<AppProvider>{children}</AppProvider>
|
||||
);
|
||||
function render(ui, options) {
|
||||
// eslint-disable-next-line react/prop-types
|
||||
function Wrapper({ children }) {
|
||||
return (
|
||||
// eslint-disable-next-line react/jsx-filename-extension
|
||||
<IntlProvider locale="en">
|
||||
<AppProvider>{children}</AppProvider>
|
||||
</IntlProvider>
|
||||
);
|
||||
}
|
||||
return rtlRender(ui, { wrapper: Wrapper, ...options });
|
||||
}
|
||||
|
||||
const renderWithProviders = (ui, options) => {
|
||||
render(ui, { wrapper: Wrapper, ...options });
|
||||
};
|
||||
Wrapper.propTypes = {
|
||||
children: PropTypes.node.isRequired,
|
||||
};
|
||||
|
||||
// Re-export everything.
|
||||
export * from '@testing-library/react';
|
||||
|
||||
// Override `render` method.
|
||||
export { renderWithProviders as render };
|
||||
export { render };
|
||||
|
||||
14
src/utils/formatDateAndTime.js
Normal file
14
src/utils/formatDateAndTime.js
Normal file
@@ -0,0 +1,14 @@
|
||||
const normalizeDigits = (value) => (value < 10 ? `0${value}` : value);
|
||||
export const formatDate = (date) => {
|
||||
const day = normalizeDigits(date.getDate());
|
||||
const month = normalizeDigits(date.getMonth() + 1);
|
||||
const year = date.getFullYear();
|
||||
|
||||
return `${year}-${month}-${day}`;
|
||||
};
|
||||
export const formatTime = (date) => {
|
||||
const hours = normalizeDigits(date.getHours());
|
||||
const mins = normalizeDigits(date.getMinutes());
|
||||
|
||||
return `${hours}:${mins}`;
|
||||
};
|
||||
52
src/utils/useAsyncReducer.js
Normal file
52
src/utils/useAsyncReducer.js
Normal file
@@ -0,0 +1,52 @@
|
||||
import { useMemo, useReducer } from 'react';
|
||||
|
||||
/**
|
||||
* This helper function wraps the useReducer dispatch function to allow for invoking function calls
|
||||
* when a state change is dispatched.
|
||||
* @param {Function} dispatch useReducer's dispatch function.
|
||||
* @returns a wrapped dispatch that execututes function actions.
|
||||
*/
|
||||
export function wrapAsync(dispatch) {
|
||||
return (action) => {
|
||||
if (typeof action === 'function') {
|
||||
return action(dispatch);
|
||||
}
|
||||
return dispatch(action);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* A utility function to combine reducers. this allows us to organize and create individual reducers
|
||||
* for components with its own slice of the store. This function the returns a combined reducer to make
|
||||
* dispatching easier amoungst multiple components. This function isnt used directly by this hook, but is a part of
|
||||
* the ecosystem around it, and is meant to be used as a step before calling the hook.
|
||||
* @param {Object} slices reducer functions to be combined.
|
||||
* @returns a single reducer function
|
||||
*/
|
||||
export function combineReducers(slices) {
|
||||
return (prevState, action) => Object.keys(slices).reduce(
|
||||
(nextState, nextProp) => ({
|
||||
...nextState,
|
||||
[nextProp]: slices[nextProp](prevState[nextProp], action),
|
||||
}),
|
||||
prevState,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* By default, the useReducer hook does not allow for async dispatches. This small
|
||||
* hook takes the dispatch function from useReducer and wraps it to allow for the execution
|
||||
* of functions that are invoked with the dispatch object. This makes it easier for us to perform
|
||||
* async operations, or to execute multiple dispatches in a row using a single thunk.
|
||||
* @param {Function} reducer a reducer function for the context state.
|
||||
* @param {Object} initialState an initial state for the context store.
|
||||
* @returns [state, asyncDispatch ]
|
||||
*/
|
||||
const useAsyncReducer = (reducer, initialState = null) => {
|
||||
const [state, dispatch] = useReducer(reducer, initialState);
|
||||
const asyncDispatch = useMemo(() => wrapAsync(dispatch), [dispatch]);
|
||||
|
||||
return [state, asyncDispatch];
|
||||
};
|
||||
|
||||
export default useAsyncReducer;
|
||||
@@ -8,16 +8,17 @@ import { useRef, useEffect } from 'react';
|
||||
* and only allow one at a time.
|
||||
* @param {function} callback The function to call once the delay ends
|
||||
* @param {millisecond} delay time to delay function call
|
||||
* @param {bool} cancel cancels the callback early if true
|
||||
*/
|
||||
export default function useTimeout(callback, delay) {
|
||||
export default function useTimeout(callback, delay, cancel) {
|
||||
const timeoutRef = useRef(null);
|
||||
|
||||
useEffect(() => {
|
||||
const timeout = timeoutRef.current;
|
||||
if (timeout) {
|
||||
if (timeout || cancel) {
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
}, []);
|
||||
}, [cancel]);
|
||||
|
||||
return () => {
|
||||
if (timeoutRef.current) {
|
||||
|
||||
Reference in New Issue
Block a user