Compare commits

..

1 Commits

Author SHA1 Message Date
David Joy
f46db1f1d4 Updating i18n-loader with all our languages. 2019-05-07 09:08:33 -04:00
137 changed files with 14225 additions and 18244 deletions

26
.babelrc Executable file
View File

@@ -0,0 +1,26 @@
{
"presets": [
[
"env",
{
"targets": {
"browsers": ["last 2 versions", "ie 11"]
}
}
],
"babel-preset-react"
],
"plugins": [
"transform-object-rest-spread",
"transform-class-properties"
],
"env": {
"i18n": {
"plugins": [
["react-intl", {
"messagesDir": "./temp"
}]
]
}
}
}

17
.env
View File

@@ -1,17 +0,0 @@
ACCESS_TOKEN_COOKIE_NAME=null
BASE_URL=null
CREDENTIALS_BASE_URL=null
CSRF_TOKEN_API_PATH=null
ECOMMERCE_BASE_URL=null
LANGUAGE_PREFERENCE_COOKIE_NAME=null
LMS_BASE_URL=null
LOGIN_URL=null
LOGOUT_URL=null
MARKETING_SITE_BASE_URL=null
NODE_ENV=null
ORDER_HISTORY_URL=null
REFRESH_ACCESS_TOKEN_ENDPOINT=null
SEGMENT_KEY=null
SITE_NAME=null
SUPPORT_URL=null
USER_INFO_COOKIE_NAME=null

View File

@@ -1,20 +0,0 @@
ACCESS_TOKEN_COOKIE_NAME='edx-jwt-cookie-header-payload'
BASE_URL='localhost:19000/account/'
CREDENTIALS_BASE_URL='http://localhost:18150'
CSRF_TOKEN_API_PATH='/csrf/api/v1/token'
ECOMMERCE_BASE_URL='http://localhost:18130'
LANGUAGE_PREFERENCE_COOKIE_NAME='openedx-language-preference'
LMS_BASE_URL='http://localhost:18000'
LOGIN_URL='http://localhost:18000/login'
LOGOUT_URL='http://localhost:18000/logout'
MARKETING_SITE_BASE_URL='http://localhost:18000'
NODE_ENV='development'
ORDER_HISTORY_URL='localhost:19000/ecommerce/orders'
PORT=1997 # For standalone dev server only.
REFRESH_ACCESS_TOKEN_ENDPOINT='http://localhost:18000/login_refresh'
SEGMENT_KEY=null
SITE_NAME='edX'
SUPPORT_URL='http://localhost:18000/support'
USER_INFO_COOKIE_NAME='edx-user-info'
# Temporary, Remove this once we are ready to release the feature.
COACHING_ENABLED=''

View File

@@ -1,18 +0,0 @@
ACCESS_TOKEN_COOKIE_NAME='edx-jwt-cookie-header-payload'
BASE_URL='localhost:1997'
CREDENTIALS_BASE_URL='http://localhost:18150'
CSRF_TOKEN_API_PATH='/csrf/api/v1/token'
ECOMMERCE_BASE_URL='http://localhost:18130'
LANGUAGE_PREFERENCE_COOKIE_NAME='openedx-language-preference'
LMS_BASE_URL='http://localhost:18000'
LOGIN_URL='http://localhost:18000/login'
LOGOUT_URL='http://localhost:18000/login'
MARKETING_SITE_BASE_URL='http://localhost:18000'
NODE_ENV=null
ORDER_HISTORY_URL='localhost:1996/orders'
REFRESH_ACCESS_TOKEN_ENDPOINT='http://localhost:18000/login_refresh'
SEGMENT_KEY=null
SITE_NAME='edX'
SUPPORT_URL='http://localhost:18000/support'
USER_INFO_COOKIE_NAME='edx-user-info'
COACHING_ENABLED=''

View File

@@ -2,4 +2,3 @@ coverage/*
dist/
node_modules/
__mocks__/
__snapshots__/

34
.eslintrc Executable file
View File

@@ -0,0 +1,34 @@
{
"extends": "eslint-config-edx",
"parser": "babel-eslint",
"rules": {
"import/no-extraneous-dependencies": [
"error",
{
"devDependencies": [
"webpack/*.js",
"**/*.test.jsx",
"**/*.test.js"
]
}
],
// https://github.com/evcohen/eslint-plugin-jsx-a11y/issues/340#issuecomment-338424908
"jsx-a11y/anchor-is-valid": [ "error", {
"components": [ "Link" ],
"specialLink": [ "to" ]
}],
"jsx-a11y/label-has-for": [ 2, {
"components": [ "label" ],
"required": {
"some": [ "nesting", "id" ]
},
"allowChildren": false
}]
},
"env": {
"jest": true
},
"globals": {
"newrelic": false
}
}

View File

@@ -1,3 +0,0 @@
const { createConfig } = require('@edx/frontend-build');
module.exports = createConfig('eslint');

2
.gitignore vendored
View File

@@ -6,8 +6,6 @@ npm-debug.log
coverage
dist/
src/i18n/transifex_input.json
temp/babel-plugin-react-intl
### pyenv ###
.python-version

View File

@@ -1,15 +1,13 @@
.tx
.eslintignore
.eslintrc.json
.gitignore
.travis.yml
docker-compose.yml
Dockerfile
Makefile
npm-debug.log
webpack
coverage
dist
node_modules
public
src
.dockerignore
.eslintignore
.eslintrc
.gitignore
.releaserc
.travis.yml
babel.config.js
Makefile
renovate.json

View File

@@ -1,15 +1,22 @@
language: node_js
node_js: 12
node_js:
- lts/*
cache:
directories:
- "~/.npm"
before_install:
- npm install -g npm@6
- npm install -g npm@latest
- npm install -g greenkeeper-lockfile@1.14.0
install:
- npm ci
- npm ci
before_script: greenkeeper-lockfile-update
after_script: greenkeeper-lockfile-upload
script:
- make validate-no-uncommitted-package-lock-changes
- npm run i18n_extract
- npm run lint
- npm run test
- npm run build
- npm run is-es5
- make validate-no-uncommitted-package-lock-changes
- npm run i18n_extract
- npm run lint
- npm run test
- npm run build
after_success:
- codecov
- npm run coveralls
- codecov

149
LICENSE
View File

@@ -1,21 +1,23 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
@@ -24,34 +26,44 @@ them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
@@ -60,7 +72,7 @@ modification follow.
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
@@ -537,45 +549,35 @@ to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
@@ -633,29 +635,40 @@ the "copyright" line and a pointer to where the full notice is found.
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
GNU General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

View File

@@ -1,50 +1,36 @@
transifex_resource = frontend-app-account
transifex_langs = "ar,fr,es_419,zh_CN"
transifex_utils = ./node_modules/.bin/transifex-utils.js
i18n = ./src/i18n
transifex_input = $(i18n)/transifex_input.json
tx_url1 = https://www.transifex.com/api/2/project/edx-platform/resource/$(transifex_resource)/translation/en/strings/
tx_url2 = https://www.transifex.com/api/2/project/edx-platform/resource/$(transifex_resource)/source/
# This directory must match .babelrc .
transifex_temp = ./temp/babel-plugin-react-intl
requirements:
extract_translations: ## no prerequisites so we can control order of operations
echo "We have to define this target due to tooling assumptions"
echo "Also we have to npm install using this hook b/c there's no other place for it in the current setup"
npm install
npm run-script i18n_extract
i18n.extract:
# Pulling display strings from .jsx files into .json files...
rm -rf $(transifex_temp)
# Pulling display strings from .jsx files into .json files...
npm run-script i18n_extract
i18n.concat:
# Gathering JSON messages into one file...
$(transifex_utils) $(transifex_temp) $(transifex_input)
# Gathering JSON messages into one file...
./src/i18n/i18n-concat.js ./temp/src ./src/i18n/transifex_input.json
extract_translations: | requirements i18n.extract i18n.concat
# Despite the name, we actually need this target to detect changes in the incoming translated message files as well.
detect_changed_source_translations:
# Checking for changed translations...
git diff --exit-code $(i18n)
git diff --exit-code ./src/i18n/transifex_input.json
# Pushes translations to Transifex. You must run make extract_translations first.
push_translations:
# Pushing strings to Transifex...
tx push -s
# Fetching hashes from Transifex...
tx_url1 = https://www.transifex.com/api/2/project/edx-platform/resource/frontend-app-account/translation/en/strings/
tx_url2 = https://www.transifex.com/api/2/project/edx-platform/resource/frontend-app-account/source/
# push translations to Transifex, doing magic so we can include the translator comments
push_translations: | i18n.extract
# Adding translator comments...
# Fetching strings from Transifex...
./node_modules/reactifex/bash_scripts/get_hashed_strings.sh $(tx_url1)
# Writing out comments to file...
$(transifex_utils) $(transifex_temp) --comments
# Pushing comments to Transifex...
# Writing out comments to file...
./src/i18n/i18n-concat.js ./temp/src --comments
# Adding comments to Transifex...
./node_modules/reactifex/bash_scripts/put_comments.sh $(tx_url2)
# Pulls translations from Transifex.
pull_translations:
tx pull -f --mode reviewed --language=$(transifex_langs)
# pull translations from Transifex
pull_translations: ## must be exactly this name for edx tooling support, see ecommerce-scripts/transifex/pull.py
tx pull -f --mode reviewed --language="ar,fr,es_419,zh_CN"
# This target is used by Travis.
validate-no-uncommitted-package-lock-changes:
# Checking for package-lock.json changes...
git diff --exit-code package-lock.json

View File

@@ -1,60 +1,22 @@
|Build Status| |Codecov| |npm_version| |npm_downloads| |license| |semantic-release|
|Build Status| |Coveralls| |npm_version| |npm_downloads| |license|
frontend-app-account
====================
=========================
This is a micro-frontend application responsible for the display and updating of a user's account information. Please tag **@edx/arch-team** on any PRs or issues.
Please tag **@edx/arch-team** on any PRs or issues.
Development
-----------
Introduction
------------
Start Devstack
^^^^^^^^^^^^^^
To use this application `devstack <https://github.com/edx/devstack>`__ must be running and you must be logged into it.
- Start devstack
- Log in (http://localhost:18000/login)
Start the development server
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
In this project, install requirements and start the development server by running:
.. code:: bash
npm install
npm start # The server will run on port 1997
Once the dev server is up visit http://localhost:1997.
Configuration and Deployment
----------------------------
This MFE is configured via node environment variables supplied at build time. See the .env file for the list of required environment variables. Example build syntax with a single environment variable:
.. code:: bash
NODE_ENV=development ACCESS_TOKEN_COOKIE_NAME='edx-jwt-cookie-header-payload' npm run build
For more information see the document: `Micro-frontend applications in Open
edX <https://github.com/edx/edx-developer-docs/blob/5191e800bf16cf42f25c58c58f983bdaf7f9305d/docs/micro-frontends-in-open-edx.rst>`__.
Notes
-----
The production Webpack configuration for this repo uses `Purgecss <https://www.purgecss.com/>`__ to remove unused CSS from the production css file. In ``webpack.prod.config.js`` the Purgecss plugin is configured to scan directories to determine what css selectors should remain. Currently the src/ directory is scanned along with all ``@edx/frontend-component*`` node modules and ``@edx/paragon``. **If you add and use a component in this repo that relies on HTML classes or ids for styling you must add it to the Purgecss configuration or it will be unstyled in the production build.**
React app for account settings.
.. |Build Status| image:: https://api.travis-ci.org/edx/frontend-app-account.svg?branch=master
:target: https://travis-ci.org/edx/frontend-app-account
.. |Codecov| image:: https://img.shields.io/codecov/c/github/edx/frontend-app-account
:target: https://codecov.io/gh/edx/frontend-app-account
.. |Coveralls| image:: https://img.shields.io/coveralls/edx/frontend-app-account.svg?branch=master
:target: https://coveralls.io/github/edx/frontend-app-account
.. |npm_version| image:: https://img.shields.io/npm/v/@edx/frontend-app-account.svg
:target: @edx/frontend-app-account
.. |npm_downloads| image:: https://img.shields.io/npm/dt/@edx/frontend-app-account.svg
:target: @edx/frontend-app-account
.. |license| image:: https://img.shields.io/npm/l/@edx/frontend-app-account.svg
:target: @edx/frontend-app-account
.. |semantic-release| image:: https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg
:target: https://github.com/semantic-release/semantic-release

View File

@@ -1,30 +0,0 @@
1. Add Coaching Consent
--------------------------------
Status
------
Accepted
Context
-------
We need to provide users who are eligible for coaching with both an always available
coaching toggle and a one-time form they can view to signup for coaching.
Decision
--------
While the coaching functionality is currently both limited, closed source, and the form
exists outside of the standard design of this MFE, it was decided to add it here as a
temporary measure due to it being at it's core, an account setting.
The longer term solutions include either:
- using the frontend plugins feature when they become available to inject our coaching
work into the account MFE
- roll it into it's own MFE if enough additional coaching frontend work is required
Consequences
------------
Code will exist inside this Open edX MFE that integrates with a closed source app.

View File

@@ -1,7 +0,0 @@
const { createConfig } = require('@edx/frontend-build');
module.exports = createConfig('jest', {
setupFiles: [
'<rootDir>/src/setupTest.js',
],
});

View File

@@ -4,4 +4,3 @@
nick: acct
oeps: {}
owner: edx/arch-team
openedx-release: {ref: master}

23419
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,89 +1,142 @@
{
"name": "@edx/frontend-app-account",
"version": "1.0.0-semantically-released",
"description": "User account micro-frontend for Open edX",
"author": "edX",
"license": "AGPL-3.0",
"version": "0.1.0",
"description": "User account React app",
"repository": {
"type": "git",
"url": "git+https://github.com/edx/frontend-app-account.git"
},
"scripts": {
"build": "fedx-scripts webpack",
"dev-build": "fedx-scripts webpack-dev",
"i18n_extract": "BABEL_ENV=i18n fedx-scripts babel src --quiet > /dev/null",
"build": "NODE_ENV=production BABEL_ENV=production webpack --config=webpack/webpack.prod.config.js",
"coveralls": "cat ./coverage/lcov.info | coveralls",
"i18n_extract": "BABEL_ENV=i18n babel src --quiet > /dev/null",
"is-es5": "es-check es5 ./dist/*.js",
"lint": "fedx-scripts eslint",
"snapshot": "fedx-scripts jest --updateSnapshot",
"start": "fedx-scripts webpack-dev-server --progress",
"test": "fedx-scripts jest --coverage --passWithNoTests"
},
"bugs": {
"url": "https://github.com/edx/frontend-app-account/issues"
"lint": "eslint --ext .js --ext .jsx .",
"precommit": "npm run lint",
"start": "NODE_ENV=development BABEL_ENV=development webpack-dev-server --config=webpack/webpack.dev.config.js --progress",
"test": "jest --coverage --passWithNoTests",
"travis-deploy-once": "travis-deploy-once"
},
"author": "edX",
"license": "AGPL-3.0",
"homepage": "https://github.com/edx/frontend-app-account#readme",
"publishConfig": {
"access": "public"
},
"browserslist": [
"last 2 versions",
"ie 11"
],
"dependencies": {
"@edx/frontend-component-footer": "10.0.9",
"@edx/frontend-component-header": "2.0.5",
"@edx/frontend-platform": "1.1.14",
"@edx/paragon": "7.1.5",
"@fortawesome/fontawesome-svg-core": "1.2.28",
"@fortawesome/free-brands-svg-icons": "5.8.2",
"@fortawesome/free-regular-svg-icons": "5.7.2",
"@fortawesome/free-solid-svg-icons": "5.8.2",
"@fortawesome/react-fontawesome": "0.1.9",
"babel-polyfill": "6.26.0",
"classnames": "2.2.6",
"font-awesome": "4.7.0",
"form-urlencoded": "4.0.1",
"formdata-polyfill": "3.0.19",
"history": "4.10.1",
"lodash.camelcase": "4.3.0",
"lodash.debounce": "4.0.8",
"lodash.findindex": "4.6.0",
"lodash.get": "4.4.2",
"lodash.isempty": "4.4.0",
"lodash.merge": "4.6.2",
"lodash.omit": "4.5.0",
"lodash.pick": "4.4.0",
"lodash.snakecase": "4.1.1",
"memoize-one": "5.1.1",
"newrelic": "5.13.1",
"prop-types": "15.7.2",
"react": "16.10.2",
"react-dom": "16.10.2",
"react-redux": "7.1.3",
"react-router": "5.1.2",
"react-router-dom": "5.1.2",
"react-router-hash-link": "1.2.2",
"react-scrollspy": "3.4.2",
"react-transition-group": "4.3.0",
"redux": "4.0.5",
"redux-devtools-extension": "2.13.8",
"redux-logger": "3.0.6",
"redux-saga": "1.1.3",
"redux-thunk": "2.3.0",
"reselect": "4.0.0",
"universal-cookie": "4.0.3"
"@cospired/i18n-iso-languages": "^2.0.2",
"@edx/edx-bootstrap": "^2.0.1",
"@edx/frontend-analytics": "^1.0.0",
"@edx/frontend-auth": "^5.0.0",
"@edx/frontend-component-footer": "^2.0.3",
"@edx/frontend-component-site-header": "^2.1.4",
"@edx/frontend-logging": "^2.0.0",
"@edx/paragon": "^4.1.3",
"@fortawesome/fontawesome-svg-core": "^1.2.17",
"@fortawesome/free-brands-svg-icons": "^5.7.2",
"@fortawesome/free-regular-svg-icons": "^5.7.1",
"@fortawesome/free-solid-svg-icons": "^5.8.1",
"@fortawesome/react-fontawesome": "^0.1.4",
"babel-polyfill": "^6.26.0",
"classnames": "^2.2.6",
"connected-react-router": "^5.0.1",
"email-prop-type": "^1.1.5",
"font-awesome": "^4.7.0",
"form-urlencoded": "^3.0.0",
"glob": "^7.1.3",
"history": "^4.7.2",
"i18n-iso-countries": "^3.7.8",
"iso-countries-languages": "^0.2.1",
"lodash.camelcase": "^4.3.0",
"lodash.get": "^4.4.2",
"lodash.pick": "^4.4.0",
"lodash.snakecase": "^4.1.1",
"newrelic": "^5.5.0",
"prop-types": "^15.5.10",
"react": "^16.8.3",
"react-dom": "^16.8.3",
"react-intl": "^2.8.0",
"react-redux": "^5.1.1",
"react-router": "^4.2.0",
"react-router-dom": "^4.2.2",
"react-transition-group": "^2.5.3",
"redux": "^4.0.1",
"redux-devtools-extension": "^2.13.2",
"redux-logger": "^3.0.6",
"redux-saga": "^1.0.1",
"redux-thunk": "^2.2.0",
"reselect": "^4.0.0",
"universal-cookie": "^3.1.0",
"webpack-rtl-plugin": "^2.0.0"
},
"devDependencies": {
"@edx/frontend-build": "github:edx/frontend-build#kdmccormick/devstack-frontends",
"codecov": "3.6.5",
"enzyme": "3.10.0",
"enzyme-adapter-react-16": "1.15.2",
"es-check": "5.0.0",
"glob": "7.1.6",
"husky": "3.0.9",
"purgecss-webpack-plugin": "1.6.0",
"react-test-renderer": "16.8.6",
"@svgr/webpack": "^4.2.0",
"autoprefixer": "^9.4.2",
"axios-mock-adapter": "^1.15.0",
"babel-cli": "^6.26.0",
"babel-eslint": "^8.2.2",
"babel-jest": "^22.4.0",
"babel-loader": "^7.1.2",
"babel-plugin-react-intl": "^3.0.1",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-plugin-transform-object-rest-spread": "^6.26.0",
"babel-preset-env": "^1.6.1",
"babel-preset-react": "^6.24.1",
"clean-webpack-plugin": "^0.1.19",
"codecov": "^3.0.0",
"copy-webpack-plugin": "^4.6.0",
"css-loader": "^0.28.9",
"enzyme": "^3.3.0",
"enzyme-adapter-react-16": "^1.1.1",
"es-check": "^2.0.2",
"eslint-config-edx": "^4.0.3",
"fetch-mock": "^6.3.0",
"file-loader": "^1.1.9",
"html-webpack-harddisk-plugin": "^0.2.0",
"html-webpack-new-relic-plugin": "^1.1.0",
"html-webpack-plugin": "^3.0.3",
"husky": "^0.14.3",
"identity-obj-proxy": "^3.0.0",
"image-webpack-loader": "^4.2.0",
"jest": "^22.4.0",
"mini-css-extract-plugin": "^0.4.0",
"node-sass": "^4.7.2",
"postcss-loader": "^3.0.0",
"react-dev-utils": "^5.0.0",
"react-test-renderer": "^16.8.6",
"reactifex": "1.1.1",
"redux-mock-store": "1.5.4"
"redux-mock-store": "^1.5.3",
"sass-loader": "^6.0.6",
"style-loader": "^0.20.2",
"travis-deploy-once": "^5.0.9",
"url-loader": "^1.1.2",
"webpack": "^4.25.1",
"webpack-cli": "^3.1.2",
"webpack-dev-server": "^3.1.0",
"webpack-merge": "^4.1.1"
},
"jest": {
"testURL": "http://localhost/",
"setupFiles": [
"./src/setupTest.js"
],
"moduleNameMapper": {
"\\.svg": "<rootDir>/__mocks__/svgrMock.js",
"\\.(jpg|jpeg|png|gif|eot|otf|webp|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
"\\.(css|scss)$": "identity-obj-proxy",
"@edx/frontend-i18n(.*)$": "<rootDir>/src/i18n$1"
},
"collectCoverageFrom": [
"src/**/*.{js,jsx}"
],
"coveragePathIgnorePatterns": [
"/node_modules/",
"src/setupTest.js",
"src/index.js",
"/tests/"
],
"transformIgnorePatterns": [
"/node_modules/(?!(@edx/paragon)/).*/"
]
}
}

View File

@@ -4,7 +4,6 @@
<title>Account | edX</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />
</head>
<body>
<div id="root"></div>

View File

@@ -1,9 +0,0 @@
{
"extends": [
"config:base"
],
"patch": {
"automerge": true
},
"rebaseStalePrs": true
}

View File

@@ -1,420 +1,131 @@
import { AppContext } from '@edx/frontend-platform/react';
import { getConfig, history, getQueryParameters } from '@edx/frontend-platform';
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import memoize from 'memoize-one';
import findIndex from 'lodash.findindex';
import { sendTrackingLogEvent } from '@edx/frontend-platform/analytics';
import {
injectIntl,
intlShape,
FormattedMessage,
getLocale,
getCountryList,
getLanguageList,
} from '@edx/frontend-platform/i18n';
import { Hyperlink } from '@edx/paragon';
} from '@edx/frontend-i18n'; // eslint-disable-line
import messages from './AccountSettingsPage.messages';
import { fetchSettings, saveSettings, updateDraft } from './data/actions';
import { accountSettingsPageSelector } from './data/selectors';
import PageLoading from './PageLoading';
import Alert from './Alert';
import JumpNav from './JumpNav';
import DeleteAccount from './delete-account';
import EditableField from './EditableField';
import ResetPassword from './reset-password';
import ThirdPartyAuth from './third-party-auth';
import BetaLanguageBanner from './BetaLanguageBanner';
import EmailField from './EmailField';
import { fetchAccount, fetchThirdPartyAuthProviders } from './actions';
import { accountSettingsSelector } from './selectors';
import { PageLoading } from '../common';
import EditableField from './components/EditableField';
import PasswordReset from './components/PasswordReset';
import ThirdPartyAuth from './components/ThirdPartyAuth';
import EmailField from './components/EmailField';
import {
YEAR_OF_BIRTH_OPTIONS,
EDUCATION_LEVELS,
GENDER_OPTIONS,
} from './data/constants';
import { fetchSiteLanguages } from './site-language';
import CoachingToggle from './coaching/CoachingToggle';
} from './constants';
class AccountSettingsPage extends React.Component {
constructor(props, context) {
super(props, context);
// If there is a "duplicate_provider" query parameter, that's the backend's
// way of telling us that the provider account the user tried to link is already linked
// to another Open edX account. We use this to display a message to that effect, and remove the
// parameter from the URL.
const duplicateTpaProvider = getQueryParameters().duplicate_provider;
if (duplicateTpaProvider !== undefined) {
history.replace(history.location.pathname);
}
this.state = {
duplicateTpaProvider,
};
constructor(props) {
super(props);
this.countryOptions = getCountryList(getLocale())
.map(({ code, name }) => ({ value: code, label: name }));
this.languageProficiencyOptions = getLanguageList(getLocale())
.map(({ code, name }) => ({ value: code, label: name }));
this.educationLevels = EDUCATION_LEVELS.map(key => ({
value: key,
label: props.intl.formatMessage(messages[`account.settings.field.education.levels.${key}`]),
}));
this.genderOptions = GENDER_OPTIONS.map(key => ({
value: key,
label: props.intl.formatMessage(messages[`account.settings.field.gender.options.${key}`]),
}));
}
componentDidMount() {
this.props.fetchSettings();
this.props.fetchSiteLanguages();
sendTrackingLogEvent('edx.user.settings.viewed', {
page: 'account',
visibility: null,
user_id: this.context.authenticatedUser.userId,
});
}
// NOTE: We need 'locale' for the memoization in getLocalizedTimeZoneOptions. Don't remove it!
// eslint-disable-next-line no-unused-vars
getLocalizedTimeZoneOptions = memoize((timeZoneOptions, countryTimeZoneOptions, locale) => {
const concatTimeZoneOptions = [{
label: this.props.intl.formatMessage(messages['account.settings.field.time.zone.default']),
value: '',
}];
if (countryTimeZoneOptions.length) {
concatTimeZoneOptions.push({
label: this.props.intl.formatMessage(messages['account.settings.field.time.zone.country']),
group: countryTimeZoneOptions,
});
}
concatTimeZoneOptions.push({
label: this.props.intl.formatMessage(messages['account.settings.field.time.zone.all']),
group: timeZoneOptions,
});
return concatTimeZoneOptions;
});
getLocalizedOptions = memoize(locale => ({
countryOptions: [{
value: '',
label: this.props.intl.formatMessage(messages['account.settings.field.country.options.empty']),
}].concat(getCountryList(locale).map(({ code, name }) => ({ value: code, label: name }))),
languageProficiencyOptions: [{
value: '',
label: this.props.intl.formatMessage(messages['account.settings.field.language_proficiencies.options.empty']),
}].concat(getLanguageList(locale).map(({ code, name }) => ({ value: code, label: name }))),
yearOfBirthOptions: [{
value: '',
label: this.props.intl.formatMessage(messages['account.settings.field.year_of_birth.options.empty']),
}].concat(YEAR_OF_BIRTH_OPTIONS),
educationLevelOptions: EDUCATION_LEVELS.map(key => ({
value: key,
label: this.props.intl.formatMessage(messages[`account.settings.field.education.levels.${key || 'empty'}`]),
})),
genderOptions: GENDER_OPTIONS.map(key => ({
value: key,
label: this.props.intl.formatMessage(messages[`account.settings.field.gender.options.${key || 'empty'}`]),
})),
}));
isEditable(fieldName) {
return !this.props.staticFields.includes(fieldName);
}
isManagedProfile() {
// Enterprise customer profiles are managed by their organizations. We determine whether
// a profile is managed or not by the presence of the profileDataManager prop.
return Boolean(this.props.profileDataManager);
}
handleEditableFieldChange = (name, value) => {
this.props.updateDraft(name, value);
};
handleSubmit = (formId, values) => {
this.props.saveSettings(formId, values);
};
renderDuplicateTpaProviderMessage() {
if (!this.state.duplicateTpaProvider) {
return null;
}
return (
<div>
<Alert className="alert alert-danger" role="alert">
<FormattedMessage
id="account.settings.message.duplicate.tpa.provider"
defaultMessage="The {provider} account you selected is already linked to another edX account."
description="alert message informing the user that the third-party account they attempted to link is already linked to another edX account"
values={{
provider: <b>{this.state.duplicateTpaProvider}</b>,
}}
/>
</Alert>
</div>
);
}
renderManagedProfileMessage() {
if (!this.isManagedProfile()) {
return null;
}
return (
<div>
<Alert className="alert alert-primary" role="alert">
<FormattedMessage
id="account.settings.message.managed.settings"
defaultMessage="Your profile settings are managed by {managerTitle}. Contact your administrator or {support} for help."
description="alert message informing the user their account data is managed by a third party"
values={{
managerTitle: <b>{this.props.profileDataManager}</b>,
support: (
<Hyperlink destination={getConfig().SUPPORT_URL} target="_blank">
<FormattedMessage
id="account.settings.message.managed.settings.support"
defaultMessage="support"
description="website support"
/>
</Hyperlink>
),
}}
/>
</Alert>
</div>
);
}
renderEmptyStaticFieldMessage() {
if (this.isManagedProfile()) {
return this.props.intl.formatMessage(messages['account.settings.static.field.empty'], {
enterprise: this.props.profileDataManager,
});
}
return this.props.intl.formatMessage(messages['account.settings.static.field.empty.no.admin']);
}
renderSecondaryEmailField(editableFieldProps) {
if (!Boolean(this.props.formValues.secondary_email_enabled)) {
return null;
}
return (
<EmailField
name="secondary_email"
label={this.props.intl.formatMessage(messages['account.settings.field.secondary.email'])}
emptyLabel={this.props.intl.formatMessage(messages['account.settings.field.secondary.email.empty'])}
value={this.props.formValues.secondary_email}
confirmationMessageDefinition={messages['account.settings.field.secondary.email.confirmation']}
{...editableFieldProps}
/>
);
this.props.fetchAccount();
this.props.fetchThirdPartyAuthProviders();
}
renderContent() {
const editableFieldProps = {
onChange: this.handleEditableFieldChange,
onSubmit: this.handleSubmit,
};
// Memoized options lists
const {
countryOptions,
languageProficiencyOptions,
yearOfBirthOptions,
educationLevelOptions,
genderOptions,
} = this.getLocalizedOptions(this.context.locale);
const timeZoneOptions = this.getLocalizedTimeZoneOptions(
this.props.timeZoneOptions,
this.props.countryTimeZoneOptions,
this.context.locale,
);
const hasLinkedTPA = findIndex(this.props.tpaProviders, provider => provider.connected) >= 0;
return (
<React.Fragment>
<div className="account-section" id="basic-information">
<h2 className="section-heading">
{this.props.intl.formatMessage(messages['account.settings.section.account.information'])}
</h2>
<p>{this.props.intl.formatMessage(messages['account.settings.section.account.information.description'])}</p>
{this.renderManagedProfileMessage()}
<div>
<div className="row">
<div className="col-md-8 col-lg-6">
<h2>{this.props.intl.formatMessage(messages['account.settings.section.account.information'])}</h2>
<p>{this.props.intl.formatMessage(messages['account.settings.section.account.information.description'])}</p>
<EditableField
name="username"
type="text"
value={this.props.formValues.username}
label={this.props.intl.formatMessage(messages['account.settings.field.username'])}
helpText={this.props.intl.formatMessage(messages['account.settings.field.username.help.text'])}
isEditable={false}
{...editableFieldProps}
/>
<EditableField
name="name"
type="text"
value={this.props.formValues.name}
label={this.props.intl.formatMessage(messages['account.settings.field.full.name'])}
emptyLabel={
this.isEditable('name') ?
this.props.intl.formatMessage(messages['account.settings.field.full.name.empty']) :
this.renderEmptyStaticFieldMessage()
}
helpText={this.props.intl.formatMessage(messages['account.settings.field.full.name.help.text'])}
isEditable={this.isEditable('name')}
{...editableFieldProps}
/>
<EmailField
name="email"
label={this.props.intl.formatMessage(messages['account.settings.field.email'])}
emptyLabel={
this.isEditable('email') ?
this.props.intl.formatMessage(messages['account.settings.field.email.empty']) :
this.renderEmptyStaticFieldMessage()
}
value={this.props.formValues.email}
confirmationMessageDefinition={messages['account.settings.field.email.confirmation']}
helpText={this.props.intl.formatMessage(messages['account.settings.field.email.help.text'])}
isEditable={this.isEditable('email')}
{...editableFieldProps}
/>
{this.renderSecondaryEmailField(editableFieldProps)}
<ResetPassword email={this.props.formValues.email} />
<EditableField
name="year_of_birth"
type="select"
label={this.props.intl.formatMessage(messages['account.settings.field.dob'])}
emptyLabel={this.props.intl.formatMessage(messages['account.settings.field.dob.empty'])}
value={this.props.formValues.year_of_birth}
options={yearOfBirthOptions}
{...editableFieldProps}
/>
<EditableField
name="country"
type="select"
value={this.props.formValues.country}
options={countryOptions}
label={this.props.intl.formatMessage(messages['account.settings.field.country'])}
emptyLabel={
this.isEditable('country') ?
this.props.intl.formatMessage(messages['account.settings.field.country.empty']) :
this.renderEmptyStaticFieldMessage()
}
isEditable={this.isEditable('country')}
{...editableFieldProps}
/>
</div>
<div className="account-section" id="profile-information">
<h2 className="section-heading">
{this.props.intl.formatMessage(messages['account.settings.section.profile.information'])}
</h2>
<EditableField
name="level_of_education"
type="select"
value={this.props.formValues.level_of_education}
options={educationLevelOptions}
label={this.props.intl.formatMessage(messages['account.settings.field.education'])}
emptyLabel={this.props.intl.formatMessage(messages['account.settings.field.education.empty'])}
{...editableFieldProps}
/>
<EditableField
name="gender"
type="select"
value={this.props.formValues.gender}
options={genderOptions}
label={this.props.intl.formatMessage(messages['account.settings.field.gender'])}
emptyLabel={this.props.intl.formatMessage(messages['account.settings.field.gender.empty'])}
{...editableFieldProps}
/>
<EditableField
name="language_proficiencies"
type="select"
value={this.props.formValues.language_proficiencies}
options={languageProficiencyOptions}
label={this.props.intl.formatMessage(messages['account.settings.field.language.proficiencies'])}
emptyLabel={this.props.intl.formatMessage(messages['account.settings.field.language.proficiencies.empty'])}
{...editableFieldProps}
/>
{getConfig().COACHING_ENABLED &&
this.props.formValues.coaching.eligible_for_coaching &&
<CoachingToggle
name="coaching"
phone_number={this.props.formValues.phone_number}
coaching={this.props.formValues.coaching}
<EditableField
name="username"
type="text"
label={this.props.intl.formatMessage(messages['account.settings.field.username'])}
isEditable={false}
/>
}
<EditableField
name="name"
type="text"
label={this.props.intl.formatMessage(messages['account.settings.field.full.name'])}
/>
<EmailField
name="email"
label={this.props.intl.formatMessage(messages['account.settings.field.email'])}
confirmationMessageDefinition={messages['account.settings.field.email.confirmation']}
/>
<EditableField
name="year_of_birth"
type="select"
label={this.props.intl.formatMessage(messages['account.settings.field.dob'])}
options={YEAR_OF_BIRTH_OPTIONS}
/>
<PasswordReset />
<EditableField
name="country"
type="select"
options={this.countryOptions}
label={this.props.intl.formatMessage(messages['account.settings.field.country'])}
/>
<EditableField
name="level_of_education"
type="select"
options={this.educationLevels}
label={this.props.intl.formatMessage(messages['account.settings.field.education'])}
/>
<EditableField
name="gender"
type="select"
options={this.genderOptions}
label={this.props.intl.formatMessage(messages['account.settings.field.gender'])}
/>
<EditableField
name="language_proficiencies"
type="select"
options={this.languageProficiencyOptions}
label={this.props.intl.formatMessage(messages['account.settings.field.language.proficiencies'])}
/>
<ThirdPartyAuth />
<h2>{this.props.intl.formatMessage(messages['account.settings.section.social.media'])}</h2>
<p>{this.props.intl.formatMessage(messages['account.settings.section.social.media.description'])}</p>
<EditableField
name="social_link_linkedIn"
type="text"
label={this.props.intl.formatMessage(messages['account.settings.field.social.platform.name.linkedin'])}
/>
<EditableField
name="social_link_facebook"
type="text"
label={this.props.intl.formatMessage(messages['account.settings.field.social.platform.name.facebook'])}
/>
<EditableField
name="social_link_twitter"
type="text"
label={this.props.intl.formatMessage(messages['account.settings.field.social.platform.name.twitter'])}
/>
</div>
</div>
<div className="account-section" id="social-media">
<h2 className="section-heading">
{this.props.intl.formatMessage(messages['account.settings.section.social.media'])}
</h2>
<p>{this.props.intl.formatMessage(messages['account.settings.section.social.media.description'])}</p>
<EditableField
name="social_link_linkedin"
type="text"
value={this.props.formValues.social_link_linkedin}
label={this.props.intl.formatMessage(messages['account.settings.field.social.platform.name.linkedin'])}
emptyLabel={this.props.intl.formatMessage(messages['account.settings.field.social.platform.name.linkedin.empty'])}
{...editableFieldProps}
/>
<EditableField
name="social_link_facebook"
type="text"
value={this.props.formValues.social_link_facebook}
label={this.props.intl.formatMessage(messages['account.settings.field.social.platform.name.facebook'])}
emptyLabel={this.props.intl.formatMessage(messages['account.settings.field.social.platform.name.facebook.empty'])}
{...editableFieldProps}
/>
<EditableField
name="social_link_twitter"
type="text"
value={this.props.formValues.social_link_twitter}
label={this.props.intl.formatMessage(messages['account.settings.field.social.platform.name.twitter'])}
emptyLabel={this.props.intl.formatMessage(messages['account.settings.field.social.platform.name.twitter.empty'])}
{...editableFieldProps}
/>
</div>
<div className="account-section" id="site-preferences">
<h2 className="section-heading">
{this.props.intl.formatMessage(messages['account.settings.section.site.preferences'])}
</h2>
<BetaLanguageBanner />
<EditableField
name="siteLanguage"
type="select"
options={this.props.siteLanguageOptions}
value={this.props.siteLanguage.draft !== undefined ? this.props.siteLanguage.draft : this.context.locale}
label={this.props.intl.formatMessage(messages['account.settings.field.site.language'])}
helpText={this.props.intl.formatMessage(messages['account.settings.field.site.language.help.text'])}
{...editableFieldProps}
/>
<EditableField
name="time_zone"
type="select"
value={this.props.formValues.time_zone}
options={timeZoneOptions}
label={this.props.intl.formatMessage(messages['account.settings.field.time.zone'])}
emptyLabel={this.props.intl.formatMessage(messages['account.settings.field.time.zone.empty'])}
helpText={this.props.intl.formatMessage(messages['account.settings.field.time.zone.description'])}
{...editableFieldProps}
onSubmit={(formId, value) => {
// the endpoint will not accept an empty string. it must be null
this.handleSubmit(formId, value || null);
}}
/>
</div>
<div className="account-section" id="linked-accounts">
<h2 className="section-heading">{this.props.intl.formatMessage(messages['account.settings.section.linked.accounts'])}</h2>
<p>{this.props.intl.formatMessage(messages['account.settings.section.linked.accounts.description'])}</p>
<ThirdPartyAuth />
</div>
<div className="account-section" id="delete-account">
<DeleteAccount
isVerifiedAccount={this.props.isActive}
hasLinkedTPA={hasLinkedTPA}
/>
</div>
</React.Fragment>
</div>
);
}
@@ -443,103 +154,34 @@ class AccountSettingsPage extends React.Component {
return (
<div className="page__account-settings container-fluid py-5">
{this.renderDuplicateTpaProviderMessage()}
<h1 className="mb-4">
<h1>
{this.props.intl.formatMessage(messages['account.settings.page.heading'])}
</h1>
<div>
<div className="row">
<div className="col-md-3">
<JumpNav />
</div>
<div className="col-md-9">
{loading ? this.renderLoading() : null}
{loaded ? this.renderContent() : null}
{loadingError ? this.renderError() : null}
</div>
</div>
</div>
{loading ? this.renderLoading() : null}
{loaded ? this.renderContent() : null}
{loadingError ? this.renderError() : null}
</div>
);
}
}
AccountSettingsPage.contextType = AppContext;
AccountSettingsPage.propTypes = {
intl: intlShape.isRequired,
loading: PropTypes.bool,
loaded: PropTypes.bool,
loadingError: PropTypes.string,
// Form data
formValues: PropTypes.shape({
username: PropTypes.string,
name: PropTypes.string,
email: PropTypes.string,
secondary_email: PropTypes.string,
year_of_birth: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
country: PropTypes.string,
level_of_education: PropTypes.string,
gender: PropTypes.string,
language_proficiencies: PropTypes.string,
phone_number: PropTypes.string,
social_link_linkedin: PropTypes.string,
social_link_facebook: PropTypes.string,
social_link_twitter: PropTypes.string,
time_zone: PropTypes.string,
coaching: PropTypes.objectOf(PropTypes.shape({
coaching_consent: PropTypes.string.isRequired,
user: PropTypes.number.isRequired,
eligible_for_coaching: PropTypes.bool.isRequired,
})),
}).isRequired,
siteLanguage: PropTypes.shape({
previousValue: PropTypes.string,
draft: PropTypes.string,
}),
siteLanguageOptions: PropTypes.arrayOf(PropTypes.shape({
label: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
})),
profileDataManager: PropTypes.string,
staticFields: PropTypes.arrayOf(PropTypes.string),
isActive: PropTypes.bool,
secondary_email_enabled: PropTypes.bool,
timeZoneOptions: PropTypes.arrayOf(PropTypes.shape({
label: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
})),
countryTimeZoneOptions: PropTypes.arrayOf(PropTypes.shape({
label: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
})),
fetchSiteLanguages: PropTypes.func.isRequired,
updateDraft: PropTypes.func.isRequired,
saveSettings: PropTypes.func.isRequired,
fetchSettings: PropTypes.func.isRequired,
tpaProviders: PropTypes.arrayOf(PropTypes.object),
fetchAccount: PropTypes.func.isRequired,
fetchThirdPartyAuthProviders: PropTypes.func.isRequired,
};
AccountSettingsPage.defaultProps = {
loading: false,
loaded: false,
loadingError: null,
siteLanguage: null,
siteLanguageOptions: [],
timeZoneOptions: [],
countryTimeZoneOptions: [],
profileDataManager: null,
staticFields: [],
tpaProviders: [],
isActive: true,
secondary_email_enabled: false,
};
export default connect(accountSettingsPageSelector, {
fetchSettings,
saveSettings,
updateDraft,
fetchSiteLanguages,
export default connect(accountSettingsSelector, {
fetchAccount,
fetchThirdPartyAuthProviders,
})(injectIntl(AccountSettingsPage));

View File

@@ -1,4 +1,4 @@
import { defineMessages } from '@edx/frontend-platform/i18n';
import { defineMessages } from 'react-intl';
const messages = defineMessages({
'account.settings.page.heading': {
@@ -8,7 +8,7 @@ const messages = defineMessages({
},
'account.settings.loading.message': {
id: 'account.settings.loading.message',
defaultMessage: 'Loading...',
defaultMessage: 'Loading',
description: 'Message when data is being loaded',
},
'account.settings.loading.error': {
@@ -16,21 +16,6 @@ const messages = defineMessages({
defaultMessage: 'Error: {error}',
description: 'Message when data failed to load',
},
'account.settings.banner.beta.language': {
id: 'account.settings.banner.beta.language',
defaultMessage: 'You have set your language to {beta_language}, which is currently not fully translated. You can help us translate this language fully by joining the Transifex community and adding translations from English for learners that speak {beta_language}.',
description: 'Message when the user selects a beta language this is not yet fully translated.',
},
'account.settings.banner.beta.language.action.switch.back': {
id: 'account.settings.banner.beta.language.action.switch.back',
defaultMessage: 'Switch Back to {previous_language}',
description: 'Button on the beta language message to switch back to the previous language.',
},
'account.settings.banner.beta.language.action.help.translate': {
id: 'account.settings.banner.beta.language.action.help.translate',
defaultMessage: 'Help Translate into {beta_language}',
description: 'Button on the beta language message to help translate the beta language.',
},
'account.settings.section.account.information': {
id: 'account.settings.section.account.information',
defaultMessage: 'Account Information',
@@ -41,86 +26,26 @@ const messages = defineMessages({
defaultMessage: 'These settings include basic information about your account.',
description: 'The basic account information section heading description.',
},
'account.settings.section.profile.information': {
id: 'account.settings.section.profile.information',
defaultMessage: 'Profile Information',
description: 'The profile information section heading.',
},
'account.settings.section.site.preferences': {
id: 'account.settings.section.site.preferences',
defaultMessage: 'Site Preferences',
description: 'The site preferences section heading.',
},
'account.settings.section.linked.accounts': {
id: 'account.settings.section.linked.accounts',
defaultMessage: 'Linked Accounts',
description: 'The linked accounts section heading.',
},
'account.settings.section.linked.accounts.description': {
id: 'account.settings.section.linked.accounts.description',
defaultMessage: 'You can link your identity accounts to simplify signing in to edX.',
description: 'The linked accounts section heading description.',
},
'account.settings.field.username': {
id: 'account.settings.field.username',
defaultMessage: 'Username',
description: 'Label for account settings username field.',
},
'account.settings.field.username.help.text': {
id: 'account.settings.field.username.help.text',
defaultMessage: 'The name that identifies you on edX. You cannot change your username.',
description: 'Help text for the account settings username field.',
},
'account.settings.field.full.name': {
id: 'account.settings.field.full.name',
defaultMessage: 'Full name',
description: 'Label for account settings name field.',
},
'account.settings.field.full.name.empty': {
id: 'account.settings.field.full.name.empty',
defaultMessage: 'Add name',
description: 'Placeholder for empty account settings name field.',
},
'account.settings.field.full.name.help.text': {
id: 'account.settings.field.full.name.help.text',
defaultMessage: 'The name that is used for ID verification and that appears on your certificates.',
description: 'Help text for the account settings name field.',
},
'account.settings.field.email': {
id: 'account.settings.field.email',
defaultMessage: 'Email address (Sign in)',
description: 'Label for account settings email field.',
},
'account.settings.field.email.empty': {
id: 'account.settings.field.email.empty',
defaultMessage: 'Add email address',
description: 'Placeholder for empty account settings email field.',
},
'account.settings.field.email.confirmation': {
id: 'account.settings.field.email.confirmation',
defaultMessage: 'Weve sent a confirmation message to {value}. Click the link in the message to update your email address.',
description: 'Confirmation message for saving the account settings email field.',
},
'account.settings.field.email.help.text': {
id: 'account.settings.field.email.help.text',
defaultMessage: 'You receive messages from edX and course teams at this address.',
description: 'Help text for the account settings email field.',
},
'account.settings.field.secondary.email': {
id: 'account.settings.field.secondary.email',
defaultMessage: 'Recovery email address',
description: 'Label for account settings recovery email field.',
},
'account.settings.field.secondary.email.empty': {
id: 'account.settings.field.secondary.email.empty',
defaultMessage: 'Add a recovery email address',
description: 'Placeholder for empty account settings recovery email field.',
},
'account.settings.field.secondary.email.confirmation': {
id: 'account.settings.field.secondary.email.confirmation',
defaultMessage: 'Weve sent a confirmation message to {value}. Click the link in the message to update your recovery email address.',
description: 'Confirmation message for saving the account settings recovery email field.',
},
'account.settings.email.field.confirmation.header': {
id: 'account.settings.email.field.confirmation.header',
defaultMessage: 'One more step!',
@@ -131,53 +56,19 @@ const messages = defineMessages({
defaultMessage: 'Year of birth',
description: 'Label for account settings year of birth field.',
},
'account.settings.field.dob.empty': {
id: 'account.settings.field.dob.empty',
defaultMessage: 'Add year of birth',
description: 'Placeholder for empty account settings year of birth field.',
},
'account.settings.field.year_of_birth.options.empty': {
id: 'account.settings.field.year_of_birth.options.empty',
defaultMessage: 'Select a year of birth',
description: 'Option for empty value on account settings year of birth field.',
},
'account.settings.field.country': {
id: 'account.settings.field.country',
defaultMessage: 'Country',
description: 'Label for account settings country field.',
},
'account.settings.field.country.empty': {
id: 'account.settings.field.country.empty',
defaultMessage: 'Add country',
description: 'Placeholder for empty account settings country field.',
},
'account.settings.field.country.options.empty': {
id: 'account.settings.field.country.options.empty',
defaultMessage: 'Select a Country',
description: 'Option for empty value on account settings country field.',
},
'account.settings.field.site.language': {
id: 'account.settings.field.site.language',
defaultMessage: 'Site language',
description: 'Label for account settings site language field.',
},
'account.settings.field.site.language.help.text': {
id: 'account.settings.field.site.language.help.text',
defaultMessage: 'The language used throughout this site. This site is currently available in a limited number of languages.',
description: 'Help text for the site language field.',
},
'account.settings.field.education': {
id: 'account.settings.field.education',
defaultMessage: 'Education',
description: 'Label for account settings education field.',
},
'account.settings.field.education.empty': {
id: 'account.settings.field.education.empty',
defaultMessage: 'Add level of education',
description: 'Placeholder for empty account settings education field.',
},
'account.settings.field.education.levels.empty': {
id: 'account.settings.field.education.levels.empty',
'account.settings.field.education.levels.null': {
id: 'account.settings.field.education.levels.null',
defaultMessage: 'Select a level of education',
description: 'Placeholder for the education levels dropdown.',
},
@@ -232,13 +123,8 @@ const messages = defineMessages({
defaultMessage: 'Gender',
description: 'Label for account settings gender field.',
},
'account.settings.field.gender.empty': {
id: 'account.settings.field.gender.empty',
defaultMessage: 'Add gender',
description: 'Placeholder for empty account settings gender field.',
},
'account.settings.field.gender.options.empty': {
id: 'account.settings.field.gender.options.empty',
'account.settings.field.gender.options.null': {
id: 'account.settings.field.gender.options.null',
defaultMessage: 'Select a gender',
description: 'Placeholder for the gender options dropdown.',
},
@@ -257,51 +143,12 @@ const messages = defineMessages({
defaultMessage: 'Other',
description: 'The label for catch-all gender option.',
},
'account.settings.field.language.proficiencies': {
id: 'account.settings.field.language.proficiencies',
defaultMessage: 'Spoken languages',
defaultMessage: 'Spoken Languages',
description: 'Label for account settings spoken languages field.',
},
'account.settings.field.language.proficiencies.empty': {
id: 'account.settings.field.language.proficiencies.empty',
defaultMessage: 'Add a spoken language',
description: 'Placeholder for empty account settings spoken languages field.',
},
'account.settings.field.language_proficiencies.options.empty': {
id: 'account.settings.field.language_proficiencies.options.empty',
defaultMessage: 'Select a Language',
description: 'Option for an empty value on account settings spoken languages field.',
},
'account.settings.field.time.zone': {
id: 'account.settings.field.time.zone',
defaultMessage: 'Time zone',
description: 'Label for time zone settings field.',
},
'account.settings.field.time.zone.empty': {
id: 'account.settings.field.time.zone.empty',
defaultMessage: 'Set time zone',
description: 'Placeholder for empty for time zone settings field.',
},
'account.settings.field.time.zone.description': {
id: 'account.settings.field.time.zone.description',
defaultMessage: 'Select the time zone for displaying course dates. If you do not specify a time zone, course dates, including assignment deadlines, will be displayed in your browsers local time zone.',
description: 'Description for time zone settings field.',
},
'account.settings.field.time.zone.default': {
id: 'account.settings.field.time.zone.default',
defaultMessage: 'Default (Local Time Zone)',
description: 'The default option for a time zone.',
},
'account.settings.field.time.zone.all': {
id: 'account.settings.field.time.zone.all',
defaultMessage: 'All time zones',
description: 'The label for the group of options for all time zones.',
},
'account.settings.field.time.zone.country': {
id: 'account.settings.field.time.zone.country',
defaultMessage: 'Country time zones',
description: 'The group of time zone options for a country.',
},
'account.settings.section.social.media': {
id: 'account.settings.section.social.media',
@@ -318,36 +165,21 @@ const messages = defineMessages({
defaultMessage: 'LinkedIn',
description: 'Label for LinkedIn',
},
'account.settings.field.social.platform.name.linkedin.empty': {
id: 'account.settings.field.social.platform.name.linkedin.empty',
defaultMessage: 'Add LinkedIn profile',
description: 'Placeholder for an empty LinkedIn field',
},
'account.settings.jump.nav.delete.account': {
id: 'account.settings.jump.nav.delete.account',
defaultMessage: 'Delete My Account',
description: 'Header for the user account deletion area',
},
'account.settings.field.social.platform.name.twitter': {
id: 'account.settings.field.social.platform.name.twitter',
defaultMessage: 'Twitter',
description: 'Label for Twitter',
},
'account.settings.field.social.platform.name.twitter.empty': {
id: 'account.settings.field.social.platform.name.twitter.empty',
defaultMessage: 'Add Twitter profile',
description: 'Placeholder for an empty Twitter field',
},
'account.settings.field.social.platform.name.facebook': {
id: 'account.settings.field.social.platform.name.facebook',
defaultMessage: 'Facebook',
description: 'Label for Facebook',
},
'account.settings.field.social.platform.name.facebook.empty': {
id: 'account.settings.field.social.platform.name.facebook.empty',
defaultMessage: 'Add Facebook profile',
description: 'Placeholder for an empty Facebook field',
'account.settings.editable.field.password.reset.button': {
id: 'account.settings.editable.field.password.reset.button',
defaultMessage: 'Reset Password',
description: 'The password reset button in account settings',
},
'account.settings.editable.field.action.save': {
id: 'account.settings.editable.field.action.save',
@@ -364,16 +196,6 @@ const messages = defineMessages({
defaultMessage: 'Edit',
description: 'The edit button on an editable field',
},
'account.settings.static.field.empty': {
id: 'account.settings.static.field.empty',
defaultMessage: 'No value set. Contact your {enterprise} administrator to make changes.',
description: 'The placeholder for an empty but uneditable field',
},
'account.settings.static.field.empty.no.admin': {
id: 'account.settings.static.field.empty.no.admin',
defaultMessage: 'No value set.',
description: 'The placeholder for an empty but uneditable field when there is no administrator',
},
});
export default messages;

View File

@@ -1,116 +0,0 @@
import React from 'react';
import PropTypes from 'prop-types';
import { AppContext } from '@edx/frontend-platform/react';
import { injectIntl, intlShape } from '@edx/frontend-platform/i18n';
import { connect } from 'react-redux';
import { Button, Hyperlink } from '@edx/paragon';
import { betaLanguageBannerSelector } from './data/selectors';
import messages from './AccountSettingsPage.messages';
import { saveSettings } from './data/actions';
import { TRANSIFEX_LANGUAGE_BASE_URL } from './data/constants';
import Alert from './Alert';
class BetaLanguageBanner extends React.Component {
getSiteLanguageEntry(languageCode) {
return this.props.siteLanguageList.filter(l => l.code === languageCode)[0];
}
/**
* Returns a link to the Transifex URL where contributors can provide translations.
* This code is tightly coupled to how Transifex chooses to design its URLs.
*/
getTransifexLink(languageCode) {
return TRANSIFEX_LANGUAGE_BASE_URL + this.getTransifexURLPath(languageCode);
}
/**
* Returns the URL path that Transifex chooses to use for its language sub-pages.
*
* For extended language codes, it returns the 2nd half capitalized, replacing
* hyphen (-) with underscore (_).
* example: pt-br -> pt_BR
*
* For short language codes, it returns the code as is.
* example: fr -> fr
*/
getTransifexURLPath(languageCode) {
const tokenizedCode = languageCode.split('-');
if (tokenizedCode.length > 1) {
return `${tokenizedCode[0]}_${tokenizedCode[1].toUpperCase()}`;
}
return tokenizedCode[0];
}
handleRevertLanguage = () => {
const previousSiteLanguage = this.props.siteLanguage.previousValue;
this.props.saveSettings('siteLanguage', previousSiteLanguage);
};
render() {
const savedLanguage = this.getSiteLanguageEntry(this.context.locale);
const isSavedLanguageReleased = savedLanguage.released === true;
const noPreviousLanguageSet = this.props.siteLanguage.previousValue === null;
if (isSavedLanguageReleased || noPreviousLanguageSet) {
return null;
}
const previousLanguage = this.getSiteLanguageEntry(this.props.siteLanguage.previousValue);
return (
<div>
<Alert className="beta_language_alert alert alert-warning" role="alert">
<p>
{this.props.intl.formatMessage(messages['account.settings.banner.beta.language'], {
beta_language: savedLanguage.name,
})}
</p>
<div>
<Button onClick={this.handleRevertLanguage} className="btn btn-primary mr-2">
{this.props.intl.formatMessage(
messages['account.settings.banner.beta.language.action.switch.back'],
{ previous_language: previousLanguage.name },
)}
</Button>
<Hyperlink
destination={this.getTransifexLink(savedLanguage.code)}
className="btn btn-outline-secondary"
target="_blank"
>
{this.props.intl.formatMessage(
messages['account.settings.banner.beta.language.action.help.translate'],
{ beta_language: savedLanguage.name },
)}
</Hyperlink>
</div>
</Alert>
</div>
);
}
}
BetaLanguageBanner.contextType = AppContext;
BetaLanguageBanner.propTypes = {
intl: intlShape.isRequired,
siteLanguage: PropTypes.shape({
previousValue: PropTypes.string,
draft: PropTypes.string,
}),
siteLanguageList: PropTypes.arrayOf(PropTypes.shape({
name: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
code: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
released: PropTypes.bool,
})).isRequired,
saveSettings: PropTypes.func.isRequired,
};
BetaLanguageBanner.defaultProps = {
siteLanguage: null,
};
export default connect(
betaLanguageBannerSelector,
{
saveSettings,
},
)(injectIntl(BetaLanguageBanner));

View File

@@ -1,65 +0,0 @@
import React from 'react';
import { injectIntl, intlShape } from '@edx/frontend-platform/i18n';
import { NavHashLink } from 'react-router-hash-link';
import Scrollspy from 'react-scrollspy';
import messages from './AccountSettingsPage.messages';
function JumpNav({ intl }) {
return (
<div className="jump-nav">
<Scrollspy
items={[
'basic-information',
'profile-information',
'social-media',
'site-preferences',
'linked-accounts',
'delete-account',
]}
className="list-unstyled"
currentClassName="font-weight-bold"
>
<li>
<NavHashLink to="#basic-information">
{intl.formatMessage(messages['account.settings.section.account.information'])}
</NavHashLink>
</li>
<li>
<NavHashLink to="#profile-information">
{intl.formatMessage(messages['account.settings.section.profile.information'])}
</NavHashLink>
</li>
<li>
<NavHashLink to="#social-media">
{intl.formatMessage(messages['account.settings.section.social.media'])}
</NavHashLink>
</li>
<li>
<NavHashLink to="#site-preferences">
{intl.formatMessage(messages['account.settings.section.site.preferences'])}
</NavHashLink>
</li>
<li>
<NavHashLink to="#linked-accounts">
{intl.formatMessage(messages['account.settings.section.linked.accounts'])}
</NavHashLink>
</li>
<li>
<NavHashLink to="#delete-account">
{intl.formatMessage(messages['account.settings.jump.nav.delete.account'])}
</NavHashLink>
</li>
</Scrollspy>
</div>
);
}
JumpNav.propTypes = {
intl: intlShape.isRequired,
};
export default injectIntl(JumpNav);

View File

@@ -11,37 +11,4 @@
padding: 0;
display: inline-block;
}
.jump-nav {
@media (min-width: map-get($grid-breakpoints, "sm")) {
padding-top: 1rem;
position: sticky;
top: 1rem;
}
li {
margin-bottom: .5rem;
a {
text-decoration: underline;
}
}
}
.section-heading {
@extend .h4;
margin-bottom: map-get($spacers, 3);
}
.account-section {
// These properties together will shift the hashlink position
margin-bottom: map-get($spacers, 5);
padding-top: 1rem;
}
.custom-switch {
padding: 0;
max-width: 500px;
.custom-control-label {
left: 2.25rem;
line-height: 1.6rem;
}
}
}

View File

@@ -0,0 +1,122 @@
import { utils } from '../common';
const { AsyncActionType } = utils;
export const FETCH_ACCOUNT = new AsyncActionType('ACCOUNT_SETTINGS', 'FETCH_ACCOUNT');
export const SAVE_ACCOUNT = new AsyncActionType('ACCOUNT_SETTINGS', 'SAVE_ACCOUNT');
export const FETCH_THIRD_PARTY_AUTH_PROVIDERS = new AsyncActionType('ACCOUNT_SETTINGS', 'FETCH_THIRD_PARTY_AUTH_PROVIDERS');
export const RESET_PASSWORD = new AsyncActionType('ACCOUNT_SETTINGS', 'RESET_PASSWORD');
export const OPEN_FORM = 'OPEN_FORM';
export const CLOSE_FORM = 'CLOSE_FORM';
export const UPDATE_DRAFT = 'UPDATE_DRAFT';
export const RESET_DRAFTS = 'RESET_DRAFTS';
// FETCH EXAMPLE ACTIONS
export const fetchAccount = () => ({
type: FETCH_ACCOUNT.BASE,
});
export const fetchAccountBegin = () => ({
type: FETCH_ACCOUNT.BEGIN,
});
export const fetchAccountSuccess = values => ({
type: FETCH_ACCOUNT.SUCCESS,
payload: { values },
});
export const fetchAccountFailure = error => ({
type: FETCH_ACCOUNT.FAILURE,
payload: { error },
});
export const fetchAccountReset = () => ({
type: FETCH_ACCOUNT.RESET,
});
export const openForm = formId => ({
type: OPEN_FORM,
payload: { formId },
});
export const closeForm = formId => ({
type: CLOSE_FORM,
payload: { formId },
});
// FORM STATE ACTIONS
export const updateDraft = (name, value) => ({
type: UPDATE_DRAFT,
payload: {
name,
value,
},
});
export const resetDrafts = () => ({
type: RESET_DRAFTS,
});
// SAVE PROFILE ACTIONS
export const saveAccount = (formId, commitValues) => ({
type: SAVE_ACCOUNT.BASE,
payload: { formId, commitValues },
});
export const saveAccountBegin = () => ({
type: SAVE_ACCOUNT.BEGIN,
});
export const saveAccountSuccess = (values, confirmationValues) => ({
type: SAVE_ACCOUNT.SUCCESS,
payload: { values, confirmationValues },
});
export const saveAccountReset = () => ({
type: SAVE_ACCOUNT.RESET,
});
export const saveAccountFailure = ({ fieldErrors, message }) => ({
type: SAVE_ACCOUNT.FAILURE,
payload: { errors: fieldErrors, message },
});
// SAVE PROFILE ACTIONS
export const resetPassword = () => ({
type: RESET_PASSWORD.BASE,
});
export const resetPasswordBegin = () => ({
type: RESET_PASSWORD.BEGIN,
});
export const resetPasswordSuccess = () => ({
type: RESET_PASSWORD.SUCCESS,
});
export const resetPasswordReset = () => ({
type: RESET_PASSWORD.RESET,
});
// fetch third party auth providers
export const fetchThirdPartyAuthProviders = () => ({
type: FETCH_THIRD_PARTY_AUTH_PROVIDERS.BASE,
});
export const fetchThirdPartyAuthProvidersBegin = () => ({
type: FETCH_THIRD_PARTY_AUTH_PROVIDERS.BEGIN,
});
export const fetchThirdPartyAuthProvidersSuccess = providers => ({
type: FETCH_THIRD_PARTY_AUTH_PROVIDERS.SUCCESS, payload: { providers },
});
export const fetchThirdPartyAuthProvidersFailure = error => ({
type: FETCH_THIRD_PARTY_AUTH_PROVIDERS.FAILURE, payload: { error },
});

View File

@@ -1,293 +0,0 @@
import React from 'react';
import { getConfig, getQueryParameters } from '@edx/frontend-platform';
import { injectIntl, intlShape } from '@edx/frontend-platform/i18n';
import { Hyperlink } from '@edx/paragon';
import { faCheck } from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import PageLoading from '../PageLoading';
import CoachingConsentForm from './CoachingConsentForm';
import messages from './CoachingConsent.messages';
import LogoSVG from '../../logo.svg';
import { fetchSettings, saveSettings } from '../data/actions';
import { coachingConsentPageSelector } from '../data/selectors';
const Logo = ({ src, alt, ...attributes }) => (
<>
<img src={src} alt={alt} {...attributes} />
</>
);
const SuccessMessage = props => (
<div className="col-12 col-lg-6 shadow-lg mx-auto mt-4 p-5">
<FontAwesomeIcon className="text-success" icon={faCheck} size="5x" />
<div className="h3">{props.header}</div>
<div>{props.message}</div>
<Hyperlink destination={props.continueUrl} className="d-block p-2 my-3 text-center text-white bg-primary rounded">
{props.continue}
</Hyperlink>
</div>
);
const AutoRedirect = (props) => {
window.location.href = props.redirectUrl;
return <></>;
};
const VIEWS = {
NOT_LOADED: 'NOT_LOADED',
LOADED: 'LOADED',
SUCCESS: 'SUCCESS',
SUCCESS_PENDING: 'SUCCESS_PENDING',
DECLINED: 'DECLINED',
DECLINE_PENDING: 'DECLINE_PENDING',
};
class CoachingConsent extends React.Component {
constructor(props, context) {
super(props, context);
// Used to redirect back to the courseware.
const nextUrl = this.sanitizeForwardingUrl(getQueryParameters().next);
this.state = {
redirectUrl: nextUrl || `${getConfig().LMS_BASE_URL}/dashboard/`,
formErrors: {},
formSubmitted: false,
declineSubmitted: false,
allSubmissionsComplete: false,
};
this.handleSubmit = this.handleSubmit.bind(this);
this.declineCoaching = this.declineCoaching.bind(this);
}
componentDidMount() {
this.props.fetchSettings();
}
componentDidUpdate(prevProps, prevState) {
/*
When we are submitting the form, we're calling saveSettings 3 times, which causes
multiple parallel redux flows. Because of this we can't rely on just the redux states
being sent in through props. For instance if the coaching submission and name
submission happen in near parallel, the coaching flow could return errors in
formErrors and the name flow could overwrite the formErrors with an empty object.
To minimize disruption to the rest of the app, we're going to manage flow state from
within this component.
*/
// If a new error comes in, store it before the next redux call overwrites it.
let allFormErrors = {};
let allSubmissionsComplete = false;
// Collect new errors and add to state (will be cleared on new submission)
const newErrorsFound = (
this.props.formErrors !== prevProps.formErrors
&& Object.keys(this.props.formErrors).length > 0
);
if (newErrorsFound) {
allFormErrors = Object.assign({}, this.state.formErrors, this.props.formErrors);
}
// Check if all values from the form have confirmation values
if (
this.state.formSubmitted &&
this.props.confirmationValues.coaching &&
this.props.confirmationValues.name &&
this.props.confirmationValues.phone_number
) {
allSubmissionsComplete = true;
}
// Check if all values from the decline link have confirmation values
if (this.props.confirmationValues.coaching && this.state.declineSubmitted) {
allSubmissionsComplete = true;
}
if (newErrorsFound || (allSubmissionsComplete !== prevState.allSubmissionsComplete)) {
this.setState({
formErrors: allFormErrors,
allSubmissionsComplete,
});
}
}
sanitizeForwardingUrl(url) {
// Redirect to root of MFE if invalid next param is sent
return url && url.startsWith(getConfig().LMS_BASE_URL) ? url : `${getConfig().LMS_BASE_URL}/dashboard/`;
}
async handleSubmit(e) {
e.preventDefault();
this.setState({
formErrors: {},
formSubmitted: true,
});
// Must store target values or they disappear before the async function can use them.
const fullName = e.target.fullName.value;
const phoneNumber = e.target.phoneNumber.value;
const coachingValues = this.props.formValues.coaching;
// These will overwrite each other's redux states (see componentDidUpdate note)
this.props.saveSettings('name', fullName);
this.props.saveSettings('phone_number', phoneNumber);
this.props.saveSettings('coaching', {
...coachingValues,
phone_number: phoneNumber,
coaching_consent: true,
consent_form_seen: true,
});
}
async declineCoaching(e) {
e.preventDefault();
this.setState({
formErrors: {},
declineSubmitted: true,
});
// Must store target values or they disappear before the async function can use them.
const coachingValues = this.props.formValues.coaching;
this.props.saveSettings('coaching', {
...coachingValues,
coaching_consent: false,
consent_form_seen: true,
});
}
renderView(currentView) {
switch (currentView) {
case VIEWS.NOT_LOADED:
return <PageLoading srMessage="" />;
case VIEWS.LOADED:
return (<CoachingConsentForm
onSubmit={this.handleSubmit}
declineCoaching={this.declineCoaching}
formErrors={this.state.formErrors}
formValues={this.props.formValues}
redirectUrl={this.state.redirectUrl}
/>);
case VIEWS.SUCCESS_PENDING:
return <PageLoading srMessage="Submitting..." />;
case VIEWS.SUCCESS:
return (<SuccessMessage
continueUrl={this.state.redirectUrl}
header={this.props.intl.formatMessage(messages['account.settings.coaching.consent.success.header'])}
message={this.props.intl.formatMessage(messages['account.settings.coaching.consent.success.message'])}
continue={this.props.intl.formatMessage(messages['account.settings.coaching.consent.success.continue'])}
/>);
case VIEWS.DECLINE_PENDING:
return <PageLoading srMessage="Redirecting..." />;
case VIEWS.DECLINED:
return <AutoRedirect redirectUrl={this.state.redirectUrl} />;
default:
return <></>;
}
}
render() {
const { loaded } = this.props;
const formHasErrors = Object.keys(this.state.formErrors).length > 0;
let currentView = null;
// This amount of logic was making the template very hard to read, so I broke it out into views.
if (!loaded) {
currentView = VIEWS.NOT_LOADED;
} else if (this.state.formSubmitted && !formHasErrors) {
if (this.state.allSubmissionsComplete) {
currentView = VIEWS.SUCCESS;
} else {
currentView = VIEWS.SUCCESS_PENDING;
}
} else if (this.state.declineSubmitted && !formHasErrors) {
if (this.state.allSubmissionsComplete) {
currentView = VIEWS.DECLINED;
} else {
currentView = VIEWS.DECLINE_PENDING;
}
} else {
currentView = VIEWS.LOADED;
}
return (
<main>
<div className="w-100 d-flex justify-content-center align-items-center shadow coaching-header">
<Logo
className="logo"
src={LogoSVG}
alt="Logo"
/>
</div>
{this.renderView(currentView)}
</main>
);
}
}
Logo.defaultProps = {
src: '',
alt: '',
};
Logo.propTypes = {
src: PropTypes.string,
alt: PropTypes.string,
};
SuccessMessage.defaultProps = {
header: '',
message: '',
continueUrl: '',
continue: '',
};
SuccessMessage.propTypes = {
header: PropTypes.string,
message: PropTypes.string,
continueUrl: PropTypes.string,
continue: PropTypes.string,
};
AutoRedirect.defaultProps = {
redirectUrl: '',
};
AutoRedirect.propTypes = {
redirectUrl: PropTypes.string,
};
CoachingConsent.defaultProps = {
loaded: false,
};
CoachingConsent.propTypes = {
intl: intlShape.isRequired,
loaded: PropTypes.bool,
formValues: PropTypes.shape({
name: PropTypes.string,
phone_number: PropTypes.string,
coaching: PropTypes.shape({
coaching_consent: PropTypes.bool.isRequired,
user: PropTypes.number.isRequired,
eligible_for_coaching: PropTypes.bool.isRequired,
consent_form_seen: PropTypes.bool.isRequired,
}),
}).isRequired,
formErrors: PropTypes.shape({
coaching: PropTypes.object,
}).isRequired,
confirmationValues: PropTypes.shape({
coaching: PropTypes.object,
name: PropTypes.object,
phone_number: PropTypes.object,
}).isRequired,
fetchSettings: PropTypes.func.isRequired,
saveSettings: PropTypes.func.isRequired,
};
export default connect(coachingConsentPageSelector, {
fetchSettings,
saveSettings,
})(injectIntl(CoachingConsent));

View File

@@ -1,61 +0,0 @@
import { defineMessages } from '@edx/frontend-platform/i18n';
const messages = defineMessages({
'account.settings.coaching.consent.welcome.header': {
id: 'account.settings.coaching.consent.welcome.header',
defaultMessage: 'Lets get started.',
description: 'The welcome header for consent form.',
},
'account.settings.coaching.consent.welcome.subheader': {
id: 'account.settings.coaching.consent.welcome.subheader',
defaultMessage: "We're here for you from start to finish",
description: 'The welcome subheader for consent form.',
},
'account.settings.coaching.consent.description': {
id: 'account.settings.coaching.consent.description',
defaultMessage: "MicroBachelors programs include coaching that focuses on your career, education, and how you'll achieve results through one-on-one communication with an experienced professional. If youre interested, provide the information below and click “Submit,” and our coaching partner will connect with you via email and/or text message to help you move forward. Terms and conditions apply.*",
description: 'Text describing what Coaching is.',
},
'account.settings.coaching.consent.text-messaging.disclaimer': {
id: 'account.settings.coaching.consent.text-messaging.disclaimer',
defaultMessage: '* Coaching services are included at no additional cost to learners with US phone numbers. Coaching includes recurring text messages. Message and data rates may apply. Text STOP to opt-out.',
description: 'Text describing what Coaching is.',
},
'account.settings.coaching.consent.accept-coaching': {
id: 'account.settings.coaching.consent.accept-coaching',
defaultMessage: 'Sign up for coaching',
description: 'Text to confirm coaching enablement',
},
'account.settings.coaching.consent.decline-coaching': {
id: 'account.settings.coaching.consent.decline-coaching',
defaultMessage: 'I prefer not to be contacted with free coaching services',
description: 'Text to decline coaching enablement',
},
'account.settings.coaching.consent.label.name': {
id: 'account.settings.coaching.consent.label.name',
defaultMessage: 'Please confirm your name',
description: 'Label for name input',
},
'account.settings.coaching.consent.label.phone-number': {
id: 'account.settings.coaching.consent.label.phone-number',
defaultMessage: 'Enter your mobile number',
description: 'Label for mobile phone number input',
},
'account.settings.coaching.consent.success.header': {
id: 'account.settings.coaching.consent.success.header',
defaultMessage: 'Success!',
description: 'Heading announcing that submission succeeded',
},
'account.settings.coaching.consent.success.message': {
id: 'account.settings.coaching.consent.success.message',
defaultMessage: "You're signed up for coaching. You will receive a text message confirmation.",
description: 'Text announcing that you have signed up and will receive texts',
},
'account.settings.coaching.consent.success.continue': {
id: 'account.settings.coaching.consent.success.continue',
defaultMessage: 'Start my course',
description: 'Text that the user will be sent back to the courseware',
},
});
export default messages;

View File

@@ -1,104 +0,0 @@
import React from 'react';
import { injectIntl, intlShape } from '@edx/frontend-platform/i18n';
import { Input, Button, Hyperlink } from '@edx/paragon';
import PropTypes from 'prop-types';
import messages from './CoachingConsent.messages';
const ErrorMessage = props => (
<div className="alert-warning mb-2">{props.message}</div>
);
const CoachingForm = props => (
<div className="col-12 col-md-6 col-xl-5 mx-auto mt-4 p-5 shadow-lg">
<h2 className="h2">
{props.intl.formatMessage(messages['account.settings.coaching.consent.welcome.header'])}
</h2>
<p>{props.intl.formatMessage(messages['account.settings.coaching.consent.description'])}</p>
<div>
<form onSubmit={props.onSubmit}>
<div className="py-3">
<ErrorMessage message={props.formErrors.name} />
<label className="h6" htmlFor="fullName">{props.intl.formatMessage(messages['account.settings.coaching.consent.label.name'])}</label>
<Input
type="text"
name="full-name"
id="fullName"
defaultValue={props.formValues.name}
/>
</div>
<div className="py-3">
<ErrorMessage message={props.formErrors.phone_number} />
<label className="h6" htmlFor="phoneNumber">{props.intl.formatMessage(messages['account.settings.coaching.consent.label.phone-number'])}</label>
<Input
type="text"
name="full-name"
id="phoneNumber"
defaultValue={props.formValues.phone_number}
/>
</div>
<div className=" py-3">
<p className="small font-italic">
{props.intl.formatMessage(messages['account.settings.coaching.consent.text-messaging.disclaimer'])}
</p>
</div>
<ErrorMessage message={props.formErrors.coaching} />
<div className="d-flex flex-column align-items-center">
<Button className="w-100 btn-outline-primary" type="submit">
{props.intl.formatMessage(messages['account.settings.coaching.consent.accept-coaching'])}
</Button>
</div>
<div className="mt-3">
<Hyperlink
className="mt-3 text-dark btn-link small"
destination={props.redirectUrl}
onClick={props.declineCoaching}
>
{props.intl.formatMessage(messages['account.settings.coaching.consent.decline-coaching'])}
</Hyperlink>
</div>
</form>
</div>
</div>
);
CoachingForm.defaultProps = {
formErrors: {
coaching: '',
name: '',
phone_number: '',
},
};
CoachingForm.propTypes = {
intl: intlShape.isRequired,
onSubmit: PropTypes.func.isRequired,
declineCoaching: PropTypes.func.isRequired,
formValues: PropTypes.shape({
name: PropTypes.string,
phone_number: PropTypes.string,
coaching: PropTypes.shape({
coaching_consent: PropTypes.bool.isRequired,
user: PropTypes.number.isRequired,
eligible_for_coaching: PropTypes.bool.isRequired,
consent_form_seen: PropTypes.bool.isRequired,
}),
}).isRequired,
formErrors: PropTypes.shape({
coaching: PropTypes.string,
name: PropTypes.string,
phone_number: PropTypes.string,
}),
redirectUrl: PropTypes.string.isRequired,
};
ErrorMessage.defaultProps = {
message: '',
};
ErrorMessage.propTypes = {
message: PropTypes.string,
};
export default injectIntl(CoachingForm);

View File

@@ -1,76 +0,0 @@
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { injectIntl, intlShape } from '@edx/frontend-platform/i18n';
import { ValidationFormGroup, Input } from '@edx/paragon';
import messages from './CoachingToggle.messages';
import { editableFieldSelector } from '../data/selectors';
import { saveSettings, updateDraft } from '../data/actions';
import EditableField from '../EditableField';
const CoachingToggle = props => (
<>
<EditableField
name="phone_number"
type="text"
value={props.phone_number}
label={props.intl.formatMessage(messages['account.settings.field.phone_number'])}
emptyLabel={props.intl.formatMessage(messages['account.settings.field.phone_number.empty'])}
onChange={props.updateDraft}
onSubmit={props.saveSettings}
/>
<ValidationFormGroup
for="coachingConsent"
helpText={props.intl.formatMessage(messages['account.settings.field.coaching_consent.tooltip'])}
invalid={!!props.error}
invalidMessage={props.intl.formatMessage(messages['account.settings.field.coaching_consent.error'])}
className="custom-control custom-switch"
>
<Input
name={props.name}
className="custom-control-input"
disabled={props.saveState === 'pending'}
type="checkbox"
id="coachingConsent"
checked={props.coaching.coaching_consent}
value={props.coaching.coaching_consent}
onChange={async (e) => {
const { name } = e.target;
const value = {
...props.coaching,
phone_number: props.phone_number,
coaching_consent: e.target.checked,
};
props.saveSettings(name, value);
}}
/>
<label className="custom-control-label" htmlFor="coachingConsent">{props.intl.formatMessage(messages['account.settings.field.coaching_consent'])}</label>
</ValidationFormGroup>
</>
);
CoachingToggle.defaultProps = {
phone_number: '',
error: '',
};
CoachingToggle.propTypes = {
name: PropTypes.string.isRequired,
error: PropTypes.string,
coaching: PropTypes.objectOf(PropTypes.shape({
coaching_consent: PropTypes.string.isRequired,
user: PropTypes.number.isRequired,
eligible_for_coaching: PropTypes.bool.isRequired,
})).isRequired,
saveState: PropTypes.func.isRequired,
saveSettings: PropTypes.func.isRequired,
updateDraft: PropTypes.func.isRequired,
intl: intlShape.isRequired,
phone_number: PropTypes.string,
};
export default connect(editableFieldSelector, {
saveSettings,
updateDraft,
})(injectIntl(CoachingToggle));

View File

@@ -1,31 +0,0 @@
import { defineMessages } from '@edx/frontend-platform/i18n';
const messages = defineMessages({
'account.settings.field.phone_number': {
id: 'account.settings.field.phone_number',
defaultMessage: 'Phone Number',
description: 'The label for a phone numbers setting in the user profile',
},
'account.settings.field.phone_number.empty': {
id: 'account.settings.field.phone_number.empty',
defaultMessage: 'Add a phone number',
description: 'placeholder for a profiles empty phone number field',
},
'account.settings.field.coaching_consent': {
id: 'account.settings.field.coaching_consent',
defaultMessage: 'Coaching consent',
description: 'The label for the coaching consent setting in the user profile',
},
'account.settings.field.coaching_consent.tooltip': {
id: 'account.settings.field.coaching_consent.tooltip',
defaultMessage: 'MicroBachelors programs include text message based coaching that helps you pair educational experiences with your career goals through one-on-one advice. Coaching services are included at no additional cost, and are available in English and Spanish languages. Standard messaging rates apply. Text STOP at anytime to opt-out of messages.',
description: 'A tooltip explaining what coaching is and who it is for',
},
'account.settings.field.coaching_consent.error': {
id: 'account.settings.field.coaching_consent.error',
defaultMessage: 'A valid US phone number is required to opt into coaching',
description: 'An error message that displays when a user attempts to consent to coaching without first providing a phone number in their profile',
},
});
export default messages;

View File

@@ -1,49 +0,0 @@
import { getAuthenticatedHttpClient } from '@edx/frontend-platform/auth';
import { getConfig } from '@edx/frontend-platform';
/**
* get all settings related to the coaching plugin. Settings used
* by Microbachelors students.
* @param {Number} userId users are identified in the api by LMS id
*/
export async function getCoachingPreferences(userId) {
let data = null;
try {
({ data } = await getAuthenticatedHttpClient()
.get(`${getConfig().LMS_BASE_URL}/api/coaching/v1/users/${userId}/`));
} catch (error) {
// Default values so the client doesn't fail if the user doesn't have an entry in the
// UserCoaching model yet, with the assumption that they'll be eligible for coaching
// when they hit this form.
data = {
coaching_consent: false,
user: userId,
eligible_for_coaching: true,
consent_form_seen: false,
};
}
return data;
}
/**
* patch all of the settings related to coaching.
* @param {Number} userId users are identified in the api by LMS id
* @param {Object} commitValues { coaching }
*/
export async function patchCoachingPreferences(userId, commitValues) {
const requestUrl = `${getConfig().LMS_BASE_URL}/api/coaching/v1/users/${userId}/`;
const { coaching } = commitValues;
coaching.user = userId;
await getAuthenticatedHttpClient()
.patch(requestUrl, coaching)
.catch((error) => {
const apiError = Object.create(error);
apiError.fieldErrors = JSON.parse(error.customAttributes.httpErrorResponseData);
// eslint-disable-next-line prefer-destructuring
apiError.fieldErrors.coaching = apiError.fieldErrors.phone_number[0];
delete apiError.fieldErrors.phone_number;
throw apiError;
});
return commitValues;
}

View File

@@ -1,26 +1,27 @@
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { injectIntl, intlShape } from '@edx/frontend-platform/i18n';
import { Button, Input, StatefulButton, ValidationFormGroup } from '@edx/paragon';
import { faPencilAlt } from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { injectIntl, intlShape } from '@edx/frontend-i18n'; // eslint-disable-line
import { Button, StatefulButton } from '@edx/paragon';
import SwitchContent from './SwitchContent';
import messages from './AccountSettingsPage.messages';
import Input from './temp/Input';
import ValidationFormGroup from './temp/ValidationFormGroup';
import SwitchContent from './temp/SwitchContent';
import messages from '../AccountSettingsPage.messages';
import {
openForm,
closeForm,
} from './data/actions';
import { editableFieldSelector } from './data/selectors';
updateDraft,
saveAccount,
} from '../actions';
import { editableFieldSelector } from '../selectors';
function EditableField(props) {
const {
name,
label,
emptyLabel,
type,
value,
options,
@@ -40,6 +41,16 @@ function EditableField(props) {
} = props;
const id = `field-${name}`;
const getValue = (rawValue) => {
if (options) {
// Use == instead of === to prevent issues when HTML casts numbers as strings
// eslint-disable-next-line eqeqeq
const selectedOption = options.find(option => option.value == rawValue);
if (selectedOption) return selectedOption.label;
}
return rawValue;
};
const handleSubmit = (e) => {
e.preventDefault();
onSubmit(name, new FormData(e.target).get(name));
@@ -57,26 +68,6 @@ function EditableField(props) {
onCancel(name);
};
const renderEmptyLabel = () => {
if (isEditable) {
return <Button onClick={handleEdit} className="btn-link p-0">{emptyLabel}</Button>;
}
return <span className="text-muted">{emptyLabel}</span>;
};
const renderValue = (rawValue) => {
if (!rawValue) return renderEmptyLabel();
if (options) {
// Use == instead of === to prevent issues when HTML casts numbers as strings
// eslint-disable-next-line eqeqeq
const selectedOption = options.find(option => option.value == rawValue);
if (selectedOption) return selectedOption.label;
}
return rawValue;
};
const renderConfirmationMessage = () => {
if (!confirmationMessageDefinition || !confirmationValue) return null;
return intl.formatMessage(confirmationMessageDefinition, {
@@ -138,15 +129,15 @@ function EditableField(props) {
),
default: (
<div className="form-group">
<div className="d-flex align-items-start">
<h6 aria-level="3">{label}</h6>
<div className="d-flex justify-content-between align-items-start">
<h6>{label}</h6>
{isEditable ? (
<Button onClick={handleEdit} className="ml-3 btn-link">
<FontAwesomeIcon className="mr-1" icon={faPencilAlt} />{intl.formatMessage(messages['account.settings.editable.field.action.edit'])}
<Button onClick={handleEdit} className="btn-link">
{intl.formatMessage(messages['account.settings.editable.field.action.edit'])}
</Button>
) : null}
</div>
<p>{renderValue(value)}</p>
<p>{getValue(value)}</p>
<p className="small text-muted mt-n2">{renderConfirmationMessage() || helpText}</p>
</div>
),
@@ -159,7 +150,6 @@ function EditableField(props) {
EditableField.propTypes = {
name: PropTypes.string.isRequired,
label: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
emptyLabel: PropTypes.node,
type: PropTypes.string.isRequired,
value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
options: PropTypes.arrayOf(PropTypes.shape({
@@ -189,7 +179,6 @@ EditableField.defaultProps = {
options: undefined,
saveState: undefined,
label: undefined,
emptyLabel: undefined,
error: undefined,
confirmationMessageDefinition: undefined,
confirmationValue: undefined,
@@ -202,4 +191,6 @@ EditableField.defaultProps = {
export default connect(editableFieldSelector, {
onEdit: openForm,
onCancel: closeForm,
onChange: updateDraft,
onSubmit: saveAccount,
})(injectIntl(EditableField));

View File

@@ -1,27 +1,31 @@
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { injectIntl, intlShape, FormattedMessage } from '@edx/frontend-platform/i18n';
import { Button, StatefulButton, Input, ValidationFormGroup } from '@edx/paragon';
import { FormattedMessage } from 'react-intl';
import { injectIntl, intlShape } from '@edx/frontend-i18n'; // eslint-disable-line
import { Button, StatefulButton } from '@edx/paragon';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faExclamationTriangle, faPencilAlt } from '@fortawesome/free-solid-svg-icons';
import { faExclamationTriangle } from '@fortawesome/free-solid-svg-icons';
import Input from './temp/Input';
import ValidationFormGroup from './temp/ValidationFormGroup';
import SwitchContent from './temp/SwitchContent';
import Alert from './Alert';
import SwitchContent from './SwitchContent';
import messages from './AccountSettingsPage.messages';
import messages from '../AccountSettingsPage.messages';
import {
openForm,
closeForm,
} from './data/actions';
import { editableFieldSelector } from './data/selectors';
updateDraft,
saveAccount,
} from '../actions';
import { editableFieldSelector } from '../selectors';
function EmailField(props) {
const {
name,
label,
emptyLabel,
value,
saveState,
error,
@@ -62,7 +66,7 @@ function EmailField(props) {
className="alert-warning mt-n2"
icon={<FontAwesomeIcon className="mr-2 h6" icon={faExclamationTriangle} />}
>
<h6 aria-level="3">
<h6>
{intl.formatMessage(messages['account.settings.email.field.confirmation.header'])}
</h6>
{intl.formatMessage(confirmationMessageDefinition, { value: confirmationValue })}
@@ -83,18 +87,6 @@ function EmailField(props) {
</span>
);
const renderEmptyLabel = () => {
if (isEditable) {
return <Button onClick={handleEdit} className="btn-link p-0">{emptyLabel}</Button>;
}
return <span className="text-muted">{emptyLabel}</span>;
};
const renderValue = () => {
if (confirmationValue) return renderConfirmationValue();
return value || renderEmptyLabel();
};
return (
<SwitchContent
expression={isEditing ? 'editing' : 'default'}
@@ -147,16 +139,15 @@ function EmailField(props) {
),
default: (
<div className="form-group">
<div className="d-flex align-items-start">
<h6 aria-level="3">{label}</h6>
<div className="d-flex justify-content-between align-items-start">
<h6>{label}</h6>
{isEditable ? (
<Button onClick={handleEdit} className="ml-3 btn-link">
<FontAwesomeIcon className="mr-1" icon={faPencilAlt} />
<Button onClick={handleEdit} className="btn-link">
{intl.formatMessage(messages['account.settings.editable.field.action.edit'])}
</Button>
) : null}
</div>
<p>{renderValue()}</p>
<p>{confirmationValue ? renderConfirmationValue() : value}</p>
{renderConfirmationMessage() || <p className="small text-muted mt-n2">{helpText}</p>}
</div>
),
@@ -169,7 +160,6 @@ function EmailField(props) {
EmailField.propTypes = {
name: PropTypes.string.isRequired,
label: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
emptyLabel: PropTypes.node,
value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
saveState: PropTypes.oneOf(['default', 'pending', 'complete', 'error']),
error: PropTypes.string,
@@ -193,7 +183,6 @@ EmailField.defaultProps = {
value: undefined,
saveState: undefined,
label: undefined,
emptyLabel: undefined,
error: undefined,
confirmationMessageDefinition: undefined,
confirmationValue: undefined,
@@ -206,4 +195,6 @@ EmailField.defaultProps = {
export default connect(editableFieldSelector, {
onEdit: openForm,
onCancel: closeForm,
onChange: updateDraft,
onSubmit: saveAccount,
})(injectIntl(EmailField));

View File

@@ -0,0 +1,84 @@
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { injectIntl, intlShape } from '@edx/frontend-i18n'; // eslint-disable-line
import { FormattedMessage } from 'react-intl';
import { StatefulButton, Hyperlink } from '@edx/paragon';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faExclamationTriangle } from '@fortawesome/free-solid-svg-icons';
import { resetPassword } from '../actions';
import { resetPasswordSelector } from '../selectors';
import messages from '../AccountSettingsPage.messages';
import Alert from './Alert';
function PasswordReset({ email, intl, ...props }) {
const renderConfirmationMessage = () => (
<Alert
className="alert-warning mt-n2"
icon={<FontAwesomeIcon className="mr-2" icon={faExclamationTriangle} />}
>
<FormattedMessage
id="account.settings.editable.field.password.reset.button"
defaultMessage="We've sent a message to {email}. Click the link in the message to reset your password. Didn't receive the message? Contact {technicalSupportLink}."
description="The password reset button in account settings"
values={{
email,
technicalSupportLink: (
<Hyperlink
destination="https://support.edx.org/hc/en-us/articles/206212088-What-if-I-did-not-receive-a-password-reset-message-"
>
<FormattedMessage
id="account.settings.editable.field.password.reset.button.support.link"
defaultMessage="technical support"
description="link text used in message: account.settings.editable.field.password.reset.button 'Contact technical support.'"
/>
</Hyperlink>
),
}}
/>
</Alert>
);
return (
<div className="form-group">
<h6>
<FormattedMessage
id="account.settings.editable.field.password.reset.label"
defaultMessage="Password"
description="The password label in account settings"
/>
</h6>
<p>
<StatefulButton
className="btn-link"
state={props.resetPasswordState}
onClick={props.resetPassword}
disabledStates={[]}
labels={{
default: intl.formatMessage(messages['account.settings.editable.field.password.reset.button']),
}}
/>
</p>
{props.resetPasswordState === 'complete' ? renderConfirmationMessage() : null}
</div>
);
}
PasswordReset.propTypes = {
resetPassword: PropTypes.func.isRequired,
email: PropTypes.string,
resetPasswordState: PropTypes.string,
intl: intlShape.isRequired,
};
PasswordReset.defaultProps = {
email: '',
resetPasswordState: undefined,
};
export default connect(resetPasswordSelector, {
resetPassword,
})(injectIntl(PasswordReset));

View File

@@ -0,0 +1,151 @@
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { FormattedMessage } from 'react-intl';
import { Hyperlink } from '@edx/paragon';
import { fetchThirdPartyAuthProviders } from '../actions';
import { thirdPartyAuthSelector } from '../selectors';
class ThirdPartyAuth extends React.Component {
componentDidMount() {
this.props.fetchThirdPartyAuthProviders();
}
renderConnectedProvider(url, name) {
return (
<React.Fragment>
<h6>{name}</h6>
<Hyperlink destination={url} className="btn btn-outline-primary">
<FormattedMessage
id="account.settings.sso.link.account"
defaultMessage="Sign in with {name}"
description="An action link to link a connected third party account.m {name} will be Google, Facebook, etc."
values={{ name }}
/>
</Hyperlink>
</React.Fragment>
);
}
renderUnconnectedProvider(url, name) {
return (
<React.Fragment>
<h6>
{name}
<span className="small font-weight-normal text-muted ml-2">
<FormattedMessage
id="account.settings.sso.account.connected"
defaultMessage="Linked"
description="A badge to show that a third party account is linked"
/>
</span>
</h6>
<Hyperlink destination={url}>
<FormattedMessage
id="account.settings.sso.unlink.account"
defaultMessage="Unlink {name} account"
description="An action link to unlink a connected third party account"
values={{ name }}
/>
</Hyperlink>
</React.Fragment>
);
}
renderProvider({
name, disconnectUrl, connectUrl, connected, id,
}) {
return (
<div className="form-group" key={id}>
{
connected ?
this.renderUnconnectedProvider(disconnectUrl, name) :
this.renderConnectedProvider(connectUrl, name)
}
</div>
);
}
renderNoProviders() {
return (
<FormattedMessage
id="account.settings.sso.no.providers"
defaultMessage="No accounts can be linked at this time."
description="Displayed when no third party accounts are available to link an edX account to"
/>
);
}
renderLoading() {
return (
<FormattedMessage
id="account.settings.sso.loading"
defaultMessage="Loading..."
description="Waiting for data to load in the third party auth provider list"
/>
);
}
renderLoadingError() {
return (
<FormattedMessage
id="account.settings.sso.loading.error"
defaultMessage="There was a problem loading linked accounts."
description="Error message for failing to load the third party auth provider list"
/>
);
}
render() {
return (
<div>
<h2>
<FormattedMessage
id="account.settings.sso.section.header"
defaultMessage="Linked Accounts"
description="Section header for the third party auth settings"
/>
</h2>
<p>
<FormattedMessage
id="account.settings.sso.section.subheader"
defaultMessage="You can link your identity accounts to simplify signing in to edX."
description="Section subheader for the third party auth settings"
/>
</p>
{this.props.providers.map(this.renderProvider, this)}
{this.props.loaded && this.props.providers.length === 0 ? this.renderNoProviders() : null}
{this.props.loading ? this.renderLoading() : null}
{this.props.loadingError ? this.renderLoadingError() : null}
</div>
);
}
}
ThirdPartyAuth.propTypes = {
fetchThirdPartyAuthProviders: PropTypes.func.isRequired,
providers: PropTypes.arrayOf(PropTypes.shape({
name: PropTypes.string,
disconnectUrl: PropTypes.string,
connectUrl: PropTypes.string,
connected: PropTypes.bool,
id: PropTypes.string,
})),
loading: PropTypes.bool,
loaded: PropTypes.bool,
loadingError: PropTypes.string,
};
ThirdPartyAuth.defaultProps = {
providers: [],
loading: false,
loaded: false,
loadingError: undefined,
};
export default connect(thirdPartyAuthSelector, {
fetchThirdPartyAuthProviders,
})(ThirdPartyAuth);

View File

@@ -0,0 +1,106 @@
import React from 'react';
import classNames from 'classnames';
import PropTypes from 'prop-types';
class Input extends React.Component {
componentDidMount() {
if (process.env.NODE_ENV === 'development') {
this.checkHasLabel();
}
}
getHTMLTagForType() {
const { type } = this.props;
if (type === 'select' || type === 'textarea') return type;
return 'input';
}
getClassNameForType() {
switch (this.props.type) {
case 'file':
return 'form-control-file';
case 'checkbox':
case 'radio':
return 'form-check-input';
default:
return 'form-control';
}
}
getRef(forwardedRef) {
if (process.env.NODE_ENV !== 'development') return forwardedRef;
if (forwardedRef) return forwardedRef;
if (!this.innerRef) this.innerRef = React.createRef();
return this.innerRef;
}
checkHasLabel() {
const htmlNode = this.getRef().current;
if (htmlNode.labels.length > 0) return;
if (htmlNode.getAttribute('aria-label') !== null) return;
// eslint-disable-next-line no-console
if (console) console.warn('Input[a11y]: There is no associated label for this Input');
}
renderOptions(options) {
return options.map((option) => {
const {
value, label, group, ...attributes
} = option;
if (group) {
return (
<optgroup key={`optgroup-${label}`} label={label} {...attributes}>
{this.renderOptions(group)}
</optgroup>
);
}
return <option key={value} value={value} {...attributes}>{label}</option>;
}, this);
}
render() {
const {
type, className, options, innerRef, ...attributes // eslint-disable-line react/prop-types
} = this.props;
const htmlTag = this.getHTMLTagForType();
const htmlProps = {
className: classNames(this.getClassNameForType(), className),
type: htmlTag === 'input' ? type : undefined,
...attributes,
ref: this.getRef(innerRef),
};
const htmlChildren = type === 'select' ? this.renderOptions(options) : null;
return React.createElement(htmlTag, htmlProps, htmlChildren);
}
}
Input.propTypes = {
type: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
className: PropTypes.string,
options: PropTypes.arrayOf(PropTypes.shape({
label: PropTypes.string,
value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
disabled: PropTypes.bool,
group: PropTypes.arrayOf(PropTypes.shape({
label: PropTypes.string,
value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
disabled: PropTypes.bool,
})),
})),
};
Input.defaultProps = {
className: undefined,
options: [],
};
// eslint-disable-next-line react/no-multi-comp
export default React.forwardRef((props, ref) => <Input innerRef={ref} {...props} />);

View File

@@ -0,0 +1,92 @@
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import Input from './Input';
const propTypes = {
for: PropTypes.string.isRequired,
className: PropTypes.string,
invalid: PropTypes.bool,
valid: PropTypes.bool,
validMessage: PropTypes.node,
invalidMessage: PropTypes.node,
helpText: PropTypes.node,
children: PropTypes.node,
};
const defaultProps = {
invalid: undefined,
valid: undefined,
validMessage: undefined,
invalidMessage: undefined,
helpText: undefined,
children: undefined,
className: undefined,
};
function ValidationFormGroup(props) {
const {
className,
invalidMessage,
invalid,
valid,
validMessage,
helpText,
for: id,
children,
} = props;
const renderChildren = () => React.Children.map(children, (child) => {
// Any non-user input element should pass through unmodified
if (['input', 'textarea', 'select', Input].indexOf(child.type) === -1) return child;
// Add validation class names and describedby values to input element
return React.cloneElement(child, {
className: classNames(child.props.className, {
'is-invalid': invalid,
'is-valid': valid,
}),
// This is a non-standard use of the classNames package, but it's exactly the same use case.
'aria-describedby': classNames(child.props['aria-describedby'], {
[`${id}-help-text`]: Boolean(helpText),
[`${id}-invalid-feedback`]: invalid && invalidMessage,
[`${id}-valid-feedback`]: valid && validMessage,
}),
});
});
const renderHelpText = (text) => {
if (!text) return null;
return <small id={`${id}-help-text`} className="form-text text-muted">{text}</small>;
};
const renderFeedback = (message, state) => {
if (!message) return null;
return (
<div
className={`${state}-feedback`}
id={`${id}-${state}-feedback`}
>
{message}
</div>
);
};
return (
<div className={classNames('form-group', className)}>
{renderChildren()}
{renderHelpText(helpText)}
{renderFeedback(invalidMessage, 'invalid')}
{renderFeedback(validMessage, 'valid')}
</div>
);
}
ValidationFormGroup.propTypes = propTypes;
ValidationFormGroup.defaultProps = defaultProps;
export default ValidationFormGroup;

View File

@@ -12,7 +12,7 @@ export const YEAR_OF_BIRTH_OPTIONS = (() => {
})();
export const EDUCATION_LEVELS = [
'',
null,
'p',
'm',
'b',
@@ -25,10 +25,8 @@ export const EDUCATION_LEVELS = [
];
export const GENDER_OPTIONS = [
'',
null,
'f',
'm',
'o',
];
export const TRANSIFEX_LANGUAGE_BASE_URL = 'https://www.transifex.com/open-edx/edx-platform/language/';

View File

@@ -1,112 +0,0 @@
import { AsyncActionType } from './utils';
export const FETCH_SETTINGS = new AsyncActionType('ACCOUNT_SETTINGS', 'FETCH_SETTINGS');
export const SAVE_SETTINGS = new AsyncActionType('ACCOUNT_SETTINGS', 'SAVE_SETTINGS');
export const FETCH_TIME_ZONES = new AsyncActionType('ACCOUNT_SETTINGS', 'FETCH_TIME_ZONES');
export const SAVE_PREVIOUS_SITE_LANGUAGE = 'SAVE_PREVIOUS_SITE_LANGUAGE';
export const OPEN_FORM = 'OPEN_FORM';
export const CLOSE_FORM = 'CLOSE_FORM';
export const UPDATE_DRAFT = 'UPDATE_DRAFT';
export const RESET_DRAFTS = 'RESET_DRAFTS';
// FETCH SETTINGS ACTIONS
export const fetchSettings = () => ({
type: FETCH_SETTINGS.BASE,
});
export const fetchSettingsBegin = () => ({
type: FETCH_SETTINGS.BEGIN,
});
export const fetchSettingsSuccess = ({
values,
thirdPartyAuthProviders,
profileDataManager,
timeZones,
}) => ({
type: FETCH_SETTINGS.SUCCESS,
payload: {
values,
thirdPartyAuthProviders,
profileDataManager,
timeZones,
},
});
export const fetchSettingsFailure = error => ({
type: FETCH_SETTINGS.FAILURE,
payload: { error },
});
export const fetchSettingsReset = () => ({
type: FETCH_SETTINGS.RESET,
});
// FORM STATE ACTIONS
export const openForm = formId => ({
type: OPEN_FORM,
payload: { formId },
});
export const closeForm = formId => ({
type: CLOSE_FORM,
payload: { formId },
});
export const updateDraft = (name, value) => ({
type: UPDATE_DRAFT,
payload: {
name,
value,
},
});
export const resetDrafts = () => ({
type: RESET_DRAFTS,
});
// SAVE SETTINGS ACTIONS
export const saveSettings = (formId, commitValues) => ({
type: SAVE_SETTINGS.BASE,
payload: { formId, commitValues },
});
export const saveSettingsBegin = () => ({
type: SAVE_SETTINGS.BEGIN,
});
export const saveSettingsSuccess = (values, confirmationValues) => ({
type: SAVE_SETTINGS.SUCCESS,
payload: { values, confirmationValues },
});
export const saveSettingsReset = () => ({
type: SAVE_SETTINGS.RESET,
});
export const saveSettingsFailure = ({ fieldErrors, message }) => ({
type: SAVE_SETTINGS.FAILURE,
payload: { errors: fieldErrors, message },
});
export const savePreviousSiteLanguage = previousSiteLanguage => ({
type: SAVE_PREVIOUS_SITE_LANGUAGE,
payload: { previousSiteLanguage },
});
// FETCH TIME_ZONE ACTIONS
export const fetchTimeZones = country => ({
type: FETCH_TIME_ZONES.BASE,
payload: { country },
});
export const fetchTimeZonesSuccess = timeZones => ({
type: FETCH_TIME_ZONES.SUCCESS,
payload: { timeZones },
});

View File

@@ -1,119 +0,0 @@
import { call, put, delay, takeEvery, all } from 'redux-saga/effects';
import { publish } from '@edx/frontend-platform';
import { getLocale, handleRtl, LOCALE_CHANGED } from '@edx/frontend-platform/i18n';
import { getAuthenticatedUser } from '@edx/frontend-platform/auth';
// Actions
import {
FETCH_SETTINGS,
fetchSettingsBegin,
fetchSettingsSuccess,
fetchSettingsFailure,
closeForm,
SAVE_SETTINGS,
saveSettingsBegin,
saveSettingsSuccess,
saveSettingsFailure,
savePreviousSiteLanguage,
FETCH_TIME_ZONES,
fetchTimeZones,
fetchTimeZonesSuccess,
} from './actions';
// Sub-modules
import { saga as deleteAccountSaga } from '../delete-account';
import { saga as resetPasswordSaga } from '../reset-password';
import {
saga as siteLanguageSaga,
patchPreferences,
postSetLang,
} from '../site-language';
import { saga as thirdPartyAuthSaga } from '../third-party-auth';
// Services
import { getSettings, patchSettings, getTimeZones } from './service';
export function* handleFetchSettings() {
try {
yield put(fetchSettingsBegin());
const { username, userId, roles: userRoles } = getAuthenticatedUser();
const {
thirdPartyAuthProviders, profileDataManager, timeZones, ...values
} = yield call(
getSettings,
username,
userRoles,
userId,
);
if (values.country) yield put(fetchTimeZones(values.country));
yield put(fetchSettingsSuccess({
values,
thirdPartyAuthProviders,
profileDataManager,
timeZones,
}));
} catch (e) {
yield put(fetchSettingsFailure(e.message));
throw e;
}
}
export function* handleSaveSettings(action) {
try {
yield put(saveSettingsBegin());
const { username, userId } = getAuthenticatedUser();
const { commitValues, formId } = action.payload;
const commitData = { [formId]: commitValues };
let savedValues = null;
if (formId === 'siteLanguage') {
const previousSiteLanguage = getLocale();
// The following two requests need to be done sequentially, with patching preferences before
// the post to setlang. They used to be done in parallel, but this might create ambiguous
// behavior.
yield call(patchPreferences, username, { prefLang: commitValues });
yield call(postSetLang, commitValues);
yield put(savePreviousSiteLanguage(previousSiteLanguage));
publish(LOCALE_CHANGED, getLocale());
handleRtl();
savedValues = commitData;
} else {
savedValues = yield call(patchSettings, username, commitData, userId);
}
yield put(saveSettingsSuccess(savedValues, commitData));
if (savedValues.country) yield put(fetchTimeZones(savedValues.country));
yield delay(1000);
yield put(closeForm(action.payload.formId));
} catch (e) {
if (e.fieldErrors) {
yield put(saveSettingsFailure({ fieldErrors: e.fieldErrors }));
} else {
yield put(saveSettingsFailure(e.message));
throw e;
}
}
}
export function* handleFetchTimeZones(action) {
const response = yield call(getTimeZones, action.payload.country);
yield put(fetchTimeZonesSuccess(response, action.payload.country));
}
export default function* saga() {
yield takeEvery(FETCH_SETTINGS.BASE, handleFetchSettings);
yield takeEvery(SAVE_SETTINGS.BASE, handleSaveSettings);
yield takeEvery(FETCH_TIME_ZONES.BASE, handleFetchTimeZones);
yield all([
deleteAccountSaga(),
siteLanguageSaga(),
resetPasswordSaga(),
thirdPartyAuthSaga(),
]);
}

View File

@@ -1,190 +0,0 @@
import { createSelector, createStructuredSelector } from 'reselect';
import { siteLanguageOptionsSelector, siteLanguageListSelector } from '../site-language';
export const storeName = 'accountSettings';
export const accountSettingsSelector = state => ({ ...state[storeName] });
const editableFieldNameSelector = (state, props) => props.name;
const valuesSelector = createSelector(
accountSettingsSelector,
accountSettings => accountSettings.values,
);
const draftsSelector = createSelector(
accountSettingsSelector,
accountSettings => accountSettings.drafts,
);
const previousSiteLanguageSelector = createSelector(
accountSettingsSelector,
accountSettings => accountSettings.previousSiteLanguage,
);
const editableFieldErrorSelector = createSelector(
editableFieldNameSelector,
accountSettingsSelector,
(name, accountSettings) => accountSettings.errors[name],
);
const editableFieldConfirmationValuesSelector = createSelector(
editableFieldNameSelector,
accountSettingsSelector,
(name, accountSettings) => accountSettings.confirmationValues[name],
);
const isEditingSelector = createSelector(
editableFieldNameSelector,
accountSettingsSelector,
(name, accountSettings) => accountSettings.openFormId === name,
);
const confirmationValuesSelector = createSelector(
accountSettingsSelector,
accountSettings => accountSettings.confirmationValues,
);
const errorSelector = createSelector(
accountSettingsSelector,
accountSettings => accountSettings.errors,
);
const saveStateSelector = createSelector(
accountSettingsSelector,
accountSettings => accountSettings.saveState,
);
export const editableFieldSelector = createStructuredSelector({
error: editableFieldErrorSelector,
confirmationValue: editableFieldConfirmationValuesSelector,
saveState: saveStateSelector,
isEditing: isEditingSelector,
});
export const profileDataManagerSelector = createSelector(
accountSettingsSelector,
accountSettings => accountSettings.profileDataManager,
);
export const staticFieldsSelector = createSelector(
accountSettingsSelector,
accountSettings => (accountSettings.profileDataManager ? ['name', 'email', 'country'] : []),
);
/**
* If there's no draft present at all (undefined), use the original committed value.
*/
function chooseFormValue(draft, committed) {
return draft !== undefined ? draft : committed;
}
const formValuesSelector = createSelector(
valuesSelector,
draftsSelector,
(values, drafts) => {
const formValues = {};
Object.entries(values).forEach(([name, value]) => {
formValues[name] = chooseFormValue(drafts[name], value) || '';
});
return formValues;
},
);
const transformTimeZonesToOptions = timeZoneArr => timeZoneArr
.map(({ time_zone, description }) => ({ // eslint-disable-line camelcase
value: time_zone, label: description,
}));
const timeZonesSelector = createSelector(
accountSettingsSelector,
accountSettings => transformTimeZonesToOptions(accountSettings.timeZones),
);
const countryTimeZonesSelector = createSelector(
accountSettingsSelector,
accountSettings => transformTimeZonesToOptions(accountSettings.countryTimeZones),
);
const activeAccountSelector = createSelector(
accountSettingsSelector,
accountSettings => accountSettings.values.is_active,
);
export const siteLanguageSelector = createSelector(
previousSiteLanguageSelector,
draftsSelector,
(previousValue, drafts) => ({
previousValue,
draft: drafts.siteLanguage,
}),
);
export const betaLanguageBannerSelector = createStructuredSelector({
siteLanguageList: siteLanguageListSelector,
siteLanguage: siteLanguageSelector,
});
export const accountSettingsPageSelector = createSelector(
accountSettingsSelector,
siteLanguageOptionsSelector,
siteLanguageSelector,
formValuesSelector,
profileDataManagerSelector,
staticFieldsSelector,
timeZonesSelector,
countryTimeZonesSelector,
activeAccountSelector,
(
accountSettings,
siteLanguageOptions,
siteLanguage,
formValues,
profileDataManager,
staticFields,
timeZoneOptions,
countryTimeZoneOptions,
activeAccount,
) => ({
siteLanguageOptions,
siteLanguage,
loading: accountSettings.loading,
loaded: accountSettings.loaded,
loadingError: accountSettings.loadingError,
timeZoneOptions,
countryTimeZoneOptions,
isActive: activeAccount,
formValues,
profileDataManager,
staticFields,
tpaProviders: accountSettings.thirdPartyAuth.providers,
}),
);
export const coachingConsentPageSelector = createSelector(
accountSettingsSelector,
formValuesSelector,
activeAccountSelector,
saveStateSelector,
confirmationValuesSelector,
errorSelector,
(
accountSettings,
formValues,
activeAccount,
saveState,
confirmationValues,
errors,
) => ({
loading: accountSettings.loading,
loaded: accountSettings.loaded,
loadingError: accountSettings.loadingError,
isActive: activeAccount,
formValues,
saveState,
confirmationValues,
formErrors: errors,
}),
);

View File

@@ -1,207 +0,0 @@
import { getConfig } from '@edx/frontend-platform';
import { getAuthenticatedHttpClient } from '@edx/frontend-platform/auth';
import pick from 'lodash.pick';
import omit from 'lodash.omit';
import isEmpty from 'lodash.isempty';
import { handleRequestError, unpackFieldErrors } from './utils';
import { getThirdPartyAuthProviders } from '../third-party-auth';
import { getCoachingPreferences, patchCoachingPreferences } from '../coaching/data/service';
const SOCIAL_PLATFORMS = [
{ id: 'twitter', key: 'social_link_twitter' },
{ id: 'facebook', key: 'social_link_facebook' },
{ id: 'linkedin', key: 'social_link_linkedin' },
];
function unpackAccountResponseData(data) {
const unpackedData = data;
// This is handled by preferences
delete unpackedData.time_zone;
SOCIAL_PLATFORMS.forEach(({ id, key }) => {
const platformData = data.social_links.find(({ platform }) => platform === id);
unpackedData[key] = typeof platformData === 'object' ? platformData.social_link : '';
});
if (Array.isArray(data.language_proficiencies)) {
if (data.language_proficiencies.length) {
unpackedData.language_proficiencies = data.language_proficiencies[0].code;
} else {
unpackedData.language_proficiencies = '';
}
}
return unpackedData;
}
function packAccountCommitData(commitData) {
const packedData = commitData;
SOCIAL_PLATFORMS.forEach(({ id, key }) => {
// Skip missing values. Empty strings are valid values and should be preserved.
if (commitData[key] === undefined) return;
packedData.social_links = [{ platform: id, social_link: commitData[key] }];
delete packedData[key];
});
if (commitData.language_proficiencies !== undefined) {
if (commitData.language_proficiencies) {
packedData.language_proficiencies = [{ code: commitData.language_proficiencies }];
} else {
// An empty string should be sent as an array.
packedData.language_proficiencies = [];
}
}
if (commitData.year_of_birth !== undefined) {
if (commitData.year_of_birth) {
packedData.year_of_birth = commitData.year_of_birth;
} else {
// An empty string should be sent as null.
packedData.year_of_birth = null;
}
}
return packedData;
}
export async function getAccount(username) {
const { data } = await getAuthenticatedHttpClient()
.get(`${getConfig().LMS_BASE_URL}/api/user/v1/accounts/${username}`);
return unpackAccountResponseData(data);
}
export async function patchAccount(username, commitValues) {
const requestConfig = {
headers: { 'Content-Type': 'application/merge-patch+json' },
};
const { data } = await getAuthenticatedHttpClient()
.patch(
`${getConfig().LMS_BASE_URL}/api/user/v1/accounts/${username}`,
packAccountCommitData(commitValues),
requestConfig,
)
.catch((error) => {
const unpackFunction = (fieldErrors) => {
const unpackedFieldErrors = fieldErrors;
if (fieldErrors.social_links) {
SOCIAL_PLATFORMS.forEach(({ key }) => {
unpackedFieldErrors[key] = fieldErrors.social_links;
});
}
return unpackFieldErrors(unpackedFieldErrors);
};
handleRequestError(error, unpackFunction);
});
return unpackAccountResponseData(data);
}
export async function getPreferences(username) {
const { data } = await getAuthenticatedHttpClient()
.get(`${getConfig().LMS_BASE_URL}/api/user/v1/preferences/${username}`);
return data;
}
export async function patchPreferences(username, commitValues) {
const requestConfig = { headers: { 'Content-Type': 'application/merge-patch+json' } };
const requestUrl = `${getConfig().LMS_BASE_URL}/api/user/v1/preferences/${username}`;
// Ignore the success response, the API does not currently return any data.
await getAuthenticatedHttpClient()
.patch(requestUrl, commitValues, requestConfig).catch(handleRequestError);
return commitValues;
}
export async function getTimeZones(forCountry) {
const { data } = await getAuthenticatedHttpClient()
.get(`${getConfig().LMS_BASE_URL}/user_api/v1/preferences/time_zones/`, {
params: { country_code: forCountry },
})
.catch(handleRequestError);
return data;
}
/**
* Determine if the user's profile data is managed by a third-party identity provider.
*/
export async function getProfileDataManager(username, userRoles) {
const userRoleNames = userRoles.map(role => role.split(':')[0]);
if (userRoleNames.includes('enterprise_learner')) {
const url = `${getConfig().LMS_BASE_URL}/enterprise/api/v1/enterprise-learner/?username=${username}`;
const { data } = await getAuthenticatedHttpClient().get(url).catch(handleRequestError);
if ('results' in data) {
for (let i = 0; i < data.results.length; i += 1) {
const enterprise = data.results[i].enterprise_customer;
if (enterprise.sync_learner_profile_data) {
return enterprise.name;
}
}
}
}
return null;
}
/**
* A single function to GET everything considered a setting.
* Currently encapsulates Account, Preferences, Coaching, and ThirdPartyAuth
*/
export async function getSettings(username, userRoles, userId) {
const results = await Promise.all([
getAccount(username),
getPreferences(username),
getThirdPartyAuthProviders(),
getProfileDataManager(username, userRoles),
getTimeZones(),
getConfig().COACHING_ENABLED && getCoachingPreferences(userId),
]);
return {
...results[0],
...results[1],
thirdPartyAuthProviders: results[2],
profileDataManager: results[3],
timeZones: results[4],
coaching: results[5],
};
}
/**
* A single function to PATCH everything considered a setting.
* Currently encapsulates Account, Preferences, coaching and ThirdPartyAuth
*/
export async function patchSettings(username, commitValues, userId) {
// Note: time_zone exists in the return value from user/v1/accounts
// but it is always null and won't update. It also exists in
// user/v1/preferences where it does update. This is the one we use.
const preferenceKeys = ['time_zone'];
const coachingKeys = ['coaching'];
const accountCommitValues = omit(commitValues, preferenceKeys);
const preferenceCommitValues = pick(commitValues, preferenceKeys);
const coachingCommitValues = pick(commitValues, coachingKeys);
const patchRequests = [];
if (!isEmpty(accountCommitValues)) {
patchRequests.push(patchAccount(username, accountCommitValues));
}
if (!isEmpty(preferenceCommitValues)) {
patchRequests.push(patchPreferences(username, preferenceCommitValues));
}
if (!isEmpty(coachingCommitValues)) {
patchRequests.push(patchCoachingPreferences(userId, coachingCommitValues));
}
const results = await Promise.all(patchRequests);
// Assigns in order of requests. Preference keys
// will override account keys. Notably time_zone.
const combinedResults = Object.assign({}, ...results);
return combinedResults;
}

View File

@@ -1,3 +0,0 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`getModuleState should throw an exception on a bad path 1`] = `"Unexpected state key uhoh given to getModuleState. Is your state path set up correctly?"`;

View File

@@ -1,12 +0,0 @@
export {
camelCaseObject,
convertKeyNames,
modifyObjectKeys,
snakeCaseObject,
} from './dataUtils';
export {
AsyncActionType,
getModuleState,
} from './reduxUtils';
export { default as handleFailure } from './sagaUtils';
export { unpackFieldErrors, handleRequestError } from './serviceUtils';

View File

@@ -1,62 +0,0 @@
/**
* Helper class to save time when writing out action types for asynchronous methods. Also helps
* ensure that actions are namespaced.
*/
export class AsyncActionType {
constructor(topic, name) {
this.topic = topic;
this.name = name;
}
get BASE() {
return `${this.topic}__${this.name}`;
}
get BEGIN() {
return `${this.topic}__${this.name}__BEGIN`;
}
get SUCCESS() {
return `${this.topic}__${this.name}__SUCCESS`;
}
get FAILURE() {
return `${this.topic}__${this.name}__FAILURE`;
}
get RESET() {
return `${this.topic}__${this.name}__RESET`;
}
}
/**
* Given a state tree and an array representing a set of keys to traverse in that tree, returns
* the portion of the tree at that key path.
*
* Example:
*
* const result = getModuleState(
* {
* first: { red: { awesome: 'sauce' }, blue: { weak: 'sauce' } },
* second: { other: 'data', }
* },
* ['first', 'red']
* );
*
* result will be:
*
* {
* awesome: 'sauce'
* }
*/
export function getModuleState(state, originalPath) {
const path = [...originalPath]; // don't modify your argument
if (path.length < 1) {
return state;
}
const key = path.shift();
if (state[key] === undefined) {
throw new Error(`Unexpected state key ${key} given to getModuleState. Is your state path set up correctly?`);
}
return getModuleState(state[key], path);
}

View File

@@ -1,51 +0,0 @@
import {
AsyncActionType,
getModuleState,
} from './reduxUtils';
describe('AsyncActionType', () => {
it('should return well formatted action strings', () => {
const actionType = new AsyncActionType('HOUSE_CATS', 'START_THE_RACE');
expect(actionType.BASE).toBe('HOUSE_CATS__START_THE_RACE');
expect(actionType.BEGIN).toBe('HOUSE_CATS__START_THE_RACE__BEGIN');
expect(actionType.SUCCESS).toBe('HOUSE_CATS__START_THE_RACE__SUCCESS');
expect(actionType.FAILURE).toBe('HOUSE_CATS__START_THE_RACE__FAILURE');
expect(actionType.RESET).toBe('HOUSE_CATS__START_THE_RACE__RESET');
});
});
describe('getModuleState', () => {
const state = {
first: { red: { awesome: 'sauce' }, blue: { weak: 'sauce' } },
second: { other: 'data' },
};
it('should return everything if given an empty path', () => {
expect(getModuleState(state, [])).toEqual(state);
});
it('should resolve paths correctly', () => {
expect(getModuleState(
state,
['first'],
)).toEqual({ red: { awesome: 'sauce' }, blue: { weak: 'sauce' } });
expect(getModuleState(
state,
['first', 'red'],
)).toEqual({ awesome: 'sauce' });
expect(getModuleState(state, ['second'])).toEqual({ other: 'data' });
});
it('should throw an exception on a bad path', () => {
expect(() => {
getModuleState(state, ['uhoh']);
}).toThrowErrorMatchingSnapshot();
});
it('should return non-objects correctly', () => {
expect(getModuleState(state, ['first', 'red', 'awesome'])).toEqual('sauce');
});
});

View File

@@ -1,16 +0,0 @@
import { put } from 'redux-saga/effects';
import { logError } from '@edx/frontend-platform/logging';
import { history } from '@edx/frontend-platform';
export default function* handleFailure(error, failureAction = null, failureRedirectPath = null) {
if (error.fieldErrors && failureAction !== null) {
yield put(failureAction({ fieldErrors: error.fieldErrors }));
}
logError(error);
if (failureAction !== null) {
yield put(failureAction(error.message));
}
if (failureRedirectPath !== null) {
history.push(failureRedirectPath);
}
}

View File

@@ -1,48 +0,0 @@
/**
* Turns field errors of the form:
*
* {
* "name":{
* "developer_message": "Nerdy message here",
* "user_message": "This value is invalid."
* },
* "other_field": {
* "developer_message": "Other Nerdy message here",
* "user_message": "This other value is invalid."
* }
* }
*
* Into:
*
* {
* "name": "This value is invalid.",
* "other_field": "This other value is invalid"
* }
*/
export function unpackFieldErrors(fieldErrors) {
return Object.entries(fieldErrors).reduce((acc, [k, v]) => {
acc[k] = v.user_message;
return acc;
}, {});
}
/**
* Processes and re-throws request errors. If the response contains a field_errors field, will
* massage the data into a form expected by the client.
*
* Field errors will be packaged as an api error with a fieldErrors field usable by the client.
* Takes an optional unpack function which is used to process the field errors,
* otherwise uses the default unpackFieldErrors function.
*
* @param error The original error object.
* @param unpackFunction (Optional) A function to use to unpack the field errors as a replacement
* for the default.
*/
export function handleRequestError(error, unpackFunction = unpackFieldErrors) {
if (error.response && error.response.data.field_errors) {
const apiError = Object.create(error);
apiError.fieldErrors = unpackFunction(error.response.data.field_errors);
throw apiError;
}
throw error;
}

View File

@@ -1,44 +0,0 @@
import React from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage, injectIntl, intlShape } from '@edx/frontend-platform/i18n';
import { faExclamationTriangle } from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { Hyperlink } from '@edx/paragon';
// Messages
import messages from './messages';
// Components
import Alert from '../Alert';
const BeforeProceedingBanner = (props) => {
const { instructionMessageId, intl, supportArticleUrl } = props;
return (
<Alert
className="alert-warning mt-n2"
icon={<FontAwesomeIcon className="mr-2" icon={faExclamationTriangle} />}
>
<FormattedMessage
id="account.settings.delete.account.before.proceeding"
defaultMessage="Before proceeding, please {actionLink}."
description="Error that appears if you are trying to delete your edX account, but something about your account needs attention first. The actionLink will be instructions, such as 'unlink your Facebook account'."
values={{
actionLink: (
<Hyperlink destination={supportArticleUrl}>
{intl.formatMessage(messages[instructionMessageId])}
</Hyperlink>
),
}}
/>
</Alert>
);
};
BeforeProceedingBanner.propTypes = {
instructionMessageId: PropTypes.string.isRequired,
intl: intlShape.isRequired,
supportArticleUrl: PropTypes.string.isRequired,
};
export default injectIntl(BeforeProceedingBanner);

View File

@@ -1,130 +0,0 @@
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Button, Input, Modal, ValidationFormGroup } from '@edx/paragon';
import { injectIntl, intlShape } from '@edx/frontend-platform/i18n';
import { faExclamationCircle, faExclamationTriangle } from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import messages from './messages';
import Alert from '../Alert';
import PrintingInstructions from './PrintingInstructions';
export class ConfirmationModal extends Component {
/**
* @returns String The message id for a short description of the error, suitable for a header or
* as the error message under an input field.
*/
getShortErrorMessageId(reason) {
switch (reason) {
case 'empty-password':
return 'account.settings.delete.account.error.no.password';
default:
return 'account.settings.delete.account.error.unable.to.delete';
}
}
renderError(reason) {
const { errorType, intl } = this.props;
if (errorType === null) {
return null;
}
const headerMessageId = this.getShortErrorMessageId(errorType);
const detailsMessageId =
reason === 'empty-password'
? null
: 'account.settings.delete.account.error.unable.to.delete.details';
return (
<Alert
className="alert-danger mt-n2"
icon={<FontAwesomeIcon className="mr-2" icon={faExclamationCircle} />}
>
<h6>{intl.formatMessage(messages[headerMessageId])}</h6>
{detailsMessageId ? (
<p className="text-danger">{intl.formatMessage(messages[detailsMessageId])}</p>
) : null}
</Alert>
);
}
render() {
const {
status,
errorType,
intl,
onCancel,
onChange,
onSubmit,
password,
} = this.props;
const open = ['confirming', 'pending', 'failed'].includes(status);
const passwordFieldId = 'passwordFieldId';
const invalidMessage = messages[this.getShortErrorMessageId(errorType)];
return (
<Modal
open={open}
title={intl.formatMessage(messages['account.settings.delete.account.modal.header'])}
body={
<div>
{this.renderError()}
<Alert
className="alert-warning mt-n2"
icon={<FontAwesomeIcon className="mr-2" icon={faExclamationTriangle} />}
>
<h6>
{intl.formatMessage(messages['account.settings.delete.account.modal.text.1'])}
</h6>
<p>{intl.formatMessage(messages['account.settings.delete.account.modal.text.2'])}</p>
<p>
<PrintingInstructions />
</p>
</Alert>
<ValidationFormGroup
for={passwordFieldId}
invalid={errorType !== null}
invalidMessage={intl.formatMessage(invalidMessage)}
>
<label className="d-block" htmlFor={passwordFieldId}>
{intl.formatMessage(messages['account.settings.delete.account.modal.enter.password'])}
</label>
<Input
name="password"
id={passwordFieldId}
type="password"
value={password}
onChange={onChange}
/>
</ValidationFormGroup>
</div>
}
buttons={[
<Button className="btn-danger" onClick={onSubmit}>
{intl.formatMessage(messages['account.settings.delete.account.modal.confirm.delete'])}
</Button>,
]}
closeText={intl.formatMessage(messages['account.settings.delete.account.modal.confirm.cancel'])}
renderHeaderCloseButton={false}
onClose={onCancel}
/>
);
}
}
ConfirmationModal.propTypes = {
status: PropTypes.oneOf(['confirming', 'pending', 'deleted', 'failed']),
errorType: PropTypes.oneOf(['empty-password', 'server']),
intl: intlShape.isRequired,
onCancel: PropTypes.func.isRequired,
onChange: PropTypes.func.isRequired,
onSubmit: PropTypes.func.isRequired,
password: PropTypes.string.isRequired,
};
ConfirmationModal.defaultProps = {
status: null,
errorType: null,
};
export default injectIntl(ConfirmationModal);

View File

@@ -1,68 +0,0 @@
import React from 'react';
import ReactDOM from 'react-dom';
import renderer from 'react-test-renderer';
import { IntlProvider, injectIntl } from '@edx/frontend-platform/i18n';
// Modal creates a portal. Overriding ReactDOM.createPortal allows portals to be tested in jest.
ReactDOM.createPortal = node => node;
import { ConfirmationModal } from './ConfirmationModal'; // eslint-disable-line import/first
const IntlConfirmationModal = injectIntl(ConfirmationModal);
describe('ConfirmationModal', () => {
let props = {};
beforeEach(() => {
props = {
onCancel: jest.fn(),
onChange: jest.fn(),
onSubmit: jest.fn(),
status: null,
errorType: null,
password: 'fluffy bunnies',
};
});
it('should match default closed confirmation modal snapshot', () => {
const tree = renderer
.create((
<IntlProvider locale="en">
<IntlConfirmationModal
{...props}
/>
</IntlProvider>
))
.toJSON();
expect(tree).toMatchSnapshot();
});
it('should match open confirmation modal snapshot', () => {
const tree = renderer
.create((
<IntlProvider locale="en">
<IntlConfirmationModal
{...props}
status="pending" // This will cause 'modal-backdrop' and 'show' to appear on the modal as CSS classes.
/>
</IntlProvider>
))
.toJSON();
expect(tree).toMatchSnapshot();
});
it('should match empty password confirmation modal snapshot', () => {
const tree = renderer
.create((
<IntlProvider locale="en">
<IntlConfirmationModal
{...props}
errorType="empty-password"
status="pending" // This will cause 'modal-backdrop' and 'show' to appear on the modal as CSS classes.
/>
</IntlProvider>
))
.toJSON();
expect(tree).toMatchSnapshot();
});
});

View File

@@ -1,149 +0,0 @@
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { getConfig } from '@edx/frontend-platform';
import { injectIntl, intlShape } from '@edx/frontend-platform/i18n';
import { Button, Hyperlink } from '@edx/paragon';
// Actions
import {
deleteAccount,
deleteAccountConfirmation,
deleteAccountFailure,
deleteAccountReset,
deleteAccountCancel,
} from './data/actions';
// Messages
import messages from './messages';
// Components
import ConnectedConfirmationModal from './ConfirmationModal';
import PrintingInstructions from './PrintingInstructions';
import ConnectedSuccessModal from './SuccessModal';
import BeforeProceedingBanner from './BeforeProceedingBanner';
export class DeleteAccount extends React.Component {
state = {
password: '',
};
handleSubmit = () => {
if (this.state.password === '') {
this.props.deleteAccountFailure('empty-password');
} else {
this.props.deleteAccount(this.state.password);
}
};
handleCancel = () => {
this.setState({ password: '' });
this.props.deleteAccountCancel();
};
handlePasswordChange = (e) => {
this.setState({ password: e.target.value.trim() });
this.props.deleteAccountReset();
};
handleFinalClose = () => {
global.location = getConfig().LOGOUT_URL;
};
render() {
const {
hasLinkedTPA, isVerifiedAccount, status, errorType, intl,
} = this.props;
const canDelete = isVerifiedAccount && !hasLinkedTPA;
return (
<div>
<h2 className="section-heading">
{intl.formatMessage(messages['account.settings.delete.account.header'])}
</h2>
<p>{intl.formatMessage(messages['account.settings.delete.account.subheader'])}</p>
<p>{intl.formatMessage(messages['account.settings.delete.account.text.1'])}</p>
<p>{intl.formatMessage(messages['account.settings.delete.account.text.2'])}</p>
<p>
<PrintingInstructions />
</p>
<p className="text-danger h6">
{intl.formatMessage(messages['account.settings.delete.account.text.warning'])}
</p>
<p>
<Hyperlink destination="https://support.edx.org/hc/en-us/sections/115004139268-Manage-Your-Account-Settings">
{intl.formatMessage(messages['account.settings.delete.account.text.change.instead'])}
</Hyperlink>
</p>
<p>
<Button
className="btn-outline-danger"
onClick={canDelete ? this.props.deleteAccountConfirmation : null}
disabled={!canDelete}
>
{intl.formatMessage(messages['account.settings.delete.account.button'])}
</Button>
</p>
{isVerifiedAccount ? null : (
<BeforeProceedingBanner
instructionMessageId="account.settings.delete.account.please.activate"
supportArticleUrl="https://support.edx.org/hc/en-us/articles/115000940568-How-do-I-activate-my-account-"
/>
)}
{hasLinkedTPA ? (
<BeforeProceedingBanner
instructionMessageId="account.settings.delete.account.please.unlink"
supportArticleUrl="https://support.edx.org/hc/en-us/articles/207206067"
/>
) : null}
<ConnectedConfirmationModal
status={status}
errorType={errorType}
onSubmit={this.handleSubmit}
onCancel={this.handleCancel}
onChange={this.handlePasswordChange}
password={this.state.password}
/>
<ConnectedSuccessModal status={status} onClose={this.handleFinalClose} />
</div>
);
}
}
DeleteAccount.propTypes = {
deleteAccount: PropTypes.func.isRequired,
deleteAccountConfirmation: PropTypes.func.isRequired,
deleteAccountFailure: PropTypes.func.isRequired,
deleteAccountReset: PropTypes.func.isRequired,
deleteAccountCancel: PropTypes.func.isRequired,
status: PropTypes.oneOf(['confirming', 'pending', 'deleted', 'failed']),
errorType: PropTypes.oneOf(['empty-password', 'server']),
hasLinkedTPA: PropTypes.bool,
isVerifiedAccount: PropTypes.bool,
intl: intlShape.isRequired,
};
DeleteAccount.defaultProps = {
hasLinkedTPA: false,
isVerifiedAccount: true,
status: null,
errorType: null,
};
// Assume we're part of the accountSettings state.
const mapStateToProps = state => state.accountSettings.deleteAccount;
export default connect(
mapStateToProps,
{
deleteAccount,
deleteAccountConfirmation,
deleteAccountFailure,
deleteAccountReset,
deleteAccountCancel,
},
)(injectIntl(DeleteAccount));

View File

@@ -1,70 +0,0 @@
import React from 'react';
import renderer from 'react-test-renderer';
import { IntlProvider, injectIntl } from '@edx/frontend-platform/i18n';
// Testing the modals separately, they just clutter up the snapshots if included here.
jest.mock('./ConfirmationModal');
jest.mock('./SuccessModal');
import { DeleteAccount } from './DeleteAccount'; // eslint-disable-line import/first
const IntlDeleteAccount = injectIntl(DeleteAccount);
describe('DeleteAccount', () => {
let props = {};
beforeEach(() => {
props = {
deleteAccount: jest.fn(),
deleteAccountConfirmation: jest.fn(),
deleteAccountFailure: jest.fn(),
deleteAccountReset: jest.fn(),
deleteAccountCancel: jest.fn(),
status: null,
errorType: null,
hasLinkedTPA: false,
isVerifiedAccount: true,
};
});
it('should match default section snapshot', () => {
const tree = renderer
.create((
<IntlProvider locale="en">
<IntlDeleteAccount
{...props}
/>
</IntlProvider>
))
.toJSON();
expect(tree).toMatchSnapshot();
});
it('should match unverified account section snapshot', () => {
const tree = renderer
.create((
<IntlProvider locale="en">
<IntlDeleteAccount
{...props}
isVerifiedAccount={false}
/>
</IntlProvider>
))
.toJSON();
expect(tree).toMatchSnapshot();
});
it('should match unverified account section snapshot', () => {
const tree = renderer
.create((
<IntlProvider locale="en">
<IntlDeleteAccount
{...props}
hasLinkedTPA
/>
</IntlProvider>
))
.toJSON();
expect(tree).toMatchSnapshot();
});
});

View File

@@ -1,30 +0,0 @@
import React from 'react';
import { FormattedMessage, injectIntl, intlShape } from '@edx/frontend-platform/i18n';
import { Hyperlink } from '@edx/paragon';
import messages from './messages';
const PrintingInstructions = (props) => {
const actionLink = (
<Hyperlink
destination="https://edx.readthedocs.io/projects/edx-guide-for-students/en/latest/SFD_certificates.html#printing-a-certificate"
>
{props.intl.formatMessage(messages['account.settings.delete.account.text.3.link'])}
</Hyperlink>
);
return (
<FormattedMessage
id="account.settings.delete.account.text.3"
defaultMessage="You may also lose access to verified certificates and other program credentials like MicroMasters certificates. If you want to make a copy of these for your records before proceeding with deletion, {actionLink}."
description="A message in the user account deletion area"
values={{ actionLink }}
/>
);
};
PrintingInstructions.propTypes = {
intl: intlShape.isRequired,
};
export default injectIntl(PrintingInstructions);

View File

@@ -1,38 +0,0 @@
import React from 'react';
import PropTypes from 'prop-types';
import { injectIntl, intlShape } from '@edx/frontend-platform/i18n';
import { Modal } from '@edx/paragon';
import messages from './messages';
export const SuccessModal = (props) => {
const { status, intl, onClose } = props;
return (
<Modal
open={status === 'deleted'}
title={intl.formatMessage(messages['account.settings.delete.account.modal.after.header'])}
body={
<div>
<p className="h6">
{intl.formatMessage(messages['account.settings.delete.account.modal.after.text'])}
</p>
</div>
}
closeText={intl.formatMessage(messages['account.settings.delete.account.modal.after.button'])}
renderHeaderCloseButton={false}
onClose={onClose}
/>
);
};
SuccessModal.propTypes = {
status: PropTypes.oneOf(['confirming', 'pending', 'deleted', 'failed']),
intl: intlShape.isRequired,
onClose: PropTypes.func.isRequired,
};
SuccessModal.defaultProps = {
status: null,
};
export default injectIntl(SuccessModal);

View File

@@ -1,58 +0,0 @@
import React from 'react';
import ReactDOM from 'react-dom';
import renderer from 'react-test-renderer';
import { IntlProvider, injectIntl } from '@edx/frontend-platform/i18n';
// Modal creates a portal. Overriding ReactDOM.createPortal allows portals to be tested in jest.
ReactDOM.createPortal = node => node;
import { SuccessModal } from './SuccessModal'; // eslint-disable-line import/first
const IntlSuccessModal = injectIntl(SuccessModal);
describe('SuccessModal', () => {
let props = {};
beforeEach(() => {
props = {
onClose: jest.fn(),
status: null,
};
});
it('should match default closed success modal snapshot', () => {
let tree = renderer.create((
<IntlProvider locale="en"><IntlSuccessModal {...props} /></IntlProvider>))
.toJSON();
expect(tree).toMatchSnapshot();
tree = renderer.create((
<IntlProvider locale="en"><IntlSuccessModal {...props} status="confirming" /></IntlProvider>))
.toJSON();
expect(tree).toMatchSnapshot();
tree = renderer.create((
<IntlProvider locale="en"><IntlSuccessModal {...props} status="pending" /></IntlProvider>))
.toJSON();
expect(tree).toMatchSnapshot();
tree = renderer.create((
<IntlProvider locale="en"><IntlSuccessModal {...props} status="failed" /></IntlProvider>))
.toJSON();
expect(tree).toMatchSnapshot();
});
it('should match open success modal snapshot', () => {
const tree = renderer
.create((
<IntlProvider locale="en">
<IntlSuccessModal
{...props}
status="deleted" // This will cause 'modal-backdrop' and 'show' to appear on the modal as CSS classes.
/>
</IntlProvider>
))
.toJSON();
expect(tree).toMatchSnapshot();
});
});

View File

@@ -1,439 +0,0 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`ConfirmationModal should match default closed confirmation modal snapshot 1`] = `
<div>
<div
className="fade"
role="presentation"
/>
<div
className="modal js-close-modal-on-click fade"
onMouseDown={[Function]}
role="presentation"
>
<div
aria-labelledby="id2"
aria-modal={true}
className=""
role="dialog"
tabIndex="-1"
>
<div
className="modal-content"
>
<div
className="modal-header"
>
<h2
className="modal-title"
id="id2"
>
Are you sure?
</h2>
</div>
<div
className="modal-body"
>
<div>
<div
className="alert d-flex align-items-start alert-warning mt-n2"
>
<div>
<svg
aria-hidden="true"
className="svg-inline--fa fa-exclamation-triangle fa-w-18 mr-2"
data-icon="exclamation-triangle"
data-prefix="fas"
focusable="false"
role="img"
style={Object {}}
viewBox="0 0 576 512"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M569.517 440.013C587.975 472.007 564.806 512 527.94 512H48.054c-36.937 0-59.999-40.055-41.577-71.987L246.423 23.985c18.467-32.009 64.72-31.951 83.154 0l239.94 416.028zM288 354c-25.405 0-46 20.595-46 46s20.595 46 46 46 46-20.595 46-46-20.595-46-46-46zm-43.673-165.346l7.418 136c.347 6.364 5.609 11.346 11.982 11.346h48.546c6.373 0 11.635-4.982 11.982-11.346l7.418-136c.375-6.874-5.098-12.654-11.982-12.654h-63.383c-6.884 0-12.356 5.78-11.981 12.654z"
fill="currentColor"
style={Object {}}
/>
</svg>
</div>
<div>
<h6>
You have selected "Delete My Account". Deletion of your account and personal data is permanent and cannot be undone. edX will not be able to recover your account or the data that is deleted.
</h6>
<p>
If you proceed, you will be unable to use this account to take courses on the edX app, edx.org, or any other site hosted by edX. This includes access to edx.org from your employer's or university's system and access to private sites offered by MIT Open Learning, Wharton Executive Education, and Harvard Medical School.
</p>
<p>
<span>
You may also lose access to verified certificates and other program credentials like MicroMasters certificates. If you want to make a copy of these for your records before proceeding with deletion,
<a
href="https://edx.readthedocs.io/projects/edx-guide-for-students/en/latest/SFD_certificates.html#printing-a-certificate"
onClick={[Function]}
target="_self"
>
follow the instructions for printing or downloading a certificate
</a>
.
</span>
</p>
</div>
</div>
<div
className="form-group"
>
<label
className="d-block"
htmlFor="passwordFieldId"
>
If you still wish to continue and delete your account, please enter your account password:
</label>
<input
aria-describedby=""
className="form-control"
id="passwordFieldId"
name="password"
onChange={[MockFunction]}
type="password"
value="fluffy bunnies"
/>
<strong
className="invalid-feedback"
id="passwordFieldId-invalid-feedback"
>
Unable to delete account
</strong>
</div>
</div>
</div>
<div
className="modal-footer"
>
<button
className="btn btn-danger"
onBlur={[Function]}
onClick={[Function]}
onKeyDown={[Function]}
type="button"
>
Yes, Delete
</button>
<button
className="btn js-close-modal-on-click btn-secondary"
id="paragonCloseModalButton1"
onBlur={[Function]}
onClick={[Function]}
onKeyDown={[Function]}
type="button"
>
Cancel
</button>
</div>
</div>
</div>
</div>
</div>
`;
exports[`ConfirmationModal should match empty password confirmation modal snapshot 1`] = `
<div>
<div
className="modal-backdrop show"
role="presentation"
/>
<div
className="modal js-close-modal-on-click show d-block"
onMouseDown={[Function]}
role="presentation"
>
<div
aria-labelledby="id6"
aria-modal={true}
className="modal-dialog"
role="dialog"
tabIndex="-1"
>
<div
className="modal-content"
>
<div
className="modal-header"
>
<h2
className="modal-title"
id="id6"
>
Are you sure?
</h2>
</div>
<div
className="modal-body"
>
<div>
<div
className="alert d-flex align-items-start alert-danger mt-n2"
>
<div>
<svg
aria-hidden="true"
className="svg-inline--fa fa-exclamation-circle fa-w-16 mr-2"
data-icon="exclamation-circle"
data-prefix="fas"
focusable="false"
role="img"
style={Object {}}
viewBox="0 0 512 512"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M504 256c0 136.997-111.043 248-248 248S8 392.997 8 256C8 119.083 119.043 8 256 8s248 111.083 248 248zm-248 50c-25.405 0-46 20.595-46 46s20.595 46 46 46 46-20.595 46-46-20.595-46-46-46zm-43.673-165.346l7.418 136c.347 6.364 5.609 11.346 11.982 11.346h48.546c6.373 0 11.635-4.982 11.982-11.346l7.418-136c.375-6.874-5.098-12.654-11.982-12.654h-63.383c-6.884 0-12.356 5.78-11.981 12.654z"
fill="currentColor"
style={Object {}}
/>
</svg>
</div>
<div>
<h6>
A password is required
</h6>
<p
className="text-danger"
>
Sorry, there was an error trying to process your request. Please try again later.
</p>
</div>
</div>
<div
className="alert d-flex align-items-start alert-warning mt-n2"
>
<div>
<svg
aria-hidden="true"
className="svg-inline--fa fa-exclamation-triangle fa-w-18 mr-2"
data-icon="exclamation-triangle"
data-prefix="fas"
focusable="false"
role="img"
style={Object {}}
viewBox="0 0 576 512"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M569.517 440.013C587.975 472.007 564.806 512 527.94 512H48.054c-36.937 0-59.999-40.055-41.577-71.987L246.423 23.985c18.467-32.009 64.72-31.951 83.154 0l239.94 416.028zM288 354c-25.405 0-46 20.595-46 46s20.595 46 46 46 46-20.595 46-46-20.595-46-46-46zm-43.673-165.346l7.418 136c.347 6.364 5.609 11.346 11.982 11.346h48.546c6.373 0 11.635-4.982 11.982-11.346l7.418-136c.375-6.874-5.098-12.654-11.982-12.654h-63.383c-6.884 0-12.356 5.78-11.981 12.654z"
fill="currentColor"
style={Object {}}
/>
</svg>
</div>
<div>
<h6>
You have selected "Delete My Account". Deletion of your account and personal data is permanent and cannot be undone. edX will not be able to recover your account or the data that is deleted.
</h6>
<p>
If you proceed, you will be unable to use this account to take courses on the edX app, edx.org, or any other site hosted by edX. This includes access to edx.org from your employer's or university's system and access to private sites offered by MIT Open Learning, Wharton Executive Education, and Harvard Medical School.
</p>
<p>
<span>
You may also lose access to verified certificates and other program credentials like MicroMasters certificates. If you want to make a copy of these for your records before proceeding with deletion,
<a
href="https://edx.readthedocs.io/projects/edx-guide-for-students/en/latest/SFD_certificates.html#printing-a-certificate"
onClick={[Function]}
target="_self"
>
follow the instructions for printing or downloading a certificate
</a>
.
</span>
</p>
</div>
</div>
<div
className="form-group"
>
<label
className="d-block"
htmlFor="passwordFieldId"
>
If you still wish to continue and delete your account, please enter your account password:
</label>
<input
aria-describedby="passwordFieldId-invalid-feedback"
className="form-control is-invalid"
id="passwordFieldId"
name="password"
onChange={[MockFunction]}
type="password"
value="fluffy bunnies"
/>
<strong
className="invalid-feedback"
id="passwordFieldId-invalid-feedback"
>
A password is required
</strong>
</div>
</div>
</div>
<div
className="modal-footer"
>
<button
className="btn btn-danger"
onBlur={[Function]}
onClick={[Function]}
onKeyDown={[Function]}
type="button"
>
Yes, Delete
</button>
<button
className="btn js-close-modal-on-click btn-secondary"
id="paragonCloseModalButton5"
onBlur={[Function]}
onClick={[Function]}
onKeyDown={[Function]}
type="button"
>
Cancel
</button>
</div>
</div>
</div>
</div>
</div>
`;
exports[`ConfirmationModal should match open confirmation modal snapshot 1`] = `
<div>
<div
className="modal-backdrop show"
role="presentation"
/>
<div
className="modal js-close-modal-on-click show d-block"
onMouseDown={[Function]}
role="presentation"
>
<div
aria-labelledby="id4"
aria-modal={true}
className="modal-dialog"
role="dialog"
tabIndex="-1"
>
<div
className="modal-content"
>
<div
className="modal-header"
>
<h2
className="modal-title"
id="id4"
>
Are you sure?
</h2>
</div>
<div
className="modal-body"
>
<div>
<div
className="alert d-flex align-items-start alert-warning mt-n2"
>
<div>
<svg
aria-hidden="true"
className="svg-inline--fa fa-exclamation-triangle fa-w-18 mr-2"
data-icon="exclamation-triangle"
data-prefix="fas"
focusable="false"
role="img"
style={Object {}}
viewBox="0 0 576 512"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M569.517 440.013C587.975 472.007 564.806 512 527.94 512H48.054c-36.937 0-59.999-40.055-41.577-71.987L246.423 23.985c18.467-32.009 64.72-31.951 83.154 0l239.94 416.028zM288 354c-25.405 0-46 20.595-46 46s20.595 46 46 46 46-20.595 46-46-20.595-46-46-46zm-43.673-165.346l7.418 136c.347 6.364 5.609 11.346 11.982 11.346h48.546c6.373 0 11.635-4.982 11.982-11.346l7.418-136c.375-6.874-5.098-12.654-11.982-12.654h-63.383c-6.884 0-12.356 5.78-11.981 12.654z"
fill="currentColor"
style={Object {}}
/>
</svg>
</div>
<div>
<h6>
You have selected "Delete My Account". Deletion of your account and personal data is permanent and cannot be undone. edX will not be able to recover your account or the data that is deleted.
</h6>
<p>
If you proceed, you will be unable to use this account to take courses on the edX app, edx.org, or any other site hosted by edX. This includes access to edx.org from your employer's or university's system and access to private sites offered by MIT Open Learning, Wharton Executive Education, and Harvard Medical School.
</p>
<p>
<span>
You may also lose access to verified certificates and other program credentials like MicroMasters certificates. If you want to make a copy of these for your records before proceeding with deletion,
<a
href="https://edx.readthedocs.io/projects/edx-guide-for-students/en/latest/SFD_certificates.html#printing-a-certificate"
onClick={[Function]}
target="_self"
>
follow the instructions for printing or downloading a certificate
</a>
.
</span>
</p>
</div>
</div>
<div
className="form-group"
>
<label
className="d-block"
htmlFor="passwordFieldId"
>
If you still wish to continue and delete your account, please enter your account password:
</label>
<input
aria-describedby=""
className="form-control"
id="passwordFieldId"
name="password"
onChange={[MockFunction]}
type="password"
value="fluffy bunnies"
/>
<strong
className="invalid-feedback"
id="passwordFieldId-invalid-feedback"
>
Unable to delete account
</strong>
</div>
</div>
</div>
<div
className="modal-footer"
>
<button
className="btn btn-danger"
onBlur={[Function]}
onClick={[Function]}
onKeyDown={[Function]}
type="button"
>
Yes, Delete
</button>
<button
className="btn js-close-modal-on-click btn-secondary"
id="paragonCloseModalButton3"
onBlur={[Function]}
onClick={[Function]}
onKeyDown={[Function]}
type="button"
>
Cancel
</button>
</div>
</div>
</div>
</div>
</div>
`;

View File

@@ -1,247 +0,0 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`DeleteAccount should match default section snapshot 1`] = `
<div>
<h2
className="section-heading"
>
Delete My Account
</h2>
<p>
We're sorry to see you go!
</p>
<p>
Please note: Deletion of your account and personal data is permanent and cannot be undone. edX will not be able to recover your account or the data that is deleted.
</p>
<p>
Once your account is deleted, you cannot use it to take courses on the edX app, edx.org, or any other site hosted by edX. This includes access to edx.org from your employers or universitys system and access to private sites offered by MIT Open Learning, Wharton Executive Education, and Harvard Medical School.
</p>
<p>
<span>
You may also lose access to verified certificates and other program credentials like MicroMasters certificates. If you want to make a copy of these for your records before proceeding with deletion,
<a
href="https://edx.readthedocs.io/projects/edx-guide-for-students/en/latest/SFD_certificates.html#printing-a-certificate"
onClick={[Function]}
target="_self"
>
follow the instructions for printing or downloading a certificate
</a>
.
</span>
</p>
<p
className="text-danger h6"
>
Warning: Account deletion is permanent. Please read the above carefully before proceeding. This is an irreversible action, and you will no longer be able to use the same email on edX.
</p>
<p>
<a
href="https://support.edx.org/hc/en-us/sections/115004139268-Manage-Your-Account-Settings"
onClick={[Function]}
target="_self"
>
Want to change your email, name, or password instead?
</a>
</p>
<p>
<button
className="btn btn-outline-danger"
disabled={false}
onBlur={[Function]}
onClick={[Function]}
onKeyDown={[Function]}
type="button"
>
Delete My Account
</button>
</p>
</div>
`;
exports[`DeleteAccount should match unverified account section snapshot 1`] = `
<div>
<h2
className="section-heading"
>
Delete My Account
</h2>
<p>
We're sorry to see you go!
</p>
<p>
Please note: Deletion of your account and personal data is permanent and cannot be undone. edX will not be able to recover your account or the data that is deleted.
</p>
<p>
Once your account is deleted, you cannot use it to take courses on the edX app, edx.org, or any other site hosted by edX. This includes access to edx.org from your employers or universitys system and access to private sites offered by MIT Open Learning, Wharton Executive Education, and Harvard Medical School.
</p>
<p>
<span>
You may also lose access to verified certificates and other program credentials like MicroMasters certificates. If you want to make a copy of these for your records before proceeding with deletion,
<a
href="https://edx.readthedocs.io/projects/edx-guide-for-students/en/latest/SFD_certificates.html#printing-a-certificate"
onClick={[Function]}
target="_self"
>
follow the instructions for printing or downloading a certificate
</a>
.
</span>
</p>
<p
className="text-danger h6"
>
Warning: Account deletion is permanent. Please read the above carefully before proceeding. This is an irreversible action, and you will no longer be able to use the same email on edX.
</p>
<p>
<a
href="https://support.edx.org/hc/en-us/sections/115004139268-Manage-Your-Account-Settings"
onClick={[Function]}
target="_self"
>
Want to change your email, name, or password instead?
</a>
</p>
<p>
<button
className="btn btn-outline-danger"
disabled={true}
onBlur={[Function]}
onClick={[Function]}
onKeyDown={[Function]}
type="button"
>
Delete My Account
</button>
</p>
<div
className="alert d-flex align-items-start alert-warning mt-n2"
>
<div>
<svg
aria-hidden="true"
className="svg-inline--fa fa-exclamation-triangle fa-w-18 mr-2"
data-icon="exclamation-triangle"
data-prefix="fas"
focusable="false"
role="img"
style={Object {}}
viewBox="0 0 576 512"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M569.517 440.013C587.975 472.007 564.806 512 527.94 512H48.054c-36.937 0-59.999-40.055-41.577-71.987L246.423 23.985c18.467-32.009 64.72-31.951 83.154 0l239.94 416.028zM288 354c-25.405 0-46 20.595-46 46s20.595 46 46 46 46-20.595 46-46-20.595-46-46-46zm-43.673-165.346l7.418 136c.347 6.364 5.609 11.346 11.982 11.346h48.546c6.373 0 11.635-4.982 11.982-11.346l7.418-136c.375-6.874-5.098-12.654-11.982-12.654h-63.383c-6.884 0-12.356 5.78-11.981 12.654z"
fill="currentColor"
style={Object {}}
/>
</svg>
</div>
<div>
<span>
Before proceeding, please
<a
href="https://support.edx.org/hc/en-us/articles/115000940568-How-do-I-activate-my-account-"
onClick={[Function]}
target="_self"
>
activate your account
</a>
.
</span>
</div>
</div>
</div>
`;
exports[`DeleteAccount should match unverified account section snapshot 2`] = `
<div>
<h2
className="section-heading"
>
Delete My Account
</h2>
<p>
We're sorry to see you go!
</p>
<p>
Please note: Deletion of your account and personal data is permanent and cannot be undone. edX will not be able to recover your account or the data that is deleted.
</p>
<p>
Once your account is deleted, you cannot use it to take courses on the edX app, edx.org, or any other site hosted by edX. This includes access to edx.org from your employers or universitys system and access to private sites offered by MIT Open Learning, Wharton Executive Education, and Harvard Medical School.
</p>
<p>
<span>
You may also lose access to verified certificates and other program credentials like MicroMasters certificates. If you want to make a copy of these for your records before proceeding with deletion,
<a
href="https://edx.readthedocs.io/projects/edx-guide-for-students/en/latest/SFD_certificates.html#printing-a-certificate"
onClick={[Function]}
target="_self"
>
follow the instructions for printing or downloading a certificate
</a>
.
</span>
</p>
<p
className="text-danger h6"
>
Warning: Account deletion is permanent. Please read the above carefully before proceeding. This is an irreversible action, and you will no longer be able to use the same email on edX.
</p>
<p>
<a
href="https://support.edx.org/hc/en-us/sections/115004139268-Manage-Your-Account-Settings"
onClick={[Function]}
target="_self"
>
Want to change your email, name, or password instead?
</a>
</p>
<p>
<button
className="btn btn-outline-danger"
disabled={true}
onBlur={[Function]}
onClick={[Function]}
onKeyDown={[Function]}
type="button"
>
Delete My Account
</button>
</p>
<div
className="alert d-flex align-items-start alert-warning mt-n2"
>
<div>
<svg
aria-hidden="true"
className="svg-inline--fa fa-exclamation-triangle fa-w-18 mr-2"
data-icon="exclamation-triangle"
data-prefix="fas"
focusable="false"
role="img"
style={Object {}}
viewBox="0 0 576 512"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M569.517 440.013C587.975 472.007 564.806 512 527.94 512H48.054c-36.937 0-59.999-40.055-41.577-71.987L246.423 23.985c18.467-32.009 64.72-31.951 83.154 0l239.94 416.028zM288 354c-25.405 0-46 20.595-46 46s20.595 46 46 46 46-20.595 46-46-20.595-46-46-46zm-43.673-165.346l7.418 136c.347 6.364 5.609 11.346 11.982 11.346h48.546c6.373 0 11.635-4.982 11.982-11.346l7.418-136c.375-6.874-5.098-12.654-11.982-12.654h-63.383c-6.884 0-12.356 5.78-11.981 12.654z"
fill="currentColor"
style={Object {}}
/>
</svg>
</div>
<div>
<span>
Before proceeding, please
<a
href="https://support.edx.org/hc/en-us/articles/207206067"
onClick={[Function]}
target="_self"
>
unlink all social media accounts
</a>
.
</span>
</div>
</div>
</div>
`;

View File

@@ -1,311 +0,0 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`SuccessModal should match default closed success modal snapshot 1`] = `
<div>
<div
className="fade"
role="presentation"
/>
<div
className="modal js-close-modal-on-click fade"
onMouseDown={[Function]}
role="presentation"
>
<div
aria-labelledby="id2"
aria-modal={true}
className=""
role="dialog"
tabIndex="-1"
>
<div
className="modal-content"
>
<div
className="modal-header"
>
<h2
className="modal-title"
id="id2"
>
We're sorry to see you go! Your account will be deleted shortly.
</h2>
</div>
<div
className="modal-body"
>
<div>
<p
className="h6"
>
Account deletion, including removal from email lists, may take a few weeks to fully process through our system. If you want to opt-out of emails before then, please unsubscribe from the footer of any email.
</p>
</div>
</div>
<div
className="modal-footer"
>
<button
className="btn js-close-modal-on-click btn-secondary"
id="paragonCloseModalButton1"
onBlur={[Function]}
onClick={[Function]}
onKeyDown={[Function]}
type="button"
>
Close
</button>
</div>
</div>
</div>
</div>
</div>
`;
exports[`SuccessModal should match default closed success modal snapshot 2`] = `
<div>
<div
className="fade"
role="presentation"
/>
<div
className="modal js-close-modal-on-click fade"
onMouseDown={[Function]}
role="presentation"
>
<div
aria-labelledby="id4"
aria-modal={true}
className=""
role="dialog"
tabIndex="-1"
>
<div
className="modal-content"
>
<div
className="modal-header"
>
<h2
className="modal-title"
id="id4"
>
We're sorry to see you go! Your account will be deleted shortly.
</h2>
</div>
<div
className="modal-body"
>
<div>
<p
className="h6"
>
Account deletion, including removal from email lists, may take a few weeks to fully process through our system. If you want to opt-out of emails before then, please unsubscribe from the footer of any email.
</p>
</div>
</div>
<div
className="modal-footer"
>
<button
className="btn js-close-modal-on-click btn-secondary"
id="paragonCloseModalButton3"
onBlur={[Function]}
onClick={[Function]}
onKeyDown={[Function]}
type="button"
>
Close
</button>
</div>
</div>
</div>
</div>
</div>
`;
exports[`SuccessModal should match default closed success modal snapshot 3`] = `
<div>
<div
className="fade"
role="presentation"
/>
<div
className="modal js-close-modal-on-click fade"
onMouseDown={[Function]}
role="presentation"
>
<div
aria-labelledby="id6"
aria-modal={true}
className=""
role="dialog"
tabIndex="-1"
>
<div
className="modal-content"
>
<div
className="modal-header"
>
<h2
className="modal-title"
id="id6"
>
We're sorry to see you go! Your account will be deleted shortly.
</h2>
</div>
<div
className="modal-body"
>
<div>
<p
className="h6"
>
Account deletion, including removal from email lists, may take a few weeks to fully process through our system. If you want to opt-out of emails before then, please unsubscribe from the footer of any email.
</p>
</div>
</div>
<div
className="modal-footer"
>
<button
className="btn js-close-modal-on-click btn-secondary"
id="paragonCloseModalButton5"
onBlur={[Function]}
onClick={[Function]}
onKeyDown={[Function]}
type="button"
>
Close
</button>
</div>
</div>
</div>
</div>
</div>
`;
exports[`SuccessModal should match default closed success modal snapshot 4`] = `
<div>
<div
className="fade"
role="presentation"
/>
<div
className="modal js-close-modal-on-click fade"
onMouseDown={[Function]}
role="presentation"
>
<div
aria-labelledby="id8"
aria-modal={true}
className=""
role="dialog"
tabIndex="-1"
>
<div
className="modal-content"
>
<div
className="modal-header"
>
<h2
className="modal-title"
id="id8"
>
We're sorry to see you go! Your account will be deleted shortly.
</h2>
</div>
<div
className="modal-body"
>
<div>
<p
className="h6"
>
Account deletion, including removal from email lists, may take a few weeks to fully process through our system. If you want to opt-out of emails before then, please unsubscribe from the footer of any email.
</p>
</div>
</div>
<div
className="modal-footer"
>
<button
className="btn js-close-modal-on-click btn-secondary"
id="paragonCloseModalButton7"
onBlur={[Function]}
onClick={[Function]}
onKeyDown={[Function]}
type="button"
>
Close
</button>
</div>
</div>
</div>
</div>
</div>
`;
exports[`SuccessModal should match open success modal snapshot 1`] = `
<div>
<div
className="modal-backdrop show"
role="presentation"
/>
<div
className="modal js-close-modal-on-click show d-block"
onMouseDown={[Function]}
role="presentation"
>
<div
aria-labelledby="id10"
aria-modal={true}
className="modal-dialog"
role="dialog"
tabIndex="-1"
>
<div
className="modal-content"
>
<div
className="modal-header"
>
<h2
className="modal-title"
id="id10"
>
We're sorry to see you go! Your account will be deleted shortly.
</h2>
</div>
<div
className="modal-body"
>
<div>
<p
className="h6"
>
Account deletion, including removal from email lists, may take a few weeks to fully process through our system. If you want to opt-out of emails before then, please unsubscribe from the footer of any email.
</p>
</div>
</div>
<div
className="modal-footer"
>
<button
className="btn js-close-modal-on-click btn-secondary"
id="paragonCloseModalButton9"
onBlur={[Function]}
onClick={[Function]}
onKeyDown={[Function]}
type="button"
>
Close
</button>
</div>
</div>
</div>
</div>
</div>
`;

View File

@@ -1,37 +0,0 @@
import { AsyncActionType } from '../../data/utils';
export const DELETE_ACCOUNT = new AsyncActionType('ACCOUNT_SETTINGS', 'DELETE_ACCOUNT');
DELETE_ACCOUNT.CONFIRMATION = 'ACCOUNT_SETTINGS__DELETE_ACCOUNT__CONFIRMATION';
DELETE_ACCOUNT.CANCEL = 'ACCOUNT_SETTINGS__DELETE_ACCOUNT__CANCEL';
export const deleteAccount = password => ({
type: DELETE_ACCOUNT.BASE,
payload: { password },
});
export const deleteAccountConfirmation = () => ({
type: DELETE_ACCOUNT.CONFIRMATION,
});
export const deleteAccountBegin = () => ({
type: DELETE_ACCOUNT.BEGIN,
});
export const deleteAccountSuccess = () => ({
type: DELETE_ACCOUNT.SUCCESS,
});
export const deleteAccountFailure = reason => ({
type: DELETE_ACCOUNT.FAILURE,
payload: { reason },
});
// to clear errors from the confirmation modal
export const deleteAccountReset = () => ({
type: DELETE_ACCOUNT.RESET,
});
// to close the modal
export const deleteAccountCancel = () => ({
type: DELETE_ACCOUNT.CANCEL,
});

View File

@@ -1,60 +0,0 @@
import { DELETE_ACCOUNT } from './actions';
export const defaultState = {
status: null,
errorType: null,
};
const reducer = (state = defaultState, action = null) => {
if (action !== null) {
switch (action.type) {
case DELETE_ACCOUNT.CONFIRMATION:
return {
...state,
status: 'confirming',
};
case DELETE_ACCOUNT.BEGIN:
return {
...state,
status: 'pending',
};
case DELETE_ACCOUNT.SUCCESS:
return {
...state,
status: 'deleted',
};
case DELETE_ACCOUNT.FAILURE:
return {
...state,
status: 'failed',
errorType: action.payload.reason || 'server',
};
case DELETE_ACCOUNT.RESET: {
const oldStatus = state.status;
return {
...state,
// clear the error state if applicable, otherwise don't change state
status: oldStatus === 'failed' ? 'confirming' : oldStatus,
errorType: null,
};
}
case DELETE_ACCOUNT.CANCEL:
return {
...state,
status: null,
errorType: null,
};
default:
}
}
return state;
};
export default reducer;

View File

@@ -1,107 +0,0 @@
import reducer from './reducers';
import {
deleteAccountConfirmation,
deleteAccountBegin,
deleteAccountSuccess,
deleteAccountFailure,
deleteAccountReset,
deleteAccountCancel,
} from './actions';
describe('delete-account reducer', () => {
let state = null;
beforeEach(() => {
state = reducer();
});
it('should process DELETE_ACCOUNT.CONFIRMATION', () => {
const result = reducer(state, deleteAccountConfirmation());
expect(result).toEqual({
errorType: null,
status: 'confirming',
});
});
it('should process DELETE_ACCOUNT.BEGIN', () => {
const result = reducer(state, deleteAccountBegin());
expect(result).toEqual({
errorType: null,
status: 'pending',
});
});
it('should process DELETE_ACCOUNT.SUCCESS', () => {
const result = reducer(state, deleteAccountSuccess());
expect(result).toEqual({
errorType: null,
status: 'deleted',
});
});
it('should process DELETE_ACCOUNT.FAILURE no reason', () => {
const result = reducer(state, deleteAccountFailure());
expect(result).toEqual({
errorType: 'server',
status: 'failed',
});
});
it('should process DELETE_ACCOUNT.FAILURE with reason', () => {
const result = reducer(state, deleteAccountFailure('carnivorous buns'));
expect(result).toEqual({
errorType: 'carnivorous buns',
status: 'failed',
});
});
it('should process DELETE_ACCOUNT.RESET no status', () => {
const result = reducer(state, deleteAccountReset());
expect(result).toEqual({
errorType: null,
status: null,
});
});
it('should process DELETE_ACCOUNT.RESET with failed old status', () => {
const result = reducer(
{
errorType: 'carnivorous buns',
status: 'failed',
},
deleteAccountReset(),
);
expect(result).toEqual({
errorType: null,
status: 'confirming',
});
});
it('should process DELETE_ACCOUNT.RESET with pending old status', () => {
const result = reducer(
{
errorType: 'carnivorous buns',
status: 'pending',
},
deleteAccountReset(),
);
expect(result).toEqual({
errorType: null,
status: 'pending',
});
});
it('should process DELETE_ACCOUNT.CANCEL', () => {
const result = reducer(
{
errorType: 'carnivorous buns',
status: 'failed',
},
deleteAccountCancel(),
);
expect(result).toEqual({
errorType: null,
status: null,
});
});
});

View File

@@ -1,28 +0,0 @@
import { put, call, takeEvery } from 'redux-saga/effects';
import {
DELETE_ACCOUNT,
deleteAccountBegin,
deleteAccountSuccess,
deleteAccountFailure,
} from './actions';
import { postDeleteAccount } from './service';
export function* handleDeleteAccount(action) {
try {
yield put(deleteAccountBegin());
const response = yield call(postDeleteAccount, action.payload.password);
yield put(deleteAccountSuccess(response));
} catch (e) {
if (typeof e.response.data === 'string') {
yield put(deleteAccountFailure());
} else {
throw e;
}
}
}
export default function* saga() {
yield takeEvery(DELETE_ACCOUNT.BASE, handleDeleteAccount);
}

View File

@@ -1,23 +0,0 @@
import { getConfig } from '@edx/frontend-platform';
import { getAuthenticatedHttpClient } from '@edx/frontend-platform/auth';
import formurlencoded from 'form-urlencoded';
import { handleRequestError } from '../../data/utils';
/**
* Request deletion of the user's account.
*/
// eslint-disable-next-line import/prefer-default-export
export async function postDeleteAccount(password) {
const { data } = await getAuthenticatedHttpClient()
.post(
`${getConfig().LMS_BASE_URL}/api/user/v1/accounts/deactivate_logout/`,
formurlencoded({ password }),
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
},
)
.catch(handleRequestError);
return data;
}

View File

@@ -1,4 +0,0 @@
export { default } from './DeleteAccount';
export { default as reducer } from './data/reducers';
export { default as saga } from './data/sagas';
export { DELETE_ACCOUNT } from './data/actions';

View File

@@ -1,116 +0,0 @@
import { defineMessages } from '@edx/frontend-platform/i18n';
const messages = defineMessages({
'account.settings.delete.account.header': {
id: 'account.settings.delete.account.header',
defaultMessage: 'Delete My Account',
description: 'Header for the user account deletion area',
},
'account.settings.delete.account.subheader': {
id: 'account.settings.delete.account.subheader',
defaultMessage: 'We\'re sorry to see you go!',
description: 'A message in the user account deletion area',
},
'account.settings.delete.account.text.1': {
id: 'account.settings.delete.account.text.1',
defaultMessage: 'Please note: Deletion of your account and personal data is permanent and cannot be undone. edX will not be able to recover your account or the data that is deleted.',
description: 'A message in the user account deletion area',
},
'account.settings.delete.account.text.2': {
id: 'account.settings.delete.account.text.2',
defaultMessage: 'Once your account is deleted, you cannot use it to take courses on the edX app, edx.org, or any other site hosted by edX. This includes access to edx.org from your employers or universitys system and access to private sites offered by MIT Open Learning, Wharton Executive Education, and Harvard Medical School.',
description: 'A message in the user account deletion area',
},
'account.settings.delete.account.text.3.link': {
id: 'account.settings.delete.account.text.3.link',
defaultMessage: 'follow the instructions for printing or downloading a certificate',
description: 'This text will be a link to a technical support page; it will go in the phrase If you want to make a copy of these for your records, ______ .',
},
'account.settings.delete.account.text.warning': {
id: 'account.settings.delete.account.text.warning',
defaultMessage: 'Warning: Account deletion is permanent. Please read the above carefully before proceeding. This is an irreversible action, and you will no longer be able to use the same email on edX.',
description: 'A message in the user account deletion area',
},
'account.settings.delete.account.text.change.instead': {
id: 'account.settings.delete.account.text.change.instead',
defaultMessage: 'Want to change your email, name, or password instead?',
description: 'A message in the user account deletion area',
},
'account.settings.delete.account.button': {
id: 'account.settings.delete.account.button',
defaultMessage: 'Delete My Account',
description: 'Button label to permanently delete your edX account',
},
'account.settings.delete.account.please.activate': {
id: 'account.settings.delete.account.please.activate',
defaultMessage: 'activate your account',
description: 'This is the text on a link that goes to the support page. It is part of this sentence: Before proceeding, please activate your account.',
},
'account.settings.delete.account.please.unlink': {
id: 'account.settings.delete.account.please.unlink',
defaultMessage: 'unlink all social media accounts',
description: 'This is the text on a link that goes to the support page. It is part of this sentence: Before proceeding, please unlink all social media accounts.',
},
'account.settings.delete.account.modal.header': {
id: 'account.settings.delete.account.modal.header',
defaultMessage: 'Are you sure?',
description: 'Title of the dialog asking user to confirm that they want to delete their entire account',
},
'account.settings.delete.account.modal.text.1': {
id: 'account.settings.delete.account.modal.text.1',
defaultMessage: 'You have selected "Delete My Account". Deletion of your account and personal data is permanent and cannot be undone. edX will not be able to recover your account or the data that is deleted.',
description: 'Messaging in the dialog asking user to confirm that they want to delete their entire account',
},
'account.settings.delete.account.modal.text.2': {
id: 'account.settings.delete.account.modal.text.2',
defaultMessage: 'If you proceed, you will be unable to use this account to take courses on the edX app, edx.org, or any other site hosted by edX. This includes access to edx.org from your employer\'s or university\'s system and access to private sites offered by MIT Open Learning, Wharton Executive Education, and Harvard Medical School.',
description: 'Messaging in the dialog asking user to confirm that they want to delete their entire account',
},
'account.settings.delete.account.modal.enter.password': {
id: 'account.settings.delete.account.modal.enter.password',
defaultMessage: 'If you still wish to continue and delete your account, please enter your account password:',
description: 'Asking for the user\'s account password',
},
'account.settings.delete.account.modal.confirm.delete': {
id: 'account.settings.delete.account.modal.confirm.delete',
defaultMessage: 'Yes, Delete',
description: 'Button label for user to confirm it is okay to delete their account',
},
'account.settings.delete.account.modal.confirm.cancel': {
id: 'account.settings.delete.account.modal.confirm.cancel',
defaultMessage: 'Cancel',
description: 'The cancel button on the delete my account modal confirmation',
},
'account.settings.delete.account.error.unable.to.delete': {
id: 'account.settings.delete.account.error.unable.to.delete',
defaultMessage: 'Unable to delete account',
description: 'Error message when account deletion failed',
},
'account.settings.delete.account.error.no.password': {
id: 'account.settings.delete.account.error.no.password',
defaultMessage: 'A password is required',
description: 'Error message when user has not entered their password',
},
'account.settings.delete.account.error.unable.to.delete.details': {
id: 'account.settings.delete.account.error.unable.to.delete.details',
defaultMessage: 'Sorry, there was an error trying to process your request. Please try again later.',
description: 'Error message when account deletion failed',
},
'account.settings.delete.account.modal.after.header': {
id: 'account.settings.delete.account.modal.after.header',
defaultMessage: 'We\'re sorry to see you go! Your account will be deleted shortly.',
description: 'Title displayed after user account is deleted',
},
'account.settings.delete.account.modal.after.text': {
id: 'account.settings.delete.account.modal.after.text',
defaultMessage: 'Account deletion, including removal from email lists, may take a few weeks to fully process through our system. If you want to opt-out of emails before then, please unsubscribe from the footer of any email.',
description: 'Text displayed after user account is deleted',
},
'account.settings.delete.account.modal.after.button': {
id: 'account.settings.delete.account.modal.after.button',
defaultMessage: 'Close',
description: 'Label on button to close a dialog',
},
});
export default messages;

View File

@@ -1,5 +1,13 @@
export { default } from './AccountSettingsPage';
export { default as reducer } from './data/reducers';
export { default as saga } from './data/sagas';
export { storeName } from './data/selectors';
export { default as NotFoundPage } from './NotFoundPage';
import ConnectedAccountSettingsPage from './AccountSettingsPage';
import reducer from './reducers';
import saga from './sagas';
import { configureApiService } from './service';
import { storeName } from './selectors';
export {
ConnectedAccountSettingsPage,
reducer,
saga,
configureApiService,
storeName,
};

View File

@@ -1,19 +1,14 @@
import {
FETCH_SETTINGS,
FETCH_ACCOUNT,
OPEN_FORM,
CLOSE_FORM,
SAVE_SETTINGS,
FETCH_TIME_ZONES,
SAVE_PREVIOUS_SITE_LANGUAGE,
SAVE_ACCOUNT,
RESET_PASSWORD,
UPDATE_DRAFT,
RESET_DRAFTS,
FETCH_THIRD_PARTY_AUTH_PROVIDERS,
} from './actions';
import { reducer as deleteAccountReducer, DELETE_ACCOUNT } from '../delete-account';
import { reducer as siteLanguageReducer, FETCH_SITE_LANGUAGES } from '../site-language';
import { reducer as resetPasswordReducer, RESET_PASSWORD } from '../reset-password';
import { reducer as thirdPartyAuthReducer, DISCONNECT_AUTH } from '../third-party-auth';
export const defaultState = {
loading: false,
loaded: false,
@@ -24,48 +19,36 @@ export const defaultState = {
confirmationValues: {},
drafts: {},
saveState: null,
timeZones: [],
countryTimeZones: [],
previousSiteLanguage: null,
deleteAccount: deleteAccountReducer(),
siteLanguage: siteLanguageReducer(),
resetPassword: resetPasswordReducer(),
thirdPartyAuth: thirdPartyAuthReducer(),
resetPasswordState: null,
};
const reducer = (state = defaultState, action) => {
const accountSettingsReducer = (state = defaultState, action) => {
let dispatcherIsOpenForm;
switch (action.type) {
case FETCH_SETTINGS.BEGIN:
case FETCH_ACCOUNT.BEGIN:
return {
...state,
loading: true,
loaded: false,
loadingError: null,
};
case FETCH_SETTINGS.SUCCESS:
case FETCH_ACCOUNT.SUCCESS:
return {
...state,
values: Object.assign({}, state.values, action.payload.values),
// Dump the providers into thirdPartyAuth.
thirdPartyAuth: Object.assign({}, state.thirdPartyAuth, {
providers: action.payload.thirdPartyAuthProviders,
}),
profileDataManager: action.payload.profileDataManager,
timeZones: action.payload.timeZones,
loading: false,
loaded: true,
loadingError: null,
};
case FETCH_SETTINGS.FAILURE:
case FETCH_ACCOUNT.FAILURE:
return {
...state,
loading: false,
loaded: false,
loadingError: action.payload.error,
};
case FETCH_SETTINGS.RESET:
case FETCH_ACCOUNT.RESET:
return {
...state,
loading: false,
@@ -109,13 +92,13 @@ const reducer = (state = defaultState, action) => {
drafts: {},
};
case SAVE_SETTINGS.BEGIN:
case SAVE_ACCOUNT.BEGIN:
return {
...state,
saveState: 'pending',
errors: {},
};
case SAVE_SETTINGS.SUCCESS:
case SAVE_ACCOUNT.SUCCESS:
return {
...state,
saveState: 'complete',
@@ -127,68 +110,58 @@ const reducer = (state = defaultState, action) => {
action.payload.confirmationValues,
),
};
case SAVE_SETTINGS.FAILURE:
case SAVE_ACCOUNT.FAILURE:
return {
...state,
saveState: 'error',
errors: Object.assign({}, state.errors, action.payload.errors),
};
case SAVE_SETTINGS.RESET:
case SAVE_ACCOUNT.RESET:
return {
...state,
saveState: null,
errors: {},
};
case SAVE_PREVIOUS_SITE_LANGUAGE:
return {
...state,
previousSiteLanguage: action.payload.previousSiteLanguage,
};
case FETCH_TIME_ZONES.SUCCESS:
return {
...state,
countryTimeZones: action.payload.timeZones,
};
// TODO: Once all the above cases have been converted into sub-reducers, we can use
// combineReducers in this file to greatly simplify it.
// Delete My Account
case DELETE_ACCOUNT.CONFIRMATION:
case DELETE_ACCOUNT.BEGIN:
case DELETE_ACCOUNT.SUCCESS:
case DELETE_ACCOUNT.FAILURE:
case DELETE_ACCOUNT.RESET:
case DELETE_ACCOUNT.CANCEL:
return {
...state,
deleteAccount: deleteAccountReducer(state.deleteAccount, action),
};
case FETCH_SITE_LANGUAGES.BEGIN:
case FETCH_SITE_LANGUAGES.SUCCESS:
case FETCH_SITE_LANGUAGES.FAILURE:
case FETCH_SITE_LANGUAGES.RESET:
return {
...state,
siteLanguage: siteLanguageReducer(state.siteLanguage, action),
};
case RESET_PASSWORD.BEGIN:
return {
...state,
resetPasswordState: 'pending',
};
case RESET_PASSWORD.SUCCESS:
return {
...state,
resetPassword: resetPasswordReducer(state.resetPassword, action),
resetPasswordState: 'complete',
};
case DISCONNECT_AUTH.BEGIN:
case DISCONNECT_AUTH.SUCCESS:
case DISCONNECT_AUTH.FAILURE:
case DISCONNECT_AUTH.RESET:
case FETCH_THIRD_PARTY_AUTH_PROVIDERS.BEGIN:
return {
...state,
thirdPartyAuth: thirdPartyAuthReducer(state.thirdPartyAuth, action),
thirdPartyAuthLoading: true,
thirdPartyAuthLoaded: false,
thirdPartyAuthLoadingError: null,
};
case FETCH_THIRD_PARTY_AUTH_PROVIDERS.SUCCESS:
return {
...state,
authProviders: action.payload.providers,
thirdPartyAuthLoading: false,
thirdPartyAuthLoaded: true,
thirdPartyAuthLoadingError: null,
};
case FETCH_THIRD_PARTY_AUTH_PROVIDERS.FAILURE:
return {
...state,
thirdPartyAuthLoading: false,
thirdPartyAuthLoaded: false,
thirdPartyAuthLoadingError: action.payload.error,
};
case FETCH_THIRD_PARTY_AUTH_PROVIDERS.RESET:
return {
...state,
thirdPartyAuthLoading: false,
thirdPartyAuthLoaded: false,
thirdPartyAuthLoadingError: null,
};
default:
@@ -196,4 +169,4 @@ const reducer = (state = defaultState, action) => {
}
};
export default reducer;
export default accountSettingsReducer;

View File

@@ -1,47 +0,0 @@
import React from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage } from '@edx/frontend-platform/i18n';
import { Hyperlink } from '@edx/paragon';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faExclamationTriangle } from '@fortawesome/free-solid-svg-icons';
import Alert from '../Alert';
const ConfirmationAlert = (props) => {
const { email } = props;
const technicalSupportLink = (
<Hyperlink
destination="https://support.edx.org/hc/en-us/articles/206212088-What-if-I-did-not-receive-a-password-reset-message-"
>
<FormattedMessage
id="account.settings.editable.field.password.reset.button.confirmation.support.link"
defaultMessage="technical support"
description="link text used in message: account.settings.editable.field.password.reset.button.confirmation 'Contact technical support.'"
/>
</Hyperlink>
);
return (
<Alert
className="alert-warning mt-n2"
icon={<FontAwesomeIcon className="mr-2" icon={faExclamationTriangle} />}
>
<FormattedMessage
id="account.settings.editable.field.password.reset.button.confirmation"
defaultMessage="We've sent a message to {email}. Click the link in the message to reset your password. Didn't receive the message? Contact {technicalSupportLink}."
description="The password reset button in account settings"
values={{
email,
technicalSupportLink,
}}
/>
</Alert>
);
};
ConfirmationAlert.propTypes = {
email: PropTypes.string.isRequired,
};
export default ConfirmationAlert;

View File

@@ -1,69 +0,0 @@
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { injectIntl, intlShape, FormattedMessage } from '@edx/frontend-platform/i18n';
import { StatefulButton } from '@edx/paragon';
import { resetPassword } from './data/actions';
import messages from './messages';
import ConfirmationAlert from './ConfirmationAlert';
const ResetPassword = (props) => {
const { email, intl, status } = props;
return (
<div className="form-group">
<h6 aria-level="3">
<FormattedMessage
id="account.settings.editable.field.password.reset.label"
defaultMessage="Password"
description="The password label in account settings"
/>
</h6>
<p>
<StatefulButton
className="btn-link"
state={status}
onClick={(e) => {
// Swallow clicks if the state is pending.
// We do this instead of disabling the button to prevent
// it from losing focus (disabled elements cannot have focus).
// Disabling it would causes upstream issues in focus management.
// Swallowing the onSubmit event on the form would be better, but
// we would have to add that logic for every field given our
// current structure of the application.
if (status === 'pending') {
e.preventDefault();
}
props.resetPassword(email);
}}
disabledStates={[]}
labels={{
default: intl.formatMessage(messages['account.settings.editable.field.password.reset.button']),
}}
/>
</p>
{status === 'complete' ? <ConfirmationAlert email={email} /> : null}
</div>
);
};
ResetPassword.propTypes = {
email: PropTypes.string,
intl: intlShape.isRequired,
resetPassword: PropTypes.func.isRequired,
status: PropTypes.string,
};
ResetPassword.defaultProps = {
email: '',
status: null,
};
const mapStateToProps = state => state.accountSettings.resetPassword;
export default connect(
mapStateToProps,
{
resetPassword,
},
)(injectIntl(ResetPassword));

View File

@@ -1,20 +0,0 @@
import { AsyncActionType } from '../../data/utils';
export const RESET_PASSWORD = new AsyncActionType('ACCOUNT_SETTINGS', 'RESET_PASSWORD');
export const resetPassword = email => ({
type: RESET_PASSWORD.BASE,
payload: { email },
});
export const resetPasswordBegin = () => ({
type: RESET_PASSWORD.BEGIN,
});
export const resetPasswordSuccess = () => ({
type: RESET_PASSWORD.SUCCESS,
});
export const resetPasswordReset = () => ({
type: RESET_PASSWORD.RESET,
});

View File

@@ -1,27 +0,0 @@
import { RESET_PASSWORD } from './actions';
export const defaultState = {
status: null,
};
const reducer = (state = defaultState, action = null) => {
if (action !== null) {
switch (action.type) {
case RESET_PASSWORD.BEGIN:
return {
...state,
status: 'pending',
};
case RESET_PASSWORD.SUCCESS:
return {
...state,
status: 'complete',
};
default:
}
}
return state;
};
export default reducer;

View File

@@ -1,14 +0,0 @@
import { put, call, takeEvery } from 'redux-saga/effects';
import { resetPasswordBegin, resetPasswordSuccess, RESET_PASSWORD } from './actions';
import { postResetPassword } from './service';
function* handleResetPassword(action) {
yield put(resetPasswordBegin());
const response = yield call(postResetPassword, action.payload.email);
yield put(resetPasswordSuccess(response));
}
export default function* saga() {
yield takeEvery(RESET_PASSWORD.BASE, handleResetPassword);
}

View File

@@ -1,21 +0,0 @@
import { getConfig } from '@edx/frontend-platform';
import { getAuthenticatedHttpClient } from '@edx/frontend-platform/auth';
import formurlencoded from 'form-urlencoded';
import { handleRequestError } from '../../data/utils';
// eslint-disable-next-line import/prefer-default-export
export async function postResetPassword(email) {
const { data } = await getAuthenticatedHttpClient()
.post(
`${getConfig().LMS_BASE_URL}/password_reset/`,
formurlencoded({ email }),
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
},
)
.catch(handleRequestError);
return data;
}

View File

@@ -1,4 +0,0 @@
export { default } from './ResetPassword';
export { default as reducer } from './data/reducers';
export { RESET_PASSWORD } from './data/actions';
export { default as saga } from './data/sagas';

View File

@@ -1,11 +0,0 @@
import { defineMessages } from '@edx/frontend-platform/i18n';
const messages = defineMessages({
'account.settings.editable.field.password.reset.button': {
id: 'account.settings.editable.field.password.reset.button',
defaultMessage: 'Reset Password',
description: 'The password reset button in account settings',
},
});
export default messages;

View File

@@ -0,0 +1,94 @@
import { call, put, delay, takeEvery, select } from 'redux-saga/effects';
import { push } from 'connected-react-router';
import { logAPIErrorResponse } from '@edx/frontend-logging';
// Actions
import {
FETCH_ACCOUNT,
fetchAccountBegin,
fetchAccountSuccess,
fetchAccountFailure,
closeForm,
SAVE_ACCOUNT,
saveAccountBegin,
saveAccountSuccess,
saveAccountFailure,
RESET_PASSWORD,
resetPasswordBegin,
resetPasswordSuccess,
FETCH_THIRD_PARTY_AUTH_PROVIDERS,
fetchThirdPartyAuthProvidersBegin,
fetchThirdPartyAuthProvidersSuccess,
fetchThirdPartyAuthProvidersFailure,
} from './actions';
import { usernameSelector } from './selectors';
// Services
import * as ApiService from './service';
export function* handleFetchAccount() {
try {
yield put(fetchAccountBegin());
const username = yield select(usernameSelector);
const values = yield call(ApiService.getAccount, username);
yield put(fetchAccountSuccess(values));
} catch (e) {
logAPIErrorResponse(e);
yield put(fetchAccountFailure(e.message));
yield put(push('/error'));
}
}
export function* handleSaveAccount(action) {
try {
yield put(saveAccountBegin());
const username = yield select(usernameSelector);
const { commitValues, formId } = action.payload;
const commitData = { [formId]: commitValues };
const savedValues = yield call(ApiService.patchAccount, username, commitData);
yield put(saveAccountSuccess(savedValues, commitData));
yield delay(1000);
yield put(closeForm(action.payload.formId));
} catch (e) {
if (e.fieldErrors) {
yield put(saveAccountFailure({ fieldErrors: e.fieldErrors }));
} else {
logAPIErrorResponse(e);
yield put(saveAccountFailure(e.message));
yield put(push('/error'));
}
}
}
export function* handleResetPassword() {
try {
yield put(resetPasswordBegin());
const response = yield call(ApiService.postResetPassword);
yield put(resetPasswordSuccess(response));
} catch (e) {
logAPIErrorResponse(e);
yield put(push('/error'));
}
}
export function* handleFetchThirdPartyAuthProviders() {
try {
yield put(fetchThirdPartyAuthProvidersBegin());
const authProviders = yield call(ApiService.getThirdPartyAuthProviders);
yield put(fetchThirdPartyAuthProvidersSuccess(authProviders));
} catch (e) {
logAPIErrorResponse(e);
yield put(fetchThirdPartyAuthProvidersFailure(e.message));
yield put(push('/error'));
}
}
export default function* saga() {
yield takeEvery(FETCH_ACCOUNT.BASE, handleFetchAccount);
yield takeEvery(SAVE_ACCOUNT.BASE, handleSaveAccount);
yield takeEvery(RESET_PASSWORD.BASE, handleResetPassword);
yield takeEvery(FETCH_THIRD_PARTY_AUTH_PROVIDERS.BASE, handleFetchThirdPartyAuthProviders);
}

View File

@@ -0,0 +1,75 @@
import { createSelector, createStructuredSelector } from 'reselect';
export const storeName = 'account-settings';
export const usernameSelector = state => state.authentication.username;
export const accountSettingsSelector = state => ({ ...state[storeName] });
const editableFieldNameSelector = (state, props) => props.name;
const valuesSelector = createSelector(
accountSettingsSelector,
accountSettings => accountSettings.values,
);
const draftsSelector = createSelector(
accountSettingsSelector,
accountSettings => accountSettings.drafts,
);
const editableFieldValueSelector = createSelector(
editableFieldNameSelector,
valuesSelector,
draftsSelector,
(name, values, drafts) => (drafts[name] !== undefined ? drafts[name] : values[name]),
);
const editableFieldErrorSelector = createSelector(
editableFieldNameSelector,
accountSettingsSelector,
(name, accountSettings) => accountSettings.errors[name],
);
const editableFieldConfirmationValuesSelector = createSelector(
editableFieldNameSelector,
accountSettingsSelector,
(name, accountSettings) => accountSettings.confirmationValues[name],
);
const isEditingSelector = createSelector(
editableFieldNameSelector,
accountSettingsSelector,
(name, accountSettings) => accountSettings.openFormId === name,
);
const saveStateSelector = createSelector(
accountSettingsSelector,
accountSettings => accountSettings.saveState,
);
export const editableFieldSelector = createStructuredSelector({
value: editableFieldValueSelector,
error: editableFieldErrorSelector,
confirmationValue: editableFieldConfirmationValuesSelector,
saveState: saveStateSelector,
isEditing: isEditingSelector,
});
export const resetPasswordSelector = createSelector(
accountSettingsSelector,
accountSettings => ({
resetPasswordState: accountSettings.resetPasswordState,
email: accountSettings.values.email,
}),
);
export const thirdPartyAuthSelector = createSelector(
accountSettingsSelector,
accountSettings => ({
providers: accountSettings.authProviders,
loading: accountSettings.thirdPartyAuthLoading,
loaded: accountSettings.thirdPartyAuthLoaded,
loadingError: accountSettings.thirdPartyAuthLoadingError,
}),
);

View File

@@ -0,0 +1,128 @@
import pick from 'lodash.pick';
let config = {
ACCOUNTS_API_BASE_URL: null,
ECOMMERCE_API_BASE_URL: null,
LMS_BASE_URL: null,
PASSWORD_RESET_URL: null,
};
const SOCIAL_PLATFORMS = [
{ id: 'twitter', key: 'social_link_twitter' },
{ id: 'facebook', key: 'social_link_facebook' },
{ id: 'linkedin', key: 'social_link_linkedin' },
];
let apiClient = null;
function validateConfiguration(newConfig) {
Object.keys(config).forEach((key) => {
if (newConfig[key] === undefined) {
throw new Error(`Service configuration error: ${key} is required.`);
}
});
}
export function configureApiService(newConfig, newApiClient) {
validateConfiguration(newConfig);
config = pick(newConfig, Object.keys(config));
apiClient = newApiClient;
}
function unpackFieldErrors(fieldErrors) {
const unpackedFieldErrors = fieldErrors;
if (fieldErrors.social_links) {
SOCIAL_PLATFORMS.forEach(({ key }) => {
unpackedFieldErrors[key] = fieldErrors.social_links;
});
}
return Object.entries(unpackedFieldErrors)
.reduce((acc, [k, v]) => {
acc[k] = v.user_message;
return acc;
}, {});
}
function unpackAccountResponseData(data) {
const unpackedData = data;
SOCIAL_PLATFORMS.forEach(({ id, key }) => {
const platformData = data.social_links.find(({ platform }) => platform === id);
unpackedData[key] = typeof platformData === 'object' ? platformData.social_link : '';
});
if (Array.isArray(data.language_proficiencies)) {
if (data.language_proficiencies.length) {
unpackedData.language_proficiencies = data.language_proficiencies[0].code;
} else {
unpackedData.language_proficiencies = '';
}
}
return unpackedData;
}
function packAccountCommitData(commitData) {
const packedData = commitData;
SOCIAL_PLATFORMS.forEach(({ id, key }) => {
if (commitData[key]) {
packedData.social_links = [{ platform: id, social_link: commitData[key] }];
}
delete packedData[key];
});
if (commitData.language_proficiencies) {
packedData.language_proficiencies = [{ code: commitData.language_proficiencies }];
}
return packedData;
}
function handleRequestError(error) {
if (error.response && error.response.data.field_errors) {
const apiError = Object.create(error);
apiError.fieldErrors = unpackFieldErrors(error.response.data.field_errors);
throw apiError;
}
throw error;
}
export async function getAccount(username) {
const { data } = await apiClient.get(`${config.ACCOUNTS_API_BASE_URL}/${username}`);
return unpackAccountResponseData(data);
}
export async function patchAccount(username, commitValues) {
const requestConfig = {
headers: { 'Content-Type': 'application/merge-patch+json' },
};
const { data } = await apiClient.patch(
`${config.ACCOUNTS_API_BASE_URL}/${username}`,
packAccountCommitData(commitValues),
requestConfig,
).catch(handleRequestError);
return unpackAccountResponseData(data);
}
export async function postResetPassword() {
const { data } = await apiClient
.post(config.PASSWORD_RESET_URL)
.catch(handleRequestError);
return data;
}
export async function getThirdPartyAuthProviders() {
const { data } = await apiClient.get(`${config.LMS_BASE_URL}/api/third_party_auth/v0/providers/user_status`)
.catch(handleRequestError);
return data.map(({ connect_url: connectUrl, disconnect_url: disconnectUrl, ...provider }) => ({
...provider,
connectUrl: `${config.LMS_BASE_URL}${connectUrl}`,
disconnectUrl: `${config.LMS_BASE_URL}${disconnectUrl}`,
}));
}

View File

@@ -1,25 +0,0 @@
import { AsyncActionType } from '../data/utils';
export const FETCH_SITE_LANGUAGES = new AsyncActionType('SITE_LANGUAGE', 'FETCH_SITE_LANGUAGES');
export const fetchSiteLanguages = () => ({
type: FETCH_SITE_LANGUAGES.BASE,
});
export const fetchSiteLanguagesBegin = () => ({
type: FETCH_SITE_LANGUAGES.BEGIN,
});
export const fetchSiteLanguagesSuccess = siteLanguageList => ({
type: FETCH_SITE_LANGUAGES.SUCCESS,
payload: { siteLanguageList },
});
export const fetchSiteLanguagesFailure = error => ({
type: FETCH_SITE_LANGUAGES.FAILURE,
payload: { error },
});
export const fetchSiteLanguagesReset = () => ({
type: FETCH_SITE_LANGUAGES.RESET,
});

View File

@@ -1,74 +0,0 @@
const siteLanguageList = [
{
code: 'en',
name: 'English',
released: true,
},
{
code: 'ar',
name: 'العربية',
released: true,
},
{
code: 'ca',
name: 'Català',
released: false,
},
{
code: 'es-419',
name: 'Español (Latinoamérica)',
released: true,
},
{
code: 'fr',
name: 'Français',
released: true,
},
{
code: 'he',
name: 'עברית',
released: false,
},
{
code: 'id',
name: 'Bahasa Indonesia',
released: false,
},
{
code: 'ko-kr',
name: '한국어 (대한민국)',
released: false,
},
{
code: 'pl',
name: 'Polski',
released: false,
},
{
code: 'pt-br',
name: 'Português (Brasil)',
released: false,
},
{
code: 'ru',
name: 'Русский',
released: false,
},
{
code: 'th',
name: 'ไทย',
released: false,
},
{
code: 'uk',
name: 'Українська',
released: false,
},
{
code: 'zh-cn',
name: '中文 (简体)',
released: true,
},
];
export default siteLanguageList;

View File

@@ -1,9 +0,0 @@
export { default as reducer } from './reducers';
export { default as saga } from './sagas';
export {
getSiteLanguageList,
patchPreferences,
postSetLang,
} from './service';
export { siteLanguageOptionsSelector, siteLanguageListSelector } from './selectors';
export { fetchSiteLanguages, FETCH_SITE_LANGUAGES } from './actions';

View File

@@ -1,48 +0,0 @@
import { FETCH_SITE_LANGUAGES } from './actions';
export const defaultState = {
loading: false,
loaded: false,
loadingError: null,
siteLanguageList: [],
};
const reducer = (state = defaultState, action = null) => {
if (action !== null) {
switch (action.type) {
case FETCH_SITE_LANGUAGES.BEGIN:
return {
...state,
loading: true,
loaded: false,
loadingError: null,
};
case FETCH_SITE_LANGUAGES.SUCCESS:
return {
...state,
siteLanguageList: action.payload.siteLanguageList,
loading: false,
loaded: true,
loadingError: null,
};
case FETCH_SITE_LANGUAGES.FAILURE:
return {
...state,
loading: false,
loaded: false,
loadingError: action.payload.error,
};
case FETCH_SITE_LANGUAGES.RESET:
return {
...state,
loading: false,
loaded: false,
loadingError: null,
};
default:
}
}
return state;
};
export default reducer;

View File

@@ -1,25 +0,0 @@
import { call, put, takeEvery } from 'redux-saga/effects';
import {
fetchSiteLanguagesBegin,
fetchSiteLanguagesSuccess,
fetchSiteLanguagesFailure,
FETCH_SITE_LANGUAGES,
} from './actions';
import { getSiteLanguageList } from './service';
import { handleFailure } from '../data/utils';
function* handleFetchSiteLanguages() {
try {
yield put(fetchSiteLanguagesBegin());
const siteLanguageList = yield call(getSiteLanguageList);
yield put(fetchSiteLanguagesSuccess(siteLanguageList));
} catch (e) {
yield call(handleFailure, e, fetchSiteLanguagesFailure);
}
}
export default function* saga() {
yield takeEvery(FETCH_SITE_LANGUAGES.BASE, handleFetchSiteLanguages);
}

View File

@@ -1,20 +0,0 @@
import { createSelector } from 'reselect';
import { getModuleState } from '../data/utils';
export const storePath = ['accountSettings', 'siteLanguage'];
const siteLanguageSelector = state => getModuleState(state, storePath);
export const siteLanguageListSelector = createSelector(
siteLanguageSelector,
siteLanguage => siteLanguage.siteLanguageList,
);
export const siteLanguageOptionsSelector = createSelector(
siteLanguageSelector,
siteLanguage =>
siteLanguage.siteLanguageList.map(({ code, name }) => ({
value: code,
label: name,
})),
);

View File

@@ -1,32 +0,0 @@
import { getConfig } from '@edx/frontend-platform';
import { getAuthenticatedHttpClient } from '@edx/frontend-platform/auth';
import siteLanguageList from './constants';
import { snakeCaseObject, convertKeyNames } from '../data/utils';
export async function getSiteLanguageList() {
return siteLanguageList;
}
export async function patchPreferences(username, params) {
let processedParams = snakeCaseObject(params);
processedParams = convertKeyNames(processedParams, {
pref_lang: 'pref-lang',
});
await getAuthenticatedHttpClient()
.patch(`${getConfig().LMS_BASE_URL}/api/user/v1/preferences/${username}`, processedParams, {
headers: { 'Content-Type': 'application/merge-patch+json' },
});
return params; // TODO: Once the server returns the updated preferences object, return that.
}
export async function postSetLang(code) {
const formData = new FormData();
formData.append('language', code);
await getAuthenticatedHttpClient()
.post(`${getConfig().LMS_BASE_URL}/i18n/setlang/`, formData, {
headers: { 'X-Requested-With': 'XMLHttpRequest' },
});
}

View File

@@ -1,144 +0,0 @@
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { FormattedMessage } from '@edx/frontend-platform/i18n';
import { Hyperlink, StatefulButton } from '@edx/paragon';
import Alert from '../Alert';
import { disconnectAuth } from './data/actions';
class ThirdPartyAuth extends Component {
onClickDisconnect = (e) => {
e.preventDefault();
const providerId = e.currentTarget.getAttribute('data-provider-id');
if (this.props.disconnectionStatuses[providerId] === 'pending') return;
const disconnectUrl = e.currentTarget.getAttribute('data-disconnect-url');
this.props.disconnectAuth(disconnectUrl, providerId);
}
renderUnconnectedProvider(url, name) {
return (
<React.Fragment>
<h6 aria-level="3">{name}</h6>
<Hyperlink destination={url} className="btn btn-outline-primary">
<FormattedMessage
id="account.settings.sso.link.account"
defaultMessage="Sign in with {name}"
description="An action link to link a connected third party account.m {name} will be Google, Facebook, etc."
values={{ name }}
/>
</Hyperlink>
</React.Fragment>
);
}
renderConnectedProvider(url, name, id) {
const hasError = this.props.errors[id];
return (
<React.Fragment>
<h6 aria-level="3">
{name}
<span className="small font-weight-normal text-muted ml-2">
<FormattedMessage
id="account.settings.sso.account.connected"
defaultMessage="Linked"
description="A badge to show that a third party account is linked"
/>
</span>
</h6>
{hasError ? (
<Alert className="alert-danger">
<FormattedMessage
id="account.settings.sso.account.disconnect.error"
defaultMessage="There was a problem disconnecting this account. Contact support if the problem persists."
description="A message displayed when an error occurred while disconnecting a third party account"
/>
</Alert>
) : null}
<StatefulButton
className="btn-link"
state={this.props.disconnectionStatuses[id]}
labels={{
default: (
<FormattedMessage
id="account.settings.sso.unlink.account"
defaultMessage="Unlink {name} account"
description="An action link to unlink a connected third party account"
values={{ name }}
/>
),
}}
onClick={this.onClickDisconnect}
disabledStates={[]}
data-disconnect-url={url}
data-provider-id={id}
/>
</React.Fragment>
);
}
renderProvider({
name, disconnectUrl, connectUrl, connected, id,
}) {
return (
<div className="form-group" key={id}>
{
connected ?
this.renderConnectedProvider(disconnectUrl, name, id) :
this.renderUnconnectedProvider(connectUrl, name)
}
</div>
);
}
renderNoProviders() {
return (
<FormattedMessage
id="account.settings.sso.no.providers"
defaultMessage="No accounts can be linked at this time."
description="Displayed when no third party accounts are available to link an edX account to"
/>
);
}
render() {
if (this.props.providers === undefined) return null;
if (this.props.providers.length === 0) {
return this.renderNoProviders();
}
return this.props.providers.map(this.renderProvider, this);
}
}
ThirdPartyAuth.propTypes = {
providers: PropTypes.arrayOf(PropTypes.shape({
name: PropTypes.string,
disconnectUrl: PropTypes.string,
connectUrl: PropTypes.string,
connected: PropTypes.bool,
id: PropTypes.string,
})),
disconnectionStatuses: PropTypes.objectOf(PropTypes.oneOf([null, 'pending', 'complete', 'error'])),
errors: PropTypes.objectOf(PropTypes.bool),
disconnectAuth: PropTypes.func.isRequired,
};
ThirdPartyAuth.defaultProps = {
providers: undefined,
disconnectionStatuses: {},
errors: {},
};
const mapStateToProps = state => state.accountSettings.thirdPartyAuth;
export default connect(
mapStateToProps,
{
disconnectAuth,
},
)(ThirdPartyAuth);

View File

@@ -1,20 +0,0 @@
import { AsyncActionType } from '../../data/utils';
export const DISCONNECT_AUTH = new AsyncActionType('ACCOUNT_SETTINGS', 'DISCONNECT_AUTH');
export const disconnectAuth = (url, providerId) => ({
type: DISCONNECT_AUTH.BASE, payload: { url, providerId },
});
export const disconnectAuthBegin = providerId => ({
type: DISCONNECT_AUTH.BEGIN, payload: { providerId },
});
export const disconnectAuthSuccess = (providerId, thirdPartyAuthProviders) => ({
type: DISCONNECT_AUTH.SUCCESS,
payload: { providerId, thirdPartyAuthProviders },
});
export const disconnectAuthFailure = providerId => ({
type: DISCONNECT_AUTH.FAILURE, payload: { providerId },
});
export const disconnectAuthReset = providerId => ({
type: DISCONNECT_AUTH.RESET, payload: { providerId },
});

View File

@@ -1,59 +0,0 @@
import { DISCONNECT_AUTH } from './actions';
export const defaultState = {
providers: [],
disconnectionStatuses: {},
errors: {},
};
const reducer = (state = defaultState, action = null) => {
if (action !== null) {
switch (action.type) {
case DISCONNECT_AUTH.BEGIN:
return {
...state,
disconnectionStatuses: {
...state.disconnectionStatuses,
[action.payload.providerId]: 'pending',
},
};
case DISCONNECT_AUTH.SUCCESS:
return {
...state,
disconnectionStatuses: {
...state.disconnectionStatuses,
[action.payload.providerId]: 'complete',
},
providers: action.payload.thirdPartyAuthProviders,
};
case DISCONNECT_AUTH.FAILURE:
return {
...state,
disconnectionStatuses: {
...state.disconnectionStatuses,
[action.payload.providerId]: 'error',
},
errors: {
...state.errors,
[action.payload.providerId]: true,
},
};
case DISCONNECT_AUTH.RESET:
return {
...state,
disconnectionStatuses: {
...state.disconnectionStatuses,
[action.payload.providerId]: null,
},
errors: {
...state.errors,
[action.payload.providerId]: null,
},
};
default:
}
}
return state;
};
export default reducer;

View File

@@ -1,33 +0,0 @@
import { call, put, takeEvery } from 'redux-saga/effects';
import { logError } from '@edx/frontend-platform/logging';
import {
disconnectAuthReset,
disconnectAuthBegin,
disconnectAuthSuccess,
disconnectAuthFailure,
DISCONNECT_AUTH,
} from './actions';
import {
getThirdPartyAuthProviders,
postDisconnectAuth,
} from './service';
function* handleDisconnectAuth(action) {
const { providerId } = action.payload;
try {
yield put(disconnectAuthReset(providerId));
yield put(disconnectAuthBegin(providerId));
yield call(postDisconnectAuth, action.payload.url);
const thirdPartyAuthProviders = yield call(getThirdPartyAuthProviders);
yield put(disconnectAuthSuccess(providerId, thirdPartyAuthProviders));
} catch (e) {
logError(e);
yield put(disconnectAuthFailure(providerId));
}
}
export default function* saga() {
yield takeEvery(DISCONNECT_AUTH.BASE, handleDisconnectAuth);
}

View File

@@ -1,23 +0,0 @@
import { getConfig } from '@edx/frontend-platform';
import { getAuthenticatedHttpClient } from '@edx/frontend-platform/auth';
import { handleRequestError } from '../../data/utils';
export async function getThirdPartyAuthProviders() {
const { data } = await getAuthenticatedHttpClient()
.get(`${getConfig().LMS_BASE_URL}/api/third_party_auth/v0/providers/user_status`)
.catch(handleRequestError);
return data.map(({ connect_url: connectUrl, disconnect_url: disconnectUrl, ...provider }) => ({
...provider,
connectUrl: `${getConfig().LMS_BASE_URL}${connectUrl}`,
disconnectUrl: `${getConfig().LMS_BASE_URL}${disconnectUrl}`,
}));
}
export async function postDisconnectAuth(url) {
const { data } = await getAuthenticatedHttpClient()
.post(url)
.catch(handleRequestError);
return data;
}

View File

@@ -1,5 +0,0 @@
export { default } from './ThirdPartyAuth';
export { default as reducer } from './data/reducers';
export { default as saga } from './data/sagas';
export { getThirdPartyAuthProviders, postDisconnectAuth } from './data/service';
export { DISCONNECT_AUTH } from './data/actions';

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

BIN
src/assets/edx-footer.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

BIN
src/assets/edx-sm.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 34 KiB

View File

Before

Width:  |  Height:  |  Size: 5.0 KiB

After

Width:  |  Height:  |  Size: 5.0 KiB

Some files were not shown because too many files have changed in this diff Show More