From 40ab9bc8de7c2650c1e4b2c7d50136f255747019 Mon Sep 17 00:00:00 2001 From: rbisson <remi.bisson@inrae.fr> Date: Mon, 22 Apr 2024 17:29:19 +0200 Subject: [PATCH 01/19] [package.json]: added eslint and prettier along with configs, and husky pre-commit hook --- package.json | 59 ++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 53 insertions(+), 6 deletions(-) diff --git a/package.json b/package.json index a4922e2..b3e53d7 100644 --- a/package.json +++ b/package.json @@ -4,15 +4,15 @@ "private": true, "homepage": ".", "dependencies": { - "moment": "^2.27.0", - "@elastic/eui": "^27.4.0", "@elastic/datemath": "^5.0.3", + "@elastic/eui": "^27.4.0", "@in-sylva/json-view": "git+ssh://git@forgemia.inra.fr:in-sylva-development/json-view.git", "@in-sylva/react-use-storage": "git+ssh://git@forgemia.inra.fr:in-sylva-development/react-use-storage.git", "@material-ui/core": "^4.11.0", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "^4.0.0-alpha.48", "@material-ui/styles": "^4.10.0", + "moment": "^2.27.0", "mui-datatables": "^3.4.0", "papaparse": "5.3.0", "react": "^16.13.1", @@ -27,10 +27,10 @@ "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", - "eject": "react-scripts eject" - }, - "eslintConfig": { - "extends": "react-app" + "eject": "react-scripts eject", + "lint": "eslint ./src", + "lint:fix": "eslint --fix ./src", + "format": "prettier --write \"./src/**/*.+(js|jsx|json|css|md)\"" }, "browserslist": { "production": [ @@ -45,6 +45,53 @@ ] }, "devDependencies": { + "eslint-config-prettier": "^9.1.0", + "eslint-plugin-prettier": "^5.1.3", + "lint-staged": "14.0.1", + "husky": "8.0.3", + "prettier": "^3.2.5", "jscs": "^3.0.7" + }, + "husky": { + "hooks": { + "pre-commit": "npm run lint:fix && npm run format" + } + }, + "eslintConfig": { + "env": { + "node": true, + "browser": true, + "es6": true + }, + "extends": [ + "plugin:react/recommended", + "plugin:prettier/recommended", + "airbnb" + ], + "parserOptions": { + "ecmaFeatures": { + "jsx": true + } + }, + "plugins": [ + "react" + ] + }, + "lint-staged": { + "*.+(js|jsx)": [ + "eslint --fix", + "git add" + ], + "*.+(json|css|md)": [ + "prettier --write", + "git add" + ] + }, + "prettier": { + "printWidth": 90, + "singleQuote": true, + "arrowParens": "always", + "trailingComma": "es5", + "tabWidth": 2 } } -- GitLab From b7e37b321fa99c08ccfa2c20a8d66d5803a5bcaa Mon Sep 17 00:00:00 2001 From: rbisson <remi.bisson@inrae.fr> Date: Mon, 22 Apr 2024 17:31:47 +0200 Subject: [PATCH 02/19] [README.md]: added documentation about new scripts and packages --- README.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/README.md b/README.md index bee13af..e9170ea 100644 --- a/README.md +++ b/README.md @@ -1 +1,27 @@ ## IN-SYLVA PORTAL + +## Available Scripts + +In the project directory, you can run: + +### `npm run start` + +Runs the app in the development mode.<br> +Open [http://localhost:3000](http://localhost:3000) to view it in the browser. + +The page will reload if you make edits.<br> +You will also see any lint errors in the console. + +### `npm run lint` + +Runs `eslint ./src` to analyze and find problems in source code. + +[ESLint](https://eslint.org/docs/latest/) package is configured in `package.json`, under `eslintConfig`. + +### `npm run lint:fix` + +Runs `eslint --fix ./src` to analyze and find problems in source code and fix them automatically if possible. + +### `npm run format` + +Format code according to [Prettier](https://prettier.io/docs/en/) config, found in `package.json`, under `prettier`. -- GitLab From 5cd1412f9cc46e97dac3d04952978742108936f9 Mon Sep 17 00:00:00 2001 From: rbisson <remi.bisson@inrae.fr> Date: Mon, 22 Apr 2024 17:47:39 +0200 Subject: [PATCH 03/19] [src]: ran format command to apply prettier config --- src/actions/group.js | 242 ++-- src/actions/index.js | 17 +- src/actions/policy.js | 465 +++---- src/actions/source.js | 517 ++++--- src/actions/user.js | 525 ++++---- src/components/App.js | 22 +- src/components/Common/Common.js | 111 +- src/components/Common/package.json | 10 +- src/components/Header/Header.js | 80 +- src/components/Header/HeaderView.js | 276 ++-- src/components/Header/styles.js | 100 +- src/components/Layout/Layout.js | 41 +- src/components/Layout/styles.js | 14 +- src/components/Notification/Notification.js | 40 +- src/components/Notification/styles.js | 32 +- src/components/PageTitle/PageTitle.js | 8 +- src/components/PageTitle/styles.js | 12 +- src/components/Sidebar/Sidebar.js | 146 +- src/components/Sidebar/SidebarView.js | 71 +- src/components/Sidebar/components/Dot.js | 19 +- .../components/SidebarLink/SidebarLink.js | 25 +- .../Sidebar/components/SidebarLink/styles.js | 26 +- src/components/Sidebar/styles.js | 26 +- src/components/UserAvatar/UserAvatar.js | 16 +- src/components/UserAvatar/styles.js | 12 +- src/components/Widget/Widget.js | 16 +- src/components/Widget/WidgetView.js | 50 +- src/components/Widget/styles.js | 24 +- src/components/Wrappers/Wrappers.js | 49 +- src/components/Wrappers/package.json | 1 - src/context/InSylvaGatekeeperClient.js | 716 +++++----- src/context/InSylvaSourceManager.js | 272 ++-- src/context/KeycloakClient.js | 161 ++- src/context/LayoutContext.js | 10 +- src/context/UserContext.js | 66 +- src/index.js | 38 +- src/pages/charts/Charts.js | 46 +- src/pages/charts/components/ApexHeatmap.js | 29 +- src/pages/charts/components/ApexLineChart.js | 37 +- src/pages/dashboard/Dashboard.js | 140 +- .../dashboard/components/BigStat/BigStat.js | 41 +- .../dashboard/components/BigStat/styles.js | 38 +- src/pages/dashboard/components/Table/Table.js | 22 +- src/pages/dashboard/mock.js | 176 ++- src/pages/dashboard/styles.js | 84 +- src/pages/error/Error.js | 12 +- src/pages/error/styles.js | 38 +- src/pages/fields/Fields.js | 674 +++++----- src/pages/fields/package.json | 10 +- src/pages/fields/styles.js | 182 +-- src/pages/group/Group.js | 699 +++++----- src/pages/group/package.json | 10 +- src/pages/group/styles.js | 86 +- src/pages/policy/Policy.js | 952 +++++++------ src/pages/policy/package.json | 10 +- src/pages/policy/styles.js | 86 +- src/pages/requests/Requests.js | 387 +++--- src/pages/requests/package.json | 10 +- src/pages/requests/styles.js | 56 +- src/pages/roles/Role.js | 650 ++++----- src/pages/roles/package.json | 10 +- src/pages/roles/styles.js | 86 +- src/pages/sources/Sources.js | 1187 +++++++++-------- src/pages/sources/package.json | 10 +- src/pages/sources/styles.js | 182 +-- src/pages/user/User.js | 535 ++++---- src/pages/user/package.json | 10 +- src/pages/user/styles.js | 56 +- src/store/CustomConnector.js | 89 +- src/store/asyncEnhancer.js | 22 +- src/store/index.js | 25 +- src/store/useStore.js | 93 +- src/themes/default.js | 97 +- src/themes/index.js | 16 +- src/utils.js | 58 +- 75 files changed, 5854 insertions(+), 5353 deletions(-) diff --git a/src/actions/group.js b/src/actions/group.js index 5889061..9aaf645 100644 --- a/src/actions/group.js +++ b/src/actions/group.js @@ -1,149 +1,149 @@ import { InSylvaGatekeeperClient } from '../context/InSylvaGatekeeperClient'; -import {getGatekeeperBaseUrl} from "../utils"; +import { getGatekeeperBaseUrl } from '../utils'; const igClient = new InSylvaGatekeeperClient(); igClient.baseUrl = getGatekeeperBaseUrl(); export const createGroup = async (store, name, description, kcId, request = igClient) => { - try { - store.setState({ isLoading: true }); - request.token = sessionStorage.getItem("access_token") - - const group = await request.createGroup({ name, description, kcId }) - if (group) { - const status = "SUCCESS" - store.setState({ status, isLoading: false }) - return group - } - } catch (error) { - const isError404 = error.response && error.response.status === 404 - const status = isError404 ? "NOT_FOUND" : "ERROR" - store.setState({ status, isLoading: false }) + try { + store.setState({ isLoading: true }); + request.token = sessionStorage.getItem('access_token'); + + const group = await request.createGroup({ name, description, kcId }); + if (group) { + const status = 'SUCCESS'; + store.setState({ status, isLoading: false }); + return group; } -} + } catch (error) { + const isError404 = error.response && error.response.status === 404; + const status = isError404 ? 'NOT_FOUND' : 'ERROR'; + store.setState({ status, isLoading: false }); + } +}; export const getGroups = async (store, request = igClient) => { - try { - store.setState({ isLoading: true }); - request.token = sessionStorage.getItem("access_token") - - const groups = await request.getGroups() - if (groups) { - const status = "SUCCESS" - store.setState({ status, isLoading: false }) - return groups - } - } catch (error) { - const isError404 = error.response && error.response.status === 404 - const status = isError404 ? "NOT_FOUND" : "ERROR" - store.setState({ status, isLoading: false }) + try { + store.setState({ isLoading: true }); + request.token = sessionStorage.getItem('access_token'); + + const groups = await request.getGroups(); + if (groups) { + const status = 'SUCCESS'; + store.setState({ status, isLoading: false }); + return groups; } -} + } catch (error) { + const isError404 = error.response && error.response.status === 404; + const status = isError404 ? 'NOT_FOUND' : 'ERROR'; + store.setState({ status, isLoading: false }); + } +}; export const createGroupUser = async (store, groupId, kcId, request = igClient) => { - try { - store.setState({ isLoading: true }); - request.token = sessionStorage.getItem("access_token") - - const groupUser = await request.createGroupUser({ groupId, kcId }) - if (groupUser) { - const status = "SUCCESS" - store.setState({ status, isLoading: false }) - return groupUser - } - } catch (error) { - const isError404 = error.response && error.response.status === 404 - const status = isError404 ? "NOT_FOUND" : "ERROR" - store.setState({ status, isLoading: false }) + try { + store.setState({ isLoading: true }); + request.token = sessionStorage.getItem('access_token'); + + const groupUser = await request.createGroupUser({ groupId, kcId }); + if (groupUser) { + const status = 'SUCCESS'; + store.setState({ status, isLoading: false }); + return groupUser; } -} + } catch (error) { + const isError404 = error.response && error.response.status === 404; + const status = isError404 ? 'NOT_FOUND' : 'ERROR'; + store.setState({ status, isLoading: false }); + } +}; export const getGroupUsers = async (store, groupId, request = igClient) => { - try { - store.setState({ isLoading: true }); - request.token = sessionStorage.getItem("access_token") - - const groupUser = await request.getGroupUsers({ groupId }) - if (groupUser) { - const status = "SUCCESS" - store.setState({ status, isLoading: false }) - return groupUser - } - } catch (error) { - const isError404 = error.response && error.response.status === 404 - const status = isError404 ? "NOT_FOUND" : "ERROR" - store.setState({ status, isLoading: false }) + try { + store.setState({ isLoading: true }); + request.token = sessionStorage.getItem('access_token'); + + const groupUser = await request.getGroupUsers({ groupId }); + if (groupUser) { + const status = 'SUCCESS'; + store.setState({ status, isLoading: false }); + return groupUser; } -} + } catch (error) { + const isError404 = error.response && error.response.status === 404; + const status = isError404 ? 'NOT_FOUND' : 'ERROR'; + store.setState({ status, isLoading: false }); + } +}; export const createGroupPolicy = async (store, groupId, policyId, request = igClient) => { - try { - store.setState({ isLoading: true }); - request.token = sessionStorage.getItem("access_token") - - const groupPolicy = await request.createGroupPolicy({ groupId, policyId }) - if (groupPolicy) { - const status = "SUCCESS" - store.setState({ status, isLoading: false }) - return groupPolicy - } - } catch (error) { - const isError404 = error.response && error.response.status === 404 - const status = isError404 ? "NOT_FOUND" : "ERROR" - store.setState({ status, isLoading: false }) + try { + store.setState({ isLoading: true }); + request.token = sessionStorage.getItem('access_token'); + + const groupPolicy = await request.createGroupPolicy({ groupId, policyId }); + if (groupPolicy) { + const status = 'SUCCESS'; + store.setState({ status, isLoading: false }); + return groupPolicy; } -} + } catch (error) { + const isError404 = error.response && error.response.status === 404; + const status = isError404 ? 'NOT_FOUND' : 'ERROR'; + store.setState({ status, isLoading: false }); + } +}; export const deleteGroup = async (store, groupId, request = igClient) => { - try { - store.setState({ isLoading: true }); - request.token = sessionStorage.getItem("access_token") - - const groupUser = await request.deleteGroup({ id: groupId }) - if (groupUser) { - const status = "SUCCESS" - store.setState({ status, isLoading: false }) - return groupUser - } - } catch (error) { - const isError404 = error.response && error.response.status === 404 - const status = isError404 ? "NOT_FOUND" : "ERROR" - store.setState({ status, isLoading: false }) + try { + store.setState({ isLoading: true }); + request.token = sessionStorage.getItem('access_token'); + + const groupUser = await request.deleteGroup({ id: groupId }); + if (groupUser) { + const status = 'SUCCESS'; + store.setState({ status, isLoading: false }); + return groupUser; } -} + } catch (error) { + const isError404 = error.response && error.response.status === 404; + const status = isError404 ? 'NOT_FOUND' : 'ERROR'; + store.setState({ status, isLoading: false }); + } +}; export const deleteGroupPolicy = async (store, id, request = igClient) => { - try { - store.setState({ isLoading: true }); - request.token = sessionStorage.getItem("access_token") - - const groupPolicy = await request.deleteGroupPolicy({ id }) - if (groupPolicy) { - const status = "SUCCESS" - store.setState({ status, isLoading: false }) - return groupPolicy - } - } catch (error) { - const isError404 = error.response && error.response.status === 404 - const status = isError404 ? "NOT_FOUND" : "ERROR" - store.setState({ status, isLoading: false }) + try { + store.setState({ isLoading: true }); + request.token = sessionStorage.getItem('access_token'); + + const groupPolicy = await request.deleteGroupPolicy({ id }); + if (groupPolicy) { + const status = 'SUCCESS'; + store.setState({ status, isLoading: false }); + return groupPolicy; } -} + } catch (error) { + const isError404 = error.response && error.response.status === 404; + const status = isError404 ? 'NOT_FOUND' : 'ERROR'; + store.setState({ status, isLoading: false }); + } +}; export const deleteGroupUser = async (store, groupId, userId, request = igClient) => { - try { - store.setState({ isLoading: true }); - request.token = sessionStorage.getItem("access_token") - - const groupPolicy = await request.deleteGroupUser({ groupId, userId }) - if (groupPolicy) { - const status = "SUCCESS" - store.setState({ status, isLoading: false }) - return groupPolicy - } - } catch (error) { - const isError404 = error.response && error.response.status === 404 - const status = isError404 ? "NOT_FOUND" : "ERROR" - store.setState({ status, isLoading: false }) + try { + store.setState({ isLoading: true }); + request.token = sessionStorage.getItem('access_token'); + + const groupPolicy = await request.deleteGroupUser({ groupId, userId }); + if (groupPolicy) { + const status = 'SUCCESS'; + store.setState({ status, isLoading: false }); + return groupPolicy; } -} + } catch (error) { + const isError404 = error.response && error.response.status === 404; + const status = isError404 ? 'NOT_FOUND' : 'ERROR'; + store.setState({ status, isLoading: false }); + } +}; diff --git a/src/actions/index.js b/src/actions/index.js index c408628..65fb44f 100644 --- a/src/actions/index.js +++ b/src/actions/index.js @@ -1,9 +1,8 @@ -import * as user from './user' -import * as source from './source' -import * as policy from './policy' -import * as group from './group' -export { user } -export { source } -export { policy } -export { group } - +import * as user from './user'; +import * as source from './source'; +import * as policy from './policy'; +import * as group from './group'; +export { user }; +export { source }; +export { policy }; +export { group }; diff --git a/src/actions/policy.js b/src/actions/policy.js index 63c5798..9e0d5d1 100644 --- a/src/actions/policy.js +++ b/src/actions/policy.js @@ -1,264 +1,275 @@ import { InSylvaGatekeeperClient } from '../context/InSylvaGatekeeperClient'; -import {getGatekeeperBaseUrl} from "../utils"; +import { getGatekeeperBaseUrl } from '../utils'; const igClient = new InSylvaGatekeeperClient(); igClient.baseUrl = getGatekeeperBaseUrl(); export const createPolicy = async (store, name, kcId, request = igClient) => { - try { - store.setState({ isLoading: true }) - request.token = sessionStorage.getItem("access_token") - - const policy = await request.createPolicy({ name, kcId }) - - if (policy) { - const status = "SUCCESS" - store.setState({ status, isLoading: false }) - return policy - } - } catch (error) { - const isError404 = error.response && error.response.status === 404 - const status = isError404 ? "NOT_FOUND" : "ERROR" - store.setState({ status, isLoading: false }) + try { + store.setState({ isLoading: true }); + request.token = sessionStorage.getItem('access_token'); + + const policy = await request.createPolicy({ name, kcId }); + + if (policy) { + const status = 'SUCCESS'; + store.setState({ status, isLoading: false }); + return policy; } -} - -export const createPolicyField = async (store, policyId, stdFieldId, request = igClient) => { - try { - store.setState({ isLoading: true }) - request.token = sessionStorage.getItem("access_token") - - const policyField = await request.createPolicyField({ policyId, stdFieldId }) - - if (policyField) { - const status = "SUCCESS" - store.setState({ status, isLoading: false }) - return policyField - } - } catch (error) { - const isError404 = error.response && error.response.status === 404 - const status = isError404 ? "NOT_FOUND" : "ERROR" - store.setState({ status, isLoading: false }) + } catch (error) { + const isError404 = error.response && error.response.status === 404; + const status = isError404 ? 'NOT_FOUND' : 'ERROR'; + store.setState({ status, isLoading: false }); + } +}; + +export const createPolicyField = async ( + store, + policyId, + stdFieldId, + request = igClient +) => { + try { + store.setState({ isLoading: true }); + request.token = sessionStorage.getItem('access_token'); + + const policyField = await request.createPolicyField({ policyId, stdFieldId }); + + if (policyField) { + const status = 'SUCCESS'; + store.setState({ status, isLoading: false }); + return policyField; } -} - -export const updatePolicy = async (store, id, name, sourceId, isDeafault, request = igClient) => { - try { - store.setState({ isLoading: true }) - request.token = sessionStorage.getItem("access_token") + } catch (error) { + const isError404 = error.response && error.response.status === 404; + const status = isError404 ? 'NOT_FOUND' : 'ERROR'; + store.setState({ status, isLoading: false }); + } +}; + +export const updatePolicy = async ( + store, + id, + name, + sourceId, + isDeafault, + request = igClient +) => { + try { + store.setState({ isLoading: true }); + request.token = sessionStorage.getItem('access_token'); + + const uPolicy = await request.updatePolicy({ id, name, sourceId, isDeafault }); + + if (uPolicy) { + const status = 'SUCCESS'; + store.setState({ status, isLoading: false }); + return uPolicy; + } + } catch (error) { + const isError404 = error.response && error.response.status === 404; + const status = isError404 ? 'NOT_FOUND' : 'ERROR'; + store.setState({ status, isLoading: false }); + } +}; + +export const updatePolicyField = async ( + store, + id, + policyId, + stdFieldId, + request = igClient +) => { + try { + store.setState({ isLoading: true }); + request.token = sessionStorage.getItem('access_token'); + + const policyField = await request.updatePolicyField({ id, policyId, stdFieldId }); + + if (policyField) { + const status = 'SUCCESS'; + store.setState({ status, isLoading: false }); + return policyField; + } + } catch (error) { + const isError404 = error.response && error.response.status === 404; + const status = isError404 ? 'NOT_FOUND' : 'ERROR'; + store.setState({ status, isLoading: false }); + } +}; - const uPolicy = await request.updatePolicy({ id, name, sourceId, isDeafault }) +export const deletePolicyField = async (store, id, request = igClient) => { + try { + store.setState({ isLoading: true }); + request.token = sessionStorage.getItem('access_token'); - if (uPolicy) { - const status = "SUCCESS" - store.setState({ status, isLoading: false }) - return uPolicy - } + const result = await request.deletePolicyField({ id }); - } catch (error) { - const isError404 = error.response && error.response.status === 404 - const status = isError404 ? "NOT_FOUND" : "ERROR" - store.setState({ status, isLoading: false }) + if (result) { + const status = 'SUCCESS'; + store.setState({ status, isLoading: false }); + return result; } -} - -export const updatePolicyField = async (store, id, policyId, stdFieldId, request = igClient) => { - try { - store.setState({ isLoading: true }) - request.token = sessionStorage.getItem("access_token") + } catch (error) { + const isError404 = error.response && error.response.status === 404; + const status = isError404 ? 'NOT_FOUND' : 'ERROR'; + store.setState({ status, isLoading: false }); + } +}; - const policyField = await request.updatePolicyField({ id, policyId, stdFieldId }) - - if (policyField) { - const status = "SUCCESS" - store.setState({ status, isLoading: false }) - return policyField - } +export const deletePolicy = async (store, id, request = igClient) => { + try { + store.setState({ isLoading: true }); + request.token = sessionStorage.getItem('access_token'); - } catch (error) { - const isError404 = error.response && error.response.status === 404 - const status = isError404 ? "NOT_FOUND" : "ERROR" - store.setState({ status, isLoading: false }) - } -} + const result = await request.deletePolicy({ id }); -export const deletePolicyField = async (store, id, request = igClient) => { - try { - store.setState({ isLoading: true }) - request.token = sessionStorage.getItem("access_token") - - const result = await request.deletePolicyField({ id }) - - if (result) { - const status = "SUCCESS" - store.setState({ status, isLoading: false }) - return result - } - - } catch (error) { - const isError404 = error.response && error.response.status === 404 - const status = isError404 ? "NOT_FOUND" : "ERROR" - store.setState({ status, isLoading: false }) + if (result) { + const status = 'SUCCESS'; + store.setState({ status, isLoading: false }); + return result; } -} + } catch (error) { + const isError404 = error.response && error.response.status === 404; + const status = isError404 ? 'NOT_FOUND' : 'ERROR'; + store.setState({ status, isLoading: false }); + } +}; -export const deletePolicy = async (store, id, request = igClient) => { - try { - store.setState({ isLoading: true }) - request.token = sessionStorage.getItem("access_token") - - const result = await request.deletePolicy({ id }) - - if (result) { - const status = "SUCCESS" - store.setState({ status, isLoading: false }) - return result - } - - } catch (error) { - const isError404 = error.response && error.response.status === 404 - const status = isError404 ? "NOT_FOUND" : "ERROR" - store.setState({ status, isLoading: false }) - } -} +export const getPolicies = async (store, request = igClient) => { + try { + store.setState({ isLoading: true }); + request.token = sessionStorage.getItem('access_token'); + const policies = await request.getPolicies({}); -export const getPolicies = async (store, request = igClient) => { - try { - store.setState({ isLoading: true }) - request.token = sessionStorage.getItem("access_token") - - const policies = await request.getPolicies({}) - - if (policies) { - const status = "SUCCESS" - store.setState({ status, isLoading: false }) - return policies - } - - } catch (error) { - const isError404 = error.response && error.response.status === 404 - const status = isError404 ? "NOT_FOUND" : "ERROR" - store.setState({ status, isLoading: false }) + if (policies) { + const status = 'SUCCESS'; + store.setState({ status, isLoading: false }); + return policies; } -} + } catch (error) { + const isError404 = error.response && error.response.status === 404; + const status = isError404 ? 'NOT_FOUND' : 'ERROR'; + store.setState({ status, isLoading: false }); + } +}; export const getPoliciesByUser = async (store, kc_id, request = igClient) => { - try { - store.setState({ isLoading: true }) - request.token = sessionStorage.getItem("access_token") - - const result = await request.getPoliciesByUser(kc_id) - - if (result) { - const status = "SUCCESS" - store.setState({ status, isLoading: false }) - return result - } - - } catch (error) { - const isError404 = error.response && error.response.status === 404 - const status = isError404 ? "NOT_FOUND" : "ERROR" - store.setState({ status, isLoading: false }) + try { + store.setState({ isLoading: true }); + request.token = sessionStorage.getItem('access_token'); + + const result = await request.getPoliciesByUser(kc_id); + + if (result) { + const status = 'SUCCESS'; + store.setState({ status, isLoading: false }); + return result; } -} + } catch (error) { + const isError404 = error.response && error.response.status === 404; + const status = isError404 ? 'NOT_FOUND' : 'ERROR'; + store.setState({ status, isLoading: false }); + } +}; export const getPoliciesWithSourcesByUser = async (store, kc_id, request = igClient) => { - try { - store.setState({ isLoading: true }) - request.token = sessionStorage.getItem("access_token") - - const result = await request.getPoliciesWithSourcesByUser(kc_id) - - if (result) { - const status = "SUCCESS" - store.setState({ status, isLoading: false }) - return result - } - - } catch (error) { - const isError404 = error.response && error.response.status === 404 - const status = isError404 ? "NOT_FOUND" : "ERROR" - store.setState({ status, isLoading: false }) + try { + store.setState({ isLoading: true }); + request.token = sessionStorage.getItem('access_token'); + + const result = await request.getPoliciesWithSourcesByUser(kc_id); + + if (result) { + const status = 'SUCCESS'; + store.setState({ status, isLoading: false }); + return result; } -} + } catch (error) { + const isError404 = error.response && error.response.status === 404; + const status = isError404 ? 'NOT_FOUND' : 'ERROR'; + store.setState({ status, isLoading: false }); + } +}; export const getAssignedPolicies = async (store, policyId, request = igClient) => { - try { - store.setState({ isLoading: true }) - request.token = sessionStorage.getItem("access_token") - - const assignedPolicies = await request.getAssignedPolicies({ policyId }) - - if (assignedPolicies) { - const status = "SUCCESS" - store.setState({ status, isLoading: false }) - return assignedPolicies - } - - } catch (error) { - const isError404 = error.response && error.response.status === 404 - const status = isError404 ? "NOT_FOUND" : "ERROR" - store.setState({ status, isLoading: false }) + try { + store.setState({ isLoading: true }); + request.token = sessionStorage.getItem('access_token'); + + const assignedPolicies = await request.getAssignedPolicies({ policyId }); + + if (assignedPolicies) { + const status = 'SUCCESS'; + store.setState({ status, isLoading: false }); + return assignedPolicies; } -} + } catch (error) { + const isError404 = error.response && error.response.status === 404; + const status = isError404 ? 'NOT_FOUND' : 'ERROR'; + store.setState({ status, isLoading: false }); + } +}; export const getPoliciesWithSources = async (store, request = igClient) => { - try { - store.setState({ isLoading: true }) - request.token = sessionStorage.getItem("access_token") - - const policiesWithSources = await request.getPoliciesWithSources() - - if (policiesWithSources) { - const status = "SUCCESS" - store.setState({ status, isLoading: false }) - return policiesWithSources - } - - } catch (error) { - const isError404 = error.response && error.response.status === 404 - const status = isError404 ? "NOT_FOUND" : "ERROR" - store.setState({ status, isLoading: false }) - } -} + try { + store.setState({ isLoading: true }); + request.token = sessionStorage.getItem('access_token'); -export const getGroupDetailsByPolicy = async (store, policyId, request = igClient) => { - try { - store.setState({ isLoading: true }) - request.token = sessionStorage.getItem("access_token") - - const groupDetailsByPolicy = await request.getGroupDetailsByPolicy({ policyId }) - - if (groupDetailsByPolicy) { - const status = "SUCCESS" - store.setState({ status, isLoading: false }) - return groupDetailsByPolicy - } - - } catch (error) { - const isError404 = error.response && error.response.status === 404 - const status = isError404 ? "NOT_FOUND" : "ERROR" - store.setState({ status, isLoading: false }) - } -} + const policiesWithSources = await request.getPoliciesWithSources(); -export const createPolicySource = async (store, policyId, sourceId, request = igClient) => { - try { - store.setState({ isLoading: true }) - request.token = sessionStorage.getItem("access_token") + if (policiesWithSources) { + const status = 'SUCCESS'; + store.setState({ status, isLoading: false }); + return policiesWithSources; + } + } catch (error) { + const isError404 = error.response && error.response.status === 404; + const status = isError404 ? 'NOT_FOUND' : 'ERROR'; + store.setState({ status, isLoading: false }); + } +}; - const policySource = await request.createPolicySource({ policyId, sourceId }) +export const getGroupDetailsByPolicy = async (store, policyId, request = igClient) => { + try { + store.setState({ isLoading: true }); + request.token = sessionStorage.getItem('access_token'); - if (policySource) { - const status = "SUCCESS" - store.setState({ status, isLoading: false }) - return policySource - } + const groupDetailsByPolicy = await request.getGroupDetailsByPolicy({ policyId }); - } catch (error) { - const isError404 = error.response && error.response.status === 404 - const status = isError404 ? "NOT_FOUND" : "ERROR" - store.setState({ status, isLoading: false }) + if (groupDetailsByPolicy) { + const status = 'SUCCESS'; + store.setState({ status, isLoading: false }); + return groupDetailsByPolicy; + } + } catch (error) { + const isError404 = error.response && error.response.status === 404; + const status = isError404 ? 'NOT_FOUND' : 'ERROR'; + store.setState({ status, isLoading: false }); + } +}; + +export const createPolicySource = async ( + store, + policyId, + sourceId, + request = igClient +) => { + try { + store.setState({ isLoading: true }); + request.token = sessionStorage.getItem('access_token'); + + const policySource = await request.createPolicySource({ policyId, sourceId }); + + if (policySource) { + const status = 'SUCCESS'; + store.setState({ status, isLoading: false }); + return policySource; } -} + } catch (error) { + const isError404 = error.response && error.response.status === 404; + const status = isError404 ? 'NOT_FOUND' : 'ERROR'; + store.setState({ status, isLoading: false }); + } +}; diff --git a/src/actions/source.js b/src/actions/source.js index 669f0d4..f2e1b87 100644 --- a/src/actions/source.js +++ b/src/actions/source.js @@ -1,249 +1,336 @@ -import { InSylvaSourceManager } from '../context/InSylvaSourceManager' +import { InSylvaSourceManager } from '../context/InSylvaSourceManager'; const smClient = new InSylvaSourceManager(); -smClient.baseUrl = (process.env.REACT_APP_IN_SYLVA_SOURCE_MANAGER_PORT) ? `${process.env.REACT_APP_IN_SYLVA_SOURCE_MANAGER_HOST}:${process.env.REACT_APP_IN_SYLVA_SOURCE_MANAGER_PORT}` : `${window._env_.REACT_APP_IN_SYLVA_SOURCE_MANAGER_HOST}` - -export const createSource = async (store, metaUrfms, name, description, kc_id, request = smClient) => { - try { - store.setState({ isLoading: true }) - request.token = sessionStorage.getItem("access_token") - - const result = await request.createSource(metaUrfms, name, description, kc_id); - if (result) { - const status = "SUCCESS" - store.setState({ status, isLoading: false }) - } - } catch (error) { - const isError404 = error.response && error.response.status === 404 - const status = isError404 ? "NOT_FOUND" : "ERROR" - store.setState({ status, isLoading: false }) +smClient.baseUrl = process.env.REACT_APP_IN_SYLVA_SOURCE_MANAGER_PORT + ? `${process.env.REACT_APP_IN_SYLVA_SOURCE_MANAGER_HOST}:${process.env.REACT_APP_IN_SYLVA_SOURCE_MANAGER_PORT}` + : `${window._env_.REACT_APP_IN_SYLVA_SOURCE_MANAGER_HOST}`; + +export const createSource = async ( + store, + metaUrfms, + name, + description, + kc_id, + request = smClient +) => { + try { + store.setState({ isLoading: true }); + request.token = sessionStorage.getItem('access_token'); + + const result = await request.createSource(metaUrfms, name, description, kc_id); + if (result) { + const status = 'SUCCESS'; + store.setState({ status, isLoading: false }); } -} + } catch (error) { + const isError404 = error.response && error.response.status === 404; + const status = isError404 ? 'NOT_FOUND' : 'ERROR'; + store.setState({ status, isLoading: false }); + } +}; export const sources = async (store, kc_id, request = smClient) => { - try { - store.setState({ isLoading: true }) - request.token = sessionStorage.getItem("access_token") - - const result = await request.sources(kc_id) - if (result) { - const status = "SUCCESS" - store.setState({ status, isLoading: false }) - return result; - } - } catch (error) { - const isError404 = error.response && error.response.status === 404 - const status = isError404 ? "NOT_FOUND" : "ERROR" - store.setState({ status, isLoading: false }) + try { + store.setState({ isLoading: true }); + request.token = sessionStorage.getItem('access_token'); + + const result = await request.sources(kc_id); + if (result) { + const status = 'SUCCESS'; + store.setState({ status, isLoading: false }); + return result; } -} + } catch (error) { + const isError404 = error.response && error.response.status === 404; + const status = isError404 ? 'NOT_FOUND' : 'ERROR'; + store.setState({ status, isLoading: false }); + } +}; export const indexedSources = async (store, kc_id, request = smClient) => { - try { - store.setState({ isLoading: true }) - request.token = sessionStorage.getItem("access_token") - - const result = await request.indexedSources(kc_id) - if (result) { - const status = "SUCCESS" - store.setState({ status, isLoading: false }) - return result; - } - } catch (error) { - const isError404 = error.response && error.response.status === 404 - const status = isError404 ? "NOT_FOUND" : "ERROR" - store.setState({ status, isLoading: false }) + try { + store.setState({ isLoading: true }); + request.token = sessionStorage.getItem('access_token'); + + const result = await request.indexedSources(kc_id); + if (result) { + const status = 'SUCCESS'; + store.setState({ status, isLoading: false }); + return result; } -} - -export const createStdField = async (store, category, field_name, definition_and_comment, obligation_or_condition, field_type, cardinality, values, ispublic, isoptional, request = smClient) => { - try { - store.setState({ isLoading: true }) - request.token = sessionStorage.getItem("access_token") - - const result = await request.addStdField(category, field_name, definition_and_comment, obligation_or_condition, field_type, cardinality, values, ispublic, isoptional); - if (result) { - const status = "SUCCESS"; - store.setState({ status, isLoading: false }) - } - } catch (error) { - const isError404 = error.response && error.response.status === 404 - const status = isError404 ? "NOT_FOUND" : "ERROR" - store.setState({ status, isLoading: false }) + } catch (error) { + const isError404 = error.response && error.response.status === 404; + const status = isError404 ? 'NOT_FOUND' : 'ERROR'; + store.setState({ status, isLoading: false }); + } +}; + +export const createStdField = async ( + store, + category, + field_name, + definition_and_comment, + obligation_or_condition, + field_type, + cardinality, + values, + ispublic, + isoptional, + request = smClient +) => { + try { + store.setState({ isLoading: true }); + request.token = sessionStorage.getItem('access_token'); + + const result = await request.addStdField( + category, + field_name, + definition_and_comment, + obligation_or_condition, + field_type, + cardinality, + values, + ispublic, + isoptional + ); + if (result) { + const status = 'SUCCESS'; + store.setState({ status, isLoading: false }); } -} - -export const createAddtlField = async (store, category, field_name, definition_and_comment, obligation_or_condition, field_type, cardinality, values, ispublic, isoptional, request = smClient) => { - try { - store.setState({ isLoading: true }) - request.token = sessionStorage.getItem("access_token") - - const result = await request.addAddtlField(category, field_name, definition_and_comment, obligation_or_condition, field_type, cardinality, values, ispublic, isoptional); - if (result) { - const status = "SUCCESS" - store.setState({ status, isLoading: false }) - } - } catch (error) { - const isError404 = error.response && error.response.status === 404 - const status = isError404 ? "NOT_FOUND" : "ERROR" - store.setState({ status, isLoading: false }) + } catch (error) { + const isError404 = error.response && error.response.status === 404; + const status = isError404 ? 'NOT_FOUND' : 'ERROR'; + store.setState({ status, isLoading: false }); + } +}; + +export const createAddtlField = async ( + store, + category, + field_name, + definition_and_comment, + obligation_or_condition, + field_type, + cardinality, + values, + ispublic, + isoptional, + request = smClient +) => { + try { + store.setState({ isLoading: true }); + request.token = sessionStorage.getItem('access_token'); + + const result = await request.addAddtlField( + category, + field_name, + definition_and_comment, + obligation_or_condition, + field_type, + cardinality, + values, + ispublic, + isoptional + ); + if (result) { + const status = 'SUCCESS'; + store.setState({ status, isLoading: false }); } -} - -export const updateStdField = async (store, category, field_name, definition_and_comment, obligation_or_condition, field_type, cardinality, values, ispublic, isoptional, request = smClient) => { - try { - store.setState({ isLoading: true }) - request.token = sessionStorage.getItem("access_token") - - const result = await request.updateStdField(category, field_name, definition_and_comment, obligation_or_condition, field_type, cardinality, values, ispublic, isoptional); - if (result) { - const status = "SUCCESS" - store.setState({ status, isLoading: false }) - } - } catch (error) { - const isError404 = error.response && error.response.status === 404 - const status = isError404 ? "NOT_FOUND" : "ERROR" - store.setState({ status, isLoading: false }) + } catch (error) { + const isError404 = error.response && error.response.status === 404; + const status = isError404 ? 'NOT_FOUND' : 'ERROR'; + store.setState({ status, isLoading: false }); + } +}; + +export const updateStdField = async ( + store, + category, + field_name, + definition_and_comment, + obligation_or_condition, + field_type, + cardinality, + values, + ispublic, + isoptional, + request = smClient +) => { + try { + store.setState({ isLoading: true }); + request.token = sessionStorage.getItem('access_token'); + + const result = await request.updateStdField( + category, + field_name, + definition_and_comment, + obligation_or_condition, + field_type, + cardinality, + values, + ispublic, + isoptional + ); + if (result) { + const status = 'SUCCESS'; + store.setState({ status, isLoading: false }); } -} + } catch (error) { + const isError404 = error.response && error.response.status === 404; + const status = isError404 ? 'NOT_FOUND' : 'ERROR'; + store.setState({ status, isLoading: false }); + } +}; export const updateSource = async (store, kc_id, source_id, request = smClient) => { - try { - store.setState({ isLoading: true }) - request.token = sessionStorage.getItem("access_token") - - const result = await request.updateSource(kc_id, source_id) - - if (result) { - const status = "SUCCESS"; - store.setState({ status, isLoading: false }); - } - } catch (error) { - const isError404 = error.response && error.response.status === 404 - const status = isError404 ? "NOT_FOUND" : "ERROR" - store.setState({ status, isLoading: false }) + try { + store.setState({ isLoading: true }); + request.token = sessionStorage.getItem('access_token'); + + const result = await request.updateSource(kc_id, source_id); + + if (result) { + const status = 'SUCCESS'; + store.setState({ status, isLoading: false }); } -} + } catch (error) { + const isError404 = error.response && error.response.status === 404; + const status = isError404 ? 'NOT_FOUND' : 'ERROR'; + store.setState({ status, isLoading: false }); + } +}; export const publicFields = async (store, request = smClient) => { - try { - store.setState({ isLoading: true }); - request.token = sessionStorage.getItem("access_token") - - const stdFields = await request.publicFields() - - if (stdFields) { - const status = "SUCCESS"; - store.setState({ status, isLoading: false }); - return stdFields - } - } catch (error) { - const isError404 = error.response && error.response.status === 404; - const status = isError404 ? "NOT_FOUND" : "ERROR"; - store.setState({ status, isLoading: false }); + try { + store.setState({ isLoading: true }); + request.token = sessionStorage.getItem('access_token'); + + const stdFields = await request.publicFields(); + + if (stdFields) { + const status = 'SUCCESS'; + store.setState({ status, isLoading: false }); + return stdFields; } -} + } catch (error) { + const isError404 = error.response && error.response.status === 404; + const status = isError404 ? 'NOT_FOUND' : 'ERROR'; + store.setState({ status, isLoading: false }); + } +}; export const privateFields = async (store, request = smClient) => { - try { - store.setState({ isLoading: true }); - request.token = sessionStorage.getItem("access_token") - - const stdFields = await request.privateFields() - - if (stdFields) { - const status = "SUCCESS"; - store.setState({ status, isLoading: false }); - return stdFields - } - } catch (error) { - const isError404 = error.response && error.response.status === 404; - const status = isError404 ? "NOT_FOUND" : "ERROR"; - store.setState({ status, isLoading: false }); + try { + store.setState({ isLoading: true }); + request.token = sessionStorage.getItem('access_token'); + + const stdFields = await request.privateFields(); + + if (stdFields) { + const status = 'SUCCESS'; + store.setState({ status, isLoading: false }); + return stdFields; } -} + } catch (error) { + const isError404 = error.response && error.response.status === 404; + const status = isError404 ? 'NOT_FOUND' : 'ERROR'; + store.setState({ status, isLoading: false }); + } +}; export const allSources = async (store, request = smClient) => { - try { - store.setState({ isLoading: true }) - request.token = sessionStorage.getItem("access_token") - const result = await request.allSource() - if (result) { - const status = "SUCCESS" - store.setState({ status, isLoading: false }) - return result; - } - } catch (error) { - const isError404 = error.response && error.response.status === 404 - const status = isError404 ? "NOT_FOUND" : "ERROR" - store.setState({ status, isLoading: false }) + try { + store.setState({ isLoading: true }); + request.token = sessionStorage.getItem('access_token'); + const result = await request.allSource(); + if (result) { + const status = 'SUCCESS'; + store.setState({ status, isLoading: false }); + return result; } -} + } catch (error) { + const isError404 = error.response && error.response.status === 404; + const status = isError404 ? 'NOT_FOUND' : 'ERROR'; + store.setState({ status, isLoading: false }); + } +}; export const allIndexedSources = async (store, request = smClient) => { - try { - store.setState({ isLoading: true }) - request.token = sessionStorage.getItem("access_token") - const result = await request.allIndexedSource() - if (result) { - const status = "SUCCESS" - store.setState({ status, isLoading: false }) - return result; - } - } catch (error) { - const isError404 = error.response && error.response.status === 404 - const status = isError404 ? "NOT_FOUND" : "ERROR" - store.setState({ status, isLoading: false }) + try { + store.setState({ isLoading: true }); + request.token = sessionStorage.getItem('access_token'); + const result = await request.allIndexedSource(); + if (result) { + const status = 'SUCCESS'; + store.setState({ status, isLoading: false }); + return result; } -} + } catch (error) { + const isError404 = error.response && error.response.status === 404; + const status = isError404 ? 'NOT_FOUND' : 'ERROR'; + store.setState({ status, isLoading: false }); + } +}; export const truncateStdField = async (store, request = smClient) => { - try { - store.setState({ isLoading: true }) - request.token = sessionStorage.getItem("access_token") - const result = await request.truncateStdField() - if (result) { - const status = "SUCCESS" - store.setState({ status, isLoading: false }) - return result; - } - } catch (error) { - const isError404 = error.response && error.response.status === 404 - const status = isError404 ? "NOT_FOUND" : "ERROR" - store.setState({ status, isLoading: false }) + try { + store.setState({ isLoading: true }); + request.token = sessionStorage.getItem('access_token'); + const result = await request.truncateStdField(); + if (result) { + const status = 'SUCCESS'; + store.setState({ status, isLoading: false }); + return result; } -} + } catch (error) { + const isError404 = error.response && error.response.status === 404; + const status = isError404 ? 'NOT_FOUND' : 'ERROR'; + store.setState({ status, isLoading: false }); + } +}; export const deleteSource = async (store, sourceId, kc_id, request = smClient) => { - try { - store.setState({ isLoading: true }) - request.token = sessionStorage.getItem("access_token") - const result = await request.deleteSource(sourceId, kc_id) - if (result) { - const status = "SUCCESS" - store.setState({ status, isLoading: false }) - return result; - } - } catch (error) { - const isError404 = error.response && error.response.status === 404 - const status = isError404 ? "NOT_FOUND" : "ERROR" - store.setState({ status, isLoading: false }) + try { + store.setState({ isLoading: true }); + request.token = sessionStorage.getItem('access_token'); + const result = await request.deleteSource(sourceId, kc_id); + if (result) { + const status = 'SUCCESS'; + store.setState({ status, isLoading: false }); + return result; } -} - -export const mergeAndSendSource = async (store, kc_id, name, description, sources, request = smClient) => { - try { - store.setState({ isLoading: true }) - request.token = sessionStorage.getItem("access_token") - const result = await request.mergeAndSendSource({ kc_id, name, description, sources }) - if (result) { - const status = "SUCCESS" - store.setState({ status, isLoading: false }) - return result; - } - } catch (error) { - const isError404 = error.response && error.response.status === 404 - const status = isError404 ? "NOT_FOUND" : "ERROR" - store.setState({ status, isLoading: false }) + } catch (error) { + const isError404 = error.response && error.response.status === 404; + const status = isError404 ? 'NOT_FOUND' : 'ERROR'; + store.setState({ status, isLoading: false }); + } +}; + +export const mergeAndSendSource = async ( + store, + kc_id, + name, + description, + sources, + request = smClient +) => { + try { + store.setState({ isLoading: true }); + request.token = sessionStorage.getItem('access_token'); + const result = await request.mergeAndSendSource({ + kc_id, + name, + description, + sources, + }); + if (result) { + const status = 'SUCCESS'; + store.setState({ status, isLoading: false }); + return result; } -} + } catch (error) { + const isError404 = error.response && error.response.status === 404; + const status = isError404 ? 'NOT_FOUND' : 'ERROR'; + store.setState({ status, isLoading: false }); + } +}; diff --git a/src/actions/user.js b/src/actions/user.js index e4fd22d..2a21e8f 100644 --- a/src/actions/user.js +++ b/src/actions/user.js @@ -1,321 +1,326 @@ import { InSylvaGatekeeperClient } from '../context/InSylvaGatekeeperClient'; -import {getGatekeeperBaseUrl} from "../utils"; +import { getGatekeeperBaseUrl } from '../utils'; const igClient = new InSylvaGatekeeperClient(); igClient.baseUrl = getGatekeeperBaseUrl(); -export const createUser = async (store, username, email, password, roleId, request = igClient) => { - try { - store.setState({ isLoading: true }); - request.token = sessionStorage.getItem("access_token") - - const nUser = await request.createUser({ username, email, password, roleId }); - if (nUser) { - const status = "SUCCESS"; - store.setState({ status, isLoading: false }); - } - } catch (error) { - const isError404 = error.response && error.response.status === 404; - const status = isError404 ? "NOT_FOUND" : "ERROR"; - store.setState({ status, isLoading: false }); +export const createUser = async ( + store, + username, + email, + password, + roleId, + request = igClient +) => { + try { + store.setState({ isLoading: true }); + request.token = sessionStorage.getItem('access_token'); + + const nUser = await request.createUser({ username, email, password, roleId }); + if (nUser) { + const status = 'SUCCESS'; + store.setState({ status, isLoading: false }); } -} + } catch (error) { + const isError404 = error.response && error.response.status === 404; + const status = isError404 ? 'NOT_FOUND' : 'ERROR'; + store.setState({ status, isLoading: false }); + } +}; export const findUser = async (store, request = igClient) => { - try { - store.setState({ isLoading: true }) - request.token = sessionStorage.getItem("access_token") - - const users = await request.findUser() - if (users) { - const status = "SUCCESS" - store.setState({ users, status, isLoading: false }) - return users - } - } catch (error) { - const isError404 = error.response && error.response.status === 404; - const status = isError404 ? "NOT_FOUND" : "ERROR"; - store.setState({ status, isLoading: false }); + try { + store.setState({ isLoading: true }); + request.token = sessionStorage.getItem('access_token'); + + const users = await request.findUser(); + if (users) { + const status = 'SUCCESS'; + store.setState({ users, status, isLoading: false }); + return users; } -} + } catch (error) { + const isError404 = error.response && error.response.status === 404; + const status = isError404 ? 'NOT_FOUND' : 'ERROR'; + store.setState({ status, isLoading: false }); + } +}; export const updateUser = async (store, puser, request = igClient) => { - try { - store.setState({ isLoading: true }); - request.token = sessionStorage.getItem("access_token") - - const user = await request.updateUser({ id: puser.id, firstName: puser.firstName, lastName: puser.lastName }); - if (user) { - const status = "SUCCESS"; - store.setState({ status, isLoading: false }); - } - - } catch (error) { - const isError404 = error.response && error.response.status === 404; - const status = isError404 ? "NOT_FOUND" : "ERROR"; - store.setState({ status, isLoading: false }); + try { + store.setState({ isLoading: true }); + request.token = sessionStorage.getItem('access_token'); + + const user = await request.updateUser({ + id: puser.id, + firstName: puser.firstName, + lastName: puser.lastName, + }); + if (user) { + const status = 'SUCCESS'; + store.setState({ status, isLoading: false }); } -} + } catch (error) { + const isError404 = error.response && error.response.status === 404; + const status = isError404 ? 'NOT_FOUND' : 'ERROR'; + store.setState({ status, isLoading: false }); + } +}; export const findOneUser = async (store, id, request = igClient) => { - try { - - store.setState({ isLoading: true }); - request.token = sessionStorage.getItem("access_token") - - const user = await request.findOneUser(id); - - if (user) { - const status = "SUCCESS"; - store.setState({ user: user, status, isLoading: false }); - return user - } - } catch (error) { - const isError404 = error.response && error.response.status === 404; - const status = isError404 ? "NOT_FOUND" : "ERROR"; - store.setState({ status, isLoading: false }); + try { + store.setState({ isLoading: true }); + request.token = sessionStorage.getItem('access_token'); + + const user = await request.findOneUser(id); + + if (user) { + const status = 'SUCCESS'; + store.setState({ user: user, status, isLoading: false }); + return user; } -} + } catch (error) { + const isError404 = error.response && error.response.status === 404; + const status = isError404 ? 'NOT_FOUND' : 'ERROR'; + store.setState({ status, isLoading: false }); + } +}; export const findOneUserWithGroupAndRole = async (store, id, request = igClient) => { - try { - - store.setState({ isLoading: true }); - request.token = sessionStorage.getItem("access_token") - - const user = await request.findOneUserWithGroupAndRole(id); - - if (user) { - const status = "SUCCESS"; - store.setState({ user: user, status, isLoading: false }); - return user - } - } catch (error) { - const isError404 = error.response && error.response.status === 404; - const status = isError404 ? "NOT_FOUND" : "ERROR"; - store.setState({ status, isLoading: false }); + try { + store.setState({ isLoading: true }); + request.token = sessionStorage.getItem('access_token'); + + const user = await request.findOneUserWithGroupAndRole(id); + + if (user) { + const status = 'SUCCESS'; + store.setState({ user: user, status, isLoading: false }); + return user; } -} + } catch (error) { + const isError404 = error.response && error.response.status === 404; + const status = isError404 ? 'NOT_FOUND' : 'ERROR'; + store.setState({ status, isLoading: false }); + } +}; export const deleteUser = async (store, id, request = igClient) => { - try { - store.setState({ isLoading: true }); - request.token = sessionStorage.getItem("access_token") - - const user = await request.deleteUser({ id: id }); - if (user) { - const status = "SUCCESS"; - store.setState({ status, isLoading: false }); - } - } catch (error) { - const isError404 = error.response && error.response.status === 404; - const status = isError404 ? "NOT_FOUND" : "ERROR"; - store.setState({ status, isLoading: false }); + try { + store.setState({ isLoading: true }); + request.token = sessionStorage.getItem('access_token'); + + const user = await request.deleteUser({ id: id }); + if (user) { + const status = 'SUCCESS'; + store.setState({ status, isLoading: false }); } -} + } catch (error) { + const isError404 = error.response && error.response.status === 404; + const status = isError404 ? 'NOT_FOUND' : 'ERROR'; + store.setState({ status, isLoading: false }); + } +}; export async function fetchRequests(store, request = igClient) { - store.setState({ isLoading: true }); - request.token = sessionStorage.getItem("access_token") - try { - const requests = await request.getRequests(); - if (requests) { - return requests - } - } catch (error) { - console.log("error fetch requests") - console.log(error) + store.setState({ isLoading: true }); + request.token = sessionStorage.getItem('access_token'); + try { + const requests = await request.getRequests(); + if (requests) { + return requests; } + } catch (error) { + console.log('error fetch requests'); + console.log(error); + } } export async function fetchPendingRequests(store, request = igClient) { - store.setState({ isLoading: true }); - request.token = sessionStorage.getItem("access_token") - try { - const requests = await request.getPendingRequests(); - if (requests) { - return requests - } - } catch (error) { - console.log("error fetch pending requests") - console.log(error) + store.setState({ isLoading: true }); + request.token = sessionStorage.getItem('access_token'); + try { + const requests = await request.getPendingRequests(); + if (requests) { + return requests; } + } catch (error) { + console.log('error fetch pending requests'); + console.log(error); + } } export async function processUserRequest(store, requestId, request = igClient) { - store.setState({ isLoading: true }); - request.token = sessionStorage.getItem("access_token") - try { - await request.processUserRequest(requestId); - } catch (error) { - console.log("error process user request") - console.log(error) - } + store.setState({ isLoading: true }); + request.token = sessionStorage.getItem('access_token'); + try { + await request.processUserRequest(requestId); + } catch (error) { + console.log('error process user request'); + console.log(error); + } } export async function deleteUserRequest(store, requestId, request = igClient) { - store.setState({ isLoading: true }); - request.token = sessionStorage.getItem("access_token") - try { - await request.deleteUserRequest(requestId); - } catch (error) { - console.log("error delete user request") - console.log(error) - } + store.setState({ isLoading: true }); + request.token = sessionStorage.getItem('access_token'); + try { + await request.deleteUserRequest(requestId); + } catch (error) { + console.log('error delete user request'); + console.log(error); + } } export const createRole = async (store, name, description, request = igClient) => { - try { - store.setState({ isLoading: true }); - request.token = sessionStorage.getItem("access_token") - - const role = await request.createRole({ name: name, description: description }); - if (role) { - const status = "SUCCESS"; - store.setState({ role, status, isLoading: false }); - } - } catch (error) { - const isError404 = error.response && error.response.status === 404; - const status = isError404 ? "NOT_FOUND" : "ERROR"; - store.setState({ status, isLoading: false }); + try { + store.setState({ isLoading: true }); + request.token = sessionStorage.getItem('access_token'); + + const role = await request.createRole({ name: name, description: description }); + if (role) { + const status = 'SUCCESS'; + store.setState({ role, status, isLoading: false }); } -} + } catch (error) { + const isError404 = error.response && error.response.status === 404; + const status = isError404 ? 'NOT_FOUND' : 'ERROR'; + store.setState({ status, isLoading: false }); + } +}; export const findRole = async (store, request = igClient) => { - try { - store.setState({ isLoading: true }); - request.token = sessionStorage.getItem("access_token") - - const roles = await request.findRole() - if (roles) { - const status = "SUCCESS" - store.setState({ roles, status, isLoading: false }) - return roles - } - } catch (error) { - const isError404 = error.response && error.response.status === 404; - const status = isError404 ? "NOT_FOUND" : "ERROR"; - store.setState({ status, isLoading: false }); + try { + store.setState({ isLoading: true }); + request.token = sessionStorage.getItem('access_token'); + + const roles = await request.findRole(); + if (roles) { + const status = 'SUCCESS'; + store.setState({ roles, status, isLoading: false }); + return roles; } -} + } catch (error) { + const isError404 = error.response && error.response.status === 404; + const status = isError404 ? 'NOT_FOUND' : 'ERROR'; + store.setState({ status, isLoading: false }); + } +}; export const allocateRoles = async (store, roles, users, request = igClient) => { - try { - store.setState({ isLoading: true }); - request.token = sessionStorage.getItem("access_token") - - const result = await request.allocateRoles({ roles, users }); - if (result === true) { - const status = "SUCCESS"; - store.setState({ status, isLoading: false }); - } - } catch (error) { - const isError404 = error.response && error.response.status === 404; - const status = isError404 ? "NOT_FOUND" : "ERROR"; - store.setState({ status, isLoading: false }); + try { + store.setState({ isLoading: true }); + request.token = sessionStorage.getItem('access_token'); + + const result = await request.allocateRoles({ roles, users }); + if (result === true) { + const status = 'SUCCESS'; + store.setState({ status, isLoading: false }); } -} + } catch (error) { + const isError404 = error.response && error.response.status === 404; + const status = isError404 ? 'NOT_FOUND' : 'ERROR'; + store.setState({ status, isLoading: false }); + } +}; export const allocateRolesToUser = async (store, userId, roleId, request = igClient) => { - try { - store.setState({ isLoading: true }); - request.token = sessionStorage.getItem("access_token") - - const result = await request.allocateRolesToUser({ userId, roleId }); - if (result === true) { - const status = "SUCCESS"; - store.setState({ status, isLoading: false }); - } - } catch (error) { - const isError404 = error.response && error.response.status === 404; - const status = isError404 ? "NOT_FOUND" : "ERROR"; - store.setState({ status, isLoading: false }); + try { + store.setState({ isLoading: true }); + request.token = sessionStorage.getItem('access_token'); + + const result = await request.allocateRolesToUser({ userId, roleId }); + if (result === true) { + const status = 'SUCCESS'; + store.setState({ status, isLoading: false }); } -} + } catch (error) { + const isError404 = error.response && error.response.status === 404; + const status = isError404 ? 'NOT_FOUND' : 'ERROR'; + store.setState({ status, isLoading: false }); + } +}; export const allocatedRoles = async (store, kc_id, request = igClient) => { - try { - store.setState({ isLoading: true }); - request.token = sessionStorage.getItem("access_token") - - const allocatedRoles = await request.allocatedRoles(kc_id); - if (allocatedRoles) { - const status = "SUCCESS"; - store.setState({ allocatedRoles, status, isLoading: false }); - } - } catch (error) { - const isError404 = error.response && error.response.status === 404; - const status = isError404 ? "NOT_FOUND" : "ERROR"; - store.setState({ status, isLoading: false }); + try { + store.setState({ isLoading: true }); + request.token = sessionStorage.getItem('access_token'); + + const allocatedRoles = await request.allocatedRoles(kc_id); + if (allocatedRoles) { + const status = 'SUCCESS'; + store.setState({ allocatedRoles, status, isLoading: false }); } -} + } catch (error) { + const isError404 = error.response && error.response.status === 404; + const status = isError404 ? 'NOT_FOUND' : 'ERROR'; + store.setState({ status, isLoading: false }); + } +}; export const setKcId = async (store, email, request = igClient) => { - try { - store.setState({ isLoading: true }) - request.token = sessionStorage.getItem("access_token") - const { kc_id } = await request.kcId(email) - - store.setState({ kcId: kc_id }) - } catch (error) { - const isError404 = error.response && error.response.status === 404; - const status = isError404 ? "NOT_FOUND" : "ERROR" - store.setState({ status, isLoading: false }) - } -} + try { + store.setState({ isLoading: true }); + request.token = sessionStorage.getItem('access_token'); + const { kc_id } = await request.kcId(email); -export const deleteRole = async (store, id, request = igClient) => { - try { - store.setState({ isLoading: true }) - request.token = sessionStorage.getItem("access_token") - const role = await request.deleteRole({ id }) - - if (role) { - const status = "SUCCESS" - store.setState({ status, isLoading: false }) - } - } catch (error) { - const isError404 = error.response && error.response.status === 404 - const status = isError404 ? "NOT_FOUND" : "ERROR" - store.setState({ status, isLoading: false }) - } -} + store.setState({ kcId: kc_id }); + } catch (error) { + const isError404 = error.response && error.response.status === 404; + const status = isError404 ? 'NOT_FOUND' : 'ERROR'; + store.setState({ status, isLoading: false }); + } +}; +export const deleteRole = async (store, id, request = igClient) => { + try { + store.setState({ isLoading: true }); + request.token = sessionStorage.getItem('access_token'); + const role = await request.deleteRole({ id }); -export const getAssignedUserByRole = async (store, id, request = igClient) => { - try { - store.setState({ isLoading: true }); - request.token = sessionStorage.getItem("access_token") - const assignedUserByRole = await request.getAssignedUserByRole({ id }); - - if (assignedUserByRole) { - const status = "SUCCESS" - store.setState({ status, isLoading: false }) - return assignedUserByRole - } - } catch (error) { - const isError404 = error.response && error.response.status === 404 - const status = isError404 ? "NOT_FOUND" : "ERROR" - store.setState({ status, isLoading: false }) + if (role) { + const status = 'SUCCESS'; + store.setState({ status, isLoading: false }); } -} + } catch (error) { + const isError404 = error.response && error.response.status === 404; + const status = isError404 ? 'NOT_FOUND' : 'ERROR'; + store.setState({ status, isLoading: false }); + } +}; +export const getAssignedUserByRole = async (store, id, request = igClient) => { + try { + store.setState({ isLoading: true }); + request.token = sessionStorage.getItem('access_token'); + const assignedUserByRole = await request.getAssignedUserByRole({ id }); + if (assignedUserByRole) { + const status = 'SUCCESS'; + store.setState({ status, isLoading: false }); + return assignedUserByRole; + } + } catch (error) { + const isError404 = error.response && error.response.status === 404; + const status = isError404 ? 'NOT_FOUND' : 'ERROR'; + store.setState({ status, isLoading: false }); + } +}; export const usersWithGroupAndRole = async (store, id, request = igClient) => { - try { - store.setState({ isLoading: true }); - request.token = sessionStorage.getItem("access_token") - const usersWithGroupAndRole = await request.usersWithGroupAndRole(); - - if (usersWithGroupAndRole) { - const status = "SUCCESS" - store.setState({ status, isLoading: false }) - return usersWithGroupAndRole - } - } catch (error) { - const isError404 = error.response && error.response.status === 404 - const status = isError404 ? "NOT_FOUND" : "ERROR" - store.setState({ status, isLoading: false }) + try { + store.setState({ isLoading: true }); + request.token = sessionStorage.getItem('access_token'); + const usersWithGroupAndRole = await request.usersWithGroupAndRole(); + + if (usersWithGroupAndRole) { + const status = 'SUCCESS'; + store.setState({ status, isLoading: false }); + return usersWithGroupAndRole; } -} + } catch (error) { + const isError404 = error.response && error.response.status === 404; + const status = isError404 ? 'NOT_FOUND' : 'ERROR'; + store.setState({ status, isLoading: false }); + } +}; diff --git a/src/components/App.js b/src/components/App.js index 49b33e7..bb8b8c7 100644 --- a/src/components/App.js +++ b/src/components/App.js @@ -1,28 +1,22 @@ -import React from "react"; -import { HashRouter, Route, Switch, Redirect } from "react-router-dom"; +import React from 'react'; +import { HashRouter, Route, Switch, Redirect } from 'react-router-dom'; // components -import Layout from "./Layout"; +import Layout from './Layout'; // pages -import Error from "../pages/error"; - +import Error from '../pages/error'; export default function App(props) { - return ( <HashRouter> <Switch> <Route exact path="/" render={() => <Redirect to="/app/dashboard" />} /> - <Route - exact - path="/app" - render={() => <Redirect to="/app/dashboard" />} - /> + <Route exact path="/app" render={() => <Redirect to="/app/dashboard" />} /> <Route path="/app" component={Layout} /> - { /* <PublicRoute path="/login" component={Login} /> */} - <Route path='/Error' component={Error} /> + {/* <PublicRoute path="/login" component={Login} /> */} + <Route path="/Error" component={Error} /> </Switch> </HashRouter> - ) + ); } diff --git a/src/components/Common/Common.js b/src/components/Common/Common.js index 26ac9f9..c2de13a 100644 --- a/src/components/Common/Common.js +++ b/src/components/Common/Common.js @@ -6,68 +6,71 @@ import Snackbar from '@material-ui/core/Snackbar'; import MuiAlert from '@material-ui/lab/Alert'; function Alert(props) { - return <MuiAlert elevation={6} variant="filled" {...props} />; - } - + return <MuiAlert elevation={6} variant="filled" {...props} />; +} export const MessageBox = (message, enabled, style) => { - return ( + return ( + <> + {enabled && ( <> - {enabled && ( - <> - <div className={style.MessageBox}>{message}</div> - </> - )} + <div className={style.MessageBox}>{message}</div> </> - ) -} + )} + </> + ); +}; export const InputFile = (onChange, style) => { - return ( - <> - <div className={style.dashedBorder}> - <label htmlFor="outlined-button-file" > - <input - className={style.input} - id="outlined-button-file" - type="file" - multiple - onChange={onChange} - /> - <Button variant="outlined" component="span" startIcon={<CloudUploadIcon />}> - télécharger - </Button> - </label> - - </div> - </> - ) -} + return ( + <> + <div className={style.dashedBorder}> + <label htmlFor="outlined-button-file"> + <input + className={style.input} + id="outlined-button-file" + type="file" + multiple + onChange={onChange} + /> + <Button variant="outlined" component="span" startIcon={<CloudUploadIcon />}> + télécharger + </Button> + </label> + </div> + </> + ); +}; export const ActionBar = (enabled, style, onSendClieck) => { - return ( + return ( + <> + {enabled && ( <> - {enabled && ( - <> - <div className={style.ActionBar}> - <Button variant="contained" - color="primary" onClick={onSendClieck} startIcon={<SaveIcon />}>Envoyez</Button> - </div> - </> - )} + <div className={style.ActionBar}> + <Button + variant="contained" + color="primary" + onClick={onSendClieck} + startIcon={<SaveIcon />} + > + Envoyez + </Button> + </div> </> - ) + )} + </> + ); +}; -} - -export const ShowAlert = (open,handleClose,message,severity) => { - return( - <> - <Snackbar open={open} autoHideDuration={6000} onClose={handleClose}> - <Alert onClose={handleClose} severity={severity}> - {message} - </Alert> - </Snackbar> - </> - ) -} +export const ShowAlert = (open, handleClose, message, severity) => { + return ( + <> + <Snackbar open={open} autoHideDuration={6000} onClose={handleClose}> + <Alert onClose={handleClose} severity={severity}> + {message} + </Alert> + </Snackbar> + </> + ); +}; diff --git a/src/components/Common/package.json b/src/components/Common/package.json index a9be85c..2065b9d 100644 --- a/src/components/Common/package.json +++ b/src/components/Common/package.json @@ -1,6 +1,6 @@ { - "name": "Common", - "version": "0.0.0", - "private": true, - "main": "Common.js" -} \ No newline at end of file + "name": "Common", + "version": "0.0.0", + "private": true, + "main": "Common.js" +} diff --git a/src/components/Header/Header.js b/src/components/Header/Header.js index 7166df4..9d73183 100644 --- a/src/components/Header/Header.js +++ b/src/components/Header/Header.js @@ -1,31 +1,25 @@ -import React, { useState, useEffect, useCallback } from "react"; -import { - AppBar, - Toolbar, - IconButton, - Menu, - MenuItem, -} from "@material-ui/core"; +import React, { useState, useEffect, useCallback } from 'react'; +import { AppBar, Toolbar, IconButton, Menu, MenuItem } from '@material-ui/core'; import { Menu as MenuIcon, Person as AccountIcon, ArrowBack as ArrowBackIcon, -} from "@material-ui/icons"; -import classNames from "classnames"; +} from '@material-ui/icons'; +import classNames from 'classnames'; // styles -import useStyles from "./styles"; +import useStyles from './styles'; // components -import { Typography } from "../Wrappers/Wrappers"; +import { Typography } from '../Wrappers/Wrappers'; // context import { useLayoutState, useLayoutDispatch, toggleSidebar, -} from "../../context/LayoutContext"; -import { useUserDispatch, signOut } from "../../context/UserContext"; +} from '../../context/LayoutContext'; +import { useUserDispatch, signOut } from '../../context/UserContext'; import store from '../../store/index'; /* const notifications = [ @@ -64,18 +58,18 @@ export default function Header(props) { var [profileMenu, setProfileMenu] = useState(null); var [, globalActions] = store(); - var [user, setUser] = useState({}) + var [user, setUser] = useState({}); const loadUser = useCallback(async () => { if (sessionStorage.getItem('userId')) { const userId = sessionStorage.getItem('userId'); - const user = await globalActions.user.findOneUser(userId) - setUser(user) + const user = await globalActions.user.findOneUser(userId); + setUser(user); } - }, [globalActions]) + }, [globalActions]); useEffect(() => { - loadUser() + loadUser(); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); @@ -87,26 +81,22 @@ export default function Header(props) { onClick={() => toggleSidebar(layoutDispatch)} className={classNames( classes.headerMenuButton, - classes.headerMenuButtonCollapse, - )}> + classes.headerMenuButtonCollapse + )} + > {layoutState.isSidebarOpened ? ( <ArrowBackIcon classes={{ - root: classNames( - classes.headerIcon, - classes.headerIconCollapse, - ), - }} /> + root: classNames(classes.headerIcon, classes.headerIconCollapse), + }} + /> ) : ( - <MenuIcon - classes={{ - root: classNames( - classes.headerIcon, - classes.headerIconCollapse, - ), - }} - /> - )} + <MenuIcon + classes={{ + root: classNames(classes.headerIcon, classes.headerIconCollapse), + }} + /> + )} </IconButton> <Typography variant="h6" weight="medium" className={classes.logotype}> IN-SYLVA IS Administration Portal @@ -117,7 +107,8 @@ export default function Header(props) { color="inherit" className={classes.headerMenuButton} aria-controls="profile-menu" - onClick={e => setProfileMenu(e.currentTarget)}> + onClick={(e) => setProfileMenu(e.currentTarget)} + > <AccountIcon classes={{ root: classes.headerIcon }} /> </IconButton> <Menu @@ -127,19 +118,16 @@ export default function Header(props) { onClose={() => setProfileMenu(null)} className={classes.headerMenu} classes={{ paper: classes.profileMenu }} - disableAutoFocusItem> + disableAutoFocusItem + > <div className={classes.profileMenuUser}> <Typography variant="h4" weight="medium"> - { - user.username - } + {user.username} </Typography> </div> <MenuItem - className={classNames( - classes.profileMenuItem, - classes.headerMenuItem, - )}> + className={classNames(classes.profileMenuItem, classes.headerMenuItem)} + > <AccountIcon className={classes.profileMenuIcon} /> Profile </MenuItem> <div className={classes.profileMenuUser}> @@ -152,7 +140,7 @@ export default function Header(props) { </Typography> </div> </Menu> - </Toolbar > - </AppBar > + </Toolbar> + </AppBar> ); } diff --git a/src/components/Header/HeaderView.js b/src/components/Header/HeaderView.js index a52e5a1..b137bc8 100644 --- a/src/components/Header/HeaderView.js +++ b/src/components/Header/HeaderView.js @@ -1,4 +1,4 @@ -import React from "react"; +import React from 'react'; import { AppBar, Toolbar, @@ -7,8 +7,8 @@ import { Menu, MenuItem, Fab, - withStyles -} from "@material-ui/core"; + withStyles, +} from '@material-ui/core'; import { Menu as MenuIcon, MailOutline as MailIcon, @@ -16,66 +16,66 @@ import { Person as AccountIcon, Search as SearchIcon, Send as SendIcon, - ArrowBack as ArrowBackIcon -} from "@material-ui/icons"; -import { fade } from "@material-ui/core/styles/colorManipulator"; -import classNames from "classnames"; + ArrowBack as ArrowBackIcon, +} from '@material-ui/icons'; +import { fade } from '@material-ui/core/styles/colorManipulator'; +import classNames from 'classnames'; -import { Badge, Typography } from "../Wrappers"; -import Notification from "../Notification"; -import UserAvatar from "../UserAvatar"; +import { Badge, Typography } from '../Wrappers'; +import Notification from '../Notification'; +import UserAvatar from '../UserAvatar'; const messages = [ { id: 0, - variant: "warning", - name: "Jane Hew", - message: "Hey! How is it going?", - time: "9:32" + variant: 'warning', + name: 'Jane Hew', + message: 'Hey! How is it going?', + time: '9:32', }, { id: 1, - variant: "success", - name: "Lloyd Brown", - message: "Check out my new Dashboard", - time: "9:18" + variant: 'success', + name: 'Lloyd Brown', + message: 'Check out my new Dashboard', + time: '9:18', }, { id: 2, - variant: "primary", - name: "Mark Winstein", - message: "I want rearrange the appointment", - time: "9:15" + variant: 'primary', + name: 'Mark Winstein', + message: 'I want rearrange the appointment', + time: '9:15', }, { id: 3, - variant: "secondary", - name: "Liana Dutti", - message: "Good news from sale department", - time: "9:09" - } + variant: 'secondary', + name: 'Liana Dutti', + message: 'Good news from sale department', + time: '9:09', + }, ]; const notifications = [ - { id: 0, color: "warning", message: "Check out this awesome ticket" }, + { id: 0, color: 'warning', message: 'Check out this awesome ticket' }, { id: 1, - color: "success", - type: "info", - message: "What is the best way to get ..." + color: 'success', + type: 'info', + message: 'What is the best way to get ...', }, { id: 2, - color: "secondary", - type: "notification", - message: "This is just a simple notification" + color: 'secondary', + type: 'notification', + message: 'This is just a simple notification', }, { id: 3, - color: "primary", - type: "e-commerce", - message: "12 new orders has arrived today" - } + color: 'primary', + type: 'e-commerce', + message: '12 new orders has arrived today', + }, ]; const Header = ({ classes, isSidebarOpened, toggleSidebar, ...props }) => ( @@ -84,35 +84,34 @@ const Header = ({ classes, isSidebarOpened, toggleSidebar, ...props }) => ( <IconButton color="inherit" onClick={toggleSidebar} - className={classNames( - classes.headerMenuButton, - classes.headerMenuButtonCollapse - )} + className={classNames(classes.headerMenuButton, classes.headerMenuButtonCollapse)} > {isSidebarOpened ? ( <ArrowBackIcon classes={{ - root: classNames(classes.headerIcon, classes.headerIconCollapse) + root: classNames(classes.headerIcon, classes.headerIconCollapse), }} /> ) : ( <MenuIcon classes={{ - root: classNames(classes.headerIcon, classes.headerIconCollapse) + root: classNames(classes.headerIcon, classes.headerIconCollapse), }} /> )} </IconButton> - <Typography variant="h6" weight="medium" className={classes.logotype}>React Material Admin</Typography> + <Typography variant="h6" weight="medium" className={classes.logotype}> + React Material Admin + </Typography> <div className={classes.grow} /> <div className={classNames(classes.search, { - [classes.searchFocused]: props.isSearchOpen + [classes.searchFocused]: props.isSearchOpen, })} > <div className={classNames(classes.searchIcon, { - [classes.searchIconOpened]: props.isSearchOpen + [classes.searchIconOpened]: props.isSearchOpen, })} onClick={props.toggleSearch} > @@ -122,7 +121,7 @@ const Header = ({ classes, isSidebarOpened, toggleSidebar, ...props }) => ( placeholder="Search…" classes={{ root: classes.inputRoot, - input: classes.inputInput + input: classes.inputInput, }} /> </div> @@ -134,9 +133,7 @@ const Header = ({ classes, isSidebarOpened, toggleSidebar, ...props }) => ( className={classes.headerMenuButton} > <Badge - badgeContent={ - props.isNotificationsUnread ? notifications.length : null - } + badgeContent={props.isNotificationsUnread ? notifications.length : null} colortheme="warning" > <NotificationsIcon classes={{ root: classes.headerIcon }} /> @@ -179,15 +176,11 @@ const Header = ({ classes, isSidebarOpened, toggleSidebar, ...props }) => ( <Typography variant="h4" weight="medium"> New Messages </Typography> - <Typography - className={classes.profileMenuLink} - component="a" - color="secondary" - > + <Typography className={classes.profileMenuLink} component="a" color="secondary"> {messages.length} New Messages </Typography> </div> - {messages.map(message => ( + {messages.map((message) => ( <MenuItem key={message.id} className={classes.messageNotification}> <div className={classes.messageNotificationSide}> <UserAvatar color={message.variant} name={message.name} /> @@ -226,7 +219,7 @@ const Header = ({ classes, isSidebarOpened, toggleSidebar, ...props }) => ( className={classes.headerMenu} disableAutoFocusItem > - {notifications.map(notification => ( + {notifications.map((notification) => ( <MenuItem key={notification.id} onClick={props.closeNotificationsMenu} @@ -258,28 +251,13 @@ const Header = ({ classes, isSidebarOpened, toggleSidebar, ...props }) => ( Flalogic.com </Typography> </div> - <MenuItem - className={classNames( - classes.profileMenuItem, - classes.headerMenuItem - )} - > + <MenuItem className={classNames(classes.profileMenuItem, classes.headerMenuItem)}> <AccountIcon className={classes.profileMenuIcon} /> Profile </MenuItem> - <MenuItem - className={classNames( - classes.profileMenuItem, - classes.headerMenuItem - )} - > + <MenuItem className={classNames(classes.profileMenuItem, classes.headerMenuItem)}> <AccountIcon className={classes.profileMenuIcon} /> Tasks </MenuItem> - <MenuItem - className={classNames( - classes.profileMenuItem, - classes.headerMenuItem - )} - > + <MenuItem className={classNames(classes.profileMenuItem, classes.headerMenuItem)}> <AccountIcon className={classes.profileMenuIcon} /> Messages </MenuItem> <div className={classes.profileMenuUser}> @@ -296,161 +274,161 @@ const Header = ({ classes, isSidebarOpened, toggleSidebar, ...props }) => ( </AppBar> ); -const styles = theme => ({ +const styles = (theme) => ({ logotype: { - color: "white", + color: 'white', marginLeft: theme.spacing.unit * 2.5, marginRight: theme.spacing.unit * 2.5, fontWeight: 500, fontSize: 18, - whiteSpace: "nowrap", - [theme.breakpoints.down("xs")]: { - display: "none" - } + whiteSpace: 'nowrap', + [theme.breakpoints.down('xs')]: { + display: 'none', + }, }, appBar: { - width: "100vw", + width: '100vw', zIndex: theme.zIndex.drawer + 1, - transition: theme.transitions.create(["margin"], { + transition: theme.transitions.create(['margin'], { easing: theme.transitions.easing.sharp, - duration: theme.transitions.duration.leavingScreen - }) + duration: theme.transitions.duration.leavingScreen, + }), }, toolbar: { paddingLeft: theme.spacing.unit * 2, - paddingRight: theme.spacing.unit * 2 + paddingRight: theme.spacing.unit * 2, }, hide: { - display: "none" + display: 'none', }, grow: { - flexGrow: 1 + flexGrow: 1, }, search: { - position: "relative", + position: 'relative', borderRadius: 25, paddingLeft: theme.spacing.unit * 2.5, width: 36, backgroundColor: fade(theme.palette.common.black, 0), - transition: theme.transitions.create(["background-color", "width"]), - "&:hover": { - cursor: "pointer", - backgroundColor: fade(theme.palette.common.black, 0.08) - } + transition: theme.transitions.create(['background-color', 'width']), + '&:hover': { + cursor: 'pointer', + backgroundColor: fade(theme.palette.common.black, 0.08), + }, }, searchFocused: { backgroundColor: fade(theme.palette.common.black, 0.08), - width: "100%", - [theme.breakpoints.up("md")]: { - width: 250 - } + width: '100%', + [theme.breakpoints.up('md')]: { + width: 250, + }, }, searchIcon: { width: 36, right: 0, - height: "100%", - position: "absolute", - display: "flex", - alignItems: "center", - justifyContent: "center", - transition: theme.transitions.create("right"), - "&:hover": { - cursor: "pointer" - } + height: '100%', + position: 'absolute', + display: 'flex', + alignItems: 'center', + justifyContent: 'center', + transition: theme.transitions.create('right'), + '&:hover': { + cursor: 'pointer', + }, }, searchIconOpened: { - right: theme.spacing.unit * 1.25 + right: theme.spacing.unit * 1.25, }, inputRoot: { - color: "inherit", - width: "100%" + color: 'inherit', + width: '100%', }, inputInput: { height: 36, padding: 0, paddingRight: 36 + theme.spacing.unit * 1.25, - width: "100%" + width: '100%', }, messageContent: { - display: "flex", - flexDirection: "column" + display: 'flex', + flexDirection: 'column', }, headerMenu: { - marginTop: theme.spacing.unit * 7 + marginTop: theme.spacing.unit * 7, }, headerMenuList: { - display: "flex", - flexDirection: "column" + display: 'flex', + flexDirection: 'column', }, headerMenuItem: { - "&:hover, &:focus": { + '&:hover, &:focus': { backgroundColor: theme.palette.primary.main, - color: "white" - } + color: 'white', + }, }, headerMenuButton: { marginLeft: theme.spacing.unit * 2, - padding: theme.spacing.unit / 2 + padding: theme.spacing.unit / 2, }, headerMenuButtonCollapse: { - marginRight: theme.spacing.unit * 2 + marginRight: theme.spacing.unit * 2, }, headerIcon: { fontSize: 28, - color: "rgba(255, 255, 255, 0.35)" + color: 'rgba(255, 255, 255, 0.35)', }, headerIconCollapse: { - color: "white" + color: 'white', }, profileMenu: { - minWidth: 265 + minWidth: 265, }, profileMenuUser: { - display: "flex", - flexDirection: "column", - padding: theme.spacing.unit * 2 + display: 'flex', + flexDirection: 'column', + padding: theme.spacing.unit * 2, }, profileMenuItem: { - color: theme.palette.text.hint + color: theme.palette.text.hint, }, profileMenuIcon: { marginRight: theme.spacing.unit * 2, - color: theme.palette.text.hint + color: theme.palette.text.hint, }, profileMenuLink: { fontSize: 16, - textDecoration: "none", - "&:hover": { - cursor: "pointer" - } + textDecoration: 'none', + '&:hover': { + cursor: 'pointer', + }, }, messageNotification: { - height: "auto", - display: "flex", - alignItems: "center", - "&:hover, &:focus": { - backgroundColor: theme.palette.background.light - } + height: 'auto', + display: 'flex', + alignItems: 'center', + '&:hover, &:focus': { + backgroundColor: theme.palette.background.light, + }, }, messageNotificationSide: { - display: "flex", - flexDirection: "column", - alignItems: "center", - marginRight: theme.spacing.unit * 2 + display: 'flex', + flexDirection: 'column', + alignItems: 'center', + marginRight: theme.spacing.unit * 2, }, messageNotificationBodySide: { - alignItems: "flex-start", - marginRight: 0 + alignItems: 'flex-start', + marginRight: 0, }, sendMessageButton: { margin: theme.spacing.unit * 4, marginTop: theme.spacing.unit * 2, marginBottom: theme.spacing.unit * 2, - textTransform: "none" + textTransform: 'none', }, sendButtonIcon: { - marginLeft: theme.spacing.unit * 2 - } + marginLeft: theme.spacing.unit * 2, + }, }); export default withStyles(styles)(Header); diff --git a/src/components/Header/styles.js b/src/components/Header/styles.js index c827db7..6bb8a0c 100644 --- a/src/components/Header/styles.js +++ b/src/components/Header/styles.js @@ -1,96 +1,96 @@ -import { makeStyles } from "@material-ui/styles"; -import { fade } from "@material-ui/core/styles/colorManipulator"; +import { makeStyles } from '@material-ui/styles'; +import { fade } from '@material-ui/core/styles/colorManipulator'; -export default makeStyles(theme => ({ +export default makeStyles((theme) => ({ logotype: { - color: "white", + color: 'white', marginLeft: theme.spacing(2.5), marginRight: theme.spacing(2.5), fontWeight: 500, fontSize: 18, - whiteSpace: "nowrap", - [theme.breakpoints.down("xs")]: { - display: "none", + whiteSpace: 'nowrap', + [theme.breakpoints.down('xs')]: { + display: 'none', }, }, appBar: { - width: "100vw", + width: '100vw', zIndex: theme.zIndex.drawer + 1, - transition: theme.transitions.create(["margin"], { + transition: theme.transitions.create(['margin'], { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.leavingScreen, - }) + }), }, toolbar: { paddingLeft: theme.spacing(2), paddingRight: theme.spacing(2), }, hide: { - display: "none", + display: 'none', }, grow: { flexGrow: 1, }, search: { - position: "relative", + position: 'relative', borderRadius: 25, paddingLeft: theme.spacing(2.5), width: 36, backgroundColor: fade(theme.palette.common.black, 0), - transition: theme.transitions.create(["background-color", "width"]), - "&:hover": { - cursor: "pointer", + transition: theme.transitions.create(['background-color', 'width']), + '&:hover': { + cursor: 'pointer', backgroundColor: fade(theme.palette.common.black, 0.08), }, }, searchFocused: { backgroundColor: fade(theme.palette.common.black, 0.08), - width: "100%", - [theme.breakpoints.up("md")]: { + width: '100%', + [theme.breakpoints.up('md')]: { width: 250, }, }, searchIcon: { width: 36, right: 0, - height: "100%", - position: "absolute", - display: "flex", - alignItems: "center", - justifyContent: "center", - transition: theme.transitions.create("right"), - "&:hover": { - cursor: "pointer", + height: '100%', + position: 'absolute', + display: 'flex', + alignItems: 'center', + justifyContent: 'center', + transition: theme.transitions.create('right'), + '&:hover': { + cursor: 'pointer', }, }, searchIconOpened: { right: theme.spacing(1.25), }, inputRoot: { - color: "inherit", - width: "100%", + color: 'inherit', + width: '100%', }, inputInput: { height: 36, padding: 0, paddingRight: 36 + theme.spacing(1.25), - width: "100%", + width: '100%', }, messageContent: { - display: "flex", - flexDirection: "column", + display: 'flex', + flexDirection: 'column', }, headerMenu: { marginTop: theme.spacing(7), }, headerMenuList: { - display: "flex", - flexDirection: "column", + display: 'flex', + flexDirection: 'column', }, headerMenuItem: { - "&:hover, &:focus": { + '&:hover, &:focus': { backgroundColor: theme.palette.primary.main, - color: "white", + color: 'white', }, }, headerMenuButton: { @@ -102,17 +102,17 @@ export default makeStyles(theme => ({ }, headerIcon: { fontSize: 28, - color: "rgba(255, 255, 255, 0.35)", + color: 'rgba(255, 255, 255, 0.35)', }, headerIconCollapse: { - color: "white", + color: 'white', }, profileMenu: { minWidth: 265, }, profileMenuUser: { - display: "flex", - flexDirection: "column", + display: 'flex', + flexDirection: 'column', padding: theme.spacing(2), }, profileMenuItem: { @@ -124,34 +124,34 @@ export default makeStyles(theme => ({ }, profileMenuLink: { fontSize: 16, - textDecoration: "none", - "&:hover": { - cursor: "pointer", + textDecoration: 'none', + '&:hover': { + cursor: 'pointer', }, }, messageNotification: { - height: "auto", - display: "flex", - alignItems: "center", - "&:hover, &:focus": { + height: 'auto', + display: 'flex', + alignItems: 'center', + '&:hover, &:focus': { backgroundColor: theme.palette.background.light, }, }, messageNotificationSide: { - display: "flex", - flexDirection: "column", - alignItems: "center", + display: 'flex', + flexDirection: 'column', + alignItems: 'center', marginRight: theme.spacing(2), }, messageNotificationBodySide: { - alignItems: "flex-start", + alignItems: 'flex-start', marginRight: 0, }, sendMessageButton: { margin: theme.spacing(4), marginTop: theme.spacing(2), marginBottom: theme.spacing(2), - textTransform: "none", + textTransform: 'none', }, sendButtonIcon: { marginLeft: theme.spacing(2), diff --git a/src/components/Layout/Layout.js b/src/components/Layout/Layout.js index 7628b5b..2c4570d 100644 --- a/src/components/Layout/Layout.js +++ b/src/components/Layout/Layout.js @@ -1,30 +1,26 @@ -import React from "react" -import { - Route, - Switch, - withRouter, -} from "react-router-dom" -import classnames from "classnames" +import React from 'react'; +import { Route, Switch, withRouter } from 'react-router-dom'; +import classnames from 'classnames'; // styles -import useStyles from "./styles" +import useStyles from './styles'; // components -import Header from "../Header" -import Sidebar from "../Sidebar" +import Header from '../Header'; +import Sidebar from '../Sidebar'; // pages -import Dashboard from "../../pages/dashboard" -import User from "../../pages/user" -import Role from "../../pages/roles" -import Requests from "../../pages/requests" -import Sources from "../../pages/sources/Sources" -import Fields from "../../pages/fields" -import Policy from '../../pages/policy' -import Group from '../../pages/group' +import Dashboard from '../../pages/dashboard'; +import User from '../../pages/user'; +import Role from '../../pages/roles'; +import Requests from '../../pages/requests'; +import Sources from '../../pages/sources/Sources'; +import Fields from '../../pages/fields'; +import Policy from '../../pages/policy'; +import Group from '../../pages/group'; // context -import { useLayoutState } from "../../context/LayoutContext" +import { useLayoutState } from '../../context/LayoutContext'; function Layout(props) { var classes = useStyles(); @@ -40,7 +36,8 @@ function Layout(props) { <div className={classnames(classes.content, { [classes.contentShift]: layoutState.isSidebarOpened, - })}> + })} + > <div className={classes.fakeToolbar} /> <Switch> <Route path="/app/dashboard" component={Dashboard} /> @@ -49,8 +46,8 @@ function Layout(props) { <Route path="/app/role" component={Role} /> <Route path="/app/sources" component={Sources} /> <Route path="/app/fields" component={Fields} /> - <Route path='/app/policies' component={Policy} /> - <Route path='/app/groups' component={Group} /> + <Route path="/app/policies" component={Policy} /> + <Route path="/app/groups" component={Group} /> </Switch> </div> </> diff --git a/src/components/Layout/styles.js b/src/components/Layout/styles.js index 4fc4fb2..05e123e 100644 --- a/src/components/Layout/styles.js +++ b/src/components/Layout/styles.js @@ -1,20 +1,20 @@ -import { makeStyles } from "@material-ui/styles"; +import { makeStyles } from '@material-ui/styles'; -export default makeStyles(theme => ({ +export default makeStyles((theme) => ({ root: { - display: "flex", - maxWidth: "100vw", - overflowX: "hidden", + display: 'flex', + maxWidth: '100vw', + overflowX: 'hidden', }, content: { flexGrow: 1, padding: theme.spacing(3), width: `calc(100vw - 240px)`, - minHeight: "100vh", + minHeight: '100vh', }, contentShift: { width: `calc(100vw - ${240 + theme.spacing(6)}px)`, - transition: theme.transitions.create(["width", "margin"], { + transition: theme.transitions.create(['width', 'margin'], { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.enteringScreen, }), diff --git a/src/components/Notification/Notification.js b/src/components/Notification/Notification.js index 8b39fe4..eb34c86 100644 --- a/src/components/Notification/Notification.js +++ b/src/components/Notification/Notification.js @@ -1,5 +1,5 @@ -import React from "react"; -import { Button } from "@material-ui/core"; +import React from 'react'; +import { Button } from '@material-ui/core'; import { NotificationsNone as NotificationsIcon, ThumbUp as ThumbUpIcon, @@ -14,19 +14,19 @@ import { AccountBox as CustomerIcon, Done as ShippedIcon, Publish as UploadIcon, -} from "@material-ui/icons"; -import { useTheme } from "@material-ui/styles"; -import classnames from "classnames"; -import tinycolor from "tinycolor2"; +} from '@material-ui/icons'; +import { useTheme } from '@material-ui/styles'; +import classnames from 'classnames'; +import tinycolor from 'tinycolor2'; // styles -import useStyles from "./styles"; +import useStyles from './styles'; // components -import { Typography } from "../Wrappers"; +import { Typography } from '../Wrappers'; const typesIcons = { - "e-commerce": <ShoppingCartIcon />, + 'e-commerce': <ShoppingCartIcon />, notification: <NotificationsIcon />, offer: <TicketIcon />, info: <ThumbUpIcon />, @@ -52,7 +52,7 @@ export default function Notification({ variant, ...props }) { }, style: { color: - variant !== "contained" && + variant !== 'contained' && theme.palette[props.color] && theme.palette[props.color].main, }, @@ -61,28 +61,26 @@ export default function Notification({ variant, ...props }) { return ( <div className={classnames(classes.notificationContainer, props.className, { - [classes.notificationContained]: variant === "contained", + [classes.notificationContained]: variant === 'contained', [classes.notificationContainedShadowless]: props.shadowless, })} style={{ backgroundColor: - variant === "contained" && + variant === 'contained' && theme.palette[props.color] && theme.palette[props.color].main, }} > <div className={classnames(classes.notificationIconContainer, { - [classes.notificationIconContainerContained]: variant === "contained", - [classes.notificationIconContainerRounded]: variant === "rounded", + [classes.notificationIconContainerContained]: variant === 'contained', + [classes.notificationIconContainerRounded]: variant === 'rounded', })} style={{ backgroundColor: - variant === "rounded" && + variant === 'rounded' && theme.palette[props.color] && - tinycolor(theme.palette[props.color].main) - .setAlpha(0.15) - .toRgbString(), + tinycolor(theme.palette[props.color].main).setAlpha(0.15).toRgbString(), }} > {iconWithStyles} @@ -90,10 +88,10 @@ export default function Notification({ variant, ...props }) { <div className={classes.messageContainer}> <Typography className={classnames({ - [classes.containedTypography]: variant === "contained", + [classes.containedTypography]: variant === 'contained', })} variant={props.typographyVariant} - size={variant !== "contained" && !props.typographyVariant && "md"} + size={variant !== 'contained' && !props.typographyVariant && 'md'} > {props.message} </Typography> @@ -112,6 +110,6 @@ export default function Notification({ variant, ...props }) { } // #################################################################### -function getIconByType(type = "offer") { +function getIconByType(type = 'offer') { return typesIcons[type]; } diff --git a/src/components/Notification/styles.js b/src/components/Notification/styles.js index fae990f..24a75ab 100644 --- a/src/components/Notification/styles.js +++ b/src/components/Notification/styles.js @@ -1,9 +1,9 @@ -import { makeStyles } from "@material-ui/styles"; +import { makeStyles } from '@material-ui/styles'; -export default makeStyles(theme => ({ +export default makeStyles((theme) => ({ notificationContainer: { - display: "flex", - alignItems: "center", + display: 'flex', + alignItems: 'center', }, notificationContained: { borderRadius: 45, @@ -11,37 +11,37 @@ export default makeStyles(theme => ({ boxShadow: theme.customShadows.widgetDark, }, notificationContainedShadowless: { - boxShadow: "none", + boxShadow: 'none', }, notificationIconContainer: { minWidth: 45, height: 45, borderRadius: 45, - display: "flex", - alignItems: "center", - justifyContent: "center", + display: 'flex', + alignItems: 'center', + justifyContent: 'center', fontSize: 24, }, notificationIconContainerContained: { fontSize: 18, - color: "#FFFFFF80", + color: '#FFFFFF80', }, notificationIconContainerRounded: { marginRight: theme.spacing(2), }, containedTypography: { - color: "white", + color: 'white', }, messageContainer: { - display: "flex", - alignItems: "center", - justifyContent: "space-between", + display: 'flex', + alignItems: 'center', + justifyContent: 'space-between', flexGrow: 1, }, extraButton: { - color: "white", - "&:hover, &:focus": { - background: "transparent", + color: 'white', + '&:hover, &:focus': { + background: 'transparent', }, }, })); diff --git a/src/components/PageTitle/PageTitle.js b/src/components/PageTitle/PageTitle.js index 61c6d52..e7be74c 100644 --- a/src/components/PageTitle/PageTitle.js +++ b/src/components/PageTitle/PageTitle.js @@ -1,11 +1,11 @@ -import React from "react"; -import { Button } from "@material-ui/core"; +import React from 'react'; +import { Button } from '@material-ui/core'; // styles -import useStyles from "./styles"; +import useStyles from './styles'; // components -import { Typography } from "../Wrappers"; +import { Typography } from '../Wrappers'; export default function PageTitle(props) { var classes = useStyles(); diff --git a/src/components/PageTitle/styles.js b/src/components/PageTitle/styles.js index cc6f3ee..2264225 100644 --- a/src/components/PageTitle/styles.js +++ b/src/components/PageTitle/styles.js @@ -1,9 +1,9 @@ -import { makeStyles } from "@material-ui/styles"; +import { makeStyles } from '@material-ui/styles'; -export default makeStyles(theme => ({ +export default makeStyles((theme) => ({ pageTitleContainer: { - display: "flex", - justifyContent: "space-between", + display: 'flex', + justifyContent: 'space-between', marginBottom: theme.spacing(4), marginTop: theme.spacing(5), }, @@ -12,8 +12,8 @@ export default makeStyles(theme => ({ }, button: { boxShadow: theme.customShadows.widget, - textTransform: "none", - "&:active": { + textTransform: 'none', + '&:active': { boxShadow: theme.customShadows.widgetWide, }, }, diff --git a/src/components/Sidebar/Sidebar.js b/src/components/Sidebar/Sidebar.js index 56bbe56..57d0303 100644 --- a/src/components/Sidebar/Sidebar.js +++ b/src/components/Sidebar/Sidebar.js @@ -1,64 +1,117 @@ -import React, { useState, useEffect } from "react"; -import { Drawer, IconButton, List } from "@material-ui/core"; +import React, { useState, useEffect } from 'react'; +import { Drawer, IconButton, List } from '@material-ui/core'; import { ArrowBack as ArrowBackIcon, People as UserIcon, GroupWork as GroupIcon, -} from "@material-ui/icons"; +} from '@material-ui/icons'; -import { EuiIcon } from '@elastic/eui' +import { EuiIcon } from '@elastic/eui'; -import { useTheme } from "@material-ui/styles"; -import { withRouter } from "react-router-dom"; -import classNames from "classnames"; +import { useTheme } from '@material-ui/styles'; +import { withRouter } from 'react-router-dom'; +import classNames from 'classnames'; // styles -import useStyles from "./styles"; +import useStyles from './styles'; // components -import SidebarLink from "./components/SidebarLink/SidebarLink"; - +import SidebarLink from './components/SidebarLink/SidebarLink'; // context import { useLayoutState, useLayoutDispatch, toggleSidebar, -} from "../../context/LayoutContext"; - +} from '../../context/LayoutContext'; function Sidebar({ location }) { var classes = useStyles(); var theme = useTheme(); const structures = [ - { id: 0, label: "Dashboard", link: "/app/dashboard", roles: [1], isAuthorized: true, icon: <EuiIcon type="dashboardApp" size="l" /> }, - { id: 1, label: "User", link: "/app/user", roles: [1], isAuthorized: true, icon: <EuiIcon type="user" size="l" /> }, - { id: 2, label: "Roles", link: "/app/role", roles: [1], isAuthorized: true, icon: <EuiIcon type="usersRolesApp" size="l" /> }, - { id: 3, label: "Groups", link: "/app/groups", roles: [1], isAuthorized: true, icon: <EuiIcon type="users" size="l" /> }, - { id: 4, label: "Requests", link: "/app/requests", roles: [1], isAuthorized: true, icon: <EuiIcon type="email" size="l" /> }, - { id: 5, label: "Policies", link: "/app/policies", roles: [1, 2], isAuthorized: true, icon: <EuiIcon type="lockOpen" size="l" /> }, - { id: 6, label: "Sources", link: "/app/sources", roles: [1, 2], isAuthorized: true, icon: <EuiIcon type="indexManagementApp" size="l" /> }, - { id: 7, label: "Fields", link: "/app/fields", roles: [1], isAuthorized: true, icon: <EuiIcon type="visTable" size="l" /> }, - { id: 8, type: "divider", roles: [0] } - ] - - let roleId = 0 - if (sessionStorage.getItem("roleId").split('#')[0]) { - roleId = sessionStorage.getItem("roleId").split('#')[0] + { + id: 0, + label: 'Dashboard', + link: '/app/dashboard', + roles: [1], + isAuthorized: true, + icon: <EuiIcon type="dashboardApp" size="l" />, + }, + { + id: 1, + label: 'User', + link: '/app/user', + roles: [1], + isAuthorized: true, + icon: <EuiIcon type="user" size="l" />, + }, + { + id: 2, + label: 'Roles', + link: '/app/role', + roles: [1], + isAuthorized: true, + icon: <EuiIcon type="usersRolesApp" size="l" />, + }, + { + id: 3, + label: 'Groups', + link: '/app/groups', + roles: [1], + isAuthorized: true, + icon: <EuiIcon type="users" size="l" />, + }, + { + id: 4, + label: 'Requests', + link: '/app/requests', + roles: [1], + isAuthorized: true, + icon: <EuiIcon type="email" size="l" />, + }, + { + id: 5, + label: 'Policies', + link: '/app/policies', + roles: [1, 2], + isAuthorized: true, + icon: <EuiIcon type="lockOpen" size="l" />, + }, + { + id: 6, + label: 'Sources', + link: '/app/sources', + roles: [1, 2], + isAuthorized: true, + icon: <EuiIcon type="indexManagementApp" size="l" />, + }, + { + id: 7, + label: 'Fields', + link: '/app/fields', + roles: [1], + isAuthorized: true, + icon: <EuiIcon type="visTable" size="l" />, + }, + { id: 8, type: 'divider', roles: [0] }, + ]; + + let roleId = 0; + if (sessionStorage.getItem('roleId').split('#')[0]) { + roleId = sessionStorage.getItem('roleId').split('#')[0]; } else { - roleId = sessionStorage.getItem("roleId") + roleId = sessionStorage.getItem('roleId'); } - const _structures = [] + const _structures = []; for (const structure of structures) { - if (structure.roles.some(e => e == roleId)) { - structure.isAuthorized = true - _structures.push(structure) + if (structure.roles.some((e) => e == roleId)) { + structure.isAuthorized = true; + _structures.push(structure); } } - // global var { isSidebarOpened } = useLayoutState(); var layoutDispatch = useLayoutDispatch(); @@ -67,16 +120,16 @@ function Sidebar({ location }) { var [isPermanent, setPermanent] = useState(true); useEffect(function () { - window.addEventListener("resize", handleWindowWidthChange); + window.addEventListener('resize', handleWindowWidthChange); handleWindowWidthChange(); return function cleanup() { - window.removeEventListener("resize", handleWindowWidthChange); + window.removeEventListener('resize', handleWindowWidthChange); }; }); return ( <Drawer - variant={isPermanent ? "permanent" : "temporary"} + variant={isPermanent ? 'permanent' : 'temporary'} className={classNames(classes.drawer, { [classes.drawerOpen]: isSidebarOpened, [classes.drawerClose]: !isSidebarOpened, @@ -87,7 +140,8 @@ function Sidebar({ location }) { [classes.drawerClose]: !isSidebarOpened, }), }} - open={isSidebarOpened}> + open={isSidebarOpened} + > <div className={classes.toolbar} /> <div className={classes.mobileBackButton}> <IconButton onClick={() => toggleSidebar(layoutDispatch)}> @@ -99,15 +153,17 @@ function Sidebar({ location }) { </IconButton> </div> <List className={classes.sidebarList}> - {_structures.map(link => ( - link.isAuthorized && - <SidebarLink - key={link.id} - location={location} - isSidebarOpened={isSidebarOpened} - {...link} - /> - ))} + {_structures.map( + (link) => + link.isAuthorized && ( + <SidebarLink + key={link.id} + location={location} + isSidebarOpened={isSidebarOpened} + {...link} + /> + ) + )} </List> </Drawer> ); diff --git a/src/components/Sidebar/SidebarView.js b/src/components/Sidebar/SidebarView.js index 691dba4..5a39146 100644 --- a/src/components/Sidebar/SidebarView.js +++ b/src/components/Sidebar/SidebarView.js @@ -1,9 +1,5 @@ import React from 'react'; -import { - Drawer, - IconButton, - List, - withStyles } from "@material-ui/core"; +import { Drawer, IconButton, List, withStyles } from '@material-ui/core'; import { Home as HomeIcon, NotificationsNone as NotificationsIcon, @@ -14,7 +10,7 @@ import { LibraryBooks as LibraryIcon, HelpOutline as FAQIcon, ArrowBack as ArrowBackIcon, -} from "@material-ui/icons"; +} from '@material-ui/icons'; import classNames from 'classnames'; import SidebarLink from './components/SidebarLink/SidebarLinkContainer'; @@ -24,7 +20,12 @@ const structure = [ { id: 0, label: 'Dashboard', link: '/app/dashboard', icon: <HomeIcon /> }, { id: 1, label: 'Typography', link: '/app/typography', icon: <TypographyIcon /> }, { id: 2, label: 'Tables', link: '/app/tables', icon: <TableIcon /> }, - { id: 3, label: 'Notifications', link: '/app/notifications', icon: <NotificationsIcon />}, + { + id: 3, + label: 'Notifications', + link: '/app/notifications', + icon: <NotificationsIcon />, + }, { id: 4, label: 'UI Elements', @@ -40,7 +41,7 @@ const structure = [ { id: 6, type: 'title', label: 'HELP' }, { id: 7, label: 'Library', link: '', icon: <LibraryIcon /> }, { id: 8, label: 'Support', link: '', icon: <SupportIcon /> }, - { id: 9, label: 'FAQ', link: '', icon: <FAQIcon />}, + { id: 9, label: 'FAQ', link: '', icon: <FAQIcon /> }, { id: 10, type: 'divider' }, { id: 11, type: 'title', label: 'PROJECTS' }, { id: 12, label: 'My recent', link: '', icon: <Dot size="large" color="secondary" /> }, @@ -48,7 +49,14 @@ const structure = [ { id: 14, label: 'Background', link: '', icon: <Dot size="large" color="secondary" /> }, ]; -const SidebarView = ({ classes, theme, toggleSidebar, isSidebarOpened, isPermanent, location }) => { +const SidebarView = ({ + classes, + theme, + toggleSidebar, + isSidebarOpened, + isPermanent, + location, +}) => { return ( <Drawer variant={isPermanent ? 'permanent' : 'temporary'} @@ -65,22 +73,29 @@ const SidebarView = ({ classes, theme, toggleSidebar, isSidebarOpened, isPermane open={isSidebarOpened} > <div className={classes.mobileBackButton}> - <IconButton - onClick={toggleSidebar} - > - <ArrowBackIcon classes={{ root: classNames(classes.headerIcon, classes.headerIconCollapse) }} /> + <IconButton onClick={toggleSidebar}> + <ArrowBackIcon + classes={{ root: classNames(classes.headerIcon, classes.headerIconCollapse) }} + /> </IconButton> </div> <List className={classes.sidebarList}> - {structure.map(link => <SidebarLink key={link.id} location={location} isSidebarOpened={isSidebarOpened} {...link} />)} + {structure.map((link) => ( + <SidebarLink + key={link.id} + location={location} + isSidebarOpened={isSidebarOpened} + {...link} + /> + ))} </List> </Drawer> ); -} +}; const drawerWidth = 240; -const styles = theme => ({ +const styles = (theme) => ({ menuButton: { marginLeft: 12, marginRight: 36, @@ -93,9 +108,9 @@ const styles = theme => ({ flexShrink: 0, whiteSpace: 'nowrap', top: theme.spacing.unit * 8, - [theme.breakpoints.down("sm")]: { + [theme.breakpoints.down('sm')]: { top: 0, - } + }, }, drawerOpen: { width: drawerWidth, @@ -111,30 +126,30 @@ const styles = theme => ({ }), overflowX: 'hidden', width: theme.spacing.unit * 7 + 40, - [theme.breakpoints.down("sm")]: { + [theme.breakpoints.down('sm')]: { width: drawerWidth, - } + }, }, toolbar: { ...theme.mixins.toolbar, - [theme.breakpoints.down("sm")]: { + [theme.breakpoints.down('sm')]: { display: 'none', - } + }, }, content: { flexGrow: 1, padding: theme.spacing.unit * 3, }, mobileBackButton: { - marginTop: theme.spacing.unit * .5, + marginTop: theme.spacing.unit * 0.5, marginLeft: theme.spacing.unit * 3, - [theme.breakpoints.only("sm")]: { - marginTop: theme.spacing.unit * .625, + [theme.breakpoints.only('sm')]: { + marginTop: theme.spacing.unit * 0.625, }, - [theme.breakpoints.up("md")]: { + [theme.breakpoints.up('md')]: { display: 'none', - } - } + }, + }, }); export default withStyles(styles, { withTheme: true })(SidebarView); diff --git a/src/components/Sidebar/components/Dot.js b/src/components/Sidebar/components/Dot.js index 478f100..73c154c 100644 --- a/src/components/Sidebar/components/Dot.js +++ b/src/components/Sidebar/components/Dot.js @@ -1,15 +1,15 @@ -import React from "react"; -import { makeStyles, useTheme } from "@material-ui/styles"; -import classnames from "classnames"; +import React from 'react'; +import { makeStyles, useTheme } from '@material-ui/styles'; +import classnames from 'classnames'; // styles -var useStyles = makeStyles(theme => ({ +var useStyles = makeStyles((theme) => ({ dotBase: { width: 5, height: 5, backgroundColor: theme.palette.text.hint, - borderRadius: "50%", - transition: theme.transitions.create("background-color"), + borderRadius: '50%', + transition: theme.transitions.create('background-color'), }, dotLarge: { width: 8, @@ -24,12 +24,11 @@ export default function Dot({ size, color }) { return ( <div className={classnames(classes.dotBase, { - [classes.dotLarge]: size === "large", - [classes.dotSmall]: size === "small", + [classes.dotLarge]: size === 'large', + [classes.dotSmall]: size === 'small', })} style={{ - backgroundColor: - color && theme.palette[color] && theme.palette[color].main, + backgroundColor: color && theme.palette[color] && theme.palette[color].main, }} /> ); diff --git a/src/components/Sidebar/components/SidebarLink/SidebarLink.js b/src/components/Sidebar/components/SidebarLink/SidebarLink.js index 2676171..c8c9d6c 100644 --- a/src/components/Sidebar/components/SidebarLink/SidebarLink.js +++ b/src/components/Sidebar/components/SidebarLink/SidebarLink.js @@ -1,4 +1,4 @@ -import React, { useState } from "react"; +import React, { useState } from 'react'; import { Collapse, Divider, @@ -7,16 +7,16 @@ import { ListItemIcon, ListItemText, Typography, -} from "@material-ui/core"; -import { Inbox as InboxIcon } from "@material-ui/icons"; -import { Link } from "react-router-dom"; -import classnames from "classnames"; +} from '@material-ui/core'; +import { Inbox as InboxIcon } from '@material-ui/icons'; +import { Link } from 'react-router-dom'; +import classnames from 'classnames'; // styles -import useStyles from "./styles"; +import useStyles from './styles'; // components -import Dot from "../Dot"; +import Dot from '../Dot'; export default function SidebarLink({ link, @@ -33,10 +33,9 @@ export default function SidebarLink({ // local var [isOpen, setIsOpen] = useState(false); var isLinkActive = - link && - (location.pathname === link || location.pathname.indexOf(link) !== -1); + link && (location.pathname === link || location.pathname.indexOf(link) !== -1); - if (type === "title") + if (type === 'title') return ( <Typography className={classnames(classes.linkText, classes.sectionTitle, { @@ -47,7 +46,7 @@ export default function SidebarLink({ </Typography> ); - if (type === "divider") return <Divider className={classes.divider} />; + if (type === 'divider') return <Divider className={classes.divider} />; if (!children) return ( @@ -69,7 +68,7 @@ export default function SidebarLink({ [classes.linkIconActive]: isLinkActive, })} > - {nested ? <Dot color={isLinkActive && "primary"} /> : icon} + {nested ? <Dot color={isLinkActive && 'primary'} /> : icon} </ListItemIcon> <ListItemText classes={{ @@ -118,7 +117,7 @@ export default function SidebarLink({ className={classes.nestedList} > <List component="div" disablePadding> - {children.map(childrenLink => ( + {children.map((childrenLink) => ( <SidebarLink key={childrenLink && childrenLink.link} location={location} diff --git a/src/components/Sidebar/components/SidebarLink/styles.js b/src/components/Sidebar/components/SidebarLink/styles.js index a18c62d..1355dd2 100644 --- a/src/components/Sidebar/components/SidebarLink/styles.js +++ b/src/components/Sidebar/components/SidebarLink/styles.js @@ -1,9 +1,9 @@ -import { makeStyles } from "@material-ui/styles"; +import { makeStyles } from '@material-ui/styles'; -export default makeStyles(theme => ({ +export default makeStyles((theme) => ({ link: { - textDecoration: "none", - "&:hover, &:focus": { + textDecoration: 'none', + '&:hover, &:focus': { backgroundColor: theme.palette.background.light, }, }, @@ -12,25 +12,25 @@ export default makeStyles(theme => ({ }, linkNested: { paddingLeft: 0, - "&:hover, &:focus": { - backgroundColor: "#FFFFFF", + '&:hover, &:focus': { + backgroundColor: '#FFFFFF', }, }, linkIcon: { marginRight: theme.spacing(1), - color: theme.palette.text.secondary + "99", - transition: theme.transitions.create("color"), + color: theme.palette.text.secondary + '99', + transition: theme.transitions.create('color'), width: 24, - display: "flex", - justifyContent: "center", + display: 'flex', + justifyContent: 'center', }, linkIconActive: { color: theme.palette.primary.main, }, linkText: { padding: 0, - color: theme.palette.text.secondary + "CC", - transition: theme.transitions.create(["opacity", "color"]), + color: theme.palette.text.secondary + 'CC', + transition: theme.transitions.create(['opacity', 'color']), fontSize: 16, }, linkTextActive: { @@ -51,6 +51,6 @@ export default makeStyles(theme => ({ marginTop: theme.spacing(2), marginBottom: theme.spacing(4), height: 1, - backgroundColor: "#D8D8D880", + backgroundColor: '#D8D8D880', }, })); diff --git a/src/components/Sidebar/styles.js b/src/components/Sidebar/styles.js index 22b2f25..f74ee96 100644 --- a/src/components/Sidebar/styles.js +++ b/src/components/Sidebar/styles.js @@ -1,42 +1,42 @@ -import { makeStyles } from "@material-ui/styles"; +import { makeStyles } from '@material-ui/styles'; const drawerWidth = 240; -export default makeStyles(theme => ({ +export default makeStyles((theme) => ({ menuButton: { marginLeft: 12, marginRight: 36, }, hide: { - display: "none", + display: 'none', }, drawer: { width: drawerWidth, flexShrink: 0, - whiteSpace: "nowrap", + whiteSpace: 'nowrap', }, drawerOpen: { width: drawerWidth, - transition: theme.transitions.create("width", { + transition: theme.transitions.create('width', { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.enteringScreen, }), }, drawerClose: { - transition: theme.transitions.create("width", { + transition: theme.transitions.create('width', { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.leavingScreen, }), - overflowX: "hidden", + overflowX: 'hidden', width: theme.spacing(7) + 40, - [theme.breakpoints.down("sm")]: { + [theme.breakpoints.down('sm')]: { width: drawerWidth, }, }, toolbar: { ...theme.mixins.toolbar, - [theme.breakpoints.down("sm")]: { - display: "none", + [theme.breakpoints.down('sm')]: { + display: 'none', }, }, content: { @@ -49,11 +49,11 @@ export default makeStyles(theme => ({ mobileBackButton: { marginTop: theme.spacing(0.5), marginLeft: theme.spacing(3), - [theme.breakpoints.only("sm")]: { + [theme.breakpoints.only('sm')]: { marginTop: theme.spacing(0.625), }, - [theme.breakpoints.up("md")]: { - display: "none", + [theme.breakpoints.up('md')]: { + display: 'none', }, }, })); diff --git a/src/components/UserAvatar/UserAvatar.js b/src/components/UserAvatar/UserAvatar.js index 68803c4..6394591 100644 --- a/src/components/UserAvatar/UserAvatar.js +++ b/src/components/UserAvatar/UserAvatar.js @@ -1,20 +1,20 @@ -import React from "react"; -import { useTheme } from "@material-ui/styles"; +import React from 'react'; +import { useTheme } from '@material-ui/styles'; // styles -import useStyles from "./styles"; +import useStyles from './styles'; // components -import { Typography } from "../Wrappers"; +import { Typography } from '../Wrappers'; -export default function UserAvatar({ color = "primary", ...props }) { +export default function UserAvatar({ color = 'primary', ...props }) { var classes = useStyles(); var theme = useTheme(); var letters = props.name - .split(" ") - .map(word => word[0]) - .join(""); + .split(' ') + .map((word) => word[0]) + .join(''); return ( <div diff --git a/src/components/UserAvatar/styles.js b/src/components/UserAvatar/styles.js index eebb39e..f507e14 100644 --- a/src/components/UserAvatar/styles.js +++ b/src/components/UserAvatar/styles.js @@ -1,15 +1,15 @@ -import { makeStyles } from "@material-ui/styles"; +import { makeStyles } from '@material-ui/styles'; export default makeStyles(() => ({ avatar: { width: 30, height: 30, - display: "flex", - alignItems: "center", - justifyContent: "center", - borderRadius: "50%", + display: 'flex', + alignItems: 'center', + justifyContent: 'center', + borderRadius: '50%', }, text: { - color: "white", + color: 'white', }, })); diff --git a/src/components/Widget/Widget.js b/src/components/Widget/Widget.js index 9685065..4aa1b3d 100644 --- a/src/components/Widget/Widget.js +++ b/src/components/Widget/Widget.js @@ -1,16 +1,10 @@ -import React, { useState } from "react"; -import { - Paper, - IconButton, - Menu, - MenuItem, - Typography, -} from "@material-ui/core"; -import { MoreVert as MoreIcon } from "@material-ui/icons"; -import classnames from "classnames"; +import React, { useState } from 'react'; +import { Paper, IconButton, Menu, MenuItem, Typography } from '@material-ui/core'; +import { MoreVert as MoreIcon } from '@material-ui/icons'; +import classnames from 'classnames'; // styles -import useStyles from "./styles"; +import useStyles from './styles'; export default function Widget({ children, diff --git a/src/components/Widget/WidgetView.js b/src/components/Widget/WidgetView.js index e7f1e21..6e39dce 100644 --- a/src/components/Widget/WidgetView.js +++ b/src/components/Widget/WidgetView.js @@ -1,14 +1,8 @@ -import React from "react"; -import classnames from "classnames"; -import { - Paper, - IconButton, - Menu, - MenuItem, - withStyles -} from "@material-ui/core"; -import { MoreVert as MoreIcon } from "@material-ui/icons"; -import Typography from "@material-ui/core/es/Typography/Typography"; +import React from 'react'; +import classnames from 'classnames'; +import { Paper, IconButton, Menu, MenuItem, withStyles } from '@material-ui/core'; +import { MoreVert as MoreIcon } from '@material-ui/icons'; +import Typography from '@material-ui/core/es/Typography/Typography'; const Widget = ({ classes, @@ -48,7 +42,7 @@ const Widget = ({ <div className={classnames(classes.widgetBody, { [classes.noPadding]: noBodyPadding, - [bodyClass]: bodyClass + [bodyClass]: bodyClass, })} > {children} @@ -77,34 +71,34 @@ const Widget = ({ </div> ); -const styles = theme => ({ +const styles = (theme) => ({ widgetWrapper: { - display: "flex", - minHeight: "100%" + display: 'flex', + minHeight: '100%', }, widgetHeader: { padding: theme.spacing.unit * 3, paddingBottom: theme.spacing.unit, - display: "flex", - justifyContent: "space-between", - alignItems: "center" + display: 'flex', + justifyContent: 'space-between', + alignItems: 'center', }, widgetRoot: { - boxShadow: theme.customShadows.widget + boxShadow: theme.customShadows.widget, }, widgetBody: { paddingBottom: theme.spacing.unit * 3, paddingRight: theme.spacing.unit * 3, - paddingLeft: theme.spacing.unit * 3 + paddingLeft: theme.spacing.unit * 3, }, noPadding: { - padding: 0 + padding: 0, }, paper: { - display: "flex", - flexDirection: "column", + display: 'flex', + flexDirection: 'column', flexGrow: 1, - overflow: "hidden" + overflow: 'hidden', }, moreButton: { margin: -theme.spacing.unit, @@ -112,11 +106,11 @@ const styles = theme => ({ width: 40, height: 40, color: theme.palette.text.hint, - "&:hover": { + '&:hover': { backgroundColor: theme.palette.primary.main, - color: "rgba(255, 255, 255, 0.35)" - } - } + color: 'rgba(255, 255, 255, 0.35)', + }, + }, }); export default withStyles(styles, { withTheme: true })(Widget); diff --git a/src/components/Widget/styles.js b/src/components/Widget/styles.js index f2d64da..a025742 100644 --- a/src/components/Widget/styles.js +++ b/src/components/Widget/styles.js @@ -1,16 +1,16 @@ -import { makeStyles } from "@material-ui/styles"; +import { makeStyles } from '@material-ui/styles'; -export default makeStyles(theme => ({ +export default makeStyles((theme) => ({ widgetWrapper: { - display: "flex", - minHeight: "100%", + display: 'flex', + minHeight: '100%', }, widgetHeader: { padding: theme.spacing(3), paddingBottom: theme.spacing(1), - display: "flex", - justifyContent: "space-between", - alignItems: "center", + display: 'flex', + justifyContent: 'space-between', + alignItems: 'center', }, widgetRoot: { boxShadow: theme.customShadows.widget, @@ -24,10 +24,10 @@ export default makeStyles(theme => ({ padding: 0, }, paper: { - display: "flex", - flexDirection: "column", + display: 'flex', + flexDirection: 'column', flexGrow: 1, - overflow: "hidden", + overflow: 'hidden', }, moreButton: { margin: -theme.spacing(1), @@ -35,9 +35,9 @@ export default makeStyles(theme => ({ width: 40, height: 40, color: theme.palette.text.hint, - "&:hover": { + '&:hover': { backgroundColor: theme.palette.primary.main, - color: "rgba(255, 255, 255, 0.35)", + color: 'rgba(255, 255, 255, 0.35)', }, }, })); diff --git a/src/components/Wrappers/Wrappers.js b/src/components/Wrappers/Wrappers.js index b67958e..e1ea9bb 100644 --- a/src/components/Wrappers/Wrappers.js +++ b/src/components/Wrappers/Wrappers.js @@ -1,15 +1,15 @@ -import React from "react"; +import React from 'react'; import { withStyles, Badge as BadgeBase, Typography as TypographyBase, Button as ButtonBase, -} from "@material-ui/core"; -import { useTheme, makeStyles } from "@material-ui/styles"; -import classnames from "classnames"; +} from '@material-ui/core'; +import { useTheme, makeStyles } from '@material-ui/styles'; +import classnames from 'classnames'; // styles -var useStyles = makeStyles(theme => ({ +var useStyles = makeStyles((theme) => ({ badge: { fontWeight: 600, height: 16, @@ -28,7 +28,7 @@ function Badge({ children, colorBrightness, color, ...props }) { return ( <Styled> - {styledProps => ( + {(styledProps) => ( <BadgeBase classes={{ badge: classnames(classes.badge, styledProps.classes.badge), @@ -42,14 +42,7 @@ function Badge({ children, colorBrightness, color, ...props }) { ); } -function Typography({ - children, - weight, - size, - colorBrightness, - color, - ...props -}) { +function Typography({ children, weight, size, colorBrightness, color, ...props }) { var theme = useTheme(); return ( @@ -73,9 +66,9 @@ function Button({ children, color, ...props }) { button: { backgroundColor: getColor(color, theme), boxShadow: theme.customShadows.widget, - color: "white", - "&:hover": { - backgroundColor: getColor(color, theme, "light"), + color: 'white', + '&:hover': { + backgroundColor: getColor(color, theme, 'light'), boxShadow: theme.customShadows.widgetWide, }, }, @@ -96,7 +89,7 @@ export { Badge, Typography, Button }; // ######################################################################## -function getColor(color, theme, brigtness = "main") { +function getColor(color, theme, brigtness = 'main') { if (color && theme.palette[color] && theme.palette[color][brigtness]) { return theme.palette[color][brigtness]; } @@ -104,31 +97,31 @@ function getColor(color, theme, brigtness = "main") { function getFontWeight(style) { switch (style) { - case "light": + case 'light': return 300; - case "medium": + case 'medium': return 500; - case "bold": + case 'bold': return 600; default: return 400; } } -function getFontSize(size, variant = "", theme) { +function getFontSize(size, variant = '', theme) { var multiplier; switch (size) { - case "sm": + case 'sm': multiplier = 0.8; break; - case "md": + case 'md': multiplier = 1.5; break; - case "xl": + case 'xl': multiplier = 2; break; - case "xxl": + case 'xxl': multiplier = 3; break; default: @@ -139,13 +132,13 @@ function getFontSize(size, variant = "", theme) { var defaultSize = variant && theme.typography[variant] ? theme.typography[variant].fontSize - : theme.typography.fontSize + "px"; + : theme.typography.fontSize + 'px'; return `calc(${defaultSize} * ${multiplier})`; } function createStyled(styles, options) { - var Styled = function(props) { + var Styled = function (props) { const { children, ...other } = props; return children(other); }; diff --git a/src/components/Wrappers/package.json b/src/components/Wrappers/package.json index 77de703..d4fef7d 100644 --- a/src/components/Wrappers/package.json +++ b/src/components/Wrappers/package.json @@ -4,4 +4,3 @@ "private": true, "main": "Wrappers.js" } - \ No newline at end of file diff --git a/src/context/InSylvaGatekeeperClient.js b/src/context/InSylvaGatekeeperClient.js index 701210a..2601b71 100644 --- a/src/context/InSylvaGatekeeperClient.js +++ b/src/context/InSylvaGatekeeperClient.js @@ -1,371 +1,359 @@ class InSylvaGatekeeperClient { - - async post(method, path, requestContent) { - - const headers = { - "Content-Type": "application/json", - "Access-Control-Allow-Origin": "*", - "Authorization": `Bearer ${this.token}` + async post(method, path, requestContent) { + const headers = { + 'Content-Type': 'application/json', + 'Access-Control-Allow-Origin': '*', + Authorization: `Bearer ${this.token}`, + }; + + const response = await fetch(`${this.baseUrl}${path}`, { + method: method, + headers, + body: JSON.stringify(requestContent), + mode: 'cors', + }); + + const responseContent = await response.json(); + + return responseContent; + } + + async createUser({ username, email, password, roleId }) { + const path = `/user`; + const user = await this.post('POST', `${path}`, { + username, + email, + password, + roleId, + }); + + return user; + } + + async kcId({ email }) { + const path = `/user/kcid`; + + const kcId = await this.post('POST', `${path}`, { + email, + }); + + return kcId; + } + + async updateUser({ id, firstName, lastName }) { + const path = `/user/update`; + const user = await this.post('PUT', `${path}`, { + id, + firstName, + lastName, + }); + + return user; + } + + async findUser() { + const path = `/user/find`; + const users = await this.post('GET', `${path}`); + return users; + } + + async findOneUser(id) { + const path = `/user/findOne`; + const user = await this.post('POST', `${path}`, { + id, + }); + return user; + } + + async deleteUser({ id }) { + const path = `/user/delete`; + const user = await this.post('DELETE', `${path}`, { + userId: id, + }); + return user; + } + + async getRequests() { + const path = `/user/list-requests`; + const requests = await this.post('GET', `${path}`); + return requests; + } + + async getPendingRequests() { + const path = `/user/list-pending-requests`; + const pendingRequests = await this.post('GET', `${path}`); + return pendingRequests; + } + + async processUserRequest(id) { + const path = `/user/process-request`; + const userRequests = await this.post('POST', `${path}`, { + id, + }); + return userRequests; + } + + async deleteUserRequest(id) { + console.log('client'); + const path = `/user/delete-request`; + const userRequests = await this.post('DELETE', `${path}`, { + id, + }); + } + + async createRole({ name, description }) { + const path = `/role`; + const role = await this.post('POST', `${path}`, { + name, + description, + }); + return role; + } + + async findRole() { + const path = `/role/find`; + const roles = await this.post('GET', `${path}`); + return roles; + } + + async allocateRoles({ roles, users }) { + try { + const path = `/allocate-role-to-user`; + for (let x = 0; x < users.length; x++) { + for (let y = 0; y < roles.length; y++) { + await this.post('POST', `${path}`, { + kc_id: users[x], + role_id: roles[y], + }); } - - const response = await fetch(`${this.baseUrl}${path}`, { - method: method, - headers, - body: JSON.stringify(requestContent), - mode: 'cors' - }); - - const responseContent = await response.json(); - - return responseContent; - } - - async createUser({ - username, - email, - password, - roleId - }) { - const path = `/user`; - const user = await this.post('POST', `${path}`, { - username, - email, - password, - roleId - }); - - return user; - } - - async kcId({ email }) { - - const path = `/user/kcid`; - - const kcId = await this.post('POST', `${path}`, { - email - }); - - return kcId; - } - - async updateUser({ - id, - firstName, - lastName - }) { - const path = `/user/update`; - const user = await this.post('PUT', `${path}`, { - id, - firstName, - lastName - }); - - return user; - } - - async findUser() { - const path = `/user/find`; - const users = await this.post('GET', `${path}`); - return users; - } - - async findOneUser(id) { - const path = `/user/findOne`; - const user = await this.post('POST', `${path}`, { - id, - }); - return user; - } - - async deleteUser({ id }) { - const path = `/user/delete`; - const user = await this.post('DELETE', `${path}`, { - userId: id, - }); - return user; - } - - async getRequests() { - const path = `/user/list-requests`; - const requests = await this.post('GET', `${path}`); - return requests; - } - - async getPendingRequests() { - const path = `/user/list-pending-requests`; - const pendingRequests = await this.post('GET', `${path}`); - return pendingRequests; - } - - async processUserRequest(id) { - const path = `/user/process-request`; - const userRequests = await this.post('POST', `${path}`, { - id - }); - return userRequests; - } - - async deleteUserRequest(id) { - console.log("client") - const path = `/user/delete-request`; - const userRequests = await this.post('DELETE', `${path}`, { - id - }); - } - - async createRole({ - name, - description }) { - - const path = `/role`; - const role = await this.post('POST', `${path}`, { - name, - description - }); - return role; - } - - async findRole() { - const path = `/role/find`; - const roles = await this.post('GET', `${path}`); - return roles; - } - - async allocateRoles({ roles, users }) { - try { - const path = `/allocate-role-to-user` - for (let x = 0; x < users.length; x++) { - for (let y = 0; y < roles.length; y++) { - await this.post('POST', `${path}`, { - kc_id: users[x], - role_id: roles[y] - }) - } - } - return true; - - } catch (error) { - return false - } - } - - async allocateRolesToUser({ userId, roleId }) { - const path = `/allocate-role-to-user` - const result = await this.post('POST', `${path}`, { - kc_id: userId, - role_id: roleId - }) - - return result - } - async allocatedRoles(kc_id) { - const path = `/allocatedRoles` - const allocatedRoles = await this.post('POST', `${path}`, { - kc_id - }) - return allocatedRoles; - } - - async createPolicy({ name, sourceId, kcId }) { - const path = `/policy/add` - const policy = await this.post('POST', `${path}`, { - name, - // sourceId, - kcId - }) - return policy - } - - async createPolicyField({ policyId, stdFieldId }) { - const path = `/policyField/add` - const policyField = await this.post('POST', `${path}`, { - policyId, - stdFieldId - }) - return policyField - } - - async updatePolicy({ id, name, sourceId, isDeafault }) { - const path = `/policy/update` - const policy = await this.post('PUT', `${path}`, { - id, name, sourceId, isDeafault - }) - return policy - } - - async updatePolicyField({ id, policyId, stdFieldId }) { - const path = `/policyField/update` - const policyField = this.post('PUT', `${path}`, { - id, policyId, stdFieldId - }) - return policyField - } - - async deletePolicyField({ id }) { - const path = `/policyField/delete` - const policyField = await this.post('DELETE', `${path}`, { - id - }) - return policyField - } - - async deletePolicy({ id }) { - const path = `/policy/delete` - const policy = await this.post('DELETE', `${path}`, { - id - }) - return policy - } - - async getPolicies() { - const path = `/policy/list` - const policies = await this.post('GET', `${path}`) - return policies - } - - async getPoliciesByUser(kcId) { - const path = `/policy/list-by-user` - const group = await this.post('POST', `${path}`, { kcId }) - return group - } - - async getPoliciesWithSourcesByUser(kcId) { - const path = `/policy/policies-with-sources-by-user` - const group = await this.post('POST', `${path}`, { kcId }) - return group - } - - async getPoliciesWithSources() { - const path = `/policy/policies-with-sources` - const policiesWithSource = await this.post('GET', `${path}`) - return policiesWithSource - } - - async getPolicyFields() { - const path = `/policyField/list` - const policyFields = await this.post('GET', `${path}`, {}) - return policyFields - } - - async getGroups() { - const path = `/user/groups` - const groups = await this.post('POST', `${path}`, {}) - return groups - } - - async getGroupPolicies() { - const path = `/user/group-policies` - const groupsPolicies = await this.post('GET', `${path}`, {}) - return groupsPolicies - } - - async getGroupUsers({ groupId }) { - const path = `/user/group-users` - const groupUsers = await this.post('POST', `${path}`, { groupId }) - return groupUsers - } - - async createGroup({ name, description, kcId }) { - const path = `/user/add-group` - const group = await this.post('POST', `${path}`, { name, description, kcId }) - return group - } - - async createGroupPolicy({ groupId, policyId }) { - const path = `/user/add-group-policy` - const groupPolicy = await this.post('POST', `${path}`, { groupId, policyId }) - return groupPolicy - } - - async createGroupUser({ groupId, kcId }) { - const path = `/user/add-group-user` - const groupUser = await this.post('POST', `${path}`, { groupId, kcId }) - return groupUser - } - - async updateGroup({ id, userId, name, description }) { - const path = `/user/update-group` - const group = await this.post('PUT', `${path}`, { name, description, id, userId }) - return group - } - - async updateGroupPolicy({ id, groupId, policyId }) { - const path = `/user/update-group-policy` - const groupPolicy = await this.post('PUT', `${path}`, { id, groupId, policyId }) - return groupPolicy - } - - async updateGroupUser({ id, kcId, groupId }) { - const path = `/user/update-group-user` - const groupUser = await this.post('PUT', `${path}`, { id, kcId, groupId }) - return groupUser - } - - async deleteGroup({ id }) { - const path = `/user/delete-group` - const group = await this.post('DELETE', `${path}`, { id }) - return group - } - - async deleteGroupPolicy({ id }) { - const path = `/user/delete-group-policy` - const groupPolicy = await this.post('DELETE', `${path}`, { id }) - return groupPolicy - } - - async deleteGroupUser({ groupId, userId }) { - const path = `/user/delete-group-user` - const groupUser = await this.post('DELETE', `${path}`, { groupId, userId }) - return groupUser - } - - async getAssignedPolicies({ policyId }) { - - const path = `/policy/assigned-fields` - const assignedPolicies = await this.post('POST', `${path}`, { policyId }) - return assignedPolicies - } - - async deleteRole({ id }) { - const path = `/role/delete` - const role = await this.post('DELETE', `${path}`, { id }) - return role - } - - async getAssignedUserByRole({ id }) { - const path = `/user/assigned-by-role` - const assignedUserByRole = await this.post('POST', `${path}`, { id }) - return assignedUserByRole - } - - async getGroupDetailsByPolicy({ policyId }) { - const path = `/policy/policies-with-groups` - const groupDetailsByPolicy = await this.post('POST', `${path}`, { policyId }) - return groupDetailsByPolicy - } - - async usersWithGroupAndRole() { - const path = `/user/with-groups-and-roles` - const usersWithGroupAndRole = await this.post('GET', `${path}`) - return usersWithGroupAndRole - } - - async findOneUserWithGroupAndRole(id) { - const path = `/user/one-with-groups-and-roles`; - const user = await this.post('POST', `${path}`, { - id, - }); - return user; - } - - async createPolicySource({ policyId, sourceId }) { - const path = `/policySource/add` - const policySource = await this.post('POST', `${path}`, { policyId, sourceId }) - return policySource - } + } + return true; + } catch (error) { + return false; + } + } + + async allocateRolesToUser({ userId, roleId }) { + const path = `/allocate-role-to-user`; + const result = await this.post('POST', `${path}`, { + kc_id: userId, + role_id: roleId, + }); + + return result; + } + async allocatedRoles(kc_id) { + const path = `/allocatedRoles`; + const allocatedRoles = await this.post('POST', `${path}`, { + kc_id, + }); + return allocatedRoles; + } + + async createPolicy({ name, sourceId, kcId }) { + const path = `/policy/add`; + const policy = await this.post('POST', `${path}`, { + name, + // sourceId, + kcId, + }); + return policy; + } + + async createPolicyField({ policyId, stdFieldId }) { + const path = `/policyField/add`; + const policyField = await this.post('POST', `${path}`, { + policyId, + stdFieldId, + }); + return policyField; + } + + async updatePolicy({ id, name, sourceId, isDeafault }) { + const path = `/policy/update`; + const policy = await this.post('PUT', `${path}`, { + id, + name, + sourceId, + isDeafault, + }); + return policy; + } + + async updatePolicyField({ id, policyId, stdFieldId }) { + const path = `/policyField/update`; + const policyField = this.post('PUT', `${path}`, { + id, + policyId, + stdFieldId, + }); + return policyField; + } + + async deletePolicyField({ id }) { + const path = `/policyField/delete`; + const policyField = await this.post('DELETE', `${path}`, { + id, + }); + return policyField; + } + + async deletePolicy({ id }) { + const path = `/policy/delete`; + const policy = await this.post('DELETE', `${path}`, { + id, + }); + return policy; + } + + async getPolicies() { + const path = `/policy/list`; + const policies = await this.post('GET', `${path}`); + return policies; + } + + async getPoliciesByUser(kcId) { + const path = `/policy/list-by-user`; + const group = await this.post('POST', `${path}`, { kcId }); + return group; + } + + async getPoliciesWithSourcesByUser(kcId) { + const path = `/policy/policies-with-sources-by-user`; + const group = await this.post('POST', `${path}`, { kcId }); + return group; + } + + async getPoliciesWithSources() { + const path = `/policy/policies-with-sources`; + const policiesWithSource = await this.post('GET', `${path}`); + return policiesWithSource; + } + + async getPolicyFields() { + const path = `/policyField/list`; + const policyFields = await this.post('GET', `${path}`, {}); + return policyFields; + } + + async getGroups() { + const path = `/user/groups`; + const groups = await this.post('POST', `${path}`, {}); + return groups; + } + + async getGroupPolicies() { + const path = `/user/group-policies`; + const groupsPolicies = await this.post('GET', `${path}`, {}); + return groupsPolicies; + } + + async getGroupUsers({ groupId }) { + const path = `/user/group-users`; + const groupUsers = await this.post('POST', `${path}`, { groupId }); + return groupUsers; + } + + async createGroup({ name, description, kcId }) { + const path = `/user/add-group`; + const group = await this.post('POST', `${path}`, { name, description, kcId }); + return group; + } + + async createGroupPolicy({ groupId, policyId }) { + const path = `/user/add-group-policy`; + const groupPolicy = await this.post('POST', `${path}`, { groupId, policyId }); + return groupPolicy; + } + + async createGroupUser({ groupId, kcId }) { + const path = `/user/add-group-user`; + const groupUser = await this.post('POST', `${path}`, { groupId, kcId }); + return groupUser; + } + + async updateGroup({ id, userId, name, description }) { + const path = `/user/update-group`; + const group = await this.post('PUT', `${path}`, { name, description, id, userId }); + return group; + } + + async updateGroupPolicy({ id, groupId, policyId }) { + const path = `/user/update-group-policy`; + const groupPolicy = await this.post('PUT', `${path}`, { id, groupId, policyId }); + return groupPolicy; + } + + async updateGroupUser({ id, kcId, groupId }) { + const path = `/user/update-group-user`; + const groupUser = await this.post('PUT', `${path}`, { id, kcId, groupId }); + return groupUser; + } + + async deleteGroup({ id }) { + const path = `/user/delete-group`; + const group = await this.post('DELETE', `${path}`, { id }); + return group; + } + + async deleteGroupPolicy({ id }) { + const path = `/user/delete-group-policy`; + const groupPolicy = await this.post('DELETE', `${path}`, { id }); + return groupPolicy; + } + + async deleteGroupUser({ groupId, userId }) { + const path = `/user/delete-group-user`; + const groupUser = await this.post('DELETE', `${path}`, { groupId, userId }); + return groupUser; + } + + async getAssignedPolicies({ policyId }) { + const path = `/policy/assigned-fields`; + const assignedPolicies = await this.post('POST', `${path}`, { policyId }); + return assignedPolicies; + } + + async deleteRole({ id }) { + const path = `/role/delete`; + const role = await this.post('DELETE', `${path}`, { id }); + return role; + } + + async getAssignedUserByRole({ id }) { + const path = `/user/assigned-by-role`; + const assignedUserByRole = await this.post('POST', `${path}`, { id }); + return assignedUserByRole; + } + + async getGroupDetailsByPolicy({ policyId }) { + const path = `/policy/policies-with-groups`; + const groupDetailsByPolicy = await this.post('POST', `${path}`, { policyId }); + return groupDetailsByPolicy; + } + + async usersWithGroupAndRole() { + const path = `/user/with-groups-and-roles`; + const usersWithGroupAndRole = await this.post('GET', `${path}`); + return usersWithGroupAndRole; + } + + async findOneUserWithGroupAndRole(id) { + const path = `/user/one-with-groups-and-roles`; + const user = await this.post('POST', `${path}`, { + id, + }); + return user; + } + + async createPolicySource({ policyId, sourceId }) { + const path = `/policySource/add`; + const policySource = await this.post('POST', `${path}`, { policyId, sourceId }); + return policySource; + } } InSylvaGatekeeperClient.prototype.baseUrl = null; InSylvaGatekeeperClient.prototype.token = null; -export { InSylvaGatekeeperClient } \ No newline at end of file +export { InSylvaGatekeeperClient }; diff --git a/src/context/InSylvaSourceManager.js b/src/context/InSylvaSourceManager.js index 97c8200..b817c6c 100644 --- a/src/context/InSylvaSourceManager.js +++ b/src/context/InSylvaSourceManager.js @@ -1,110 +1,172 @@ class InSylvaSourceManager { - - async post(method, path, requestContent) { - - const headers = { - "Content-Type": "application/json", - "Access-Control-Allow-Origin": "*", - "Authorization": `Bearer ${this.token}` - } - - const response = await fetch(`${this.baseUrl}${path}`, { - method: method, - headers, - body: JSON.stringify(requestContent), - mode: 'cors' - }); - - const responseContent = await response.json(); - - return responseContent; - } - - async createSource(metaUrfms, name, description, kc_id) { - const path = `/source` - const result = await this.post('POST', `${path}`, { metaUrfms, name, description, kc_id }); - return result + async post(method, path, requestContent) { + const headers = { + 'Content-Type': 'application/json', + 'Access-Control-Allow-Origin': '*', + Authorization: `Bearer ${this.token}`, }; - async sources(kc_id) { - const path = '/sources' - const result = await this.post('POST', `${path}`, { kc_id }); - return result - } - - async indexedSources(kc_id) { - const path = '/indexed-sources' - const result = await this.post('POST', `${path}`, { kc_id }); - return result - } - - async allSource() { - const path = '/allSource' - const result = await this.post('GET', `${path}`); - return result - } - - async allIndexedSource() { - const path = '/allIndexedSource' - const result = await this.post('GET', `${path}`); - return result - } - - async addStdField(category, field_name, definition_and_comment, obligation_or_condition, field_type, cardinality, values, ispublic, isoptional) { - const path = `/addStdField` - const result = await this.post('POST', `${path}`, { category, field_name, definition_and_comment, obligation_or_condition, field_type, cardinality, values, ispublic, isoptional }) - return result - } - - async addAddtlField(category, field_name, definition_and_comment, obligation_or_condition, field_type, cardinality, values, ispublic, isoptional) { - const path = `/addAddtlField` - const result = await this.post('POST', `${path}`, { category, field_name, definition_and_comment, obligation_or_condition, field_type, cardinality, values, ispublic, isoptional }) - return result - } - - async updateStdField(category, field_name, definition_and_comment, obligation_or_condition, field_type, cardinality, values, ispublic, isoptional) { - const path = `/updateStdField` - const result = await this.post('POST', `${path}`, { category, field_name, definition_and_comment, obligation_or_condition, field_type, cardinality, values, ispublic, isoptional }) - return result - } - - async updateSource(kc_id, source_id) { - const path = '/update_source' - const result = await this.post('POST', `${path}`, { kc_id, source_id }); - return result - } - - async publicFields() { - const path = `/stdFields` - const result = this.post('GET', `${path}`) - return result - } - async privateFields() { - const path = `/privateFieldList` - const result = this.post('GET', `${path}`) - return result - } - - async truncateStdField() { - const path = `/stdFields/truncate` - const result = this.post('DELETE', `${path}`) - return result - } - - async deleteSource(sourceId, kc_id) { - const path = `/source/delete` - const result = this.post('POST', `${path}`, { sourceId, kc_id }) - return result - } - - async mergeAndSendSource({ kc_id, name, description, sources }) { - const path = `/source/merge-and-send` - const result = this.post('POST', `${path}`, { kc_id, name, description, sources }) - return result - } + const response = await fetch(`${this.baseUrl}${path}`, { + method: method, + headers, + body: JSON.stringify(requestContent), + mode: 'cors', + }); + + const responseContent = await response.json(); + + return responseContent; + } + + async createSource(metaUrfms, name, description, kc_id) { + const path = `/source`; + const result = await this.post('POST', `${path}`, { + metaUrfms, + name, + description, + kc_id, + }); + return result; + } + + async sources(kc_id) { + const path = '/sources'; + const result = await this.post('POST', `${path}`, { kc_id }); + return result; + } + + async indexedSources(kc_id) { + const path = '/indexed-sources'; + const result = await this.post('POST', `${path}`, { kc_id }); + return result; + } + + async allSource() { + const path = '/allSource'; + const result = await this.post('GET', `${path}`); + return result; + } + + async allIndexedSource() { + const path = '/allIndexedSource'; + const result = await this.post('GET', `${path}`); + return result; + } + + async addStdField( + category, + field_name, + definition_and_comment, + obligation_or_condition, + field_type, + cardinality, + values, + ispublic, + isoptional + ) { + const path = `/addStdField`; + const result = await this.post('POST', `${path}`, { + category, + field_name, + definition_and_comment, + obligation_or_condition, + field_type, + cardinality, + values, + ispublic, + isoptional, + }); + return result; + } + + async addAddtlField( + category, + field_name, + definition_and_comment, + obligation_or_condition, + field_type, + cardinality, + values, + ispublic, + isoptional + ) { + const path = `/addAddtlField`; + const result = await this.post('POST', `${path}`, { + category, + field_name, + definition_and_comment, + obligation_or_condition, + field_type, + cardinality, + values, + ispublic, + isoptional, + }); + return result; + } + + async updateStdField( + category, + field_name, + definition_and_comment, + obligation_or_condition, + field_type, + cardinality, + values, + ispublic, + isoptional + ) { + const path = `/updateStdField`; + const result = await this.post('POST', `${path}`, { + category, + field_name, + definition_and_comment, + obligation_or_condition, + field_type, + cardinality, + values, + ispublic, + isoptional, + }); + return result; + } + + async updateSource(kc_id, source_id) { + const path = '/update_source'; + const result = await this.post('POST', `${path}`, { kc_id, source_id }); + return result; + } + + async publicFields() { + const path = `/stdFields`; + const result = this.post('GET', `${path}`); + return result; + } + async privateFields() { + const path = `/privateFieldList`; + const result = this.post('GET', `${path}`); + return result; + } + + async truncateStdField() { + const path = `/stdFields/truncate`; + const result = this.post('DELETE', `${path}`); + return result; + } + + async deleteSource(sourceId, kc_id) { + const path = `/source/delete`; + const result = this.post('POST', `${path}`, { sourceId, kc_id }); + return result; + } + + async mergeAndSendSource({ kc_id, name, description, sources }) { + const path = `/source/merge-and-send`; + const result = this.post('POST', `${path}`, { kc_id, name, description, sources }); + return result; + } } - - InSylvaSourceManager.prototype.baseUrl = null; - InSylvaSourceManager.prototype.token = null; -export { InSylvaSourceManager } +InSylvaSourceManager.prototype.baseUrl = null; +InSylvaSourceManager.prototype.token = null; +export { InSylvaSourceManager }; diff --git a/src/context/KeycloakClient.js b/src/context/KeycloakClient.js index 43ed617..34dfa8b 100644 --- a/src/context/KeycloakClient.js +++ b/src/context/KeycloakClient.js @@ -1,108 +1,101 @@ class KeycloakClient { + async post(path, requestContent) { + // const access_token = sessionStorage.getItem("access_token"); - async post(path, requestContent) { - - // const access_token = sessionStorage.getItem("access_token"); - - const headers = { - 'Content-Type': 'application/x-www-form-urlencoded', - // "Access-Control-Allow-Methods": "GET,HEAD,PUT,PATCH,POST,DELETE", - // "Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept, Authorization" - }; - /* + const headers = { + 'Content-Type': 'application/x-www-form-urlencoded', + // "Access-Control-Allow-Methods": "GET,HEAD,PUT,PATCH,POST,DELETE", + // "Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept, Authorization" + }; + /* if (access_token) { headers["Authorization"] = "Bearer " + access_token } */ - var formBody = []; - for (var property in requestContent) { - var encodedKey = encodeURIComponent(property); - var encodedValue = encodeURIComponent(requestContent[property]); - formBody.push(encodedKey + "=" + encodedValue); - } - formBody = formBody.join("&"); - - const response = await fetch(`${this.baseUrl}${path}`, { - method: 'POST', - headers, - body: formBody, - mode: 'cors' - }); + var formBody = []; + for (var property in requestContent) { + var encodedKey = encodeURIComponent(property); + var encodedValue = encodeURIComponent(requestContent[property]); + formBody.push(encodedKey + '=' + encodedValue); + } + formBody = formBody.join('&'); - if (response.ok === true) { - // ok - } else { - // throw new Error(response.status); + const response = await fetch(`${this.baseUrl}${path}`, { + method: 'POST', + headers, + body: formBody, + mode: 'cors', + }); - const responseContent = await response.json(); + if (response.ok === true) { + // ok + } else { + // throw new Error(response.status); - return responseContent; - - } + const responseContent = await response.json(); - if (response.statusText === "No Content") { - // ok - } else { - const responseContent = await response.json(); + return responseContent; + } - return responseContent; - } - }; + if (response.statusText === 'No Content') { + // ok + } else { + const responseContent = await response.json(); - async login({ - realm = this.realm, - client_id = this.client_id, - username, - password, - grant_type = this.grant_type - }) { - const path = `/auth/realms/${realm}/protocol/openid-connect/token`; - const token = await this.post(`${path}`, { - client_id, - username, - password, - grant_type - }); - - return { token } + return responseContent; } + } - async refreshToken({ - realm = this.realm, - client_id = this.client_id, - // client_secret : 'optional depending on the type of client', - grant_type = "refresh_token", - refresh_token - }) { - - const path = `/auth/realms/${realm}/protocol/openid-connect/token`; - const token = await this.post(`${path}`, { - client_id, - grant_type, - refresh_token - }); + async login({ + realm = this.realm, + client_id = this.client_id, + username, + password, + grant_type = this.grant_type, + }) { + const path = `/auth/realms/${realm}/protocol/openid-connect/token`; + const token = await this.post(`${path}`, { + client_id, + username, + password, + grant_type, + }); - return { token } - } + return { token }; + } - async logout({ - realm = this.realm, - client_id = this.client_id - }) { - const refresh_token = sessionStorage.getItem("refresh_token"); - const path = `/auth/realms/${realm}/protocol/openid-connect/logout`; - if (refresh_token) { - await this.post(`${path}`, { - client_id, - refresh_token - }); - } + async refreshToken({ + realm = this.realm, + client_id = this.client_id, + // client_secret : 'optional depending on the type of client', + grant_type = 'refresh_token', + refresh_token, + }) { + const path = `/auth/realms/${realm}/protocol/openid-connect/token`; + const token = await this.post(`${path}`, { + client_id, + grant_type, + refresh_token, + }); + + return { token }; + } + + async logout({ realm = this.realm, client_id = this.client_id }) { + const refresh_token = sessionStorage.getItem('refresh_token'); + const path = `/auth/realms/${realm}/protocol/openid-connect/logout`; + if (refresh_token) { + await this.post(`${path}`, { + client_id, + refresh_token, + }); } + } } KeycloakClient.prototype.baseUrl = null; KeycloakClient.prototype.client_id = null; KeycloakClient.prototype.grant_type = null; KeycloakClient.prototype.realm = null; -export { KeycloakClient } \ No newline at end of file +export { KeycloakClient }; diff --git a/src/context/LayoutContext.js b/src/context/LayoutContext.js index 12ea4fd..d4207ff 100644 --- a/src/context/LayoutContext.js +++ b/src/context/LayoutContext.js @@ -1,11 +1,11 @@ -import React from "react"; +import React from 'react'; var LayoutStateContext = React.createContext(); var LayoutDispatchContext = React.createContext(); function layoutReducer(state, action) { switch (action.type) { - case "TOGGLE_SIDEBAR": + case 'TOGGLE_SIDEBAR': return { ...state, isSidebarOpened: !state.isSidebarOpened }; default: { throw new Error(`Unhandled action type: ${action.type}`); @@ -29,7 +29,7 @@ function LayoutProvider({ children }) { function useLayoutState() { var context = React.useContext(LayoutStateContext); if (context === undefined) { - throw new Error("useLayoutState must be used within a LayoutProvider"); + throw new Error('useLayoutState must be used within a LayoutProvider'); } return context; } @@ -37,7 +37,7 @@ function useLayoutState() { function useLayoutDispatch() { var context = React.useContext(LayoutDispatchContext); if (context === undefined) { - throw new Error("useLayoutDispatch must be used within a LayoutProvider"); + throw new Error('useLayoutDispatch must be used within a LayoutProvider'); } return context; } @@ -47,6 +47,6 @@ export { LayoutProvider, useLayoutState, useLayoutDispatch, toggleSidebar }; // ########################################################### function toggleSidebar(dispatch) { dispatch({ - type: "TOGGLE_SIDEBAR", + type: 'TOGGLE_SIDEBAR', }); } diff --git a/src/context/UserContext.js b/src/context/UserContext.js index 58e1b0b..60ceb5f 100644 --- a/src/context/UserContext.js +++ b/src/context/UserContext.js @@ -1,30 +1,38 @@ -import React from "react"; +import React from 'react'; -import { KeycloakClient } from './KeycloakClient' -import { InSylvaGatekeeperClient } from './InSylvaGatekeeperClient' -import {getGatekeeperBaseUrl, getLoginUrl, redirect} from '../utils.js'; +import { KeycloakClient } from './KeycloakClient'; +import { InSylvaGatekeeperClient } from './InSylvaGatekeeperClient'; +import { getGatekeeperBaseUrl, getLoginUrl, redirect } from '../utils.js'; const UserStateContext = React.createContext(); const UserDispatchContext = React.createContext(); const kcClient = new KeycloakClient(); -kcClient.baseUrl = (process.env.REACT_APP_IN_SYLVA_KEYCLOAK_PORT) ? `${process.env.REACT_APP_IN_SYLVA_KEYCLOAK_HOST}:${process.env.REACT_APP_IN_SYLVA_KEYCLOAK_PORT}` : `${window._env_.REACT_APP_IN_SYLVA_KEYCLOAK_HOST}` -kcClient.realm = (process.env.REACT_APP_IN_SYLVA_KEYCLOAK_PORT) ? `${process.env.REACT_APP_IN_SYLVA_REALM}` : `${window._env_.REACT_APP_IN_SYLVA_REALM}` -kcClient.client_id = (process.env.REACT_APP_IN_SYLVA_KEYCLOAK_PORT) ? `${process.env.REACT_APP_IN_SYLVA_CLIENT_ID}` : `${window._env_.REACT_APP_IN_SYLVA_CLIENT_ID}` -kcClient.grant_type = (process.env.REACT_APP_IN_SYLVA_KEYCLOAK_PORT) ? `${process.env.REACT_APP_IN_SYLVA_GRANT_TYPE}` : `${window._env_.REACT_APP_IN_SYLVA_GRANT_TYPE}` +kcClient.baseUrl = process.env.REACT_APP_IN_SYLVA_KEYCLOAK_PORT + ? `${process.env.REACT_APP_IN_SYLVA_KEYCLOAK_HOST}:${process.env.REACT_APP_IN_SYLVA_KEYCLOAK_PORT}` + : `${window._env_.REACT_APP_IN_SYLVA_KEYCLOAK_HOST}`; +kcClient.realm = process.env.REACT_APP_IN_SYLVA_KEYCLOAK_PORT + ? `${process.env.REACT_APP_IN_SYLVA_REALM}` + : `${window._env_.REACT_APP_IN_SYLVA_REALM}`; +kcClient.client_id = process.env.REACT_APP_IN_SYLVA_KEYCLOAK_PORT + ? `${process.env.REACT_APP_IN_SYLVA_CLIENT_ID}` + : `${window._env_.REACT_APP_IN_SYLVA_CLIENT_ID}`; +kcClient.grant_type = process.env.REACT_APP_IN_SYLVA_KEYCLOAK_PORT + ? `${process.env.REACT_APP_IN_SYLVA_GRANT_TYPE}` + : `${window._env_.REACT_APP_IN_SYLVA_GRANT_TYPE}`; const igClient = new InSylvaGatekeeperClient(); igClient.baseUrl = getGatekeeperBaseUrl(); function userReducer(state, action) { switch (action.type) { - case "LOGIN_SUCCESS": + case 'LOGIN_SUCCESS': return { ...state, isAuthenticated: true }; - case "SIGN_OUT_SUCCESS": + case 'SIGN_OUT_SUCCESS': return { ...state, isAuthenticated: false }; - case "LOGIN_FAILURE": + case 'LOGIN_FAILURE': return { ...state, isAuthenticated: false }; - case "USER_CREATED": + case 'USER_CREATED': return { ...state }; default: { throw new Error(`Unhandled action type: ${action.type} `); @@ -34,7 +42,7 @@ function userReducer(state, action) { function UserProvider({ children }) { const [state, dispatch] = React.useReducer(userReducer, { - isAuthenticated: !!sessionStorage.getItem("access_token"), + isAuthenticated: !!sessionStorage.getItem('access_token'), }); return ( @@ -49,7 +57,7 @@ function UserProvider({ children }) { function useUserState() { const context = React.useContext(UserStateContext); if (context === undefined) { - throw new Error("useUserState must be used within a UserProvider"); + throw new Error('useUserState must be used within a UserProvider'); } return context; } @@ -57,39 +65,39 @@ function useUserState() { function useUserDispatch() { const context = React.useContext(UserDispatchContext); if (context === undefined) { - throw new Error("useUserDispatch must be used within a UserProvider"); + throw new Error('useUserDispatch must be used within a UserProvider'); } return context; } async function checkUserLogin(userId, accessToken, refreshToken, roleId) { if (!!userId && !!accessToken && !!refreshToken && !!roleId) { - sessionStorage.setItem("userId", userId) - sessionStorage.setItem("access_token", accessToken) - sessionStorage.setItem("refresh_token", refreshToken) - sessionStorage.setItem("roleId", roleId) + sessionStorage.setItem('userId', userId); + sessionStorage.setItem('access_token', accessToken); + sessionStorage.setItem('refresh_token', refreshToken); + sessionStorage.setItem('roleId', roleId); //To Do: // Load the user histories from UserHistory(userId) endpoint // Load the user result filters from Result_Filter(userId) endpoints // Load the user policies from Policy(userId) endpoint - if (!sessionStorage.getItem("token_refresh_time")) { - sessionStorage.setItem("token_refresh_time", Date.now()) + if (!sessionStorage.getItem('token_refresh_time')) { + sessionStorage.setItem('token_refresh_time', Date.now()); } } else { - console.log('user not logged in') + console.log('user not logged in'); } } async function signOut(dispatch, history) { await kcClient.logout({}); - dispatch({ type: "SIGN_OUT_SUCCESS" }); - sessionStorage.removeItem("access_token"); - sessionStorage.removeItem("refresh_token"); - sessionStorage.removeItem("portal"); - sessionStorage.removeItem("userId") - sessionStorage.removeItem("roleId") - redirect(getLoginUrl() + '?requestType=portal') + dispatch({ type: 'SIGN_OUT_SUCCESS' }); + sessionStorage.removeItem('access_token'); + sessionStorage.removeItem('refresh_token'); + sessionStorage.removeItem('portal'); + sessionStorage.removeItem('userId'); + sessionStorage.removeItem('roleId'); + redirect(getLoginUrl() + '?requestType=portal'); } export { UserProvider, useUserState, useUserDispatch, signOut, checkUserLogin }; diff --git a/src/index.js b/src/index.js index 5870165..622919b 100755 --- a/src/index.js +++ b/src/index.js @@ -1,29 +1,29 @@ -import React from "react"; -import ReactDOM from "react-dom"; -import { ThemeProvider } from "@material-ui/styles"; -import { CssBaseline } from "@material-ui/core"; -import Themes from "./themes"; +import React from 'react'; +import ReactDOM from 'react-dom'; +import { ThemeProvider } from '@material-ui/styles'; +import { CssBaseline } from '@material-ui/core'; +import Themes from './themes'; import '@elastic/eui/dist/eui_theme_light.css'; -import App from "./components/App"; -import { LayoutProvider } from "./context/LayoutContext"; -import { UserProvider, checkUserLogin } from "./context/UserContext"; -import {getLoginUrl, getUrlParam, redirect} from './utils.js'; +import App from './components/App'; +import { LayoutProvider } from './context/LayoutContext'; +import { UserProvider, checkUserLogin } from './context/UserContext'; +import { getLoginUrl, getUrlParam, redirect } from './utils.js'; -const userId = getUrlParam("kcId", "") -const accessToken = getUrlParam("accessToken", "") -const roleId = getUrlParam("roleId","") +const userId = getUrlParam('kcId', ''); +const accessToken = getUrlParam('accessToken', ''); +const roleId = getUrlParam('roleId', ''); -let refreshToken = getUrlParam("refreshToken", "") +let refreshToken = getUrlParam('refreshToken', ''); if (refreshToken.includes('#/app/portal')) - refreshToken = refreshToken.substring(0, refreshToken.indexOf('#')) + refreshToken = refreshToken.substring(0, refreshToken.indexOf('#')); -checkUserLogin(userId, accessToken, refreshToken,roleId) +checkUserLogin(userId, accessToken, refreshToken, roleId); //To-Do // * delete previous tokens from session storage // * refresh tokens -if (sessionStorage.getItem("access_token")) { +if (sessionStorage.getItem('access_token')) { ReactDOM.render( <LayoutProvider> <UserProvider> @@ -33,10 +33,8 @@ if (sessionStorage.getItem("access_token")) { </ThemeProvider> </UserProvider> </LayoutProvider>, - document.getElementById("root"), + document.getElementById('root') ); } else { - redirect(getLoginUrl() + '?requestType=portal') + redirect(getLoginUrl() + '?requestType=portal'); } - - diff --git a/src/pages/charts/Charts.js b/src/pages/charts/Charts.js index 59e8e47..db19851 100644 --- a/src/pages/charts/Charts.js +++ b/src/pages/charts/Charts.js @@ -1,6 +1,6 @@ -import React, { useState } from "react"; -import { Grid } from "@material-ui/core"; -import { useTheme } from "@material-ui/styles"; +import React, { useState } from 'react'; +import { Grid } from '@material-ui/core'; +import { useTheme } from '@material-ui/styles'; import { CartesianGrid, Legend, @@ -13,53 +13,53 @@ import { Tooltip, XAxis, YAxis, -} from "recharts"; +} from 'recharts'; // components -import Widget from "../../components/Widget/Widget"; -import ApexLineChart from "./components/ApexLineChart"; -import ApexHeatmap from "./components/ApexHeatmap"; -import PageTitle from "../../components/PageTitle/PageTitle"; +import Widget from '../../components/Widget/Widget'; +import ApexLineChart from './components/ApexLineChart'; +import ApexHeatmap from './components/ApexHeatmap'; +import PageTitle from '../../components/PageTitle/PageTitle'; const lineChartData = [ { - name: "Page A", + name: 'Page A', uv: 4000, pv: 2400, amt: 2400, }, { - name: "Page B", + name: 'Page B', uv: 3000, pv: 1398, amt: 2210, }, { - name: "Page C", + name: 'Page C', uv: 2000, pv: 9800, amt: 2290, }, { - name: "Page D", + name: 'Page D', uv: 2780, pv: 3908, amt: 2000, }, { - name: "Page E", + name: 'Page E', uv: 1890, pv: 4800, amt: 2181, }, { - name: "Page F", + name: 'Page F', uv: 2390, pv: 3800, amt: 2500, }, { - name: "Page G", + name: 'Page G', uv: 3490, pv: 4300, amt: 2100, @@ -67,10 +67,10 @@ const lineChartData = [ ]; const pieChartData = [ - { name: "Group A", value: 400 }, - { name: "Group B", value: 300 }, - { name: "Group C", value: 300 }, - { name: "Group D", value: 200 }, + { name: 'Group A', value: 400 }, + { name: 'Group B', value: 300 }, + { name: 'Group C', value: 300 }, + { name: 'Group D', value: 200 }, ]; export default function Charts(props) { @@ -177,7 +177,7 @@ function renderActiveShape(props) { var my = cy + (outerRadius + 30) * sin; var ex = mx + (cos >= 0 ? 1 : -1) * 22; var ey = my; - var textAnchor = cos >= 0 ? "start" : "end"; + var textAnchor = cos >= 0 ? 'start' : 'end'; return ( <g> @@ -202,11 +202,7 @@ function renderActiveShape(props) { outerRadius={outerRadius + 10} fill={fill} /> - <path - d={`M${sx},${sy}L${mx},${my}L${ex},${ey}`} - stroke={fill} - fill="none" - /> + <path d={`M${sx},${sy}L${mx},${my}L${ex},${ey}`} stroke={fill} fill="none" /> <circle cx={ex} cy={ey} r={2} fill={fill} stroke="none" /> <text x={ex + (cos >= 0 ? 1 : -1) * 12} diff --git a/src/pages/charts/components/ApexHeatmap.js b/src/pages/charts/components/ApexHeatmap.js index 3d089c8..ebd119f 100644 --- a/src/pages/charts/components/ApexHeatmap.js +++ b/src/pages/charts/components/ApexHeatmap.js @@ -1,66 +1,66 @@ -import React from "react"; -import { useTheme } from "@material-ui/styles"; -import ApexCharts from "react-apexcharts"; +import React from 'react'; +import { useTheme } from '@material-ui/styles'; +import ApexCharts from 'react-apexcharts'; const series = [ { - name: "Metric1", + name: 'Metric1', data: generateData(18, { min: 0, max: 90, }), }, { - name: "Metric2", + name: 'Metric2', data: generateData(18, { min: 0, max: 90, }), }, { - name: "Metric3", + name: 'Metric3', data: generateData(18, { min: 0, max: 90, }), }, { - name: "Metric4", + name: 'Metric4', data: generateData(18, { min: 0, max: 90, }), }, { - name: "Metric5", + name: 'Metric5', data: generateData(18, { min: 0, max: 90, }), }, { - name: "Metric6", + name: 'Metric6', data: generateData(18, { min: 0, max: 90, }), }, { - name: "Metric7", + name: 'Metric7', data: generateData(18, { min: 0, max: 90, }), }, { - name: "Metric8", + name: 'Metric8', data: generateData(18, { min: 0, max: 90, }), }, { - name: "Metric9", + name: 'Metric9', data: generateData(18, { min: 0, max: 90, @@ -86,9 +86,8 @@ function generateData(count, yrange) { var i = 0; var series = []; while (i < count) { - var x = "w" + (i + 1).toString(); - var y = - Math.floor(Math.random() * (yrange.max - yrange.min + 1)) + yrange.min; + var x = 'w' + (i + 1).toString(); + var y = Math.floor(Math.random() * (yrange.max - yrange.min + 1)) + yrange.min; series.push({ x: x, diff --git a/src/pages/charts/components/ApexLineChart.js b/src/pages/charts/components/ApexLineChart.js index b1c59fe..14d212a 100644 --- a/src/pages/charts/components/ApexLineChart.js +++ b/src/pages/charts/components/ApexLineChart.js @@ -1,14 +1,14 @@ -import React from "react"; -import ApexCharts from "react-apexcharts"; -import { useTheme } from "@material-ui/styles"; +import React from 'react'; +import ApexCharts from 'react-apexcharts'; +import { useTheme } from '@material-ui/styles'; const series = [ { - name: "series1", + name: 'series1', data: [31, 40, 28, 51, 42, 109, 100], }, { - name: "series2", + name: 'series2', data: [11, 32, 45, 32, 34, 52, 41], }, ]; @@ -17,12 +17,7 @@ export default function ApexLineChart() { var theme = useTheme(); return ( - <ApexCharts - options={themeOptions(theme)} - series={series} - type="area" - height={350} - /> + <ApexCharts options={themeOptions(theme)} series={series} type="area" height={350} /> ); } @@ -33,23 +28,23 @@ function themeOptions(theme) { enabled: false, }, stroke: { - curve: "smooth", + curve: 'smooth', }, xaxis: { - type: "datetime", + type: 'datetime', categories: [ - "2018-09-19T00:00:00", - "2018-09-19T01:30:00", - "2018-09-19T02:30:00", - "2018-09-19T03:30:00", - "2018-09-19T04:30:00", - "2018-09-19T05:30:00", - "2018-09-19T06:30:00", + '2018-09-19T00:00:00', + '2018-09-19T01:30:00', + '2018-09-19T02:30:00', + '2018-09-19T03:30:00', + '2018-09-19T04:30:00', + '2018-09-19T05:30:00', + '2018-09-19T06:30:00', ], }, tooltip: { x: { - format: "dd/MM/yy HH:mm", + format: 'dd/MM/yy HH:mm', }, }, fill: { diff --git a/src/pages/dashboard/Dashboard.js b/src/pages/dashboard/Dashboard.js index 851ab3b..054205f 100644 --- a/src/pages/dashboard/Dashboard.js +++ b/src/pages/dashboard/Dashboard.js @@ -1,11 +1,8 @@ -import React from "react"; -import { - Grid, - LinearProgress, -} from "@material-ui/core"; -import { useTheme } from "@material-ui/styles"; +import React from 'react'; +import { Grid, LinearProgress } from '@material-ui/core'; +import { useTheme } from '@material-ui/styles'; -import keycloakLogo from '../../images/Keycloak_Logo.svg' +import keycloakLogo from '../../images/Keycloak_Logo.svg'; import { ResponsiveContainer, AreaChart, @@ -15,7 +12,7 @@ import { PieChart, Pie, Cell, -} from "recharts"; +} from 'recharts'; import { EuiButton, @@ -23,33 +20,58 @@ import { EuiIcon, EuiFlexGroup, EuiFlexItem, - EuiSpacer -} from '@elastic/eui' + EuiSpacer, +} from '@elastic/eui'; // styles -import useStyles from "./styles"; +import useStyles from './styles'; // components -import Widget from "../../components/Widget"; -import { Typography } from "../../components/Wrappers"; -import Dot from "../../components/Sidebar/components/Dot"; +import Widget from '../../components/Widget'; +import { Typography } from '../../components/Wrappers'; +import Dot from '../../components/Sidebar/components/Dot'; const PieChartData = [ - { name: "Super User", value: 400, color: "primary" }, - { name: "Source Manager", value: 300, color: "secondary" }, - { name: "Standard User", value: 300, color: "warning" }, + { name: 'Super User', value: 400, color: 'primary' }, + { name: 'Source Manager', value: 300, color: 'secondary' }, + { name: 'Standard User', value: 300, color: 'warning' }, // { name: "Group D", value: 200, color: "success" }, ]; -const urlMaps = new Map() - -urlMaps.set('kibana', window._env_ ? window._env_.REACT_APP_IN_SYLVA_KIBANA_URL : "http://localhost:5601/") -urlMaps.set('postgresql', window._env_ ? window._env_.REACT_APP_IN_SYLVA_POSTGRESQL_URL : "http://localhost:5050/login?next=%2F") -urlMaps.set('mongoDb', window._env_ ? window._env_.REACT_APP_IN_SYLVA_MONGODB_URL : "http://localhost:8881/") -urlMaps.set('elasticsearch', window._env_ ? window._env_.REACT_APP_IN_SYLVA_ELASTICSEARCH_URL : "http://localhost:9200/") -urlMaps.set('keycloak', window._env_ ? window._env_.REACT_APP_IN_SYLVA_KEYCLOAK_URL : "http://localhost:7000/keycloak/auth") -urlMaps.set('portainer', window._env_ ? window._env_.REACT_APP_IN_SYLVA_PORTAINER_URL : "http://localhost:9000/#/init/admin") +const urlMaps = new Map(); +urlMaps.set( + 'kibana', + window._env_ ? window._env_.REACT_APP_IN_SYLVA_KIBANA_URL : 'http://localhost:5601/' +); +urlMaps.set( + 'postgresql', + window._env_ + ? window._env_.REACT_APP_IN_SYLVA_POSTGRESQL_URL + : 'http://localhost:5050/login?next=%2F' +); +urlMaps.set( + 'mongoDb', + window._env_ ? window._env_.REACT_APP_IN_SYLVA_MONGODB_URL : 'http://localhost:8881/' +); +urlMaps.set( + 'elasticsearch', + window._env_ + ? window._env_.REACT_APP_IN_SYLVA_ELASTICSEARCH_URL + : 'http://localhost:9200/' +); +urlMaps.set( + 'keycloak', + window._env_ + ? window._env_.REACT_APP_IN_SYLVA_KEYCLOAK_URL + : 'http://localhost:7000/keycloak/auth' +); +urlMaps.set( + 'portainer', + window._env_ + ? window._env_.REACT_APP_IN_SYLVA_PORTAINER_URL + : 'http://localhost:9000/#/init/admin' +); export default function Dashboard(props) { var classes = useStyles(); @@ -68,7 +90,14 @@ export default function Dashboard(props) { description="Access to Kibana." footer={ <div> - <EuiButton aria-label="Go to Kibana" onClick={() => { window.open(urlMaps.get('kibana'), "_blank") }}>Go for it</EuiButton> + <EuiButton + aria-label="Go to Kibana" + onClick={() => { + window.open(urlMaps.get('kibana'), '_blank'); + }} + > + Go for it + </EuiButton> <EuiSpacer size="xs" /> </div> } @@ -81,7 +110,14 @@ export default function Dashboard(props) { description="Access to Postgresql" footer={ <div> - <EuiButton aria-label="Go to Postgresql" onClick={() => { window.open(urlMaps.get('postgresql'), "_blank") }}>Go for it</EuiButton> + <EuiButton + aria-label="Go to Postgresql" + onClick={() => { + window.open(urlMaps.get('postgresql'), '_blank'); + }} + > + Go for it + </EuiButton> <EuiSpacer size="xs" /> </div> } @@ -94,7 +130,14 @@ export default function Dashboard(props) { description="Access to MongoDb" footer={ <div> - <EuiButton aria-label="Go to MongoDb" onClick={() => { window.open(urlMaps.get('mongoDb'), "_blank") }}>Go for it</EuiButton> + <EuiButton + aria-label="Go to MongoDb" + onClick={() => { + window.open(urlMaps.get('mongoDb'), '_blank'); + }} + > + Go for it + </EuiButton> <EuiSpacer size="xs" /> </div> } @@ -107,7 +150,14 @@ export default function Dashboard(props) { description="Access to Elasticsearch" footer={ <div> - <EuiButton aria-label="Go to Elasticsearch" onClick={() => { window.open(urlMaps.get('elasticsearch'), "_blank") }}>Go for it</EuiButton> + <EuiButton + aria-label="Go to Elasticsearch" + onClick={() => { + window.open(urlMaps.get('elasticsearch'), '_blank'); + }} + > + Go for it + </EuiButton> <EuiSpacer size="xs" /> </div> } @@ -115,15 +165,19 @@ export default function Dashboard(props) { </EuiFlexItem> <EuiFlexItem> <EuiCard - icon={<EuiIcon - type={keycloakLogo} - size="xxl" - />} + icon={<EuiIcon type={keycloakLogo} size="xxl" />} title="Keycloak" description="Access to Keycloak" footer={ <div> - <EuiButton aria-label="Go to Keycloak" onClick={() => { window.open(urlMaps.get('keycloak'), "_blank") }}>Go for it</EuiButton> + <EuiButton + aria-label="Go to Keycloak" + onClick={() => { + window.open(urlMaps.get('keycloak'), '_blank'); + }} + > + Go for it + </EuiButton> <EuiSpacer size="xs" /> </div> } @@ -136,7 +190,14 @@ export default function Dashboard(props) { description="Access to Portainer" footer={ <div> - <EuiButton aria-label="Go to Portainer" onClick={() => { window.open(urlMaps.get('portainer'), "_blank") }}>Go for it</EuiButton> + <EuiButton + aria-label="Go to Portainer" + onClick={() => { + window.open(urlMaps.get('portainer'), '_blank'); + }} + > + Go for it + </EuiButton> <EuiSpacer size="xs" /> </div> } @@ -177,12 +238,7 @@ export default function Dashboard(props) { /> </LineChart> </div> - <Grid - container - direction="row" - justify="space-between" - alignItems="center" - > + <Grid container direction="row" justify="space-between" alignItems="center"> <Grid item> <Typography color="text" colorBrightness="secondary"> Registrations @@ -372,7 +428,7 @@ export default function Dashboard(props) { {PieChartData.map(({ name, value, color }, index) => ( <div key={color} className={classes.legendItemContainer}> <Dot color={color} /> - <Typography style={{ whiteSpace: "nowrap" }}> + <Typography style={{ whiteSpace: 'nowrap' }}> {name} </Typography> <Typography color="text" colorBrightness="secondary"> diff --git a/src/pages/dashboard/components/BigStat/BigStat.js b/src/pages/dashboard/components/BigStat/BigStat.js index e12590f..0ebcfab 100644 --- a/src/pages/dashboard/components/BigStat/BigStat.js +++ b/src/pages/dashboard/components/BigStat/BigStat.js @@ -1,16 +1,16 @@ -import React, { useState } from "react"; -import { Grid, Select, MenuItem, Input } from "@material-ui/core"; -import { ArrowForward as ArrowForwardIcon } from "@material-ui/icons"; -import { useTheme } from "@material-ui/styles"; -import { BarChart, Bar } from "recharts"; -import classnames from "classnames"; +import React, { useState } from 'react'; +import { Grid, Select, MenuItem, Input } from '@material-ui/core'; +import { ArrowForward as ArrowForwardIcon } from '@material-ui/icons'; +import { useTheme } from '@material-ui/styles'; +import { BarChart, Bar } from 'recharts'; +import classnames from 'classnames'; // styles -import useStyles from "./styles"; +import useStyles from './styles'; // components -import Widget from "../../../../components/Widget"; -import { Typography } from "../../../../components/Wrappers"; +import Widget from '../../../../components/Widget'; +import { Typography } from '../../../../components/Wrappers'; export default function BigStat(props) { var { product, total, color, registrations, bounce } = props; @@ -18,7 +18,7 @@ export default function BigStat(props) { var theme = useTheme(); // local - var [value, setValue] = useState("daily"); + var [value, setValue] = useState('daily'); return ( <Widget @@ -28,13 +28,8 @@ export default function BigStat(props) { <Select value={value} - onChange={e => setValue(e.target.value)} - input={ - <Input - disableUnderline - classes={{ input: classes.selectInput }} - /> - } + onChange={(e) => setValue(e.target.value)} + input={<Input disableUnderline classes={{ input: classes.selectInput }} />} className={classes.select} > <MenuItem value="daily">Daily</MenuItem> @@ -43,15 +38,15 @@ export default function BigStat(props) { </Select> </div> } - upperTitle> - + upperTitle + > <div className={classes.totalValueContainer}> <div className={classes.totalValue}> <Typography size="xxl" color="text" colorBrightness="secondary"> {total[value]} </Typography> - <Typography color={total.percent.profit ? "success" : "secondary"}> - {total.percent.profit ? "+" : "-"} + <Typography color={total.percent.profit ? 'success' : 'secondary'}> + {total.percent.profit ? '+' : '-'} {total.percent.value}% </Typography> </div> @@ -93,9 +88,7 @@ export default function BigStat(props) { </div> <div className={classnames(classes.statCell, classes.borderRight)}> <Grid container alignItems="center"> - <Typography variant="h6"> - {registrations[value].value * 10} - </Typography> + <Typography variant="h6">{registrations[value].value * 10}</Typography> <ArrowForwardIcon className={classnames(classes.profitArrow, { [classes.profitArrowDanger]: !registrations[value].profit, diff --git a/src/pages/dashboard/components/BigStat/styles.js b/src/pages/dashboard/components/BigStat/styles.js index 853a28e..535ac67 100644 --- a/src/pages/dashboard/components/BigStat/styles.js +++ b/src/pages/dashboard/components/BigStat/styles.js @@ -1,17 +1,17 @@ -import { makeStyles } from "@material-ui/styles"; +import { makeStyles } from '@material-ui/styles'; -export default makeStyles(theme => ({ +export default makeStyles((theme) => ({ title: { - display: "flex", - flexDirection: "row", - justifyContent: "space-between", - alignItems: "center", - width: "100%", + display: 'flex', + flexDirection: 'row', + justifyContent: 'space-between', + alignItems: 'center', + width: '100%', marginBottom: theme.spacing(1), }, bottomStatsContainer: { - display: "flex", - justifyContent: "space-between", + display: 'flex', + justifyContent: 'space-between', margin: theme.spacing(1) * -2, marginTop: theme.spacing(1), }, @@ -19,27 +19,27 @@ export default makeStyles(theme => ({ padding: theme.spacing(2), }, totalValueContainer: { - display: "flex", - alignItems: "flex-end", - justifyContent: "space-between", + display: 'flex', + alignItems: 'flex-end', + justifyContent: 'space-between', }, totalValue: { - display: "flex", - alignItems: "baseline", + display: 'flex', + alignItems: 'baseline', }, profitArrow: { - transform: "rotate(-45deg)", + transform: 'rotate(-45deg)', fill: theme.palette.success.main, }, profitArrowDanger: { - transform: "rotate(45deg)", + transform: 'rotate(45deg)', fill: theme.palette.secondary.main, }, selectInput: { padding: 10, paddingRight: 25, - "&:focus": { - backgroundColor: "white", + '&:focus': { + backgroundColor: 'white', }, }, -})); \ No newline at end of file +})); diff --git a/src/pages/dashboard/components/Table/Table.js b/src/pages/dashboard/components/Table/Table.js index cb25bb5..de752a8 100644 --- a/src/pages/dashboard/components/Table/Table.js +++ b/src/pages/dashboard/components/Table/Table.js @@ -1,30 +1,24 @@ -import React from "react"; -import { - Table, - TableRow, - TableHead, - TableBody, - TableCell, -} from "@material-ui/core"; +import React from 'react'; +import { Table, TableRow, TableHead, TableBody, TableCell } from '@material-ui/core'; // components -import { Button } from "../../../../components/Wrappers"; +import { Button } from '../../../../components/Wrappers'; const states = { - sent: "success", - pending: "warning", - declined: "secondary", + sent: 'success', + pending: 'warning', + declined: 'secondary', }; export default function TableComponent({ data }) { - var keys = Object.keys(data[0]).map(i => i.toUpperCase()); + var keys = Object.keys(data[0]).map((i) => i.toUpperCase()); keys.shift(); // delete "id" key return ( <Table className="mb-0"> <TableHead> <TableRow> - {keys.map(key => ( + {keys.map((key) => ( <TableCell key={key}>{key}</TableCell> ))} </TableRow> diff --git a/src/pages/dashboard/mock.js b/src/pages/dashboard/mock.js index 65b46c5..2f4e484 100644 --- a/src/pages/dashboard/mock.js +++ b/src/pages/dashboard/mock.js @@ -2,181 +2,179 @@ export default { tasks: [ { id: 0, - type: "Meeting", - title: "Meeting with Andrew Piker", - time: "9:00" + type: 'Meeting', + title: 'Meeting with Andrew Piker', + time: '9:00', }, { id: 1, - type: "Call", - title: "Call with HT Company", - time: "12:00" + type: 'Call', + title: 'Call with HT Company', + time: '12:00', }, { id: 2, - type: "Meeting", - title: "Meeting with Zoe Alison", - time: "14:00" + type: 'Meeting', + title: 'Meeting with Zoe Alison', + time: '14:00', }, { id: 3, - type: "Interview", - title: "Interview with HR", - time: "15:00" - } + type: 'Interview', + title: 'Interview with HR', + time: '15:00', + }, ], bigStat: [ { - product: "Light Blue", + product: 'Light Blue', total: { monthly: 4232, weekly: 1465, daily: 199, - percent: { value: 3.7, profit: false } + percent: { value: 3.7, profit: false }, }, - color: "primary", + color: 'primary', registrations: { monthly: { value: 830, profit: false }, weekly: { value: 215, profit: true }, - daily: { value: 33, profit: true } + daily: { value: 33, profit: true }, }, bounce: { monthly: { value: 4.5, profit: false }, weekly: { value: 3, profit: true }, - daily: { value: 3.25, profit: true } - } + daily: { value: 3.25, profit: true }, + }, }, { - product: "Sing App", + product: 'Sing App', total: { monthly: 754, weekly: 180, daily: 27, - percent: { value: 2.5, profit: true } + percent: { value: 2.5, profit: true }, }, - color: "warning", + color: 'warning', registrations: { monthly: { value: 32, profit: true }, weekly: { value: 8, profit: true }, - daily: { value: 2, profit: false } + daily: { value: 2, profit: false }, }, bounce: { monthly: { value: 2.5, profit: true }, weekly: { value: 4, profit: false }, - daily: { value: 4.5, profit: false } - } + daily: { value: 4.5, profit: false }, + }, }, { - product: "RNS", + product: 'RNS', total: { monthly: 1025, weekly: 301, daily: 44, - percent: { value: 3.1, profit: true } + percent: { value: 3.1, profit: true }, }, - color: "secondary", + color: 'secondary', registrations: { monthly: { value: 230, profit: true }, weekly: { value: 58, profit: false }, - daily: { value: 15, profit: false } + daily: { value: 15, profit: false }, }, bounce: { monthly: { value: 21.5, profit: false }, weekly: { value: 19.35, profit: false }, - daily: { value: 10.1, profit: true } - } - } + daily: { value: 10.1, profit: true }, + }, + }, ], notifications: [ { id: 0, - icon: "thumbs-up", - color: "primary", - content: - 'Ken <span className="fw-semi-bold">accepts</span> your invitation' + icon: 'thumbs-up', + color: 'primary', + content: 'Ken <span className="fw-semi-bold">accepts</span> your invitation', }, { id: 1, - icon: "file", - color: "success", - content: "Report from LT Company" + icon: 'file', + color: 'success', + content: 'Report from LT Company', }, { id: 2, - icon: "envelope", - color: "danger", - content: '4 <span className="fw-semi-bold">Private</span> Mails' + icon: 'envelope', + color: 'danger', + content: '4 <span className="fw-semi-bold">Private</span> Mails', }, { id: 3, - icon: "comment", - color: "success", - content: '3 <span className="fw-semi-bold">Comments</span> to your Post' + icon: 'comment', + color: 'success', + content: '3 <span className="fw-semi-bold">Comments</span> to your Post', }, { id: 4, - icon: "cog", - color: "light", - content: 'New <span className="fw-semi-bold">Version</span> of RNS app' + icon: 'cog', + color: 'light', + content: 'New <span className="fw-semi-bold">Version</span> of RNS app', }, { id: 5, - icon: "bell", - color: "info", - content: - '15 <span className="fw-semi-bold">Notifications</span> from Social Apps' - } + icon: 'bell', + color: 'info', + content: '15 <span className="fw-semi-bold">Notifications</span> from Social Apps', + }, ], table: [ { id: 0, - name: "Mark Otto", - email: "ottoto@wxample.com", - product: "ON the Road", - price: "$25 224.2", - date: "11 May 2017", - city: "Otsego", - status: "Sent" + name: 'Mark Otto', + email: 'ottoto@wxample.com', + product: 'ON the Road', + price: '$25 224.2', + date: '11 May 2017', + city: 'Otsego', + status: 'Sent', }, { id: 1, - name: "Jacob Thornton", - email: "thornton@wxample.com", - product: "HP Core i7", - price: "$1 254.2", - date: "4 Jun 2017", - city: "Fivepointville", - status: "Sent" + name: 'Jacob Thornton', + email: 'thornton@wxample.com', + product: 'HP Core i7', + price: '$1 254.2', + date: '4 Jun 2017', + city: 'Fivepointville', + status: 'Sent', }, { id: 2, - name: "Larry the Bird", - email: "bird@wxample.com", - product: "Air Pro", - price: "$1 570.0", - date: "27 Aug 2017", - city: "Leadville North", - status: "Pending" + name: 'Larry the Bird', + email: 'bird@wxample.com', + product: 'Air Pro', + price: '$1 570.0', + date: '27 Aug 2017', + city: 'Leadville North', + status: 'Pending', }, { id: 3, - name: "Joseph May", - email: "josephmay@wxample.com", - product: "Version Control", - price: "$5 224.5", - date: "19 Feb 2018", - city: "Seaforth", - status: "Declined" + name: 'Joseph May', + email: 'josephmay@wxample.com', + product: 'Version Control', + price: '$5 224.5', + date: '19 Feb 2018', + city: 'Seaforth', + status: 'Declined', }, { id: 4, - name: "Peter Horadnia", - email: "horadnia@wxample.com", + name: 'Peter Horadnia', + email: 'horadnia@wxample.com', product: "Let's Dance", - price: "$43 594.7", - date: "1 Mar 2018", - city: "Hanoverton", - status: "Sent" - } - ] + price: '$43 594.7', + date: '1 Mar 2018', + city: 'Hanoverton', + status: 'Sent', + }, + ], }; diff --git a/src/pages/dashboard/styles.js b/src/pages/dashboard/styles.js index c67257e..11e091c 100644 --- a/src/pages/dashboard/styles.js +++ b/src/pages/dashboard/styles.js @@ -1,14 +1,14 @@ -import { makeStyles } from "@material-ui/styles"; +import { makeStyles } from '@material-ui/styles'; -export default makeStyles(theme => ({ +export default makeStyles((theme) => ({ card: { - minHeight: "100%", - display: "flex", - flexDirection: "column", + minHeight: '100%', + display: 'flex', + flexDirection: 'column', }, visitsNumberContainer: { - display: "flex", - alignItems: "center", + display: 'flex', + alignItems: 'center', flexGrow: 1, paddingBottom: theme.spacing(1), }, @@ -23,93 +23,93 @@ export default makeStyles(theme => ({ backgroundColor: theme.palette.primary.main, }, pieChartLegendWrapper: { - height: "100%", - display: "flex", - flexDirection: "column", - justifyContent: "center", - alignItems: "flex-end", + height: '100%', + display: 'flex', + flexDirection: 'column', + justifyContent: 'center', + alignItems: 'flex-end', marginRight: theme.spacing(1), }, legendItemContainer: { - display: "flex", - alignItems: "center", + display: 'flex', + alignItems: 'center', marginBottom: theme.spacing(1), }, fullHeightBody: { - display: "flex", + display: 'flex', flexGrow: 1, - flexDirection: "column", - justifyContent: "space-between", + flexDirection: 'column', + justifyContent: 'space-between', }, tableWidget: { - overflowX: "auto", + overflowX: 'auto', }, progressBar: { backgroundColor: theme.palette.warning.main, }, performanceLegendWrapper: { - display: "flex", + display: 'flex', flexGrow: 1, - alignItems: "center", + alignItems: 'center', marginBottom: theme.spacing(1), }, legendElement: { - display: "flex", - alignItems: "center", + display: 'flex', + alignItems: 'center', marginRight: theme.spacing(2), }, legendElementText: { marginLeft: theme.spacing(1), }, serverOverviewElement: { - display: "flex", - alignItems: "center", - maxWidth: "100%", + display: 'flex', + alignItems: 'center', + maxWidth: '100%', }, serverOverviewElementText: { minWidth: 145, paddingRight: theme.spacing(2), }, serverOverviewElementChartWrapper: { - width: "100%", + width: '100%', }, mainChartBody: { - overflowX: "auto", + overflowX: 'auto', }, mainChartHeader: { - width: "100%", - display: "flex", - alignItems: "center", - justifyContent: "space-between", - [theme.breakpoints.only("xs")]: { - flexWrap: "wrap", + width: '100%', + display: 'flex', + alignItems: 'center', + justifyContent: 'space-between', + [theme.breakpoints.only('xs')]: { + flexWrap: 'wrap', }, }, mainChartHeaderLabels: { - display: "flex", - alignItems: "center", - [theme.breakpoints.only("xs")]: { + display: 'flex', + alignItems: 'center', + [theme.breakpoints.only('xs')]: { order: 3, - width: "100%", - justifyContent: "center", + width: '100%', + justifyContent: 'center', marginTop: theme.spacing(3), marginBottom: theme.spacing(2), }, }, mainChartHeaderLabel: { - display: "flex", - alignItems: "center", + display: 'flex', + alignItems: 'center', marginLeft: theme.spacing(3), }, mainChartSelectRoot: { - borderColor: theme.palette.text.hint + "80 !important", + borderColor: theme.palette.text.hint + '80 !important', }, mainChartSelect: { padding: 10, paddingRight: 25, }, mainChartLegentElement: { - fontSize: "18px !important", + fontSize: '18px !important', marginLeft: theme.spacing(1), }, })); diff --git a/src/pages/error/Error.js b/src/pages/error/Error.js index 24e2048..fde6b95 100644 --- a/src/pages/error/Error.js +++ b/src/pages/error/Error.js @@ -1,13 +1,13 @@ -import React from "react"; -import { Grid, Paper, Typography, Button } from "@material-ui/core"; -import { Link } from "react-router-dom"; -import classnames from "classnames"; +import React from 'react'; +import { Grid, Paper, Typography, Button } from '@material-ui/core'; +import { Link } from 'react-router-dom'; +import classnames from 'classnames'; // styles -import useStyles from "./styles"; +import useStyles from './styles'; // logo -import logo from "./logo.png"; +import logo from './logo.png'; export default function Error() { var classes = useStyles(); diff --git a/src/pages/error/styles.js b/src/pages/error/styles.js index faeb522..7546f5d 100644 --- a/src/pages/error/styles.js +++ b/src/pages/error/styles.js @@ -1,29 +1,29 @@ -import { makeStyles } from "@material-ui/styles"; +import { makeStyles } from '@material-ui/styles'; -export default makeStyles(theme => ({ +export default makeStyles((theme) => ({ container: { - height: "100vh", - width: "100vw", - display: "flex", - flexDirection: "column", - justifyContent: "center", - alignItems: "center", + height: '100vh', + width: '100vw', + display: 'flex', + flexDirection: 'column', + justifyContent: 'center', + alignItems: 'center', backgroundColor: theme.palette.primary.main, - position: "absolute", + position: 'absolute', top: 0, left: 0, }, logotype: { - display: "flex", - alignItems: "center", + display: 'flex', + alignItems: 'center', marginBottom: theme.spacing(12), - [theme.breakpoints.down("sm")]: { - display: "none", + [theme.breakpoints.down('sm')]: { + display: 'none', }, }, logotypeText: { fontWeight: 500, - color: "white", + color: 'white', marginLeft: theme.spacing(2), }, logotypeIcon: { @@ -32,9 +32,9 @@ export default makeStyles(theme => ({ }, paperRoot: { boxShadow: theme.customShadows.widgetDark, - display: "flex", - flexDirection: "column", - alignItems: "center", + display: 'flex', + flexDirection: 'column', + alignItems: 'center', paddingTop: theme.spacing(8), paddingBottom: theme.spacing(8), paddingLeft: theme.spacing(6), @@ -43,7 +43,7 @@ export default makeStyles(theme => ({ }, textRow: { marginBottom: theme.spacing(10), - textAlign: "center", + textAlign: 'center', }, errorCode: { fontSize: 148, @@ -55,7 +55,7 @@ export default makeStyles(theme => ({ }, backButton: { boxShadow: theme.customShadows.widget, - textTransform: "none", + textTransform: 'none', fontSize: 22, }, })); diff --git a/src/pages/fields/Fields.js b/src/pages/fields/Fields.js index 4af8419..57045b9 100644 --- a/src/pages/fields/Fields.js +++ b/src/pages/fields/Fields.js @@ -1,356 +1,370 @@ -import React, { - useState, - useCallback, - useEffect, - memo, - useRef -} from "react" -import store from "../../store/index" +import React, { useState, useCallback, useEffect, memo, useRef } from 'react'; +import store from '../../store/index'; import { - EuiForm, - EuiPageContent, - EuiPageContentHeader, - EuiPageContentHeaderSection, - EuiTitle, - EuiPageContentBody, - EuiTabbedContent, - EuiFormRow, - EuiText, - EuiFilePicker, - EuiButton, - EuiInMemoryTable -} from '@elastic/eui' -import { ShowAlert } from '../../components/Common' + EuiForm, + EuiPageContent, + EuiPageContentHeader, + EuiPageContentHeaderSection, + EuiTitle, + EuiPageContentBody, + EuiTabbedContent, + EuiFormRow, + EuiText, + EuiFilePicker, + EuiButton, + EuiInMemoryTable, +} from '@elastic/eui'; +import { ShowAlert } from '../../components/Common'; import Papa from 'papaparse'; const renderFiles = (files) => { - if (files && files.length > 0) { - return ( - <ul> - {Object.keys(files).map((item, i) => ( - <li key={i}> - <strong>{files[item].name}</strong> ({files[item].size} bytes) - </li> - ))} - </ul> - ); - } else { - return ( - <p>Please, add some files to upload.</p> - ); - } -} - -const NewFieldsForm = memo(({ files, globalState, onFilePickerChange, onSaveField }) => { + if (files && files.length > 0) { return ( - <> - <EuiForm component="form"> - <EuiFormRow - label="Standard Field Files"> - <EuiFilePicker - id="filePicker1" - multiple - initialPromptText="Select or drag and drop multiple source files" - onChange={files => { - onFilePickerChange(files); - }} - display={'large'} - /> - </EuiFormRow> - <EuiFormRow label=""> - <EuiText> - <h3>Files attached</h3> - {renderFiles(files)} - </EuiText> - </EuiFormRow> - <EuiFormRow label=""> - {<EuiButton fill onClick={onSaveField} isLoading={globalState.isLoading}> - Load - </EuiButton>} - </EuiFormRow> - </EuiForm> - </> - ) -}) - -const StdFields = memo(({ stdFields, stdFieldColumns, tableref, pagination, sorting, onTableChange, onSelection, search, isLoading }) => { + <ul> + {Object.keys(files).map((item, i) => ( + <li key={i}> + <strong>{files[item].name}</strong> ({files[item].size} bytes) + </li> + ))} + </ul> + ); + } else { + return <p>Please, add some files to upload.</p>; + } +}; +const NewFieldsForm = memo(({ files, globalState, onFilePickerChange, onSaveField }) => { + return ( + <> + <EuiForm component="form"> + <EuiFormRow label="Standard Field Files"> + <EuiFilePicker + id="filePicker1" + multiple + initialPromptText="Select or drag and drop multiple source files" + onChange={(files) => { + onFilePickerChange(files); + }} + display={'large'} + /> + </EuiFormRow> + <EuiFormRow label=""> + <EuiText> + <h3>Files attached</h3> + {renderFiles(files)} + </EuiText> + </EuiFormRow> + <EuiFormRow label=""> + { + <EuiButton fill onClick={onSaveField} isLoading={globalState.isLoading}> + Load + </EuiButton> + } + </EuiFormRow> + </EuiForm> + </> + ); +}); + +const StdFields = memo( + ({ + stdFields, + stdFieldColumns, + tableref, + pagination, + sorting, + onTableChange, + onSelection, + search, + isLoading, + }) => { return ( - <> - <EuiForm component="form"> - <EuiFormRow - label="Uploaded Standard Fields" fullWidth> - <EuiInMemoryTable - // ref={tableref} - // itemId="id" - // isSelectable={true} - items={stdFields} - loading={isLoading} - columns={stdFieldColumns} - search={search} - pagination={true} - sorting={true} - // onChange={onTableChange} - // rowheader={"field_name"} - // selection={onSelection} - /> - </EuiFormRow> - </EuiForm> - </> - ) -}) + <> + <EuiForm component="form"> + <EuiFormRow label="Uploaded Standard Fields" fullWidth> + <EuiInMemoryTable + // ref={tableref} + // itemId="id" + // isSelectable={true} + items={stdFields} + loading={isLoading} + columns={stdFieldColumns} + search={search} + pagination={true} + sorting={true} + // onChange={onTableChange} + // rowheader={"field_name"} + // selection={onSelection} + /> + </EuiFormRow> + </EuiForm> + </> + ); + } +); let debounceTimeoutId; let requestTimeoutId; const Fields = (props) => { - const [globalState, globalActions] = store(); - const [selectedTabNumber, setSelectedTabNumber] = useState(0) - const [open, setOpen] = useState(false); - const [alertMessage, setAlertMessage] = useState("") - const [severity, setSeverity] = useState("info") - const [files, setFiles] = useState() - // const [fieldsCol, setFieldsCol] = useState([]) - const [fields, setFields] = useState([]) - const [stdFields, setStdFields] = useState([]) - const [pageIndex, setPageIndex] = useState(0); - const [pageSize, setPageSize] = useState(5); - const [sortDirection, setSortDirection] = useState('asc'); - const [sortField, setSortField] = useState('field_name'); - const [totalItemCount, setTotalItemCount] = useState(0) - const tableref = useRef(); - const [isLoading, setIsLoading] = useState(false); - - const loadStdFields = useCallback(async () => { - const fields = await globalActions.source.publicFields() - if (fields) { - setStdFields(prevFields => ([...prevFields, ...fields])) - setTotalItemCount((typeof fields === typeof undefined ? 0 : fields.length)) - } - }, [globalActions.source]) + const [globalState, globalActions] = store(); + const [selectedTabNumber, setSelectedTabNumber] = useState(0); + const [open, setOpen] = useState(false); + const [alertMessage, setAlertMessage] = useState(''); + const [severity, setSeverity] = useState('info'); + const [files, setFiles] = useState(); + // const [fieldsCol, setFieldsCol] = useState([]) + const [fields, setFields] = useState([]); + const [stdFields, setStdFields] = useState([]); + const [pageIndex, setPageIndex] = useState(0); + const [pageSize, setPageSize] = useState(5); + const [sortDirection, setSortDirection] = useState('asc'); + const [sortField, setSortField] = useState('field_name'); + const [totalItemCount, setTotalItemCount] = useState(0); + const tableref = useRef(); + const [isLoading, setIsLoading] = useState(false); + + const loadStdFields = useCallback(async () => { + const fields = await globalActions.source.publicFields(); + if (fields) { + setStdFields((prevFields) => [...prevFields, ...fields]); + setTotalItemCount(typeof fields === typeof undefined ? 0 : fields.length); + } + }, [globalActions.source]); - useEffect(() => { - // clean up controller - let isSubscribed = true; - if (isSubscribed) { - loadStdFields() + useEffect(() => { + // clean up controller + let isSubscribed = true; + if (isSubscribed) { + loadStdFields(); + } + // cancel subscription to useEffect + return () => (isSubscribed = false); + }, [totalItemCount, loadStdFields]); + + const onQueryChange = ({ query }) => { + clearTimeout(debounceTimeoutId); + clearTimeout(requestTimeoutId); + + debounceTimeoutId = setTimeout(() => { + setIsLoading(true); + requestTimeoutId = setTimeout(() => { + const items = stdFields.filter((field) => { + const normalizedFieldName = + `${field.field_name} ${field.Definition_and_comment}`.toLowerCase(); + const normalizedQuery = query.text.toLowerCase(); + return normalizedFieldName.indexOf(normalizedQuery) !== -1; + }); + if (query.text !== '') { + setIsLoading(false); + setStdFields(items); + } else { + loadStdFields(); } - // cancel subscription to useEffect - return () => (isSubscribed = false) - }, [totalItemCount, loadStdFields]) - - - const onQueryChange = ({ query }) => { - clearTimeout(debounceTimeoutId); - clearTimeout(requestTimeoutId); - - debounceTimeoutId = setTimeout(() => { - setIsLoading(true); - requestTimeoutId = setTimeout(() => { - const items = stdFields.filter(field => { - const normalizedFieldName = `${field.field_name} ${field.Definition_and_comment}`.toLowerCase() - const normalizedQuery = query.text.toLowerCase() - return normalizedFieldName.indexOf(normalizedQuery) !== -1; - }); - if (query.text !== "") { - setIsLoading(false); - setStdFields(items); - } else { - loadStdFields() - } - }, 1000); - }, 300); - }; - - const search = { - onChange: onQueryChange, - box: { - incremental: true, - }, - }; - - - /* + }, 1000); + }, 300); + }; + + const search = { + onChange: onQueryChange, + box: { + incremental: true, + }, + }; + + /* const onSelection = { selectable: source => !source.is_send, onSelectionChange: onSelectionChange, initialSelected: unsentSources, }; */ - const onTableChange = ({ page = {}, sort = {} }) => { - const { index: pageIndex, size: pageSize } = page; - const { field: sortField, direction: sortDirection } = sort; - - setPageIndex(pageIndex); - setPageSize(pageSize); - setSortField(sortField); - setSortDirection(sortDirection); - }; - - const pagination = { - pageIndex: pageIndex, - pageSize: pageSize, - totalItemCount: totalItemCount, - pageSizeOptions: [3, 5, 8], - }; - - const sorting = { - sort: { - field: sortField, - direction: sortDirection, - }, - }; - - const onFilePickerChange = async (files) => { - setFiles(files) - await handleSelectedFile(files); + const onTableChange = ({ page = {}, sort = {} }) => { + const { index: pageIndex, size: pageSize } = page; + const { field: sortField, direction: sortDirection } = sort; + + setPageIndex(pageIndex); + setPageSize(pageSize); + setSortField(sortField); + setSortDirection(sortDirection); + }; + + const pagination = { + pageIndex: pageIndex, + pageSize: pageSize, + totalItemCount: totalItemCount, + pageSizeOptions: [3, 5, 8], + }; + + const sorting = { + sort: { + field: sortField, + direction: sortDirection, + }, + }; + + const onFilePickerChange = async (files) => { + setFiles(files); + await handleSelectedFile(files); + }; + + const handleSelectedFile = async (files) => { + for (const file of files) { + const reader = new FileReader(); + await reader.readAsText(file); + reader.onload = () => handleData(reader.result); } - - const handleSelectedFile = async (files) => { - for (const file of files) { - const reader = new FileReader() - await reader.readAsText(file); - reader.onload = () => handleData(reader.result) - } - } - - const handleData = (file) => { - if (file) { - var result = Papa.parse(file, { header: true }); - var columns = []; - const rows = []; - result.meta.fields.forEach((item) => { - var column = { - name: item, - options: { - display: true - } - } - columns.push(column); - }); - - result.data.forEach((item) => { - rows.push(item); - }); - - if (columns && rows) { - // (preColumns => ([...preColumns, ...columns])) - setFields(preRows => ([...preRows, ...rows])) - } - } - } - - const onSaveField = async () => { - if (fields) { - await globalActions.source.truncateStdField() - - await fields.forEach((item) => { - globalActions.source.createStdField( - item.Category, - item.Field_name, - item.Definition_and_comment, - item.Obligation_or_condition, - item.Field_type, - item.Cardinality, - item.Values, - item.is_public, - false - ) - }) - - setOpen(true) - setAlertMessage("Standard fields added successfully!") - setSeverity("success") - loadStdFields() - } + }; + + const handleData = (file) => { + if (file) { + var result = Papa.parse(file, { header: true }); + var columns = []; + const rows = []; + result.meta.fields.forEach((item) => { + var column = { + name: item, + options: { + display: true, + }, + }; + columns.push(column); + }); + + result.data.forEach((item) => { + rows.push(item); + }); + + if (columns && rows) { + // (preColumns => ([...preColumns, ...columns])) + setFields((preRows) => [...preRows, ...rows]); + } } + }; + + const onSaveField = async () => { + if (fields) { + await globalActions.source.truncateStdField(); + + await fields.forEach((item) => { + globalActions.source.createStdField( + item.Category, + item.Field_name, + item.Definition_and_comment, + item.Obligation_or_condition, + item.Field_type, + item.Cardinality, + item.Values, + item.is_public, + false + ); + }); - - const stdFieldColumns = [ - { - field: 'field_name', - name: 'Field Name', - sortable: true, - truncateText: true, - }, - { - field: 'field_type', - name: 'Field Type', - }, - { - field: 'definition_and_comment', - name: 'Definition And Comment', - // truncateText: true, - }, - { - field: 'Obligation_or_condition', - name: 'Obligation or Condition', - }, - { - field: 'values', - name: 'Values', - sortable: true, - truncateText: true, - // render: date => formatDate(date, 'dobLong'), - }, - - ] - - const tabContents = [ - { - id: 'tab1', - name: 'Upload Fields', - content: ( - <> - <br /> - <NewFieldsForm files={files} globalState={globalState} onFilePickerChange={onFilePickerChange} onSaveField={onSaveField} /> - </> - ) - }, - { - id: 'tab2', - name: 'Fields', - content: ( - <> - <br /> - <StdFields stdFields={stdFields} stdFieldColumns={stdFieldColumns} pagination={pagination} sorting={sorting} tableref={tableref} onTableChange={onTableChange} search={search} loading={isLoading} /> - </> - ) - } - ] - - const handleClose = (event, reason) => { - if (reason === 'clickaway') { - return; - } - setOpen(false); + setOpen(true); + setAlertMessage('Standard fields added successfully!'); + setSeverity('success'); + loadStdFields(); } - - return ( + }; + + const stdFieldColumns = [ + { + field: 'field_name', + name: 'Field Name', + sortable: true, + truncateText: true, + }, + { + field: 'field_type', + name: 'Field Type', + }, + { + field: 'definition_and_comment', + name: 'Definition And Comment', + // truncateText: true, + }, + { + field: 'Obligation_or_condition', + name: 'Obligation or Condition', + }, + { + field: 'values', + name: 'Values', + sortable: true, + truncateText: true, + // render: date => formatDate(date, 'dobLong'), + }, + ]; + + const tabContents = [ + { + id: 'tab1', + name: 'Upload Fields', + content: ( <> - <EuiPageContent> - <EuiPageContentHeader> - <EuiPageContentHeaderSection> - <EuiTitle> - <h6>Field Management</h6> - </EuiTitle> - </EuiPageContentHeaderSection> - </EuiPageContentHeader> - <EuiPageContentBody> - <EuiForm> - <EuiTabbedContent - tabs={tabContents} - selectedTab={tabContents[selectedTabNumber]} - onTabClick={tab => { - setSelectedTabNumber(tabContents.indexOf(tab)) - loadStdFields() - }} - /> - </EuiForm> - </EuiPageContentBody> - </EuiPageContent> - {ShowAlert(open, handleClose, alertMessage, severity)} + <br /> + <NewFieldsForm + files={files} + globalState={globalState} + onFilePickerChange={onFilePickerChange} + onSaveField={onSaveField} + /> </> - ) -} + ), + }, + { + id: 'tab2', + name: 'Fields', + content: ( + <> + <br /> + <StdFields + stdFields={stdFields} + stdFieldColumns={stdFieldColumns} + pagination={pagination} + sorting={sorting} + tableref={tableref} + onTableChange={onTableChange} + search={search} + loading={isLoading} + /> + </> + ), + }, + ]; -export default Fields \ No newline at end of file + const handleClose = (event, reason) => { + if (reason === 'clickaway') { + return; + } + setOpen(false); + }; + + return ( + <> + <EuiPageContent> + <EuiPageContentHeader> + <EuiPageContentHeaderSection> + <EuiTitle> + <h6>Field Management</h6> + </EuiTitle> + </EuiPageContentHeaderSection> + </EuiPageContentHeader> + <EuiPageContentBody> + <EuiForm> + <EuiTabbedContent + tabs={tabContents} + selectedTab={tabContents[selectedTabNumber]} + onTabClick={(tab) => { + setSelectedTabNumber(tabContents.indexOf(tab)); + loadStdFields(); + }} + /> + </EuiForm> + </EuiPageContentBody> + </EuiPageContent> + {ShowAlert(open, handleClose, alertMessage, severity)} + </> + ); +}; + +export default Fields; diff --git a/src/pages/fields/package.json b/src/pages/fields/package.json index 12a49cf..7f0ff5a 100644 --- a/src/pages/fields/package.json +++ b/src/pages/fields/package.json @@ -1,6 +1,6 @@ { - "name": "Fields", - "version": "1.0.0", - "private": true, - "main": "Fields.js" -} \ No newline at end of file + "name": "Fields", + "version": "1.0.0", + "private": true, + "main": "Fields.js" +} diff --git a/src/pages/fields/styles.js b/src/pages/fields/styles.js index d23f5a3..9e578a3 100644 --- a/src/pages/fields/styles.js +++ b/src/pages/fields/styles.js @@ -1,96 +1,96 @@ -import { makeStyles } from "@material-ui/styles"; +import { makeStyles } from '@material-ui/styles'; -export default makeStyles(theme => ({ - titleBold: { - fontWeight: 600, - }, - tab: { - color: theme.palette.primary.light + "CC", - }, - iconsContainer: { - boxShadow: theme.customShadows.widget, - overflow: "hidden", - paddingBottom: theme.spacing(2), - }, - text: { - marginBottom: theme.spacing(2), - }, - root: { - padding: theme.spacing(3, 2), - }, +export default makeStyles((theme) => ({ + titleBold: { + fontWeight: 600, + }, + tab: { + color: theme.palette.primary.light + 'CC', + }, + iconsContainer: { + boxShadow: theme.customShadows.widget, + overflow: 'hidden', + paddingBottom: theme.spacing(2), + }, + text: { + marginBottom: theme.spacing(2), + }, + root: { + padding: theme.spacing(3, 2), + }, - body: { - backgroundColor: "#f2ede8", - margin: 0, - padding: 0, - fontSize: "16px", - fontFamily: "sans-serif", - display: "flex", - height: "100vh" - }, - FileUploadForm: { - backgroundColor: "#fff", - padding: "2rem", - display: "grid", - gridGap: "1.6rem", - }, - ActionBar: { - textAlign: "right" - }, + body: { + backgroundColor: '#f2ede8', + margin: 0, + padding: 0, + fontSize: '16px', + fontFamily: 'sans-serif', + display: 'flex', + height: '100vh', + }, + FileUploadForm: { + backgroundColor: '#fff', + padding: '2rem', + display: 'grid', + gridGap: '1.6rem', + }, + ActionBar: { + textAlign: 'right', + }, - ActionBarButton: { - padding: ".4rem" - }, + ActionBarButton: { + padding: '.4rem', + }, - MessageBox: { - padding: "1.6rem", - backgroundColor: "#faf4e9", - borderTop: "3px solid #ffa600" - }, - input: { - display: 'none', - }, - dashedBorder: { - border: "1px dashed", - borderColor: theme.palette.primary.main, - padding: theme.spacing(2), - paddingTop: theme.spacing(4), - paddingBottom: theme.spacing(4), - marginTop: theme.spacing(1), - }, + MessageBox: { + padding: '1.6rem', + backgroundColor: '#faf4e9', + borderTop: '3px solid #ffa600', + }, + input: { + display: 'none', + }, + dashedBorder: { + border: '1px dashed', + borderColor: theme.palette.primary.main, + padding: theme.spacing(2), + paddingTop: theme.spacing(4), + paddingBottom: theme.spacing(4), + marginTop: theme.spacing(1), + }, - appBar: { - position: 'relative', - }, - layout: { - width: 'auto', - marginLeft: theme.spacing(2), - marginRight: theme.spacing(2), - [theme.breakpoints.up(600 + theme.spacing(2) * 2)]: { - width: 600, - marginLeft: 'auto', - marginRight: 'auto', - }, - }, - paper: { - marginTop: theme.spacing(3), - marginBottom: theme.spacing(3), - padding: theme.spacing(2), - [theme.breakpoints.up(600 + theme.spacing(3) * 2)]: { - marginTop: theme.spacing(6), - marginBottom: theme.spacing(6), - padding: theme.spacing(3), - }, - }, - stepper: { - padding: theme.spacing(3, 0, 5), - }, - buttons: { - display: 'flex', - justifyContent: 'flex-end', - }, - button: { - marginTop: theme.spacing(3), - marginLeft: theme.spacing(1), - }, -})); \ No newline at end of file + appBar: { + position: 'relative', + }, + layout: { + width: 'auto', + marginLeft: theme.spacing(2), + marginRight: theme.spacing(2), + [theme.breakpoints.up(600 + theme.spacing(2) * 2)]: { + width: 600, + marginLeft: 'auto', + marginRight: 'auto', + }, + }, + paper: { + marginTop: theme.spacing(3), + marginBottom: theme.spacing(3), + padding: theme.spacing(2), + [theme.breakpoints.up(600 + theme.spacing(3) * 2)]: { + marginTop: theme.spacing(6), + marginBottom: theme.spacing(6), + padding: theme.spacing(3), + }, + }, + stepper: { + padding: theme.spacing(3, 0, 5), + }, + buttons: { + display: 'flex', + justifyContent: 'flex-end', + }, + button: { + marginTop: theme.spacing(3), + marginLeft: theme.spacing(1), + }, +})); diff --git a/src/pages/group/Group.js b/src/pages/group/Group.js index 81ca8ea..252f11f 100644 --- a/src/pages/group/Group.js +++ b/src/pages/group/Group.js @@ -1,341 +1,394 @@ - -import React, { useState, Fragment, useEffect, memo, useCallback } from "react" -import store from "../../store/index" -import { ShowAlert } from '../../components/Common' +import React, { useState, Fragment, useEffect, memo, useCallback } from 'react'; +import store from '../../store/index'; +import { ShowAlert } from '../../components/Common'; import { - EuiForm, - EuiPageContent, - EuiPageContentHeader, - EuiPageContentHeaderSection, - EuiTitle, - EuiPageContentBody, - EuiTabbedContent, - EuiFormRow, - EuiFieldText, - EuiFlexGroup, - EuiFlexItem, - EuiSpacer, - EuiButton, - EuiBasicTable, - EuiSelectable, - EuiComboBox -} from '@elastic/eui' - -const NewGroupForm = memo(({ globalState, groupNameValue, setGroupNameValue, groupDescriptionValue, setGroupDescriptionValue, onSaveGroup, groups, groupColumns }) => { - + EuiForm, + EuiPageContent, + EuiPageContentHeader, + EuiPageContentHeaderSection, + EuiTitle, + EuiPageContentBody, + EuiTabbedContent, + EuiFormRow, + EuiFieldText, + EuiFlexGroup, + EuiFlexItem, + EuiSpacer, + EuiButton, + EuiBasicTable, + EuiSelectable, + EuiComboBox, +} from '@elastic/eui'; + +const NewGroupForm = memo( + ({ + globalState, + groupNameValue, + setGroupNameValue, + groupDescriptionValue, + setGroupDescriptionValue, + onSaveGroup, + groups, + groupColumns, + }) => { return ( - <> - <br /> - <EuiForm component="form"> - <EuiFormRow label="Group Name"> - <EuiFieldText value={groupNameValue} onChange={e => setGroupNameValue(e.target.value)} /> - </EuiFormRow> - <EuiFormRow label="Group Description"> - <EuiFieldText id="descriptionValue" value={groupDescriptionValue} onChange={e => setGroupDescriptionValue(e.target.value)} /> - </EuiFormRow> - <EuiSpacer /> - {<EuiButton fill onClick={onSaveGroup} isLoading={globalState.isLoading}> - Save - </EuiButton>} - <EuiSpacer /> - <EuiFormRow - fullWidth - label=""> - <EuiBasicTable - items={groups} - columns={groupColumns} - /> - </EuiFormRow> - </EuiForm> - </> - ) - -}) - -const GroupAssignment = memo(({ groups, setGroups, users, setUsers, onGroupAssignment, globalState }) => { + <> + <br /> + <EuiForm component="form"> + <EuiFormRow label="Group Name"> + <EuiFieldText + value={groupNameValue} + onChange={(e) => setGroupNameValue(e.target.value)} + /> + </EuiFormRow> + <EuiFormRow label="Group Description"> + <EuiFieldText + id="descriptionValue" + value={groupDescriptionValue} + onChange={(e) => setGroupDescriptionValue(e.target.value)} + /> + </EuiFormRow> + <EuiSpacer /> + { + <EuiButton fill onClick={onSaveGroup} isLoading={globalState.isLoading}> + Save + </EuiButton> + } + <EuiSpacer /> + <EuiFormRow fullWidth label=""> + <EuiBasicTable items={groups} columns={groupColumns} /> + </EuiFormRow> + </EuiForm> + </> + ); + } +); + +const GroupAssignment = memo( + ({ groups, setGroups, users, setUsers, onGroupAssignment, globalState }) => { return ( - <> - <EuiForm component="form"> - <EuiFlexGroup component="span"> - <EuiFlexItem component="span"> - <EuiFormRow label="Groups" fullWidth> - <EuiSelectable - searchable - singleSelection={{ asPlainText: true }} - options={groups} - onChange={newOptions => setGroups(newOptions)}> - {(list, search) => ( - <Fragment> - {search} - {list} - </Fragment> - )} - </EuiSelectable> - </EuiFormRow> - </EuiFlexItem> - <EuiFlexItem component="span"> - <EuiFormRow label="Users" fullWidth> - <EuiSelectable - searchable - options={users} - onChange={newOptions => setUsers(newOptions)}> - {(list, search) => ( - <Fragment> - {search} - {list} - </Fragment> - )} - </EuiSelectable> - </EuiFormRow> - </EuiFlexItem> - </EuiFlexGroup> - <EuiSpacer /> - {<EuiButton type="submit" onClick={onGroupAssignment} isLoading={globalState.isLoading} fill> - Save - </EuiButton>} - </EuiForm> - </> - ) -}) - -const AssignedGroups = memo(({ groups, selectedGroup, onSelectedGroup, groupedUsers, assignedGroupedUserColumns }) => { - + <> + <EuiForm component="form"> + <EuiFlexGroup component="span"> + <EuiFlexItem component="span"> + <EuiFormRow label="Groups" fullWidth> + <EuiSelectable + searchable + singleSelection={{ asPlainText: true }} + options={groups} + onChange={(newOptions) => setGroups(newOptions)} + > + {(list, search) => ( + <Fragment> + {search} + {list} + </Fragment> + )} + </EuiSelectable> + </EuiFormRow> + </EuiFlexItem> + <EuiFlexItem component="span"> + <EuiFormRow label="Users" fullWidth> + <EuiSelectable + searchable + options={users} + onChange={(newOptions) => setUsers(newOptions)} + > + {(list, search) => ( + <Fragment> + {search} + {list} + </Fragment> + )} + </EuiSelectable> + </EuiFormRow> + </EuiFlexItem> + </EuiFlexGroup> + <EuiSpacer /> + { + <EuiButton + type="submit" + onClick={onGroupAssignment} + isLoading={globalState.isLoading} + fill + > + Save + </EuiButton> + } + </EuiForm> + </> + ); + } +); + +const AssignedGroups = memo( + ({ + groups, + selectedGroup, + onSelectedGroup, + groupedUsers, + assignedGroupedUserColumns, + }) => { return ( - <> - <EuiForm component="form"> - <EuiFormRow - label="Select Specific Group"> - <EuiComboBox - placeholder="Select a group" - singleSelection={{ asPlainText: true }} - options={groups} - selectedOptions={selectedGroup} - onChange={e => { - onSelectedGroup(e) - }} - /> - </EuiFormRow> - <EuiFormRow - label="Assigned Policies" fullWidth> - <EuiBasicTable - items={groupedUsers} - columns={assignedGroupedUserColumns} - /> - </EuiFormRow> - </EuiForm> - </> - ) -}) + <> + <EuiForm component="form"> + <EuiFormRow label="Select Specific Group"> + <EuiComboBox + placeholder="Select a group" + singleSelection={{ asPlainText: true }} + options={groups} + selectedOptions={selectedGroup} + onChange={(e) => { + onSelectedGroup(e); + }} + /> + </EuiFormRow> + <EuiFormRow label="Assigned Policies" fullWidth> + <EuiBasicTable items={groupedUsers} columns={assignedGroupedUserColumns} /> + </EuiFormRow> + </EuiForm> + </> + ); + } +); const Group = (props) => { - - const [selectedTabNumber, setSelectedTabNumber] = useState(0) - const [globalState, globalActions] = store() - const [groupNameValue, setGroupNameValue] = useState('') - const [groupDescriptionValue, setGroupDescriptionValue] = useState('') - const [groups, setGroups] = useState([]) - const [open, setOpen] = useState(false); - const [alertMessage, setAlertMessage] = useState('') - const [severity, setSeverity] = useState("info") - const [users, setUsers] = useState([]) - const [tblGroups, setTblGroups] = useState([]) - const [selectedGroup, setSelectedGroup] = useState([]) - const [groupedUsers, setGroupedUsers] = useState([]) - - const loadGroups = useCallback(async () => { - const _groups = await globalActions.group.getGroups() - if (_groups) { - const grouplist = [] - for (const group of _groups) { - grouplist.push({ value: group.id, label: group.name }) - } - if (grouplist) { - setTblGroups(grouplist) - } - setGroups(_groups) - } - }, [globalActions.group]) - - const loadUsers = useCallback(async () => { - const _users = await globalActions.user.findUser() - const usersList = [] - if (_users) { - for (const user of _users) { - usersList.push({ value: user.id, label: user.username }) - } - if (usersList) { - setUsers(usersList) - } - } - }, [globalActions.user]) - - useEffect(() => { - let isSubscribed = true; - if (isSubscribed) { - loadGroups() - loadUsers() - } - return () => (isSubscribed = false) - }, [loadGroups, loadUsers]) - - const onDeleteGroup = async (group) => { - if (group) { - await globalActions.group.deleteGroup(group.id) - } - loadGroups() + const [selectedTabNumber, setSelectedTabNumber] = useState(0); + const [globalState, globalActions] = store(); + const [groupNameValue, setGroupNameValue] = useState(''); + const [groupDescriptionValue, setGroupDescriptionValue] = useState(''); + const [groups, setGroups] = useState([]); + const [open, setOpen] = useState(false); + const [alertMessage, setAlertMessage] = useState(''); + const [severity, setSeverity] = useState('info'); + const [users, setUsers] = useState([]); + const [tblGroups, setTblGroups] = useState([]); + const [selectedGroup, setSelectedGroup] = useState([]); + const [groupedUsers, setGroupedUsers] = useState([]); + + const loadGroups = useCallback(async () => { + const _groups = await globalActions.group.getGroups(); + if (_groups) { + const grouplist = []; + for (const group of _groups) { + grouplist.push({ value: group.id, label: group.name }); + } + if (grouplist) { + setTblGroups(grouplist); + } + setGroups(_groups); } - - const onSaveGroup = async () => { - - if (groupNameValue && sessionStorage.getItem('userId')) { - await globalActions.group.createGroup(groupNameValue, groupDescriptionValue, sessionStorage.getItem('userId')) - - if (globalState.status === 'SUCCESS') { - setOpen(true) - setAlertMessage("Group created succesfully !") - setSeverity("success") - } - await loadGroups() - } + }, [globalActions.group]); + + const loadUsers = useCallback(async () => { + const _users = await globalActions.user.findUser(); + const usersList = []; + if (_users) { + for (const user of _users) { + usersList.push({ value: user.id, label: user.username }); + } + if (usersList) { + setUsers(usersList); + } } + }, [globalActions.user]); - const onGroupAssignment = async () => { - const checkedGroups = tblGroups.filter(e => { - return e.checked === 'on' - }) - - const checkedUsers = users.filter(e => { - return e.checked === 'on' - }) - - for (const user of checkedUsers) { - for (const group of checkedGroups) { - const assignedUserToGroup = await globalActions.group.createGroupUser(group.value, user.value) - console.log(assignedUserToGroup) - } - } - - if (globalState.status === 'SUCCESS') { - setOpen(true) - setAlertMessage("User-Group assignment completed succesfully !") - setSeverity("success") - } - + useEffect(() => { + let isSubscribed = true; + if (isSubscribed) { + loadGroups(); + loadUsers(); } + return () => (isSubscribed = false); + }, [loadGroups, loadUsers]); - const onRemoveUserFromGroup = async (e) => { - await globalActions.group.deleteGroupUser(e.groupid, e.userid) - const groupedUsers = await globalActions.group.getGroupUsers(e.groupid) - setGroupedUsers(groupedUsers) + const onDeleteGroup = async (group) => { + if (group) { + await globalActions.group.deleteGroup(group.id); } - - const onSelectedGroup = async (e) => { - if (e.length > 0) { - const groupedUsers = await globalActions.group.getGroupUsers(e[0].value) - setGroupedUsers(groupedUsers) - setSelectedGroup(e) - } else { - setSelectedGroup(e) - } + loadGroups(); + }; + + const onSaveGroup = async () => { + if (groupNameValue && sessionStorage.getItem('userId')) { + await globalActions.group.createGroup( + groupNameValue, + groupDescriptionValue, + sessionStorage.getItem('userId') + ); + + if (globalState.status === 'SUCCESS') { + setOpen(true); + setAlertMessage('Group created succesfully !'); + setSeverity('success'); + } + await loadGroups(); } - - const groupActions = [ - { - name: 'Delete', - description: 'Delete this group', - icon: 'trash', - type: 'icon', - color: 'danger', - onClick: onDeleteGroup, - }, - ]; - - const assignedGroupedUserActions = [ - { - name: 'Delete', - description: 'Delete this person', - icon: 'trash', - type: 'icon', - color: 'danger', - onClick: onRemoveUserFromGroup, - }, - ] - - const groupColumns = [ - { field: 'name', name: 'Group Name' }, - { field: 'description', name: 'Group description' }, - { name: 'Actions', actions: groupActions } - ] - - const assignedGroupedUserColumns = [ - { field: 'username', name: 'Username' }, - { field: 'name', name: 'Group name' }, - { field: 'description', name: 'Group description' }, - { name: 'Actions', actions: assignedGroupedUserActions }] - - const tabContents = [ - { - id: 'tab1', - name: 'New Group', - content: ( - <> - <NewGroupForm globalState={globalState} groupNameValue={groupNameValue} setGroupNameValue={setGroupNameValue} groupDescriptionValue={groupDescriptionValue} setGroupDescriptionValue={setGroupDescriptionValue} onSaveGroup={onSaveGroup} groups={groups} groupColumns={groupColumns} /> - </> - ) - }, { - id: 'tab2', - name: 'Group Assignment', - content: ( - <> - <GroupAssignment groups={tblGroups} setGroups={setTblGroups} users={users} setUsers={setUsers} onGroupAssignment={onGroupAssignment} globalState={globalState} /> - </> - ) - }, { - id: 'tab3', - name: 'Assigned Groups', - content: ( - <> - <AssignedGroups groups={tblGroups} selectedGroup={selectedGroup} onSelectedGroup={onSelectedGroup} groupedUsers={groupedUsers} assignedGroupedUserColumns={assignedGroupedUserColumns} /> - </> - ) - } - ] - - const handleClose = (event, reason) => { - if (reason === 'clickaway') { - return; - } - setOpen(false); + }; + + const onGroupAssignment = async () => { + const checkedGroups = tblGroups.filter((e) => { + return e.checked === 'on'; + }); + + const checkedUsers = users.filter((e) => { + return e.checked === 'on'; + }); + + for (const user of checkedUsers) { + for (const group of checkedGroups) { + const assignedUserToGroup = await globalActions.group.createGroupUser( + group.value, + user.value + ); + console.log(assignedUserToGroup); + } } - return ( + if (globalState.status === 'SUCCESS') { + setOpen(true); + setAlertMessage('User-Group assignment completed succesfully !'); + setSeverity('success'); + } + }; + + const onRemoveUserFromGroup = async (e) => { + await globalActions.group.deleteGroupUser(e.groupid, e.userid); + const groupedUsers = await globalActions.group.getGroupUsers(e.groupid); + setGroupedUsers(groupedUsers); + }; + + const onSelectedGroup = async (e) => { + if (e.length > 0) { + const groupedUsers = await globalActions.group.getGroupUsers(e[0].value); + setGroupedUsers(groupedUsers); + setSelectedGroup(e); + } else { + setSelectedGroup(e); + } + }; + + const groupActions = [ + { + name: 'Delete', + description: 'Delete this group', + icon: 'trash', + type: 'icon', + color: 'danger', + onClick: onDeleteGroup, + }, + ]; + + const assignedGroupedUserActions = [ + { + name: 'Delete', + description: 'Delete this person', + icon: 'trash', + type: 'icon', + color: 'danger', + onClick: onRemoveUserFromGroup, + }, + ]; + + const groupColumns = [ + { field: 'name', name: 'Group Name' }, + { field: 'description', name: 'Group description' }, + { name: 'Actions', actions: groupActions }, + ]; + + const assignedGroupedUserColumns = [ + { field: 'username', name: 'Username' }, + { field: 'name', name: 'Group name' }, + { field: 'description', name: 'Group description' }, + { name: 'Actions', actions: assignedGroupedUserActions }, + ]; + + const tabContents = [ + { + id: 'tab1', + name: 'New Group', + content: ( <> - <EuiPageContent> - <EuiPageContentHeader> - <EuiPageContentHeaderSection> - <EuiTitle> - <h6>Groups</h6> - </EuiTitle> - </EuiPageContentHeaderSection> - </EuiPageContentHeader> - <EuiPageContentBody> - <EuiForm> - <EuiForm> - <EuiTabbedContent - tabs={tabContents} - selectedTab={tabContents[selectedTabNumber]} - onTabClick={tab => { - setSelectedTabNumber(tabContents.indexOf(tab)) - }} - /> - </EuiForm> - </EuiForm> - </EuiPageContentBody> - </EuiPageContent> - {ShowAlert(open, handleClose, alertMessage, severity)} + <NewGroupForm + globalState={globalState} + groupNameValue={groupNameValue} + setGroupNameValue={setGroupNameValue} + groupDescriptionValue={groupDescriptionValue} + setGroupDescriptionValue={setGroupDescriptionValue} + onSaveGroup={onSaveGroup} + groups={groups} + groupColumns={groupColumns} + /> </> - ) - -} + ), + }, + { + id: 'tab2', + name: 'Group Assignment', + content: ( + <> + <GroupAssignment + groups={tblGroups} + setGroups={setTblGroups} + users={users} + setUsers={setUsers} + onGroupAssignment={onGroupAssignment} + globalState={globalState} + /> + </> + ), + }, + { + id: 'tab3', + name: 'Assigned Groups', + content: ( + <> + <AssignedGroups + groups={tblGroups} + selectedGroup={selectedGroup} + onSelectedGroup={onSelectedGroup} + groupedUsers={groupedUsers} + assignedGroupedUserColumns={assignedGroupedUserColumns} + /> + </> + ), + }, + ]; -export default Group \ No newline at end of file + const handleClose = (event, reason) => { + if (reason === 'clickaway') { + return; + } + setOpen(false); + }; + + return ( + <> + <EuiPageContent> + <EuiPageContentHeader> + <EuiPageContentHeaderSection> + <EuiTitle> + <h6>Groups</h6> + </EuiTitle> + </EuiPageContentHeaderSection> + </EuiPageContentHeader> + <EuiPageContentBody> + <EuiForm> + <EuiForm> + <EuiTabbedContent + tabs={tabContents} + selectedTab={tabContents[selectedTabNumber]} + onTabClick={(tab) => { + setSelectedTabNumber(tabContents.indexOf(tab)); + }} + /> + </EuiForm> + </EuiForm> + </EuiPageContentBody> + </EuiPageContent> + {ShowAlert(open, handleClose, alertMessage, severity)} + </> + ); +}; + +export default Group; diff --git a/src/pages/group/package.json b/src/pages/group/package.json index 9e2a215..0d7c574 100644 --- a/src/pages/group/package.json +++ b/src/pages/group/package.json @@ -1,6 +1,6 @@ { - "name": "Group", - "version": "1.0.0", - "private": true, - "main": "Group.js" -} \ No newline at end of file + "name": "Group", + "version": "1.0.0", + "private": true, + "main": "Group.js" +} diff --git a/src/pages/group/styles.js b/src/pages/group/styles.js index d135699..4842f10 100644 --- a/src/pages/group/styles.js +++ b/src/pages/group/styles.js @@ -1,44 +1,44 @@ -import { makeStyles } from "@material-ui/styles"; +import { makeStyles } from '@material-ui/styles'; -export default makeStyles(theme => ({ - titleBold: { - fontWeight: 600, - }, - tab: { - color: theme.palette.primary.light + "CC", - }, - roleContainer: { - boxShadow: theme.customShadows.widget, - overflow: "hidden", - paddingBottom: theme.spacing(2), - }, - dashedBorder: { - border: "1px dashed", - borderColor: theme.palette.primary.main, - padding: theme.spacing(2), - paddingTop: theme.spacing(4), - paddingBottom: theme.spacing(4), - marginTop: theme.spacing(1), - }, - text: { - marginBottom: theme.spacing(2), - }, - root: { - padding: theme.spacing(3, 2), - }, - formControl: { - margin: theme.spacing(1), - minWidth: 120, - maxWidth: 300, - }, - chips: { - display: 'flex', - flexWrap: 'wrap', - }, - chip: { - margin: 2, - }, - noLabel: { - marginTop: theme.spacing(3), - }, -})); \ No newline at end of file +export default makeStyles((theme) => ({ + titleBold: { + fontWeight: 600, + }, + tab: { + color: theme.palette.primary.light + 'CC', + }, + roleContainer: { + boxShadow: theme.customShadows.widget, + overflow: 'hidden', + paddingBottom: theme.spacing(2), + }, + dashedBorder: { + border: '1px dashed', + borderColor: theme.palette.primary.main, + padding: theme.spacing(2), + paddingTop: theme.spacing(4), + paddingBottom: theme.spacing(4), + marginTop: theme.spacing(1), + }, + text: { + marginBottom: theme.spacing(2), + }, + root: { + padding: theme.spacing(3, 2), + }, + formControl: { + margin: theme.spacing(1), + minWidth: 120, + maxWidth: 300, + }, + chips: { + display: 'flex', + flexWrap: 'wrap', + }, + chip: { + margin: 2, + }, + noLabel: { + marginTop: theme.spacing(3), + }, +})); diff --git a/src/pages/policy/Policy.js b/src/pages/policy/Policy.js index bfa6a6e..48d761f 100644 --- a/src/pages/policy/Policy.js +++ b/src/pages/policy/Policy.js @@ -1,9 +1,5 @@ -import React, { - useState, Fragment, - useCallback, - useEffect, memo -} from "react" -import store from "../../store/index" +import React, { useState, Fragment, useCallback, useEffect, memo } from 'react'; +import store from '../../store/index'; import { EuiForm, @@ -22,28 +18,43 @@ import { EuiButton, EuiBasicTable, EuiSelectable, - EuiComboBox -} from '@elastic/eui' - -import { ShowAlert } from '../../components/Common' - -const NewPolicyForm = memo(({ globalState, policyName, setPolicyName, sources, isSwitchChecked, onSwitchChange, selectedSource, setSelectedSource, onSaveNewPolicy, policies, policyColumns }) => { - - return ( - <> - <EuiForm component="form"> - <EuiFormRow label="Policy Name"> - <EuiFieldText value={policyName} onChange={e => setPolicyName(e.target.value)} /> - </EuiFormRow> - {/* <EuiFormRow + EuiComboBox, +} from '@elastic/eui'; + +import { ShowAlert } from '../../components/Common'; + +const NewPolicyForm = memo( + ({ + globalState, + policyName, + setPolicyName, + sources, + isSwitchChecked, + onSwitchChange, + selectedSource, + setSelectedSource, + onSaveNewPolicy, + policies, + policyColumns, + }) => { + return ( + <> + <EuiForm component="form"> + <EuiFormRow label="Policy Name"> + <EuiFieldText + value={policyName} + onChange={(e) => setPolicyName(e.target.value)} + /> + </EuiFormRow> + {/* <EuiFormRow label="Select Specific Source"> <EuiSelect options={sources} value={selectedSource} onChange={e => setSelectedSource(e.target.value)} /> - </EuiFormRow> */ } - {/*<EuiFormRow + </EuiFormRow> */} + {/*<EuiFormRow // label="Use a switch instead of a single checkbox and set 'hasChildLabel' to false" hasChildLabel={false}> <EuiSwitch @@ -53,482 +64,550 @@ const NewPolicyForm = memo(({ globalState, policyName, setPolicyName, sources, i onChange={onSwitchChange} /> </EuiFormRow>*/} - <EuiSpacer /> - <EuiButton type="submit" onClick={onSaveNewPolicy} isLoading={globalState.isLoading} fill> - Save - </EuiButton> - <EuiSpacer /> - <EuiFormRow - label="" fullWidth> - <EuiBasicTable - items={policies} - rowheader="Name" - columns={policyColumns} - // rowProps={getRowProps} - // cellProps={getCellProps} - /> - </EuiFormRow> - </EuiForm> - </> - ) -}) - -const PolicyAssignment = memo(({ globalState, optPolicies, setOptPolicies, optStdFields, setOptStdFields, onPolicyAssignment }) => { - return ( - <> - <EuiForm component="form"> - <EuiFlexGroup component="span"> - <EuiFlexItem component="span"> - <EuiFormRow label="Policies" fullWidth> - <EuiSelectable - searchable - singleSelection={{ asPlainText: true }} - options={optPolicies} - onChange={newOptions => setOptPolicies(newOptions)}> - {(list, search) => ( - <Fragment> - {search} - {list} - </Fragment> - )} - </EuiSelectable> - </EuiFormRow> - </EuiFlexItem> - <EuiFlexItem component="span"> - <EuiFormRow label="Standard Fields" fullWidth> - <EuiSelectable - searchable - options={optStdFields} - onChange={newOptions => setOptStdFields(newOptions)}> - {(list, search) => ( - <Fragment> - {search} - {list} - </Fragment> - )} - </EuiSelectable> - </EuiFormRow> - </EuiFlexItem> - </EuiFlexGroup> - <EuiSpacer /> - <EuiButton type="submit" onClick={onPolicyAssignment} isLoading={globalState.isLoading} fill> - Save + <EuiSpacer /> + <EuiButton + type="submit" + onClick={onSaveNewPolicy} + isLoading={globalState.isLoading} + fill + > + Save </EuiButton> - </EuiForm> - </> - ) -}) - -const PolicyGroupAssignment = memo(({ globalState, optPolicies, setOptPolicies, optGroups, setOPtGroups, onPolicyGroupAssignment }) => { - return ( - <> - <EuiForm component="form"> - <EuiFlexGroup component="span"> - <EuiFlexItem component="span"> - <EuiFormRow label="Policies" fullWidth> - <EuiSelectable - searchable - singleSelection={{ asPlainText: true }} - options={optPolicies} - onChange={newOptions => setOptPolicies(newOptions)}> - {(list, search) => ( - <Fragment> - {search} - {list} - </Fragment> - )} - </EuiSelectable> - </EuiFormRow> - </EuiFlexItem> - <EuiFlexItem component="span"> - <EuiFormRow label="Groups" fullWidth> - <EuiSelectable - searchable - options={optGroups} - onChange={newOptions => setOPtGroups(newOptions)}> - {(list, search) => ( - <Fragment> - {search} - {list} - </Fragment> - )} - </EuiSelectable> - </EuiFormRow> - </EuiFlexItem> - </EuiFlexGroup> - <EuiSpacer /> - <EuiButton type="submit" onClick={onPolicyGroupAssignment} isLoading={globalState.isLoading} fill> - Save - </EuiButton> - </EuiForm> - </> - ) -}) - -const PolicySourceAssignment = memo(({ globalState, optPolicies, setOptPolicies, optSources, setOptSources, onPolicySourceAssignment }) => { - return ( - <> - <EuiForm component="form"> - <EuiFlexGroup component="span"> - <EuiFlexItem component="span"> - <EuiFormRow label="Policies" fullWidth> - <EuiSelectable - searchable - singleSelection={{ asPlainText: true }} - options={optPolicies} - onChange={newOptions => setOptPolicies(newOptions)}> - {(list, search) => ( - <Fragment> - {search} - {list} - </Fragment> - )} - </EuiSelectable> - </EuiFormRow> - </EuiFlexItem> - <EuiFlexItem component="span"> - <EuiFormRow label="Sources" fullWidth> - <EuiSelectable - searchable - singleSelection={{ asPlainText: true }} - options={optSources} - onChange={newOptions => setOptSources(newOptions)}> - {(list, search) => ( - <Fragment> - {search} - {list} - </Fragment> - )} - </EuiSelectable> - </EuiFormRow> - </EuiFlexItem> - </EuiFlexGroup> - <EuiSpacer /> - <EuiButton type="submit" onClick={onPolicySourceAssignment} isLoading={globalState.isLoading} fill> - Save - </EuiButton> - </EuiForm> - </> - ) -}) - -const AssignedPolicies = memo(({ policies, selectedPolicy, setSelectedPolicy, fields, assignedPolicyColumns, getRowProps, getCellProps, onSelectedPolicy, assignedPolicyGroups, assignedPolicyGroupColumns }) => { - - return ( - <> - <EuiForm component="form"> - <EuiFormRow - label="Select Specific Policy"> - <EuiComboBox - placeholder="Select a policy" - singleSelection={{ asPlainText: true }} - options={policies} - selectedOptions={selectedPolicy} - onChange={e => { - onSelectedPolicy(e) - }} - /> - </EuiFormRow> - <EuiFormRow - label="Assigned Standard Fields" fullWidth> - <EuiBasicTable - items={fields} - columns={assignedPolicyColumns} - rowProps={getRowProps} - cellProps={getCellProps} - /> - </EuiFormRow> - <EuiFormRow - label="Assigned Groups" fullWidth> - <EuiBasicTable - items={assignedPolicyGroups} - columns={assignedPolicyGroupColumns} - /> - </EuiFormRow> - </EuiForm> - </> - ) -}) - - + <EuiSpacer /> + <EuiFormRow label="" fullWidth> + <EuiBasicTable + items={policies} + rowheader="Name" + columns={policyColumns} + // rowProps={getRowProps} + // cellProps={getCellProps} + /> + </EuiFormRow> + </EuiForm> + </> + ); + } +); + +const PolicyAssignment = memo( + ({ + globalState, + optPolicies, + setOptPolicies, + optStdFields, + setOptStdFields, + onPolicyAssignment, + }) => { + return ( + <> + <EuiForm component="form"> + <EuiFlexGroup component="span"> + <EuiFlexItem component="span"> + <EuiFormRow label="Policies" fullWidth> + <EuiSelectable + searchable + singleSelection={{ asPlainText: true }} + options={optPolicies} + onChange={(newOptions) => setOptPolicies(newOptions)} + > + {(list, search) => ( + <Fragment> + {search} + {list} + </Fragment> + )} + </EuiSelectable> + </EuiFormRow> + </EuiFlexItem> + <EuiFlexItem component="span"> + <EuiFormRow label="Standard Fields" fullWidth> + <EuiSelectable + searchable + options={optStdFields} + onChange={(newOptions) => setOptStdFields(newOptions)} + > + {(list, search) => ( + <Fragment> + {search} + {list} + </Fragment> + )} + </EuiSelectable> + </EuiFormRow> + </EuiFlexItem> + </EuiFlexGroup> + <EuiSpacer /> + <EuiButton + type="submit" + onClick={onPolicyAssignment} + isLoading={globalState.isLoading} + fill + > + Save + </EuiButton> + </EuiForm> + </> + ); + } +); + +const PolicyGroupAssignment = memo( + ({ + globalState, + optPolicies, + setOptPolicies, + optGroups, + setOPtGroups, + onPolicyGroupAssignment, + }) => { + return ( + <> + <EuiForm component="form"> + <EuiFlexGroup component="span"> + <EuiFlexItem component="span"> + <EuiFormRow label="Policies" fullWidth> + <EuiSelectable + searchable + singleSelection={{ asPlainText: true }} + options={optPolicies} + onChange={(newOptions) => setOptPolicies(newOptions)} + > + {(list, search) => ( + <Fragment> + {search} + {list} + </Fragment> + )} + </EuiSelectable> + </EuiFormRow> + </EuiFlexItem> + <EuiFlexItem component="span"> + <EuiFormRow label="Groups" fullWidth> + <EuiSelectable + searchable + options={optGroups} + onChange={(newOptions) => setOPtGroups(newOptions)} + > + {(list, search) => ( + <Fragment> + {search} + {list} + </Fragment> + )} + </EuiSelectable> + </EuiFormRow> + </EuiFlexItem> + </EuiFlexGroup> + <EuiSpacer /> + <EuiButton + type="submit" + onClick={onPolicyGroupAssignment} + isLoading={globalState.isLoading} + fill + > + Save + </EuiButton> + </EuiForm> + </> + ); + } +); + +const PolicySourceAssignment = memo( + ({ + globalState, + optPolicies, + setOptPolicies, + optSources, + setOptSources, + onPolicySourceAssignment, + }) => { + return ( + <> + <EuiForm component="form"> + <EuiFlexGroup component="span"> + <EuiFlexItem component="span"> + <EuiFormRow label="Policies" fullWidth> + <EuiSelectable + searchable + singleSelection={{ asPlainText: true }} + options={optPolicies} + onChange={(newOptions) => setOptPolicies(newOptions)} + > + {(list, search) => ( + <Fragment> + {search} + {list} + </Fragment> + )} + </EuiSelectable> + </EuiFormRow> + </EuiFlexItem> + <EuiFlexItem component="span"> + <EuiFormRow label="Sources" fullWidth> + <EuiSelectable + searchable + singleSelection={{ asPlainText: true }} + options={optSources} + onChange={(newOptions) => setOptSources(newOptions)} + > + {(list, search) => ( + <Fragment> + {search} + {list} + </Fragment> + )} + </EuiSelectable> + </EuiFormRow> + </EuiFlexItem> + </EuiFlexGroup> + <EuiSpacer /> + <EuiButton + type="submit" + onClick={onPolicySourceAssignment} + isLoading={globalState.isLoading} + fill + > + Save + </EuiButton> + </EuiForm> + </> + ); + } +); + +const AssignedPolicies = memo( + ({ + policies, + selectedPolicy, + setSelectedPolicy, + fields, + assignedPolicyColumns, + getRowProps, + getCellProps, + onSelectedPolicy, + assignedPolicyGroups, + assignedPolicyGroupColumns, + }) => { + return ( + <> + <EuiForm component="form"> + <EuiFormRow label="Select Specific Policy"> + <EuiComboBox + placeholder="Select a policy" + singleSelection={{ asPlainText: true }} + options={policies} + selectedOptions={selectedPolicy} + onChange={(e) => { + onSelectedPolicy(e); + }} + /> + </EuiFormRow> + <EuiFormRow label="Assigned Standard Fields" fullWidth> + <EuiBasicTable + items={fields} + columns={assignedPolicyColumns} + rowProps={getRowProps} + cellProps={getCellProps} + /> + </EuiFormRow> + <EuiFormRow label="Assigned Groups" fullWidth> + <EuiBasicTable + items={assignedPolicyGroups} + columns={assignedPolicyGroupColumns} + /> + </EuiFormRow> + </EuiForm> + </> + ); + } +); const Policy = (props) => { const [globalState, globalActions] = store(); - const [selectedTabNumber, setSelectedTabNumber] = useState(0) - const [isSwitchChecked, setIsSwitchChecked] = useState(false) - const [policyName, setPolicyName] = useState("") - const [sources, setSources] = useState([{ value: 0, text: "select a source" }]) - const [selectedSource, setSelectedSource] = useState() + const [selectedTabNumber, setSelectedTabNumber] = useState(0); + const [isSwitchChecked, setIsSwitchChecked] = useState(false); + const [policyName, setPolicyName] = useState(''); + const [sources, setSources] = useState([{ value: 0, text: 'select a source' }]); + const [selectedSource, setSelectedSource] = useState(); const [open, setOpen] = useState(false); - const [alertMessage, setAlertMessage] = useState("") - const [severity, setSeverity] = useState("info") - const [optPolicies, setOptPolicies] = useState([]) - const [selectedPolicy, setSelectedPolicy] = useState() - const [optStdFields, setOptStdFields] = useState([]) - const [assignedPolicyItems, setAssignedPolicyItems] = useState([]) - const [policies, setPolicies] = useState([]) - const [optGroupPolicies, setOptGroupPolicies] = useState([]) - const [optGroups, setOPtGroups] = useState([]) - const [assignedPolicyGroups, setAssignedPolicyGroups] = useState([]) - const [optSourcePolicies, setOptSourcePolicies] = useState([]) - const [optSources, setOptSources] = useState([]) + const [alertMessage, setAlertMessage] = useState(''); + const [severity, setSeverity] = useState('info'); + const [optPolicies, setOptPolicies] = useState([]); + const [selectedPolicy, setSelectedPolicy] = useState(); + const [optStdFields, setOptStdFields] = useState([]); + const [assignedPolicyItems, setAssignedPolicyItems] = useState([]); + const [policies, setPolicies] = useState([]); + const [optGroupPolicies, setOptGroupPolicies] = useState([]); + const [optGroups, setOPtGroups] = useState([]); + const [assignedPolicyGroups, setAssignedPolicyGroups] = useState([]); + const [optSourcePolicies, setOptSourcePolicies] = useState([]); + const [optSources, setOptSources] = useState([]); const loadSources = useCallback(async () => { if (sessionStorage.getItem('userId')) { - const user = await globalActions.user.findOneUserWithGroupAndRole(sessionStorage.getItem('userId')) - const role = user[0].roleid - let result + const user = await globalActions.user.findOneUserWithGroupAndRole( + sessionStorage.getItem('userId') + ); + const role = user[0].roleid; + let result; if (role === 1) { - result = await globalActions.source.allIndexedSources() + result = await globalActions.source.allIndexedSources(); } else { - result = await globalActions.source.indexedSources(sessionStorage.getItem('userId')) + result = await globalActions.source.indexedSources( + sessionStorage.getItem('userId') + ); } if (result) { - const _sources = [] + const _sources = []; // const _sources2 = [] for (const source of result) { //_sources.push({ value: source.id, text: source.name }) - _sources.push({ value: source.id, label: source.name }) + _sources.push({ value: source.id, label: source.name }); } // setSources(prevSources => ([...prevSources, ..._sources])) - setOptSources(_sources) + setOptSources(_sources); } } - }, [globalActions.source]) + }, [globalActions.source]); const loadPolicies = useCallback(async () => { if (sessionStorage.getItem('userId')) { - const user = await globalActions.user.findOneUserWithGroupAndRole(sessionStorage.getItem('userId')) - const role = user[0].roleid - let result + const user = await globalActions.user.findOneUserWithGroupAndRole( + sessionStorage.getItem('userId') + ); + const role = user[0].roleid; + let result; if (role === 1) { - result = await globalActions.policy.getPolicies() + result = await globalActions.policy.getPolicies(); } else { - result = await globalActions.policy.getPoliciesByUser(sessionStorage.getItem('userId')) + result = await globalActions.policy.getPoliciesByUser( + sessionStorage.getItem('userId') + ); } if (result) { - const _policies = [] + const _policies = []; for (const policy of result) { - _policies.push({ value: policy.id, label: policy.name }) + _policies.push({ value: policy.id, label: policy.name }); } - setOptPolicies(_policies) - setOptGroupPolicies(_policies) - setOptSourcePolicies(_policies) + setOptPolicies(_policies); + setOptGroupPolicies(_policies); + setOptSourcePolicies(_policies); } } - }, [globalActions.policy]) + }, [globalActions.policy]); const loadPoliciesWithSources = useCallback(async () => { if (sessionStorage.getItem('userId')) { - const user = await globalActions.user.findOneUserWithGroupAndRole(sessionStorage.getItem('userId')) - const role = user[0].roleid - let result + const user = await globalActions.user.findOneUserWithGroupAndRole( + sessionStorage.getItem('userId') + ); + const role = user[0].roleid; + let result; if (role === 1) { - result = await globalActions.policy.getPoliciesWithSources() + result = await globalActions.policy.getPoliciesWithSources(); } else { - result = await globalActions.policy.getPoliciesWithSourcesByUser(sessionStorage.getItem('userId')) + result = await globalActions.policy.getPoliciesWithSourcesByUser( + sessionStorage.getItem('userId') + ); } if (result) { - const policyList = [] - const policyNames = [] - result.forEach(policy => { + const policyList = []; + const policyNames = []; + result.forEach((policy) => { if (policyNames.includes(policy.policyname)) { - policyList[policyNames.indexOf(policy.policyname)].sourcename = `${policyList[policyNames.indexOf(policy.policyname)].sourcename}, ${policy.sourcename}` + policyList[policyNames.indexOf(policy.policyname)].sourcename = + `${policyList[policyNames.indexOf(policy.policyname)].sourcename}, ${policy.sourcename}`; } else { - policyNames.push(policy.policyname) - policyList.push(policy) + policyNames.push(policy.policyname); + policyList.push(policy); } - }) - setPolicies(policyList) + }); + setPolicies(policyList); } } - }, [globalActions.policy]) + }, [globalActions.policy]); const loadStdFields = useCallback(async () => { - const result = await globalActions.source.privateFields() + const result = await globalActions.source.privateFields(); if (result) { - const _fields = [] + const _fields = []; for (const field of result) { - _fields.push({ value: field.id, label: field.field_name }) + _fields.push({ value: field.id, label: field.field_name }); } - setOptStdFields(_fields) + setOptStdFields(_fields); } - }, [globalActions.source]) + }, [globalActions.source]); const loadGroups = useCallback(async () => { - const _groups = await globalActions.group.getGroups() + const _groups = await globalActions.group.getGroups(); if (_groups) { - const groups = [] + const groups = []; for (const group of _groups) { - groups.push({ value: group.id, label: group.name }) + groups.push({ value: group.id, label: group.name }); } - setOPtGroups(groups) + setOPtGroups(groups); } - }, [globalActions.group]) - + }, [globalActions.group]); useEffect(() => { // clean up controller let isSubscribed = true; if (isSubscribed) { - loadSources() - loadPolicies() - loadStdFields() - loadPoliciesWithSources() - loadGroups() + loadSources(); + loadPolicies(); + loadStdFields(); + loadPoliciesWithSources(); + loadGroups(); // eslint-disable-next-line react-hooks/exhaustive-deps } // cancel subscription to useEffect - return () => (isSubscribed = false) - }, [loadGroups, loadPolicies, loadPoliciesWithSources, loadSources, loadStdFields]) - + return () => (isSubscribed = false); + }, [loadGroups, loadPolicies, loadPoliciesWithSources, loadSources, loadStdFields]); const onPolicySourceAssignment = async () => { - const checkedPolicies = optSourcePolicies.filter(e => { - return e.checked === "on" - }) + const checkedPolicies = optSourcePolicies.filter((e) => { + return e.checked === 'on'; + }); - const checkedSources = optSources.filter(e => { - return e.checked === "on" - }) + const checkedSources = optSources.filter((e) => { + return e.checked === 'on'; + }); if (checkedPolicies && checkedSources) { for (const policy of checkedPolicies) { for (const source of checkedSources) { - await globalActions.policy.createPolicySource(policy.value, source.value) + await globalActions.policy.createPolicySource(policy.value, source.value); } } if (globalState.status === 'SUCCESS') { - loadPoliciesWithSources() - setOpen(true) - setAlertMessage("Policy-Source assignment completed succesfully !") - setSeverity("success") + loadPoliciesWithSources(); + setOpen(true); + setAlertMessage('Policy-Source assignment completed succesfully !'); + setSeverity('success'); } } - } - + }; const onSwitchChange = () => { setIsSwitchChecked(!isSwitchChecked); }; const onSaveNewPolicy = async () => { - if (policyName && sessionStorage.getItem('userId')) { - await globalActions.policy.createPolicy(policyName, sessionStorage.getItem('userId')) + await globalActions.policy.createPolicy( + policyName, + sessionStorage.getItem('userId') + ); if (globalState.status === 'SUCCESS') { - setOpen(true) - setAlertMessage("Policy was created succesfully !") - setSeverity("success") - loadPolicies() - loadPoliciesWithSources() + setOpen(true); + setAlertMessage('Policy was created succesfully !'); + setSeverity('success'); + loadPolicies(); + loadPoliciesWithSources(); } } - } - + }; const onPolicyAssignment = async () => { + const checkedPolicies = optPolicies.filter((e) => { + return e.checked === 'on'; + }); - const checkedPolicies = optPolicies.filter(e => { - return e.checked === "on" - }) - - const checkedStdFields = optStdFields.filter(e => { - return e.checked === "on" - }) + const checkedStdFields = optStdFields.filter((e) => { + return e.checked === 'on'; + }); for (const policy of checkedPolicies) { for (const stdField of checkedStdFields) { - //to-do: if policy is already defined, do not let insert them into table. - await globalActions.policy.createPolicyField(policy.value, stdField.value) + await globalActions.policy.createPolicyField(policy.value, stdField.value); } } if (globalState.status === 'SUCCESS') { - setOpen(true) - setAlertMessage("Policy-Assignment completed succesfully !") - setSeverity("success") + setOpen(true); + setAlertMessage('Policy-Assignment completed succesfully !'); + setSeverity('success'); } - } + }; const onPolicyGroupAssignment = async () => { + const checkedPolicies = optGroupPolicies.filter((e) => { + return e.checked === 'on'; + }); - const checkedPolicies = optGroupPolicies.filter(e => { - return e.checked === "on" - }) - - const checkedGroups = optGroups.filter(e => { - return e.checked === "on" - }) + const checkedGroups = optGroups.filter((e) => { + return e.checked === 'on'; + }); if (checkedPolicies && checkedGroups) { for (const group of checkedGroups) { for (const policy of checkedPolicies) { - - await globalActions.group.createGroupPolicy(group.value, policy.value) + await globalActions.group.createGroupPolicy(group.value, policy.value); } } if (globalState.status === 'SUCCESS') { - setOpen(true) - setAlertMessage("Policy-Group assignment completed succesfully !") - setSeverity("success") + setOpen(true); + setAlertMessage('Policy-Group assignment completed succesfully !'); + setSeverity('success'); } } - } + }; const onSelectedPolicy = async (e) => { if (e.length > 0) { - const aPolicies = await globalActions.policy.getAssignedPolicies(e[0].value) - const groupDetailsByPolicy = await globalActions.policy.getGroupDetailsByPolicy(e[0].value) + const aPolicies = await globalActions.policy.getAssignedPolicies(e[0].value); + const groupDetailsByPolicy = await globalActions.policy.getGroupDetailsByPolicy( + e[0].value + ); if (aPolicies) { - const policyItemsList = [] - const fieldNames = [] - aPolicies.forEach(aPolicy => { + const policyItemsList = []; + const fieldNames = []; + aPolicies.forEach((aPolicy) => { if (!fieldNames.includes(aPolicy.field_name)) { - fieldNames.push(aPolicy.field_name) - policyItemsList.push(aPolicy) + fieldNames.push(aPolicy.field_name); + policyItemsList.push(aPolicy); } - }) - setAssignedPolicyItems(policyItemsList) + }); + setAssignedPolicyItems(policyItemsList); } if (groupDetailsByPolicy) { - const policyGroupList = [] - const groupIds = [] - groupDetailsByPolicy.forEach(groupDetail => { + const policyGroupList = []; + const groupIds = []; + groupDetailsByPolicy.forEach((groupDetail) => { if (groupIds.includes(groupDetail.groupid)) { - policyGroupList[groupIds.indexOf(groupDetail.groupid)].source_name = `${policyGroupList[groupIds.indexOf(groupDetail.groupid)].source_name}, ${groupDetail.source_name}` + policyGroupList[groupIds.indexOf(groupDetail.groupid)].source_name = + `${policyGroupList[groupIds.indexOf(groupDetail.groupid)].source_name}, ${groupDetail.source_name}`; } else { - groupIds.push(groupDetail.groupid) - policyGroupList.push(groupDetail) + groupIds.push(groupDetail.groupid); + policyGroupList.push(groupDetail); } - }) - setAssignedPolicyGroups(policyGroupList) + }); + setAssignedPolicyGroups(policyGroupList); } - setSelectedPolicy(e) + setSelectedPolicy(e); } else { - setSelectedPolicy(e) + setSelectedPolicy(e); } - } - + }; const onDeletePolicyField = async (e) => { - if (e.id) { - await globalActions.policy.deletePolicyField(e.id) + await globalActions.policy.deletePolicyField(e.id); - setOpen(true) - setAlertMessage("Policy-Field deleted succesfully !") - setSeverity("success") + setOpen(true); + setAlertMessage('Policy-Field deleted succesfully !'); + setSeverity('success'); } - } + }; const assignedPolicyActions = [ /*{ @@ -585,17 +664,17 @@ const Policy = (props) => { name: 'Actions', actions: assignedPolicyActions, }, - ] + ]; const onAassignedPolicyGroup = async (e) => { if (e.grouppolicyid) { - await globalActions.group.deleteGroupPolicy(e.grouppolicyid) + await globalActions.group.deleteGroupPolicy(e.grouppolicyid); - setOpen(true) - setAlertMessage("Policy-group deleted succesfully !") - setSeverity("success") + setOpen(true); + setAlertMessage('Policy-group deleted succesfully !'); + setSeverity('success'); } - } + }; const aassignedPolicyGroupActions = [ { @@ -606,27 +685,25 @@ const Policy = (props) => { color: 'danger', onClick: onAassignedPolicyGroup, }, - ] + ]; const assignedPolicyGroupColumns = [ { field: 'group_name', name: 'Group Name' }, { field: 'source_name', name: 'Source Name' }, { field: 'source_description', name: 'Source Description' }, - { name: 'Actions', actions: aassignedPolicyGroupActions } - ] - + { name: 'Actions', actions: aassignedPolicyGroupActions }, + ]; const onDeletePolicy = async (e) => { - - await globalActions.policy.deletePolicy(e.id) + await globalActions.policy.deletePolicy(e.id); if (globalState.status === 'SUCCESS') { - setOpen(true) - setAlertMessage("Policy deleted succesfully !") - setSeverity("success") - loadPoliciesWithSources() - loadPolicies() + setOpen(true); + setAlertMessage('Policy deleted succesfully !'); + setSeverity('success'); + loadPoliciesWithSources(); + loadPolicies(); } - } + }; const policyColumnAction = [ { @@ -637,21 +714,23 @@ const Policy = (props) => { color: 'danger', onClick: onDeletePolicy, }, - ] - const policyColumns = [{ - - field: 'policyname', - name: 'Policy Name', - - }, { - field: 'sourcename', - name: 'Source Name', - }, { - name: 'Actions', - actions: policyColumnAction, - },] + ]; + const policyColumns = [ + { + field: 'policyname', + name: 'Policy Name', + }, + { + field: 'sourcename', + name: 'Source Name', + }, + { + name: 'Actions', + actions: policyColumnAction, + }, + ]; - const getRowProps = item => { + const getRowProps = (item) => { const { id } = item; return { 'data-test-subj': `row-${id}`, @@ -675,7 +754,7 @@ const Policy = (props) => { return; } setOpen(false); - } + }; const tabContents = [ { @@ -684,9 +763,22 @@ const Policy = (props) => { content: ( <> <br /> - <NewPolicyForm globalState={globalState} policyName={policyName} setPolicyName={setPolicyName} sources={sources} isSwitchChecked={isSwitchChecked} setIsSwitchChecked={setIsSwitchChecked} onSwitchChange={onSwitchChange} selectedSource={selectedSource} setSelectedSource={setSelectedSource} onSaveNewPolicy={onSaveNewPolicy} policies={policies} policyColumns={policyColumns} /> + <NewPolicyForm + globalState={globalState} + policyName={policyName} + setPolicyName={setPolicyName} + sources={sources} + isSwitchChecked={isSwitchChecked} + setIsSwitchChecked={setIsSwitchChecked} + onSwitchChange={onSwitchChange} + selectedSource={selectedSource} + setSelectedSource={setSelectedSource} + onSaveNewPolicy={onSaveNewPolicy} + policies={policies} + policyColumns={policyColumns} + /> </> - ) + ), }, { id: 'tab2', @@ -694,9 +786,16 @@ const Policy = (props) => { content: ( <> <br /> - <PolicySourceAssignment globalState={globalState} optPolicies={optSourcePolicies} setOptPolicies={setOptSourcePolicies} optSources={optSources} setOptSources={setOptSources} onPolicySourceAssignment={onPolicySourceAssignment} /> + <PolicySourceAssignment + globalState={globalState} + optPolicies={optSourcePolicies} + setOptPolicies={setOptSourcePolicies} + optSources={optSources} + setOptSources={setOptSources} + onPolicySourceAssignment={onPolicySourceAssignment} + /> </> - ) + ), }, { id: 'tab3', @@ -704,9 +803,16 @@ const Policy = (props) => { content: ( <> <br /> - <PolicyAssignment globalState={globalState} optPolicies={optPolicies} setOptPolicies={setOptPolicies} optStdFields={optStdFields} setOptStdFields={setOptStdFields} onPolicyAssignment={onPolicyAssignment} /> + <PolicyAssignment + globalState={globalState} + optPolicies={optPolicies} + setOptPolicies={setOptPolicies} + optStdFields={optStdFields} + setOptStdFields={setOptStdFields} + onPolicyAssignment={onPolicyAssignment} + /> </> - ) + ), }, { id: 'tab4', @@ -714,9 +820,16 @@ const Policy = (props) => { content: ( <> <br /> - <PolicyGroupAssignment globalState={globalState} optPolicies={optGroupPolicies} setOptPolicies={setOptGroupPolicies} optGroups={optGroups} setOPtGroups={setOPtGroups} onPolicyGroupAssignment={onPolicyGroupAssignment} /> + <PolicyGroupAssignment + globalState={globalState} + optPolicies={optGroupPolicies} + setOptPolicies={setOptGroupPolicies} + optGroups={optGroups} + setOPtGroups={setOPtGroups} + onPolicyGroupAssignment={onPolicyGroupAssignment} + /> </> - ) + ), }, { id: 'tab5', @@ -724,11 +837,22 @@ const Policy = (props) => { content: ( <> <br /> - <AssignedPolicies policies={optPolicies} selectedPolicy={selectedPolicy} setSelectedPolicy={setSelectedPolicy} fields={assignedPolicyItems} assignedPolicyColumns={assignedPolicyColumns} getRowProps={getRowProps} getCellProps={getCellProps} onSelectedPolicy={onSelectedPolicy} assignedPolicyGroups={assignedPolicyGroups} assignedPolicyGroupColumns={assignedPolicyGroupColumns} /> + <AssignedPolicies + policies={optPolicies} + selectedPolicy={selectedPolicy} + setSelectedPolicy={setSelectedPolicy} + fields={assignedPolicyItems} + assignedPolicyColumns={assignedPolicyColumns} + getRowProps={getRowProps} + getCellProps={getCellProps} + onSelectedPolicy={onSelectedPolicy} + assignedPolicyGroups={assignedPolicyGroups} + assignedPolicyGroupColumns={assignedPolicyGroupColumns} + /> </> - ) + ), }, - ] + ]; return ( <> @@ -745,8 +869,8 @@ const Policy = (props) => { <EuiTabbedContent tabs={tabContents} selectedTab={tabContents[selectedTabNumber]} - onTabClick={tab => { - setSelectedTabNumber(tabContents.indexOf(tab)) + onTabClick={(tab) => { + setSelectedTabNumber(tabContents.indexOf(tab)); }} /> </EuiForm> @@ -754,9 +878,7 @@ const Policy = (props) => { </EuiPageContent> {ShowAlert(open, handleClose, alertMessage, severity)} </> - ) - -} - + ); +}; -export default Policy \ No newline at end of file +export default Policy; diff --git a/src/pages/policy/package.json b/src/pages/policy/package.json index 097fd0a..bd72886 100644 --- a/src/pages/policy/package.json +++ b/src/pages/policy/package.json @@ -1,6 +1,6 @@ { - "name": "Policy", - "version": "1.0.0", - "private": true, - "main": "Policy.js" -} \ No newline at end of file + "name": "Policy", + "version": "1.0.0", + "private": true, + "main": "Policy.js" +} diff --git a/src/pages/policy/styles.js b/src/pages/policy/styles.js index d135699..4842f10 100644 --- a/src/pages/policy/styles.js +++ b/src/pages/policy/styles.js @@ -1,44 +1,44 @@ -import { makeStyles } from "@material-ui/styles"; +import { makeStyles } from '@material-ui/styles'; -export default makeStyles(theme => ({ - titleBold: { - fontWeight: 600, - }, - tab: { - color: theme.palette.primary.light + "CC", - }, - roleContainer: { - boxShadow: theme.customShadows.widget, - overflow: "hidden", - paddingBottom: theme.spacing(2), - }, - dashedBorder: { - border: "1px dashed", - borderColor: theme.palette.primary.main, - padding: theme.spacing(2), - paddingTop: theme.spacing(4), - paddingBottom: theme.spacing(4), - marginTop: theme.spacing(1), - }, - text: { - marginBottom: theme.spacing(2), - }, - root: { - padding: theme.spacing(3, 2), - }, - formControl: { - margin: theme.spacing(1), - minWidth: 120, - maxWidth: 300, - }, - chips: { - display: 'flex', - flexWrap: 'wrap', - }, - chip: { - margin: 2, - }, - noLabel: { - marginTop: theme.spacing(3), - }, -})); \ No newline at end of file +export default makeStyles((theme) => ({ + titleBold: { + fontWeight: 600, + }, + tab: { + color: theme.palette.primary.light + 'CC', + }, + roleContainer: { + boxShadow: theme.customShadows.widget, + overflow: 'hidden', + paddingBottom: theme.spacing(2), + }, + dashedBorder: { + border: '1px dashed', + borderColor: theme.palette.primary.main, + padding: theme.spacing(2), + paddingTop: theme.spacing(4), + paddingBottom: theme.spacing(4), + marginTop: theme.spacing(1), + }, + text: { + marginBottom: theme.spacing(2), + }, + root: { + padding: theme.spacing(3, 2), + }, + formControl: { + margin: theme.spacing(1), + minWidth: 120, + maxWidth: 300, + }, + chips: { + display: 'flex', + flexWrap: 'wrap', + }, + chip: { + margin: 2, + }, + noLabel: { + marginTop: theme.spacing(3), + }, +})); diff --git a/src/pages/requests/Requests.js b/src/pages/requests/Requests.js index 85227f4..e3b183e 100644 --- a/src/pages/requests/Requests.js +++ b/src/pages/requests/Requests.js @@ -1,215 +1,204 @@ -import React, { - useState, - useCallback, - useEffect, - memo, - useRef -} from "react" +import React, { useState, useCallback, useEffect, memo, useRef } from 'react'; -import store from "../../store/index" -import { ShowAlert } from '../../components/Common/Common' +import store from '../../store/index'; +import { ShowAlert } from '../../components/Common/Common'; import { - EuiForm, - EuiPageContent, - EuiPageContentHeader, - EuiPageContentHeaderSection, - EuiTitle, - EuiPageContentBody, - EuiTabbedContent, - EuiFormRow, - EuiFieldText, - EuiFieldPassword, - EuiSelect, - EuiButton, - EuiBasicTable -} from '@elastic/eui' + EuiForm, + EuiPageContent, + EuiPageContentHeader, + EuiPageContentHeaderSection, + EuiTitle, + EuiPageContentBody, + EuiTabbedContent, + EuiFormRow, + EuiFieldText, + EuiFieldPassword, + EuiSelect, + EuiButton, + EuiBasicTable, +} from '@elastic/eui'; const RequestList = memo(({ requests, requestColumns }) => { - return ( - <> - <EuiForm component="form"> - <EuiFormRow fullWidth> - <EuiBasicTable - itemId="id" - isSelectable={true} - items={requests} - columns={requestColumns} - // selection={selection} - /> - </EuiFormRow> - </EuiForm> - </> - ) -}) + return ( + <> + <EuiForm component="form"> + <EuiFormRow fullWidth> + <EuiBasicTable + itemId="id" + isSelectable={true} + items={requests} + columns={requestColumns} + // selection={selection} + /> + </EuiFormRow> + </EuiForm> + </> + ); +}); const Requests = (props) => { - const [globalState, globalActions] = store(); - const [selectedTabNumber, setSelectedTabNumber] = useState(0) - const [open, setOpen] = useState(false); - const [alertMessage, setAlertMessage] = useState(""); - const [severity, setSeverity] = useState("info") - const [dual,] = useState(true); - const [requests, setRequests] = useState([]) - const [pendingRequests, setPendingRequests] = useState([]) - - const loadRequests = useCallback(async () => { - const requestList = await globalActions.user.fetchRequests() - - if (requestList) { - console.log(requestList) - setRequests(requestList) - } - - }, [globalActions.user]) - - const loadPendingRequests = useCallback(async () => { - const requestList = await globalActions.user.fetchPendingRequests() - - if (requestList) { - console.log(requestList) - setPendingRequests(requestList) - } - - }, [globalActions.user]) - - useEffect(() => { - // clean up controller - let isSubscribed = true; - if (isSubscribed) { - loadRequests() - loadPendingRequests() - } - // cancel subscription to useEffect - return () => (isSubscribed = false) - }, [loadRequests, loadPendingRequests]) - - const onDeleteRequest = async (request) => { - - if (request) { - await globalActions.user.deleteUserRequest(request.id) - - setOpen(true) - setAlertMessage("Request was deleted succesfully!") - setSeverity("success") - await loadRequests() - await loadPendingRequests() - } + const [globalState, globalActions] = store(); + const [selectedTabNumber, setSelectedTabNumber] = useState(0); + const [open, setOpen] = useState(false); + const [alertMessage, setAlertMessage] = useState(''); + const [severity, setSeverity] = useState('info'); + const [dual] = useState(true); + const [requests, setRequests] = useState([]); + const [pendingRequests, setPendingRequests] = useState([]); + + const loadRequests = useCallback(async () => { + const requestList = await globalActions.user.fetchRequests(); + + if (requestList) { + console.log(requestList); + setRequests(requestList); } + }, [globalActions.user]); - const onProcessRequest = async (request) => { - - if (request) { - await globalActions.user.processUserRequest(request.id) + const loadPendingRequests = useCallback(async () => { + const requestList = await globalActions.user.fetchPendingRequests(); - setOpen(true) - setAlertMessage("Request was deleted succesfully!") - setSeverity("success") - await loadRequests() - await loadPendingRequests() - } + if (requestList) { + console.log(requestList); + setPendingRequests(requestList); + } + }, [globalActions.user]); + + useEffect(() => { + // clean up controller + let isSubscribed = true; + if (isSubscribed) { + loadRequests(); + loadPendingRequests(); + } + // cancel subscription to useEffect + return () => (isSubscribed = false); + }, [loadRequests, loadPendingRequests]); + + const onDeleteRequest = async (request) => { + if (request) { + await globalActions.user.deleteUserRequest(request.id); + + setOpen(true); + setAlertMessage('Request was deleted succesfully!'); + setSeverity('success'); + await loadRequests(); + await loadPendingRequests(); } + }; - const requestActions = [ - { - name: 'Delete', - description: 'Delete this request', - icon: 'trash', - type: 'icon', - color: 'danger', - onClick: onDeleteRequest, - }, - ] - - const pendingRequestActions = [ - { - name: 'Process', - description: 'Process this request', - icon: 'check', - type: 'icon', - color: 'danger', - onClick: onProcessRequest, - }, - { - name: 'Delete', - description: 'Delete this request', - icon: 'trash', - type: 'icon', - color: 'danger', - onClick: onDeleteRequest, - } - ] - - const requestColumns = [ - { field: 'request_message', name: 'Message', width: "90%" }, - { field: 'is_processed', name: 'Processed' }, - { name: 'Delete', actions: requestActions } - - ] - - const pendingRequestColumns = [ - { field: 'request_message', name: 'Message', width: "90%" }, - { field: 'is_processed', name: 'Processed' }, - { name: 'Delete', actions: pendingRequestActions } - - ] - - const tabContents = [ - - { - id: 'tab1', - name: 'Pending Requests List', - content: ( - <> - <br /> - <RequestList requests={pendingRequests} requestColumns={pendingRequestColumns} /> - </> - ) - }, { - id: 'tab2', - name: 'Full Requests List', - content: ( - <> - <br /> - <RequestList requests={requests} requestColumns={requestColumns} /> - </> - ) - }, - - ] - - const handleClose = (event, reason) => { - if (reason === 'clickaway') { - return; - } - setOpen(false); + const onProcessRequest = async (request) => { + if (request) { + await globalActions.user.processUserRequest(request.id); + + setOpen(true); + setAlertMessage('Request was deleted succesfully!'); + setSeverity('success'); + await loadRequests(); + await loadPendingRequests(); } - return ( + }; + + const requestActions = [ + { + name: 'Delete', + description: 'Delete this request', + icon: 'trash', + type: 'icon', + color: 'danger', + onClick: onDeleteRequest, + }, + ]; + + const pendingRequestActions = [ + { + name: 'Process', + description: 'Process this request', + icon: 'check', + type: 'icon', + color: 'danger', + onClick: onProcessRequest, + }, + { + name: 'Delete', + description: 'Delete this request', + icon: 'trash', + type: 'icon', + color: 'danger', + onClick: onDeleteRequest, + }, + ]; + + const requestColumns = [ + { field: 'request_message', name: 'Message', width: '90%' }, + { field: 'is_processed', name: 'Processed' }, + { name: 'Delete', actions: requestActions }, + ]; + + const pendingRequestColumns = [ + { field: 'request_message', name: 'Message', width: '90%' }, + { field: 'is_processed', name: 'Processed' }, + { name: 'Delete', actions: pendingRequestActions }, + ]; + + const tabContents = [ + { + id: 'tab1', + name: 'Pending Requests List', + content: ( <> - <EuiPageContent> - <EuiPageContentHeader> - <EuiPageContentHeaderSection> - <EuiTitle> - <h6>Users</h6> - </EuiTitle> - </EuiPageContentHeaderSection> - </EuiPageContentHeader> - <EuiPageContentBody> - <EuiForm> - <EuiTabbedContent - tabs={tabContents} - selectedTab={tabContents[selectedTabNumber]} - onTabClick={tab => { - setSelectedTabNumber(tabContents.indexOf(tab)) - }} - /> - </EuiForm> - </EuiPageContentBody> - </EuiPageContent> - {ShowAlert(open, handleClose, alertMessage, severity)} + <br /> + <RequestList + requests={pendingRequests} + requestColumns={pendingRequestColumns} + /> </> - ) -} - + ), + }, + { + id: 'tab2', + name: 'Full Requests List', + content: ( + <> + <br /> + <RequestList requests={requests} requestColumns={requestColumns} /> + </> + ), + }, + ]; -export default Requests \ No newline at end of file + const handleClose = (event, reason) => { + if (reason === 'clickaway') { + return; + } + setOpen(false); + }; + return ( + <> + <EuiPageContent> + <EuiPageContentHeader> + <EuiPageContentHeaderSection> + <EuiTitle> + <h6>Users</h6> + </EuiTitle> + </EuiPageContentHeaderSection> + </EuiPageContentHeader> + <EuiPageContentBody> + <EuiForm> + <EuiTabbedContent + tabs={tabContents} + selectedTab={tabContents[selectedTabNumber]} + onTabClick={(tab) => { + setSelectedTabNumber(tabContents.indexOf(tab)); + }} + /> + </EuiForm> + </EuiPageContentBody> + </EuiPageContent> + {ShowAlert(open, handleClose, alertMessage, severity)} + </> + ); +}; + +export default Requests; diff --git a/src/pages/requests/package.json b/src/pages/requests/package.json index ed8bad0..84490c3 100644 --- a/src/pages/requests/package.json +++ b/src/pages/requests/package.json @@ -1,6 +1,6 @@ { - "name": "Requests", - "version": "1.0.0", - "private": true, - "main": "Requests.js" -} \ No newline at end of file + "name": "Requests", + "version": "1.0.0", + "private": true, + "main": "Requests.js" +} diff --git a/src/pages/requests/styles.js b/src/pages/requests/styles.js index 7733076..366d14e 100644 --- a/src/pages/requests/styles.js +++ b/src/pages/requests/styles.js @@ -1,29 +1,29 @@ -import { makeStyles } from "@material-ui/styles"; +import { makeStyles } from '@material-ui/styles'; -export default makeStyles(theme => ({ - titleBold: { - fontWeight: 600, - }, - tab: { - color: theme.palette.primary.light + "CC", - }, - iconsContainer: { - boxShadow: theme.customShadows.widget, - overflow: "hidden", - paddingBottom: theme.spacing(2), - }, - dashedBorder: { - border: "1px dashed", - borderColor: theme.palette.primary.main, - padding: theme.spacing(2), - paddingTop: theme.spacing(4), - paddingBottom: theme.spacing(4), - marginTop: theme.spacing(1), - }, - text: { - marginBottom: theme.spacing(2), - }, - root: { - padding: theme.spacing(3, 2), - }, -})); \ No newline at end of file +export default makeStyles((theme) => ({ + titleBold: { + fontWeight: 600, + }, + tab: { + color: theme.palette.primary.light + 'CC', + }, + iconsContainer: { + boxShadow: theme.customShadows.widget, + overflow: 'hidden', + paddingBottom: theme.spacing(2), + }, + dashedBorder: { + border: '1px dashed', + borderColor: theme.palette.primary.main, + padding: theme.spacing(2), + paddingTop: theme.spacing(4), + paddingBottom: theme.spacing(4), + marginTop: theme.spacing(1), + }, + text: { + marginBottom: theme.spacing(2), + }, + root: { + padding: theme.spacing(3, 2), + }, +})); diff --git a/src/pages/roles/Role.js b/src/pages/roles/Role.js index 5047fe8..827e5c3 100644 --- a/src/pages/roles/Role.js +++ b/src/pages/roles/Role.js @@ -1,334 +1,372 @@ -import React, { - useState, Fragment, - useCallback, - useEffect -} from "react" +import React, { useState, Fragment, useCallback, useEffect } from 'react'; -import store from "../../store/index" -import { ShowAlert } from '../../components/Common' +import store from '../../store/index'; +import { ShowAlert } from '../../components/Common'; import { - EuiForm, - EuiPageContent, - EuiPageContentHeader, - EuiPageContentHeaderSection, - EuiTitle, - EuiPageContentBody, - EuiTabbedContent, - EuiFormRow, - EuiFieldText, - EuiFlexGroup, - EuiFlexItem, - EuiSpacer, - EuiButton, - EuiBasicTable, - EuiSelectable, - EuiComboBox -} from '@elastic/eui' - - -const newRoleForm = ({ roleNameValue, setRoleNameValue, roleDescriptionValue, setRoleDescriptionValue, globalState, onSaveRole, roleColumns }) => { - - return ( - <> - <EuiForm component="form"> - <EuiFormRow label="Role Name"> - <EuiFieldText value={roleNameValue} onChange={e => setRoleNameValue(e.target.value)} /> - </EuiFormRow> - <EuiFormRow label="Role Description"> - <EuiFieldText value={roleDescriptionValue} onChange={e => setRoleDescriptionValue(e.target.value)} /> - </EuiFormRow> - <EuiSpacer /> - {<EuiButton fill onClick={onSaveRole} isLoading={globalState.isLoading}> - Save - </EuiButton>} - <EuiSpacer /> - <EuiFormRow - label="" fullWidth> - <EuiBasicTable - items={globalState.roles} - rowheader="Name" - columns={roleColumns} - // rowProps={getRowProps} - // cellProps={getCellProps} - /> - </EuiFormRow> - </EuiForm> - </> - ) -} -const roleAssignment = (globalState, roles, setRoles, users, setUsers, onRoleAssignment) => { - return ( - <> - <EuiForm component="form"> - <EuiFlexGroup component="span"> - <EuiFlexItem component="span"> - <EuiFormRow label="Roles" fullWidth> - <EuiSelectable - searchable - singleSelection={{ asPlainText: true }} - options={roles} - onChange={newOptions => setRoles(newOptions)}> - {(list, search) => ( - <Fragment> - {search} - {list} - </Fragment> - )} - </EuiSelectable> - </EuiFormRow> - </EuiFlexItem> - <EuiFlexItem component="span"> - <EuiFormRow label="Users" fullWidth> - <EuiSelectable - searchable - options={users} - onChange={newOptions => setUsers(newOptions)}> - {(list, search) => ( - <Fragment> - {search} - {list} - </Fragment> - )} - </EuiSelectable> - </EuiFormRow> - </EuiFlexItem> - </EuiFlexGroup> - <EuiSpacer /> - - - <EuiButton type="submit" onClick={onRoleAssignment} fill> - Save + EuiForm, + EuiPageContent, + EuiPageContentHeader, + EuiPageContentHeaderSection, + EuiTitle, + EuiPageContentBody, + EuiTabbedContent, + EuiFormRow, + EuiFieldText, + EuiFlexGroup, + EuiFlexItem, + EuiSpacer, + EuiButton, + EuiBasicTable, + EuiSelectable, + EuiComboBox, +} from '@elastic/eui'; + +const newRoleForm = ({ + roleNameValue, + setRoleNameValue, + roleDescriptionValue, + setRoleDescriptionValue, + globalState, + onSaveRole, + roleColumns, +}) => { + return ( + <> + <EuiForm component="form"> + <EuiFormRow label="Role Name"> + <EuiFieldText + value={roleNameValue} + onChange={(e) => setRoleNameValue(e.target.value)} + /> + </EuiFormRow> + <EuiFormRow label="Role Description"> + <EuiFieldText + value={roleDescriptionValue} + onChange={(e) => setRoleDescriptionValue(e.target.value)} + /> + </EuiFormRow> + <EuiSpacer /> + { + <EuiButton fill onClick={onSaveRole} isLoading={globalState.isLoading}> + Save + </EuiButton> + } + <EuiSpacer /> + <EuiFormRow label="" fullWidth> + <EuiBasicTable + items={globalState.roles} + rowheader="Name" + columns={roleColumns} + // rowProps={getRowProps} + // cellProps={getCellProps} + /> + </EuiFormRow> + </EuiForm> + </> + ); +}; +const roleAssignment = ( + globalState, + roles, + setRoles, + users, + setUsers, + onRoleAssignment +) => { + return ( + <> + <EuiForm component="form"> + <EuiFlexGroup component="span"> + <EuiFlexItem component="span"> + <EuiFormRow label="Roles" fullWidth> + <EuiSelectable + searchable + singleSelection={{ asPlainText: true }} + options={roles} + onChange={(newOptions) => setRoles(newOptions)} + > + {(list, search) => ( + <Fragment> + {search} + {list} + </Fragment> + )} + </EuiSelectable> + </EuiFormRow> + </EuiFlexItem> + <EuiFlexItem component="span"> + <EuiFormRow label="Users" fullWidth> + <EuiSelectable + searchable + options={users} + onChange={(newOptions) => setUsers(newOptions)} + > + {(list, search) => ( + <Fragment> + {search} + {list} + </Fragment> + )} + </EuiSelectable> + </EuiFormRow> + </EuiFlexItem> + </EuiFlexGroup> + <EuiSpacer /> + + <EuiButton type="submit" onClick={onRoleAssignment} fill> + Save </EuiButton> - </EuiForm> - </> - ) -} -const assignedRoles = ({ roles, selectedRole, onSelectedRole, assignedRoleToUsers, assignedRolesColumns }) => { - - - return ( - <> - <EuiForm component="form"> - <EuiFormRow - label="Select Specific Role"> - <EuiComboBox - placeholder="Select a role" - singleSelection={{ asPlainText: true }} - options={roles} - selectedOptions={selectedRole} - onChange={e => { - onSelectedRole(e) - }} - /> - </EuiFormRow> - <EuiFormRow - label="Assigned Roles" fullWidth> - <EuiBasicTable - items={assignedRoleToUsers} - rowheader="" - columns={assignedRolesColumns} - // rowProps={getRowProps} - // cellProps={getCellProps} - /> - </EuiFormRow> - </EuiForm> - </> - ) -} + </EuiForm> + </> + ); +}; +const assignedRoles = ({ + roles, + selectedRole, + onSelectedRole, + assignedRoleToUsers, + assignedRolesColumns, +}) => { + return ( + <> + <EuiForm component="form"> + <EuiFormRow label="Select Specific Role"> + <EuiComboBox + placeholder="Select a role" + singleSelection={{ asPlainText: true }} + options={roles} + selectedOptions={selectedRole} + onChange={(e) => { + onSelectedRole(e); + }} + /> + </EuiFormRow> + <EuiFormRow label="Assigned Roles" fullWidth> + <EuiBasicTable + items={assignedRoleToUsers} + rowheader="" + columns={assignedRolesColumns} + // rowProps={getRowProps} + // cellProps={getCellProps} + /> + </EuiFormRow> + </EuiForm> + </> + ); +}; const Role = (props) => { - const [globalState, globalActions] = store(); - const [selectedTabNumber, setSelectedTabNumber] = useState(0) - const [roleNameValue, setRoleNameValue] = useState() - const [roleDescriptionValue, setRoleDescriptionValue] = useState() - const [roles, setRoles] = useState([]) - const [users, setUsers] = useState([]) - const [open, setOpen] = useState(false); - const [alertMessage, setAlertMessage] = useState(""); - const [severity, setSeverity] = useState("info") - const [selectedRole, setSelectedRole] = useState() - const [assignedRoleToUsers, setAssignedRoleToUsers] = useState([]) - - const loads = useCallback(async () => { - const roles = await globalActions.user.findRole() - const users = await globalActions.user.findUser() - if (globalState.user.id) { - await globalActions.user.allocatedRoles(globalState.user.id) - } - - if (roles && users) { - const _roles = [] - for (const role of roles) { - _roles.push({ value: role.id, label: role.name }) - } - setRoles(_roles) - - const _users = [] - for (const user of users) { - _users.push({ value: user.id, label: user.username }) - } - setUsers(_users) - } - }, [globalActions.user, globalState.user.id]) - - useEffect(() => { - // clean up controller - let isSubscribed = true; - if (isSubscribed) { - loads() - } - // cancel subscription to useEffect - return () => (isSubscribed = false) - }, [loads]) - - - const onSaveRole = async () => { - await globalActions.user.createRole(roleNameValue, roleDescriptionValue) - await globalActions.user.findRole() + const [globalState, globalActions] = store(); + const [selectedTabNumber, setSelectedTabNumber] = useState(0); + const [roleNameValue, setRoleNameValue] = useState(); + const [roleDescriptionValue, setRoleDescriptionValue] = useState(); + const [roles, setRoles] = useState([]); + const [users, setUsers] = useState([]); + const [open, setOpen] = useState(false); + const [alertMessage, setAlertMessage] = useState(''); + const [severity, setSeverity] = useState('info'); + const [selectedRole, setSelectedRole] = useState(); + const [assignedRoleToUsers, setAssignedRoleToUsers] = useState([]); + + const loads = useCallback(async () => { + const roles = await globalActions.user.findRole(); + const users = await globalActions.user.findUser(); + if (globalState.user.id) { + await globalActions.user.allocatedRoles(globalState.user.id); } - const onRoleAssignment = async () => { - - const checkedRoles = roles.filter(e => { - return e.checked === "on" - }) - - const checkedUsers = users.filter(e => { - return e.checked === "on" - }) - - for (const user of checkedUsers) { - for (const role of checkedRoles) { - await globalActions.user.allocateRolesToUser(user.value, role.value) - } - } - - if (globalState.status === 'SUCCESS') { - setOpen(true) - setAlertMessage("Role-Assignment completed succesfully !") - setSeverity("success") - } - + if (roles && users) { + const _roles = []; + for (const role of roles) { + _roles.push({ value: role.id, label: role.name }); + } + setRoles(_roles); + + const _users = []; + for (const user of users) { + _users.push({ value: user.id, label: user.username }); + } + setUsers(_users); } + }, [globalActions.user, globalState.user.id]); - const onSelectedRole = async (e) => { - if (e.length > 0) { - setSelectedRole(e) - const assignedUserByRoleItems = await globalActions.user.getAssignedUserByRole(e[0].value) - setAssignedRoleToUsers(assignedUserByRoleItems) - } else { - setSelectedRole(e) - } - + useEffect(() => { + // clean up controller + let isSubscribed = true; + if (isSubscribed) { + loads(); + } + // cancel subscription to useEffect + return () => (isSubscribed = false); + }, [loads]); + + const onSaveRole = async () => { + await globalActions.user.createRole(roleNameValue, roleDescriptionValue); + await globalActions.user.findRole(); + }; + + const onRoleAssignment = async () => { + const checkedRoles = roles.filter((e) => { + return e.checked === 'on'; + }); + + const checkedUsers = users.filter((e) => { + return e.checked === 'on'; + }); + + for (const user of checkedUsers) { + for (const role of checkedRoles) { + await globalActions.user.allocateRolesToUser(user.value, role.value); + } } - const onDeleteRole = async (e) => { + if (globalState.status === 'SUCCESS') { + setOpen(true); + setAlertMessage('Role-Assignment completed succesfully !'); + setSeverity('success'); + } + }; + + const onSelectedRole = async (e) => { + if (e.length > 0) { + setSelectedRole(e); + const assignedUserByRoleItems = await globalActions.user.getAssignedUserByRole( + e[0].value + ); + setAssignedRoleToUsers(assignedUserByRoleItems); + } else { + setSelectedRole(e); + } + }; - await globalActions.user.deleteRole(e.id) - if (globalState.status === 'SUCCESS') { - setOpen(true) - setAlertMessage("Role delete succesfully !") - setSeverity("success") + const onDeleteRole = async (e) => { + await globalActions.user.deleteRole(e.id); + if (globalState.status === 'SUCCESS') { + setOpen(true); + setAlertMessage('Role delete succesfully !'); + setSeverity('success'); - await globalActions.user.findRole() - } + await globalActions.user.findRole(); } + }; - const roleActions = [ - /*{ + const roleActions = [ + /*{ name: 'Clone', description: 'Clone this person', icon: 'copy', type: 'icon', onClick: cloneUser, },*/ - { - name: 'Delete', - description: 'Delete this person', - icon: 'trash', - type: 'icon', - color: 'danger', - onClick: onDeleteRole, - }, - ]; - const roleColumns = [ - { field: 'name', name: 'Role Name' }, - { field: 'description', name: 'Role Description' }, - { name: 'Actions', actions: roleActions } - ] - - const assignedRolesColumns = [{ field: 'username', name: 'Username' }, + { + name: 'Delete', + description: 'Delete this person', + icon: 'trash', + type: 'icon', + color: 'danger', + onClick: onDeleteRole, + }, + ]; + const roleColumns = [ + { field: 'name', name: 'Role Name' }, + { field: 'description', name: 'Role Description' }, + { name: 'Actions', actions: roleActions }, + ]; + + const assignedRolesColumns = [ + { field: 'username', name: 'Username' }, { field: 'useremail', name: 'e-mail' }, { field: 'rolename', name: 'Role' }, - { name: 'Actions', actions: roleActions }] + { name: 'Actions', actions: roleActions }, + ]; - const handleClose = (event, reason) => { - if (reason === 'clickaway') { - return; - } - setOpen(false); + const handleClose = (event, reason) => { + if (reason === 'clickaway') { + return; } - - - const tabContents = [ - { - id: 'tab1', - name: 'New Role', - content: ( - <> - <br /> - {newRoleForm({ roleNameValue, setRoleNameValue, roleDescriptionValue, setRoleDescriptionValue, globalState, onSaveRole, roleColumns })} - </> - ) - }, { - id: 'tab2', - name: 'Role Assignment', - content: ( - <> - <br /> - {roleAssignment(globalState, roles, setRoles, users, setUsers, onRoleAssignment)} - </> - ) - }, { - id: 'tab3', - name: 'Assigned Roles', - content: ( - <> - <br /> - {assignedRoles({ roles, selectedRole, onSelectedRole, assignedRoleToUsers: assignedRoleToUsers, assignedRolesColumns })} - </> - ) - } - ] - - return ( - + setOpen(false); + }; + + const tabContents = [ + { + id: 'tab1', + name: 'New Role', + content: ( <> - <EuiPageContent> - <EuiPageContentHeader> - <EuiPageContentHeaderSection> - <EuiTitle> - <h6>Roles</h6> - </EuiTitle> - </EuiPageContentHeaderSection> - </EuiPageContentHeader> - <EuiPageContentBody> - <EuiForm> - <EuiTabbedContent - tabs={tabContents} - selectedTab={tabContents[selectedTabNumber]} - onTabClick={tab => { - setSelectedTabNumber(tabContents.indexOf(tab)) - }} - /> - </EuiForm> - </EuiPageContentBody> - </EuiPageContent> - {ShowAlert(open, handleClose, alertMessage, severity)} + <br /> + {newRoleForm({ + roleNameValue, + setRoleNameValue, + roleDescriptionValue, + setRoleDescriptionValue, + globalState, + onSaveRole, + roleColumns, + })} </> - ) - -} - -export default Role \ No newline at end of file + ), + }, + { + id: 'tab2', + name: 'Role Assignment', + content: ( + <> + <br /> + {roleAssignment( + globalState, + roles, + setRoles, + users, + setUsers, + onRoleAssignment + )} + </> + ), + }, + { + id: 'tab3', + name: 'Assigned Roles', + content: ( + <> + <br /> + {assignedRoles({ + roles, + selectedRole, + onSelectedRole, + assignedRoleToUsers: assignedRoleToUsers, + assignedRolesColumns, + })} + </> + ), + }, + ]; + + return ( + <> + <EuiPageContent> + <EuiPageContentHeader> + <EuiPageContentHeaderSection> + <EuiTitle> + <h6>Roles</h6> + </EuiTitle> + </EuiPageContentHeaderSection> + </EuiPageContentHeader> + <EuiPageContentBody> + <EuiForm> + <EuiTabbedContent + tabs={tabContents} + selectedTab={tabContents[selectedTabNumber]} + onTabClick={(tab) => { + setSelectedTabNumber(tabContents.indexOf(tab)); + }} + /> + </EuiForm> + </EuiPageContentBody> + </EuiPageContent> + {ShowAlert(open, handleClose, alertMessage, severity)} + </> + ); +}; + +export default Role; diff --git a/src/pages/roles/package.json b/src/pages/roles/package.json index c14f161..0f4db35 100644 --- a/src/pages/roles/package.json +++ b/src/pages/roles/package.json @@ -1,6 +1,6 @@ { - "name": "Role", - "version": "1.0.0", - "private": true, - "main": "Role.js" -} \ No newline at end of file + "name": "Role", + "version": "1.0.0", + "private": true, + "main": "Role.js" +} diff --git a/src/pages/roles/styles.js b/src/pages/roles/styles.js index d135699..4842f10 100644 --- a/src/pages/roles/styles.js +++ b/src/pages/roles/styles.js @@ -1,44 +1,44 @@ -import { makeStyles } from "@material-ui/styles"; +import { makeStyles } from '@material-ui/styles'; -export default makeStyles(theme => ({ - titleBold: { - fontWeight: 600, - }, - tab: { - color: theme.palette.primary.light + "CC", - }, - roleContainer: { - boxShadow: theme.customShadows.widget, - overflow: "hidden", - paddingBottom: theme.spacing(2), - }, - dashedBorder: { - border: "1px dashed", - borderColor: theme.palette.primary.main, - padding: theme.spacing(2), - paddingTop: theme.spacing(4), - paddingBottom: theme.spacing(4), - marginTop: theme.spacing(1), - }, - text: { - marginBottom: theme.spacing(2), - }, - root: { - padding: theme.spacing(3, 2), - }, - formControl: { - margin: theme.spacing(1), - minWidth: 120, - maxWidth: 300, - }, - chips: { - display: 'flex', - flexWrap: 'wrap', - }, - chip: { - margin: 2, - }, - noLabel: { - marginTop: theme.spacing(3), - }, -})); \ No newline at end of file +export default makeStyles((theme) => ({ + titleBold: { + fontWeight: 600, + }, + tab: { + color: theme.palette.primary.light + 'CC', + }, + roleContainer: { + boxShadow: theme.customShadows.widget, + overflow: 'hidden', + paddingBottom: theme.spacing(2), + }, + dashedBorder: { + border: '1px dashed', + borderColor: theme.palette.primary.main, + padding: theme.spacing(2), + paddingTop: theme.spacing(4), + paddingBottom: theme.spacing(4), + marginTop: theme.spacing(1), + }, + text: { + marginBottom: theme.spacing(2), + }, + root: { + padding: theme.spacing(3, 2), + }, + formControl: { + margin: theme.spacing(1), + minWidth: 120, + maxWidth: 300, + }, + chips: { + display: 'flex', + flexWrap: 'wrap', + }, + chip: { + margin: 2, + }, + noLabel: { + marginTop: theme.spacing(3), + }, +})); diff --git a/src/pages/sources/Sources.js b/src/pages/sources/Sources.js index 7829e10..285ebeb 100644 --- a/src/pages/sources/Sources.js +++ b/src/pages/sources/Sources.js @@ -1,593 +1,670 @@ -import React, { useState, useCallback, useEffect, memo, useRef, useReducer } from "react" -import store from "../../store/index" +import React, { useState, useCallback, useEffect, memo, useRef, useReducer } from 'react'; +import store from '../../store/index'; import { - EuiForm, - EuiPageContent, - EuiPageContentHeader, - EuiPageContentHeaderSection, - EuiTitle, - EuiPageContentBody, - EuiTabbedContent, - EuiFormRow, - EuiFieldText, - EuiText, - EuiFlexGroup, - EuiFlexItem, - EuiSpacer, - EuiButton, - EuiFilePicker, - EuiBasicTable, - EuiHealth, - EuiProgress, - EuiConfirmModal, - EuiOverlayMask, - EuiModal, - EuiModalHeader, - EuiModalHeaderTitle, - EuiModalBody, - EuiModalFooter, - EuiButtonEmpty, - EuiCallOut -} from '@elastic/eui' - -import { ShowAlert } from '../../components/Common' -import JsonView from '@in-sylva/json-view' - -const NewSourceForm = memo(({ globalState, nameValue, setNameValue, descriptionValue, setDescriptionValue, onSaveSource, onFilePickerChange, files, renderFiles, metaUrfms }) => { - + EuiForm, + EuiPageContent, + EuiPageContentHeader, + EuiPageContentHeaderSection, + EuiTitle, + EuiPageContentBody, + EuiTabbedContent, + EuiFormRow, + EuiFieldText, + EuiText, + EuiFlexGroup, + EuiFlexItem, + EuiSpacer, + EuiButton, + EuiFilePicker, + EuiBasicTable, + EuiHealth, + EuiProgress, + EuiConfirmModal, + EuiOverlayMask, + EuiModal, + EuiModalHeader, + EuiModalHeaderTitle, + EuiModalBody, + EuiModalFooter, + EuiButtonEmpty, + EuiCallOut, +} from '@elastic/eui'; + +import { ShowAlert } from '../../components/Common'; +import JsonView from '@in-sylva/json-view'; + +const NewSourceForm = memo( + ({ + globalState, + nameValue, + setNameValue, + descriptionValue, + setDescriptionValue, + onSaveSource, + onFilePickerChange, + files, + renderFiles, + metaUrfms, + }) => { return ( - <> - <br /> - <EuiForm component="form"> - <EuiFlexGroup> - <EuiFlexItem grow={3}> - <EuiFormRow label="Source / File Name"> - <EuiFieldText id="nameValue" value={nameValue} onChange={e => setNameValue(e.target.value)} /> - </EuiFormRow> - <EuiFormRow label="Source Description"> - <EuiFieldText id="descriptionValue" value={descriptionValue} onChange={e => setDescriptionValue(e.target.value)} /> - </EuiFormRow> - <EuiSpacer /> - <EuiFormRow - label="Source Files"> - <EuiFilePicker - id="filePicker1" - multiple - initialPromptText="Select or drag and drop multiple source files" - onChange={files => { - onFilePickerChange(files); - }} - display={'large'} - /> - </EuiFormRow> - <EuiFormRow label=""> - <EuiText> - <h3>Files attached</h3> - {renderFiles(files)} - </EuiText> - </EuiFormRow> - <EuiFormRow label=""> - {<EuiButton fill onClick={onSaveSource} isLoading={globalState.isLoading}> - Save - </EuiButton>} - </EuiFormRow> - </EuiFlexItem> - <EuiFlexItem grow={3}> - <> - <br /> - <JsonView name="Metadata Records" collapsed={true} iconStyle={'triangle'} src={metaUrfms} /> - </> - </EuiFlexItem> - </EuiFlexGroup> - </EuiForm> - </> - ) -}) - -const SourcesForm = memo(({ metaUrfmColumns, sources, onTableChange, tableref, pagination, sorting, selection, mergeButton }) => { + <> + <br /> + <EuiForm component="form"> + <EuiFlexGroup> + <EuiFlexItem grow={3}> + <EuiFormRow label="Source / File Name"> + <EuiFieldText + id="nameValue" + value={nameValue} + onChange={(e) => setNameValue(e.target.value)} + /> + </EuiFormRow> + <EuiFormRow label="Source Description"> + <EuiFieldText + id="descriptionValue" + value={descriptionValue} + onChange={(e) => setDescriptionValue(e.target.value)} + /> + </EuiFormRow> + <EuiSpacer /> + <EuiFormRow label="Source Files"> + <EuiFilePicker + id="filePicker1" + multiple + initialPromptText="Select or drag and drop multiple source files" + onChange={(files) => { + onFilePickerChange(files); + }} + display={'large'} + /> + </EuiFormRow> + <EuiFormRow label=""> + <EuiText> + <h3>Files attached</h3> + {renderFiles(files)} + </EuiText> + </EuiFormRow> + <EuiFormRow label=""> + { + <EuiButton + fill + onClick={onSaveSource} + isLoading={globalState.isLoading} + > + Save + </EuiButton> + } + </EuiFormRow> + </EuiFlexItem> + <EuiFlexItem grow={3}> + <> + <br /> + <JsonView + name="Metadata Records" + collapsed={true} + iconStyle={'triangle'} + src={metaUrfms} + /> + </> + </EuiFlexItem> + </EuiFlexGroup> + </EuiForm> + </> + ); + } +); + +const SourcesForm = memo( + ({ + metaUrfmColumns, + sources, + onTableChange, + tableref, + pagination, + sorting, + selection, + mergeButton, + }) => { return ( - <> - <br /> - <EuiForm component="form"> - - <EuiFlexGroup alignItems="center"> - - {mergeButton} - </EuiFlexGroup> - - <EuiSpacer size="l" /> - - <EuiFormRow - label="Uploaded Sources" fullWidth> - <EuiBasicTable - itemId="id" - isSelectable={true} - items={sources} - columns={metaUrfmColumns} - onChange={onTableChange} - ref={tableref} - pagination={pagination} - sorting={sorting} - selection={selection} - /> - </EuiFormRow> - </EuiForm> - </> - ) -}) + <> + <br /> + <EuiForm component="form"> + <EuiFlexGroup alignItems="center">{mergeButton}</EuiFlexGroup> + + <EuiSpacer size="l" /> + + <EuiFormRow label="Uploaded Sources" fullWidth> + <EuiBasicTable + itemId="id" + isSelectable={true} + items={sources} + columns={metaUrfmColumns} + onChange={onTableChange} + ref={tableref} + pagination={pagination} + sorting={sorting} + selection={selection} + /> + </EuiFormRow> + </EuiForm> + </> + ); + } +); const ShareSources = memo(() => { - return ( - <> - <br /> - </> - ) -}) + return ( + <> + <br /> + </> + ); +}); const SharedSources = memo(() => { - return ( - <> - <br /> - </> - ) -}) + return ( + <> + <br /> + </> + ); +}); const renderFiles = (files) => { - if (files.length > 0) { - return ( - <ul> - {Object.keys(files).map((item, i) => ( - <li key={i}> - <strong>{files[item].name}</strong> ({files[item].size} bytes) - </li> - ))} - </ul> - ); - } else { - return ( - <p>Please, add some files to upload.</p> - ); - } -} + if (files.length > 0) { + return ( + <ul> + {Object.keys(files).map((item, i) => ( + <li key={i}> + <strong>{files[item].name}</strong> ({files[item].size} bytes) + </li> + ))} + </ul> + ); + } else { + return <p>Please, add some files to upload.</p>; + } +}; const Sources = () => { - - const initialState = { - nameValue: "", - descriptionValue: "", - metaUrfms: [], + const initialState = { + nameValue: '', + descriptionValue: '', + metaUrfms: [], + }; + + const reducer = (state, action) => { + if (action.type === 'reset') { + return initialState; } - - const reducer = (state, action) => { - if (action.type === "reset") { - return initialState; - } - const result = { ...state }; - result[action.type] = action.value; - return result; + const result = { ...state }; + result[action.type] = action.value; + return result; + }; + + const [state, dispatch] = useReducer(reducer, initialState); + + const [metaUrfms, setMetaUrfms] = useState([]); + // const [metaUrfmsCol, setMetaUrfmsCol] = useState([]) + const [selectedTabNumber, setSelectedTabNumber] = useState(0); + const [globalState, globalActions] = store(); + const [files, setFiles] = useState([]); + const [nameValue, setNameValue] = useState(); + const [descriptionValue, setDescriptionValue] = useState(); + const [open, setOpen] = useState(false); + const [alertMessage, setAlertMessage] = useState(''); + const [severity, setSeverity] = useState('info'); + const [sources, setSources] = useState([]); + const [pageIndex, setPageIndex] = useState(0); + const [pageSize, setPageSize] = useState(5); + const [sortDirection, setSortDirection] = useState('asc'); + const [selectedSources, setSelectedSources] = useState([]); + const [sortField, setSortField] = useState('name'); + const tableref = useRef(); + const [source, setSource] = useState({}); + const [isModalVisible, setIsModalVisible] = useState(false); + const [isMergeModalVisible, setIsMergeModalVisible] = useState(false); + const [sourceName, setSourceName] = useState(''); + const [sourceDescription, setSourceDescription] = useState(''); + + const onClickMergeSource = () => { + openMergeSourceModal(); + }; + + const renderMergeButton = () => { + if (selectedSources.length === 0 || selectedSources.length === 1) { + return; } - const [state, dispatch] = useReducer(reducer, initialState); - - const [metaUrfms, setMetaUrfms] = useState([]) - // const [metaUrfmsCol, setMetaUrfmsCol] = useState([]) - const [selectedTabNumber, setSelectedTabNumber] = useState(0) - const [globalState, globalActions] = store() - const [files, setFiles] = useState([]) - const [nameValue, setNameValue] = useState() - const [descriptionValue, setDescriptionValue] = useState() - const [open, setOpen] = useState(false); - const [alertMessage, setAlertMessage] = useState("") - const [severity, setSeverity] = useState("info") - const [sources, setSources] = useState([]) - const [pageIndex, setPageIndex] = useState(0) - const [pageSize, setPageSize] = useState(5) - const [sortDirection, setSortDirection] = useState('asc') - const [selectedSources, setSelectedSources] = useState([]) - const [sortField, setSortField] = useState('name') - const tableref = useRef() - const [source, setSource] = useState({}) - const [isModalVisible, setIsModalVisible] = useState(false) - const [isMergeModalVisible, setIsMergeModalVisible] = useState(false) - const [sourceName, setSourceName] = useState('') - const [sourceDescription, setSourceDescription] = useState('') - - const onClickMergeSource = () => { - openMergeSourceModal() - } - - const renderMergeButton = () => { - if (selectedSources.length === 0 || selectedSources.length === 1) { - return - } - - return ( - <EuiButton color="secondary" iconType="merge" onClick={onClickMergeSource}> - Merge and Send {selectedSources.length} Source File(s) - </EuiButton> - ); - }; + return ( + <EuiButton color="secondary" iconType="merge" onClick={onClickMergeSource}> + Merge and Send {selectedSources.length} Source File(s) + </EuiButton> + ); + }; - const onTableChange = ({ page = {}, sort = {} }) => { - const { index: pageIndex, size: pageSize } = page; + const onTableChange = ({ page = {}, sort = {} }) => { + const { index: pageIndex, size: pageSize } = page; - const { field: sortField, direction: sortDirection } = sort; + const { field: sortField, direction: sortDirection } = sort; - setPageIndex(pageIndex); - setPageSize(pageSize); - setSortField(sortField); - setSortDirection(sortDirection); - }; + setPageIndex(pageIndex); + setPageSize(pageSize); + setSortField(sortField); + setSortDirection(sortDirection); + }; - const onSelectionChange = (selectedItems) => { - setSelectedSources(selectedItems); - }; - const totalItemCount = (typeof sources === ([] || null) ? 0 : sources.length) + const onSelectionChange = (selectedItems) => { + setSelectedSources(selectedItems); + }; + const totalItemCount = typeof sources === ([] || null) ? 0 : sources.length; - const pagination = { - pageIndex: pageIndex, - pageSize: pageSize, - totalItemCount: totalItemCount, - pageSizeOptions: [3, 5, 8], - }; + const pagination = { + pageIndex: pageIndex, + pageSize: pageSize, + totalItemCount: totalItemCount, + pageSizeOptions: [3, 5, 8], + }; - // const unsentSources = (typeof sources === ([] || null) ? [] : sources.filter(e => { return e.is_send === false })) + // const unsentSources = (typeof sources === ([] || null) ? [] : sources.filter(e => { return e.is_send === false })) - const selection = { - selectable: source => !source.is_send, - onSelectionChange: onSelectionChange, - // initialSelected: unsentSources, - } + const selection = { + selectable: (source) => !source.is_send, + onSelectionChange: onSelectionChange, + // initialSelected: unsentSources, + }; - /* + /* const onSelection = () => { tableref.current.setSelection(typeof sources === ([] || null) ? [] : sources.filter(e => { return e.is_send === false })); }; */ - const sorting = { - sort: { - field: sortField, - direction: sortDirection, - }, - } - - const closeModal = () => setIsModalVisible(false); - const showModal = () => setIsModalVisible(true); - - const closeMergeSourceModal = () => setIsMergeModalVisible(false) - const openMergeSourceModal = () => setIsMergeModalVisible(true) - - // delete source from db, elasticsearch and mongodb - const onDeleteSource = async (source) => { - setSource(source) - showModal() - } - - const onDeleteSourceConfirm = async () => { - closeModal() - if (source.id && sessionStorage.getItem('userId')) { - await globalActions.source.deleteSource(source.id, sessionStorage.getItem('userId')) - setOpen(true) - setAlertMessage("Source is deleted succesfully") - setSeverity("success") - - await loadSources() - } else { - setOpen(true) - setAlertMessage("While deletion the sources to elastic stack, unexpected error has been occurred.") - setSeverity("error") - } - } - - const onMergeAndSendSourcesConfirmed = async () => { - - if (sourceName && sourceDescription && selectedSources) { - - const kcId = sessionStorage.getItem('userId') - const result = await globalActions.source.mergeAndSendSource(kcId, sourceName, sourceDescription, selectedSources) - console.log(result) - if (result.status === 201) { - setOpen(true) - setAlertMessage("Sources are merged and send to elasticsearch successfully !") - setSeverity("success") - - await loadSources() - } else { - setOpen(true) - setAlertMessage("While merging the sources, unexpected error has been occurred.") - setSeverity("error") - } - closeMergeSourceModal() - } - + const sorting = { + sort: { + field: sortField, + direction: sortDirection, + }, + }; + + const closeModal = () => setIsModalVisible(false); + const showModal = () => setIsModalVisible(true); + + const closeMergeSourceModal = () => setIsMergeModalVisible(false); + const openMergeSourceModal = () => setIsMergeModalVisible(true); + + // delete source from db, elasticsearch and mongodb + const onDeleteSource = async (source) => { + setSource(source); + showModal(); + }; + + const onDeleteSourceConfirm = async () => { + closeModal(); + if (source.id && sessionStorage.getItem('userId')) { + await globalActions.source.deleteSource( + source.id, + sessionStorage.getItem('userId') + ); + setOpen(true); + setAlertMessage('Source is deleted succesfully'); + setSeverity('success'); + + await loadSources(); + } else { + setOpen(true); + setAlertMessage( + 'While deletion the sources to elastic stack, unexpected error has been occurred.' + ); + setSeverity('error'); } - - const updateSource = async (kc_id, source_id) => { - await globalActions.source.updateSource(kc_id, source_id) + }; + + const onMergeAndSendSourcesConfirmed = async () => { + if (sourceName && sourceDescription && selectedSources) { + const kcId = sessionStorage.getItem('userId'); + const result = await globalActions.source.mergeAndSendSource( + kcId, + sourceName, + sourceDescription, + selectedSources + ); + console.log(result); + if (result.status === 201) { + setOpen(true); + setAlertMessage('Sources are merged and send to elasticsearch successfully !'); + setSeverity('success'); + + await loadSources(); + } else { + setOpen(true); + setAlertMessage('While merging the sources, unexpected error has been occurred.'); + setSeverity('error'); + } + closeMergeSourceModal(); } - // import source document to elasticsearch - const onSendSource = async (source) => { - if (sessionStorage.getItem('userId') && source) { - - const kc_id = sessionStorage.getItem('userId') - const source_id = source.id - - await updateSource(kc_id, source_id) - if (globalState.status === 'SUCCESS') { - setOpen(true) - setAlertMessage("Source imported to elastic stack succesfully") - setSeverity("success") - - await loadSources() - } else { - setOpen(true) - setAlertMessage("While importation the sources to elastic stack, unexpected error has been occurred.") - setSeverity("error") - } - } + }; + + const updateSource = async (kc_id, source_id) => { + await globalActions.source.updateSource(kc_id, source_id); + }; + // import source document to elasticsearch + const onSendSource = async (source) => { + if (sessionStorage.getItem('userId') && source) { + const kc_id = sessionStorage.getItem('userId'); + const source_id = source.id; + + await updateSource(kc_id, source_id); + if (globalState.status === 'SUCCESS') { + setOpen(true); + setAlertMessage('Source imported to elastic stack succesfully'); + setSeverity('success'); + + await loadSources(); + } else { + setOpen(true); + setAlertMessage( + 'While importation the sources to elastic stack, unexpected error has been occurred.' + ); + setSeverity('error'); + } } - - const metaUrfmActions = [ - { - name: 'Send', - description: 'Send this source', - icon: 'aggregate', - type: 'icon', - enabled: (value) => !value.is_send, - onClick: onSendSource, - }, - { - name: 'Delete', - description: 'Delete this source', - icon: 'trash', - type: 'icon', - color: 'danger', - enable: () => false, - onClick: onDeleteSource, - }, - ] - const metaUrfmColumns = [ - { field: 'name', name: 'Source / File Name' }, - { field: 'index_id', name: 'Elasticsearch Index' }, - { field: 'mng_id', name: 'MongoDb Index' }, - { field: 'description', name: 'Source Description' }, - { - field: 'is_send', - name: 'Status', - dataType: 'boolean', - render: value => { - const color = value ? 'success' : 'danger'; - const label = value ? 'sent' : 'unsent'; - return <EuiHealth color={color}>{label}</EuiHealth>; - }, - }, - { name: 'Actions', actions: metaUrfmActions } - ] - - const onFilePickerChange = async (files) => { - setFiles(files) - await handleSelectedFile(files); + }; + + const metaUrfmActions = [ + { + name: 'Send', + description: 'Send this source', + icon: 'aggregate', + type: 'icon', + enabled: (value) => !value.is_send, + onClick: onSendSource, + }, + { + name: 'Delete', + description: 'Delete this source', + icon: 'trash', + type: 'icon', + color: 'danger', + enable: () => false, + onClick: onDeleteSource, + }, + ]; + const metaUrfmColumns = [ + { field: 'name', name: 'Source / File Name' }, + { field: 'index_id', name: 'Elasticsearch Index' }, + { field: 'mng_id', name: 'MongoDb Index' }, + { field: 'description', name: 'Source Description' }, + { + field: 'is_send', + name: 'Status', + dataType: 'boolean', + render: (value) => { + const color = value ? 'success' : 'danger'; + const label = value ? 'sent' : 'unsent'; + return <EuiHealth color={color}>{label}</EuiHealth>; + }, + }, + { name: 'Actions', actions: metaUrfmActions }, + ]; + + const onFilePickerChange = async (files) => { + setFiles(files); + await handleSelectedFile(files); + }; + + const handleSelectedFile = async (files) => { + for (const file of files) { + const reader = new FileReader(); + await reader.readAsText(file); + reader.onload = () => handleData(reader.result); } - - const handleSelectedFile = async (files) => { - for (const file of files) { - const reader = new FileReader() - await reader.readAsText(file); - reader.onload = () => handleData(reader.result) - } + }; + + const handleData = (file) => { + const { metadataRecords } = JSON.parse(file); + + if (metadataRecords) { + const columns = []; + const rows = []; + + const prop = Object.keys(metadataRecords[0]); + + prop.forEach((item) => { + const column = { + name: item, + options: { + display: true, + }, + }; + columns.push(column); + }); + + metadataRecords.forEach((row) => { + rows.push(row); + }); + + if (columns && rows) { + // setMetaUrfmsCol(columns) + setMetaUrfms(rows); + } } - - const handleData = (file) => { - - const { metadataRecords } = JSON.parse(file) - - if (metadataRecords) { - const columns = []; - const rows = []; - - const prop = Object.keys(metadataRecords[0]) - - prop.forEach((item) => { - const column = { - name: item, - options: { - display: true - } - } - columns.push(column); - }) - - metadataRecords.forEach((row) => { - rows.push(row) - }) - - if (columns && rows) { - // setMetaUrfmsCol(columns) - setMetaUrfms(rows) - } - } + }; + + const onSaveSource = async () => { + if (nameValue && descriptionValue && metaUrfms) { + await globalActions.source.createSource( + metaUrfms, + nameValue, + descriptionValue, + sessionStorage.getItem('userId') + ); + + if (globalState.status === 'SUCCESS') { + setOpen(true); + setAlertMessage('Source was created succesfully'); + setSeverity('success'); + + await loadSources(); + } else { + setOpen(true); + setAlertMessage('While creating the sources unexpected error has been occurred.'); + setSeverity('error'); + } } - - const onSaveSource = async () => { - - if (nameValue && descriptionValue && metaUrfms) { - await globalActions.source.createSource(metaUrfms, nameValue, descriptionValue, sessionStorage.getItem('userId')); - - if (globalState.status === 'SUCCESS') { - setOpen(true) - setAlertMessage("Source was created succesfully") - setSeverity("success") - - await loadSources() - } else { - setOpen(true) - setAlertMessage("While creating the sources unexpected error has been occurred.") - setSeverity("error") - } - } - + }; + + const loadSources = useCallback(async () => { + if (sessionStorage.getItem('userId')) { + const user = await globalActions.user.findOneUserWithGroupAndRole( + sessionStorage.getItem('userId') + ); + const role = user[0].roleid; + let result; + if (role === 1) { + result = await globalActions.source.allSources(); + } else { + result = await globalActions.source.sources(sessionStorage.getItem('userId')); + } + if (result) { + setSources(result); + } } + }, [globalActions.source]); - const loadSources = useCallback(async () => { - if (sessionStorage.getItem('userId')) { - const user = await globalActions.user.findOneUserWithGroupAndRole(sessionStorage.getItem('userId')) - const role = user[0].roleid - let result - if (role === 1) { - result = await globalActions.source.allSources() - } else { - result = await globalActions.source.sources(sessionStorage.getItem('userId')) - } - if (result) { - setSources(result) - } - } - }, [globalActions.source]) - - useEffect(() => { - // clean up controller - let isSubscribed = true; - if (isSubscribed) { - loadSources() - } - // cancel subscription to useEffect - return () => (isSubscribed = false) - }, [loadSources]) - - const handleClose = (event, reason) => { - if (reason === 'clickaway') { - return; - } - setOpen(false); + useEffect(() => { + // clean up controller + let isSubscribed = true; + if (isSubscribed) { + loadSources(); } - const mergeButton = renderMergeButton() - - const tabContents = [ - { - id: 'tab1', - name: 'New Source', - content: ( - <> - <NewSourceForm nameValue={nameValue} setNameValue={setNameValue} descriptionValue={descriptionValue} setDescriptionValue={setDescriptionValue} globalState={globalState} onFilePickerChange={onFilePickerChange} files={files} renderFiles={renderFiles} onSaveSource={onSaveSource} metaUrfms={metaUrfms} /> - </> - ) - }, { - id: 'tab2', - name: 'Sources', - content: ( - <> - <SourcesForm metaUrfmColumns={metaUrfmColumns} sources={typeof sources === undefined ? [] : sources} onTableChange={onTableChange} tableref={tableref} pagination={pagination} sorting={sorting} selection={selection} mergeButton={mergeButton} /> - </> - ) - }, { - id: 'tab3', - name: 'Share Sources', - content: ( - <> - <ShareSources /> - </> - ) - }, - { - id: 'tab4', - name: 'Shared Sources', - content: ( - <> - <SharedSources /> - </> - ) - } - ] - - - const mergeModalForm = ( - <EuiForm> - <EuiCallOut title="Proceed with caution!" color="warning" iconType="help"> - <p> - Source / File Name is unique field for the In-Sylva Search App. - </p> - </EuiCallOut> <br /> - <EuiFormRow label="Source / File Name"> - <EuiFieldText name="sourceName" value={sourceName} onChange={e => setSourceName(e.target.value)} /> - </EuiFormRow> - <EuiFormRow label="Source Description"> - <EuiFieldText name="sourceDescription" value={sourceDescription} onChange={e => setSourceDescription(e.target.value)} /> - </EuiFormRow> - <EuiSpacer /> - </EuiForm> - ); + // cancel subscription to useEffect + return () => (isSubscribed = false); + }, [loadSources]); - - let mergeSourceModal; - if (isMergeModalVisible) { - mergeSourceModal = ( - <EuiOverlayMask> - <EuiModal onClose={closeMergeSourceModal} initialFocus="[name=popswitch]"> - <EuiModalHeader> - <EuiModalHeaderTitle>Merge and Send Selected Source Files</EuiModalHeaderTitle> - </EuiModalHeader> - - <EuiModalBody>{mergeModalForm}</EuiModalBody> - - <EuiModalFooter> - <EuiButtonEmpty onClick={closeMergeSourceModal}>Cancel</EuiButtonEmpty> - - <EuiButton onClick={onMergeAndSendSourcesConfirmed} fill> - Save - </EuiButton> - </EuiModalFooter> - </EuiModal> - </EuiOverlayMask> - ) + const handleClose = (event, reason) => { + if (reason === 'clickaway') { + return; } - - let Warningmodal; - if (isModalVisible) { - Warningmodal = ( - <EuiOverlayMask> - <EuiConfirmModal - title="Warning" - onCancel={closeModal} - onConfirm={onDeleteSourceConfirm} - cancelButtonText="Cancel" - confirmButtonText="Confirm" - buttonColor="danger" - defaultFocusedButton="confirm"> - <p>Are you sure you want to delete this file?</p> - </EuiConfirmModal> - </EuiOverlayMask> - ); - } - - return ( + setOpen(false); + }; + const mergeButton = renderMergeButton(); + + const tabContents = [ + { + id: 'tab1', + name: 'New Source', + content: ( <> - <EuiPageContent> - <EuiPageContentHeader> - <EuiPageContentHeaderSection> - <EuiTitle> - <h6>Source Management</h6> - </EuiTitle> - </EuiPageContentHeaderSection> - </EuiPageContentHeader> - <EuiPageContentBody> - <EuiForm> - <EuiForm> - <EuiTabbedContent - tabs={tabContents} - selectedTab={tabContents[selectedTabNumber]} - onTabClick={tab => { - setSelectedTabNumber(tabContents.indexOf(tab)) - }} - /> - </EuiForm> - </EuiForm> - {globalState.isLoading && <EuiProgress postion="fixed" size="l" color="accent" />} - </EuiPageContentBody> - </EuiPageContent> - {ShowAlert(open, handleClose, alertMessage, severity)} - {Warningmodal} - {mergeSourceModal} + <NewSourceForm + nameValue={nameValue} + setNameValue={setNameValue} + descriptionValue={descriptionValue} + setDescriptionValue={setDescriptionValue} + globalState={globalState} + onFilePickerChange={onFilePickerChange} + files={files} + renderFiles={renderFiles} + onSaveSource={onSaveSource} + metaUrfms={metaUrfms} + /> </> - ) -} - -export default Sources \ No newline at end of file + ), + }, + { + id: 'tab2', + name: 'Sources', + content: ( + <> + <SourcesForm + metaUrfmColumns={metaUrfmColumns} + sources={typeof sources === undefined ? [] : sources} + onTableChange={onTableChange} + tableref={tableref} + pagination={pagination} + sorting={sorting} + selection={selection} + mergeButton={mergeButton} + /> + </> + ), + }, + { + id: 'tab3', + name: 'Share Sources', + content: ( + <> + <ShareSources /> + </> + ), + }, + { + id: 'tab4', + name: 'Shared Sources', + content: ( + <> + <SharedSources /> + </> + ), + }, + ]; + + const mergeModalForm = ( + <EuiForm> + <EuiCallOut title="Proceed with caution!" color="warning" iconType="help"> + <p>Source / File Name is unique field for the In-Sylva Search App.</p> + </EuiCallOut>{' '} + <br /> + <EuiFormRow label="Source / File Name"> + <EuiFieldText + name="sourceName" + value={sourceName} + onChange={(e) => setSourceName(e.target.value)} + /> + </EuiFormRow> + <EuiFormRow label="Source Description"> + <EuiFieldText + name="sourceDescription" + value={sourceDescription} + onChange={(e) => setSourceDescription(e.target.value)} + /> + </EuiFormRow> + <EuiSpacer /> + </EuiForm> + ); + + let mergeSourceModal; + if (isMergeModalVisible) { + mergeSourceModal = ( + <EuiOverlayMask> + <EuiModal onClose={closeMergeSourceModal} initialFocus="[name=popswitch]"> + <EuiModalHeader> + <EuiModalHeaderTitle> + Merge and Send Selected Source Files + </EuiModalHeaderTitle> + </EuiModalHeader> + + <EuiModalBody>{mergeModalForm}</EuiModalBody> + + <EuiModalFooter> + <EuiButtonEmpty onClick={closeMergeSourceModal}>Cancel</EuiButtonEmpty> + + <EuiButton onClick={onMergeAndSendSourcesConfirmed} fill> + Save + </EuiButton> + </EuiModalFooter> + </EuiModal> + </EuiOverlayMask> + ); + } + + let Warningmodal; + if (isModalVisible) { + Warningmodal = ( + <EuiOverlayMask> + <EuiConfirmModal + title="Warning" + onCancel={closeModal} + onConfirm={onDeleteSourceConfirm} + cancelButtonText="Cancel" + confirmButtonText="Confirm" + buttonColor="danger" + defaultFocusedButton="confirm" + > + <p>Are you sure you want to delete this file?</p> + </EuiConfirmModal> + </EuiOverlayMask> + ); + } + + return ( + <> + <EuiPageContent> + <EuiPageContentHeader> + <EuiPageContentHeaderSection> + <EuiTitle> + <h6>Source Management</h6> + </EuiTitle> + </EuiPageContentHeaderSection> + </EuiPageContentHeader> + <EuiPageContentBody> + <EuiForm> + <EuiForm> + <EuiTabbedContent + tabs={tabContents} + selectedTab={tabContents[selectedTabNumber]} + onTabClick={(tab) => { + setSelectedTabNumber(tabContents.indexOf(tab)); + }} + /> + </EuiForm> + </EuiForm> + {globalState.isLoading && ( + <EuiProgress postion="fixed" size="l" color="accent" /> + )} + </EuiPageContentBody> + </EuiPageContent> + {ShowAlert(open, handleClose, alertMessage, severity)} + {Warningmodal} + {mergeSourceModal} + </> + ); +}; + +export default Sources; diff --git a/src/pages/sources/package.json b/src/pages/sources/package.json index 1c06aeb..873f45f 100644 --- a/src/pages/sources/package.json +++ b/src/pages/sources/package.json @@ -1,6 +1,6 @@ { - "name": "Sources", - "version": "1.0.0", - "private": true, - "main": "Sources.js" -} \ No newline at end of file + "name": "Sources", + "version": "1.0.0", + "private": true, + "main": "Sources.js" +} diff --git a/src/pages/sources/styles.js b/src/pages/sources/styles.js index d23f5a3..9e578a3 100644 --- a/src/pages/sources/styles.js +++ b/src/pages/sources/styles.js @@ -1,96 +1,96 @@ -import { makeStyles } from "@material-ui/styles"; +import { makeStyles } from '@material-ui/styles'; -export default makeStyles(theme => ({ - titleBold: { - fontWeight: 600, - }, - tab: { - color: theme.palette.primary.light + "CC", - }, - iconsContainer: { - boxShadow: theme.customShadows.widget, - overflow: "hidden", - paddingBottom: theme.spacing(2), - }, - text: { - marginBottom: theme.spacing(2), - }, - root: { - padding: theme.spacing(3, 2), - }, +export default makeStyles((theme) => ({ + titleBold: { + fontWeight: 600, + }, + tab: { + color: theme.palette.primary.light + 'CC', + }, + iconsContainer: { + boxShadow: theme.customShadows.widget, + overflow: 'hidden', + paddingBottom: theme.spacing(2), + }, + text: { + marginBottom: theme.spacing(2), + }, + root: { + padding: theme.spacing(3, 2), + }, - body: { - backgroundColor: "#f2ede8", - margin: 0, - padding: 0, - fontSize: "16px", - fontFamily: "sans-serif", - display: "flex", - height: "100vh" - }, - FileUploadForm: { - backgroundColor: "#fff", - padding: "2rem", - display: "grid", - gridGap: "1.6rem", - }, - ActionBar: { - textAlign: "right" - }, + body: { + backgroundColor: '#f2ede8', + margin: 0, + padding: 0, + fontSize: '16px', + fontFamily: 'sans-serif', + display: 'flex', + height: '100vh', + }, + FileUploadForm: { + backgroundColor: '#fff', + padding: '2rem', + display: 'grid', + gridGap: '1.6rem', + }, + ActionBar: { + textAlign: 'right', + }, - ActionBarButton: { - padding: ".4rem" - }, + ActionBarButton: { + padding: '.4rem', + }, - MessageBox: { - padding: "1.6rem", - backgroundColor: "#faf4e9", - borderTop: "3px solid #ffa600" - }, - input: { - display: 'none', - }, - dashedBorder: { - border: "1px dashed", - borderColor: theme.palette.primary.main, - padding: theme.spacing(2), - paddingTop: theme.spacing(4), - paddingBottom: theme.spacing(4), - marginTop: theme.spacing(1), - }, + MessageBox: { + padding: '1.6rem', + backgroundColor: '#faf4e9', + borderTop: '3px solid #ffa600', + }, + input: { + display: 'none', + }, + dashedBorder: { + border: '1px dashed', + borderColor: theme.palette.primary.main, + padding: theme.spacing(2), + paddingTop: theme.spacing(4), + paddingBottom: theme.spacing(4), + marginTop: theme.spacing(1), + }, - appBar: { - position: 'relative', - }, - layout: { - width: 'auto', - marginLeft: theme.spacing(2), - marginRight: theme.spacing(2), - [theme.breakpoints.up(600 + theme.spacing(2) * 2)]: { - width: 600, - marginLeft: 'auto', - marginRight: 'auto', - }, - }, - paper: { - marginTop: theme.spacing(3), - marginBottom: theme.spacing(3), - padding: theme.spacing(2), - [theme.breakpoints.up(600 + theme.spacing(3) * 2)]: { - marginTop: theme.spacing(6), - marginBottom: theme.spacing(6), - padding: theme.spacing(3), - }, - }, - stepper: { - padding: theme.spacing(3, 0, 5), - }, - buttons: { - display: 'flex', - justifyContent: 'flex-end', - }, - button: { - marginTop: theme.spacing(3), - marginLeft: theme.spacing(1), - }, -})); \ No newline at end of file + appBar: { + position: 'relative', + }, + layout: { + width: 'auto', + marginLeft: theme.spacing(2), + marginRight: theme.spacing(2), + [theme.breakpoints.up(600 + theme.spacing(2) * 2)]: { + width: 600, + marginLeft: 'auto', + marginRight: 'auto', + }, + }, + paper: { + marginTop: theme.spacing(3), + marginBottom: theme.spacing(3), + padding: theme.spacing(2), + [theme.breakpoints.up(600 + theme.spacing(3) * 2)]: { + marginTop: theme.spacing(6), + marginBottom: theme.spacing(6), + padding: theme.spacing(3), + }, + }, + stepper: { + padding: theme.spacing(3, 0, 5), + }, + buttons: { + display: 'flex', + justifyContent: 'flex-end', + }, + button: { + marginTop: theme.spacing(3), + marginLeft: theme.spacing(1), + }, +})); diff --git a/src/pages/user/User.js b/src/pages/user/User.js index 189717e..184cbb2 100644 --- a/src/pages/user/User.js +++ b/src/pages/user/User.js @@ -1,283 +1,318 @@ -import React, { - useState, - useCallback, - useEffect, - memo, - useRef -} from "react" +import React, { useState, useCallback, useEffect, memo, useRef } from 'react'; -import store from "../../store/index" -import { ShowAlert } from '../../components/Common' +import store from '../../store/index'; +import { ShowAlert } from '../../components/Common'; import { - EuiForm, - EuiPageContent, - EuiPageContentHeader, - EuiPageContentHeaderSection, - EuiTitle, - EuiPageContentBody, - EuiTabbedContent, - EuiFormRow, - EuiFieldText, - EuiFieldPassword, - EuiSelect, - EuiButton, - EuiBasicTable -} from '@elastic/eui' + EuiForm, + EuiPageContent, + EuiPageContentHeader, + EuiPageContentHeaderSection, + EuiTitle, + EuiPageContentBody, + EuiTabbedContent, + EuiFormRow, + EuiFieldText, + EuiFieldPassword, + EuiSelect, + EuiButton, + EuiBasicTable, +} from '@elastic/eui'; - -const NewUserForm = memo(({ globalState, usernameValue, setUsername, passwordValue, setPasswordValue, email, setEmail, dual, roles, selectedRole, setSelectedRole, onSaveUser }) => { +const NewUserForm = memo( + ({ + globalState, + usernameValue, + setUsername, + passwordValue, + setPasswordValue, + email, + setEmail, + dual, + roles, + selectedRole, + setSelectedRole, + onSaveUser, + }) => { return ( - <> - <EuiForm component="form"> - <EuiFormRow label="Username"> - <EuiFieldText value={usernameValue} onChange={e => setUsername(e.target.value)} /> - </EuiFormRow> - <EuiFormRow label="Password"> - <EuiFieldPassword - fullWidth - placeholder="Password" - type={'dual'} - value={passwordValue} - onChange={e => setPasswordValue(e.target.value)} - aria-label="Use aria labels when no actual label is in use" - /> - </EuiFormRow> - <EuiFormRow label="e-mail"> - <EuiFieldText value={email} onChange={e => setEmail(e.target.value)} /> - </EuiFormRow> - <EuiFormRow - label="Select Specific Role"> - <EuiSelect - options={roles} - value={selectedRole} - onChange={e => setSelectedRole(e.target.value)} - /> - </EuiFormRow> - <EuiFormRow label=""> - {<EuiButton fill onClick={onSaveUser} isLoading={globalState.isLoading}> - Save - </EuiButton>} - </EuiFormRow> - </EuiForm> - </> - ) -}) + <> + <EuiForm component="form"> + <EuiFormRow label="Username"> + <EuiFieldText + value={usernameValue} + onChange={(e) => setUsername(e.target.value)} + /> + </EuiFormRow> + <EuiFormRow label="Password"> + <EuiFieldPassword + fullWidth + placeholder="Password" + type={'dual'} + value={passwordValue} + onChange={(e) => setPasswordValue(e.target.value)} + aria-label="Use aria labels when no actual label is in use" + /> + </EuiFormRow> + <EuiFormRow label="e-mail"> + <EuiFieldText value={email} onChange={(e) => setEmail(e.target.value)} /> + </EuiFormRow> + <EuiFormRow label="Select Specific Role"> + <EuiSelect + options={roles} + value={selectedRole} + onChange={(e) => setSelectedRole(e.target.value)} + /> + </EuiFormRow> + <EuiFormRow label=""> + { + <EuiButton fill onClick={onSaveUser} isLoading={globalState.isLoading}> + Save + </EuiButton> + } + </EuiFormRow> + </EuiForm> + </> + ); + } +); -const UserList = memo(({ users, userColumns, onTableChange, tableRef, pagination, sorting }) => { +const UserList = memo( + ({ users, userColumns, onTableChange, tableRef, pagination, sorting }) => { return ( - <> - <EuiForm component="form"> - <EuiFormRow - label="Users" fullWidth> - <EuiBasicTable - itemId="id" - isSelectable={true} - items={users} - columns={userColumns} - onChange={onTableChange} - ref={tableRef} - pagination={pagination} - sorting={sorting} - // selection={selection} - /> - </EuiFormRow> - </EuiForm> - </> - ) -}) + <> + <EuiForm component="form"> + <EuiFormRow label="Users" fullWidth> + <EuiBasicTable + itemId="id" + isSelectable={true} + items={users} + columns={userColumns} + onChange={onTableChange} + ref={tableRef} + pagination={pagination} + sorting={sorting} + // selection={selection} + /> + </EuiFormRow> + </EuiForm> + </> + ); + } +); const User = (props) => { - const [globalState, globalActions] = store(); - const [selectedTabNumber, setSelectedTabNumber] = useState(0) - const [open, setOpen] = useState(false); - const [alertMessage, setAlertMessage] = useState(""); - const [severity, setSeverity] = useState("info") - const [dual,] = useState(true); - const [passwordValue, setPasswordValue] = useState('') - const [usernameValue, setUsername] = useState('') - const [email, setEmail] = useState('') - const [roles, setRoles] = useState([{ value: 0, text: "select a role" }]) - const [selectedRole, setSelectedRole] = useState() - const [users, setUsers] = useState([]) - const [sortDirection, setSortDirection] = useState('asc'); - const [sortField, setSortField] = useState('username'); - const tableRef = useRef(); - const [pageIndex, setPageIndex] = useState(0); - const [pageSize, setPageSize] = useState(5); - const [selectedUsers, setSetSelectedUsers] = useState([]) - - const loadRoles = useCallback(async () => { - const _roles = [] - const roles = await globalActions.user.findRole() - if (roles) { - for (const role of roles) { - _roles.push({ value: role.id, text: role.name }) - } - } - setRoles(prevRoles => ([...prevRoles, ..._roles])) - }, [globalActions.user]) - - const loadUsers = useCallback(async () => { - const users = await globalActions.user.usersWithGroupAndRole() - - if (users) { - console.log(users) - const userList = [] - const userNameList = [] - users.forEach(user => { - if (userNameList.includes(user.username)) { - userList[userNameList.indexOf(user.username)].groupname = `${userList[userNameList.indexOf(user.username)].groupname}, ${user.groupname}` - } else { - userNameList.push(user.username) - userList.push(user) - } - }) - setUsers(userList) - } - - }, [globalActions.user]) + const [globalState, globalActions] = store(); + const [selectedTabNumber, setSelectedTabNumber] = useState(0); + const [open, setOpen] = useState(false); + const [alertMessage, setAlertMessage] = useState(''); + const [severity, setSeverity] = useState('info'); + const [dual] = useState(true); + const [passwordValue, setPasswordValue] = useState(''); + const [usernameValue, setUsername] = useState(''); + const [email, setEmail] = useState(''); + const [roles, setRoles] = useState([{ value: 0, text: 'select a role' }]); + const [selectedRole, setSelectedRole] = useState(); + const [users, setUsers] = useState([]); + const [sortDirection, setSortDirection] = useState('asc'); + const [sortField, setSortField] = useState('username'); + const tableRef = useRef(); + const [pageIndex, setPageIndex] = useState(0); + const [pageSize, setPageSize] = useState(5); + const [selectedUsers, setSetSelectedUsers] = useState([]); - useEffect(() => { - // clean up controller - let isSubscribed = true; - if (isSubscribed) { - loadRoles() - loadUsers() - } - // cancel subscription to useEffect - return () => (isSubscribed = false) - }, [loadRoles, loadUsers]) + const loadRoles = useCallback(async () => { + const _roles = []; + const roles = await globalActions.user.findRole(); + if (roles) { + for (const role of roles) { + _roles.push({ value: role.id, text: role.name }); + } + } + setRoles((prevRoles) => [...prevRoles, ..._roles]); + }, [globalActions.user]); - const onSaveUser = async () => { - if (usernameValue && passwordValue && email && selectedRole) { - await globalActions.user.createUser(usernameValue, email, passwordValue, selectedRole) + const loadUsers = useCallback(async () => { + const users = await globalActions.user.usersWithGroupAndRole(); - setOpen(true) - setAlertMessage("User is created succesfully!") - setSeverity("success") - loadUsers() + if (users) { + console.log(users); + const userList = []; + const userNameList = []; + users.forEach((user) => { + if (userNameList.includes(user.username)) { + userList[userNameList.indexOf(user.username)].groupname = + `${userList[userNameList.indexOf(user.username)].groupname}, ${user.groupname}`; + } else { + userNameList.push(user.username); + userList.push(user); } + }); + setUsers(userList); } + }, [globalActions.user]); - const onDeleteUser = async (user) => { + useEffect(() => { + // clean up controller + let isSubscribed = true; + if (isSubscribed) { + loadRoles(); + loadUsers(); + } + // cancel subscription to useEffect + return () => (isSubscribed = false); + }, [loadRoles, loadUsers]); - if (user) { - await globalActions.user.deleteUser(user.kc_id) + const onSaveUser = async () => { + if (usernameValue && passwordValue && email && selectedRole) { + await globalActions.user.createUser( + usernameValue, + email, + passwordValue, + selectedRole + ); - setOpen(true) - setAlertMessage("User is deleted succesfully!") - setSeverity("success") - await loadUsers() - } + setOpen(true); + setAlertMessage('User is created succesfully!'); + setSeverity('success'); + loadUsers(); } + }; - const userActions = [ - { - name: 'Delete', - description: 'Delete this user', - icon: 'trash', - type: 'icon', - color: 'danger', - onClick: onDeleteUser, - }, - ] - - const onTableChange = ({ page = {}, sort = {} }) => { - const { index: pageIndex, size: pageSize } = page; + const onDeleteUser = async (user) => { + if (user) { + await globalActions.user.deleteUser(user.kc_id); - const { field: sortField, direction: sortDirection } = sort; + setOpen(true); + setAlertMessage('User is deleted succesfully!'); + setSeverity('success'); + await loadUsers(); + } + }; - setPageIndex(pageIndex); - setPageSize(pageSize); - setSortField(sortField); - setSortDirection(sortDirection); - }; - const totalItemCount = (typeof USERS === typeof undefined ? 0 : users.length) + const userActions = [ + { + name: 'Delete', + description: 'Delete this user', + icon: 'trash', + type: 'icon', + color: 'danger', + onClick: onDeleteUser, + }, + ]; - const onSelectionChange = (selectedItems) => { - setSetSelectedUsers(selectedItems); - }; + const onTableChange = ({ page = {}, sort = {} }) => { + const { index: pageIndex, size: pageSize } = page; - const pagination = { - pageIndex: pageIndex, - pageSize: pageSize, - totalItemCount: totalItemCount, - pageSizeOptions: [3, 5, 8], - }; + const { field: sortField, direction: sortDirection } = sort; - const sorting = { - sort: { - field: sortField, - direction: sortDirection, - }, - }; + setPageIndex(pageIndex); + setPageSize(pageSize); + setSortField(sortField); + setSortDirection(sortDirection); + }; + const totalItemCount = typeof USERS === typeof undefined ? 0 : users.length; - const userColumns = [ - { field: 'username', name: 'Username' }, - { field: 'email', name: 'Email' }, - { field: 'groupname', name: 'Group' }, - { field: 'rolename', name: 'Role' }, - { field: 'roledescription', name: 'Role description' }, - { name: 'Actions', actions: userActions } - ] + const onSelectionChange = (selectedItems) => { + setSetSelectedUsers(selectedItems); + }; - const tabContents = [ + const pagination = { + pageIndex: pageIndex, + pageSize: pageSize, + totalItemCount: totalItemCount, + pageSizeOptions: [3, 5, 8], + }; - { - id: 'tab1', - name: 'New User', - content: ( - <> - <br /> - <NewUserForm globalState={globalState} dual={dual} usernameValue={usernameValue} setUsername={setUsername} passwordValue={passwordValue} setPasswordValue={setPasswordValue} email={email} setEmail={setEmail} onSaveUser={onSaveUser} selectedRole={selectedRole} setSelectedRole={setSelectedRole} roles={roles} /> - </> - ) - }, { - id: 'tab2', - name: 'User List', - content: ( - <> - <br /> - <UserList users={users} userColumns={userColumns} onTableChange={onTableChange} tableRef={tableRef} pagination={pagination} sorting={sorting} /> - </> - ) - }, + const sorting = { + sort: { + field: sortField, + direction: sortDirection, + }, + }; - ] + const userColumns = [ + { field: 'username', name: 'Username' }, + { field: 'email', name: 'Email' }, + { field: 'groupname', name: 'Group' }, + { field: 'rolename', name: 'Role' }, + { field: 'roledescription', name: 'Role description' }, + { name: 'Actions', actions: userActions }, + ]; - const handleClose = (event, reason) => { - if (reason === 'clickaway') { - return; - } - setOpen(false); - } - return ( + const tabContents = [ + { + id: 'tab1', + name: 'New User', + content: ( <> - <EuiPageContent> - <EuiPageContentHeader> - <EuiPageContentHeaderSection> - <EuiTitle> - <h6>Users</h6> - </EuiTitle> - </EuiPageContentHeaderSection> - </EuiPageContentHeader> - <EuiPageContentBody> - <EuiForm> - <EuiTabbedContent - tabs={tabContents} - selectedTab={tabContents[selectedTabNumber]} - onTabClick={tab => { - setSelectedTabNumber(tabContents.indexOf(tab)) - }} - /> - </EuiForm> - </EuiPageContentBody> - </EuiPageContent> - {ShowAlert(open, handleClose, alertMessage, severity)} + <br /> + <NewUserForm + globalState={globalState} + dual={dual} + usernameValue={usernameValue} + setUsername={setUsername} + passwordValue={passwordValue} + setPasswordValue={setPasswordValue} + email={email} + setEmail={setEmail} + onSaveUser={onSaveUser} + selectedRole={selectedRole} + setSelectedRole={setSelectedRole} + roles={roles} + /> </> - ) -} + ), + }, + { + id: 'tab2', + name: 'User List', + content: ( + <> + <br /> + <UserList + users={users} + userColumns={userColumns} + onTableChange={onTableChange} + tableRef={tableRef} + pagination={pagination} + sorting={sorting} + /> + </> + ), + }, + ]; + const handleClose = (event, reason) => { + if (reason === 'clickaway') { + return; + } + setOpen(false); + }; + return ( + <> + <EuiPageContent> + <EuiPageContentHeader> + <EuiPageContentHeaderSection> + <EuiTitle> + <h6>Users</h6> + </EuiTitle> + </EuiPageContentHeaderSection> + </EuiPageContentHeader> + <EuiPageContentBody> + <EuiForm> + <EuiTabbedContent + tabs={tabContents} + selectedTab={tabContents[selectedTabNumber]} + onTabClick={(tab) => { + setSelectedTabNumber(tabContents.indexOf(tab)); + }} + /> + </EuiForm> + </EuiPageContentBody> + </EuiPageContent> + {ShowAlert(open, handleClose, alertMessage, severity)} + </> + ); +}; -export default User \ No newline at end of file +export default User; diff --git a/src/pages/user/package.json b/src/pages/user/package.json index 5d47621..b261e71 100644 --- a/src/pages/user/package.json +++ b/src/pages/user/package.json @@ -1,6 +1,6 @@ { - "name": "User", - "version": "1.0.0", - "private": true, - "main": "User.js" -} \ No newline at end of file + "name": "User", + "version": "1.0.0", + "private": true, + "main": "User.js" +} diff --git a/src/pages/user/styles.js b/src/pages/user/styles.js index 7733076..366d14e 100644 --- a/src/pages/user/styles.js +++ b/src/pages/user/styles.js @@ -1,29 +1,29 @@ -import { makeStyles } from "@material-ui/styles"; +import { makeStyles } from '@material-ui/styles'; -export default makeStyles(theme => ({ - titleBold: { - fontWeight: 600, - }, - tab: { - color: theme.palette.primary.light + "CC", - }, - iconsContainer: { - boxShadow: theme.customShadows.widget, - overflow: "hidden", - paddingBottom: theme.spacing(2), - }, - dashedBorder: { - border: "1px dashed", - borderColor: theme.palette.primary.main, - padding: theme.spacing(2), - paddingTop: theme.spacing(4), - paddingBottom: theme.spacing(4), - marginTop: theme.spacing(1), - }, - text: { - marginBottom: theme.spacing(2), - }, - root: { - padding: theme.spacing(3, 2), - }, -})); \ No newline at end of file +export default makeStyles((theme) => ({ + titleBold: { + fontWeight: 600, + }, + tab: { + color: theme.palette.primary.light + 'CC', + }, + iconsContainer: { + boxShadow: theme.customShadows.widget, + overflow: 'hidden', + paddingBottom: theme.spacing(2), + }, + dashedBorder: { + border: '1px dashed', + borderColor: theme.palette.primary.main, + padding: theme.spacing(2), + paddingTop: theme.spacing(4), + paddingBottom: theme.spacing(4), + marginTop: theme.spacing(1), + }, + text: { + marginBottom: theme.spacing(2), + }, + root: { + padding: theme.spacing(3, 2), + }, +})); diff --git a/src/store/CustomConnector.js b/src/store/CustomConnector.js index 02b65c7..28b24ca 100644 --- a/src/store/CustomConnector.js +++ b/src/store/CustomConnector.js @@ -1,52 +1,53 @@ -import React, { Component } from "react"; +import React, { Component } from 'react'; export const CustomConnectorContext = React.createContext(); export class CustomConnectorProvider extends Component { - - render() { - return <CustomConnectorContext.Provider value={this.props.dataStore}> - {this.props.children} - </CustomConnectorContext.Provider> - } + render() { + return ( + <CustomConnectorContext.Provider value={this.props.dataStore}> + {this.props.children} + </CustomConnectorContext.Provider> + ); + } } export class CustomConnector extends React.Component { - static contextType = CustomConnectorContext; - - constructor(props, context) { - super(props, context); - this.state = this.selectData(); - this.functionProps = Object.entries(this.props.dispatchers) - .map(([k, v]) => [k, (...args) => this.context.dispatch(v(...args))]) - .reduce((result, [k, v]) => ({ ...result, [k]: v }), {}) - } - - render() { - return React.Children.map(this.props.children, c => - React.cloneElement(c, { ...this.state, ...this.functionProps })) - } - - selectData() { - let storeState = this.context.getState(); - return Object.entries(this.props.selectors).map(([k, v]) => - [k, v(storeState)]) - .reduce((result, [k, v]) => ({ ...result, [k]: v }), {}); - } - - handleDataStoreChange() { - let newData = this.selectData(); - Object.keys(this.props.selectors) - .filter(key => this.state[key] !== newData[key]) - .forEach(key => this.setState({ [key]: newData[key] })); - } - - componentDidMount() { - this.unsubscriber = - this.context.subscribe(() => this.handleDataStoreChange()); - } - - componentWillUnmount() { - this.unsubscriber(); - } + static contextType = CustomConnectorContext; + + constructor(props, context) { + super(props, context); + this.state = this.selectData(); + this.functionProps = Object.entries(this.props.dispatchers) + .map(([k, v]) => [k, (...args) => this.context.dispatch(v(...args))]) + .reduce((result, [k, v]) => ({ ...result, [k]: v }), {}); + } + + render() { + return React.Children.map(this.props.children, (c) => + React.cloneElement(c, { ...this.state, ...this.functionProps }) + ); + } + + selectData() { + let storeState = this.context.getState(); + return Object.entries(this.props.selectors) + .map(([k, v]) => [k, v(storeState)]) + .reduce((result, [k, v]) => ({ ...result, [k]: v }), {}); + } + + handleDataStoreChange() { + let newData = this.selectData(); + Object.keys(this.props.selectors) + .filter((key) => this.state[key] !== newData[key]) + .forEach((key) => this.setState({ [key]: newData[key] })); + } + + componentDidMount() { + this.unsubscriber = this.context.subscribe(() => this.handleDataStoreChange()); + } + + componentWillUnmount() { + this.unsubscriber(); + } } diff --git a/src/store/asyncEnhancer.js b/src/store/asyncEnhancer.js index 79668fd..7f9e47e 100644 --- a/src/store/asyncEnhancer.js +++ b/src/store/asyncEnhancer.js @@ -1,12 +1,16 @@ -export const asyncEnhancer = delay => createStoreFunction => (...args) => { +export const asyncEnhancer = + (delay) => + (createStoreFunction) => + (...args) => { const store = createStoreFunction(...args); return { - ...store, - dispatchAsync: (action) => new Promise((resolve, reject) => { - setTimeout(() => { - store.dispatch(action); - resolve(); - }, delay); - }) + ...store, + dispatchAsync: (action) => + new Promise((resolve, reject) => { + setTimeout(() => { + store.dispatch(action); + resolve(); + }, delay); + }), }; -} + }; diff --git a/src/store/index.js b/src/store/index.js index a4db4da..905e71e 100644 --- a/src/store/index.js +++ b/src/store/index.js @@ -1,18 +1,17 @@ -import React from "react"; +import React from 'react'; import useStore from './useStore'; -import * as actions from "../actions"; +import * as actions from '../actions'; const initialState = { - isLoading: false, - status: "INITIAL", - users: [], - roles: [], - role: {}, - user: {}, - allocatedRoles: [], - error: false, - resources: [] -} + isLoading: false, + status: 'INITIAL', + users: [], + roles: [], + role: {}, + user: {}, + allocatedRoles: [], + error: false, + resources: [], +}; const store = useStore(React, initialState, actions); export default store; - diff --git a/src/store/useStore.js b/src/store/useStore.js index 8438e32..bb16c7e 100644 --- a/src/store/useStore.js +++ b/src/store/useStore.js @@ -1,63 +1,60 @@ -import { useSessionStorage } from '@in-sylva/react-use-storage' - +import { useSessionStorage } from '@in-sylva/react-use-storage'; function setState(store, newState, afterUpdateCallback) { - store.state = { ...store.state, ...newState }; - store.listeners.forEach((listener) => { - listener.run(store.state); - }); - afterUpdateCallback && afterUpdateCallback(); + store.state = { ...store.state, ...newState }; + store.listeners.forEach((listener) => { + listener.run(store.state); + }); + afterUpdateCallback && afterUpdateCallback(); } function useCustom(store, React, mapState, mapActions) { - const [, originalHook] = useSessionStorage("portal",Object.create(null)); - const state = mapState ? mapState(store.state) : store.state; - const actions = React.useMemo( - () => (mapActions ? mapActions(store.actions) : store.actions), - [mapActions, store.actions] - ); + const [, originalHook] = useSessionStorage('portal', Object.create(null)); + const state = mapState ? mapState(store.state) : store.state; + const actions = React.useMemo( + () => (mapActions ? mapActions(store.actions) : store.actions), + [mapActions, store.actions] + ); - React.useEffect(() => { - const newListener = { oldState: {} }; - newListener.run = mapState - ? newState => { - const mappedState = mapState(newState); - if (mappedState !== newListener.oldState) { - newListener.oldState = mappedState; - originalHook(mappedState); - } - } - : originalHook; - store.listeners.push(newListener); - newListener.run(store.state); - return () => { - store.listeners = store.listeners.filter( - listener => listener !== newListener - ); - }; - }, []); // eslint-disable-line - return [state, actions]; + React.useEffect(() => { + const newListener = { oldState: {} }; + newListener.run = mapState + ? (newState) => { + const mappedState = mapState(newState); + if (mappedState !== newListener.oldState) { + newListener.oldState = mappedState; + originalHook(mappedState); + } + } + : originalHook; + store.listeners.push(newListener); + newListener.run(store.state); + return () => { + store.listeners = store.listeners.filter((listener) => listener !== newListener); + }; + }, []); // eslint-disable-line + return [state, actions]; } function associateActions(store, actions) { - const associatedActions = {}; - Object.keys(actions).forEach(key => { - if (typeof actions[key] === "function") { - associatedActions[key] = actions[key].bind(null, store); - } - if (typeof actions[key] === "object") { - associatedActions[key] = associateActions(store, actions[key]); - } - }); - return associatedActions; + const associatedActions = {}; + Object.keys(actions).forEach((key) => { + if (typeof actions[key] === 'function') { + associatedActions[key] = actions[key].bind(null, store); + } + if (typeof actions[key] === 'object') { + associatedActions[key] = associateActions(store, actions[key]); + } + }); + return associatedActions; } const useStore = (React, initialState, actions, initializer) => { - const store = { state: initialState, listeners: [] }; - store.setState = setState.bind(null, store); - store.actions = associateActions(store, actions); - if (initializer) initializer(store); - return useCustom.bind(null, store, React); + const store = { state: initialState, listeners: [] }; + store.setState = setState.bind(null, store); + store.actions = associateActions(store, actions); + if (initializer) initializer(store); + return useCustom.bind(null, store, React); }; export default useStore; diff --git a/src/themes/default.js b/src/themes/default.js index 9f77b83..2e498db 100644 --- a/src/themes/default.js +++ b/src/themes/default.js @@ -1,10 +1,10 @@ -import tinycolor from "tinycolor2"; +import tinycolor from 'tinycolor2'; -const primary = "#689f38"; -const secondary = "#FF5C93"; -const warning = "#FFC260"; -const success = "#3CD4A0"; -const info = "#9013FE"; +const primary = '#689f38'; +const secondary = '#FF5C93'; +const warning = '#FFC260'; +const success = '#3CD4A0'; +const info = '#9013FE'; const lightenRate = 7.5; const darkenRate = 15; @@ -13,103 +13,82 @@ export default { palette: { primary: { main: primary, - light: tinycolor(primary) - .lighten(lightenRate) - .toHexString(), - dark: tinycolor(primary) - .darken(darkenRate) - .toHexString(), + light: tinycolor(primary).lighten(lightenRate).toHexString(), + dark: tinycolor(primary).darken(darkenRate).toHexString(), }, secondary: { main: secondary, - light: tinycolor(secondary) - .lighten(lightenRate) - .toHexString(), - dark: tinycolor(secondary) - .darken(darkenRate) - .toHexString(), - contrastText: "#FFFFFF", + light: tinycolor(secondary).lighten(lightenRate).toHexString(), + dark: tinycolor(secondary).darken(darkenRate).toHexString(), + contrastText: '#FFFFFF', }, warning: { main: warning, - light: tinycolor(warning) - .lighten(lightenRate) - .toHexString(), - dark: tinycolor(warning) - .darken(darkenRate) - .toHexString(), + light: tinycolor(warning).lighten(lightenRate).toHexString(), + dark: tinycolor(warning).darken(darkenRate).toHexString(), }, success: { main: success, - light: tinycolor(success) - .lighten(lightenRate) - .toHexString(), - dark: tinycolor(success) - .darken(darkenRate) - .toHexString(), + light: tinycolor(success).lighten(lightenRate).toHexString(), + dark: tinycolor(success).darken(darkenRate).toHexString(), }, info: { main: info, - light: tinycolor(info) - .lighten(lightenRate) - .toHexString(), - dark: tinycolor(info) - .darken(darkenRate) - .toHexString(), + light: tinycolor(info).lighten(lightenRate).toHexString(), + dark: tinycolor(info).darken(darkenRate).toHexString(), }, text: { - primary: "#4A4A4A", - secondary: "#6E6E6E", - hint: "#B9B9B9", + primary: '#4A4A4A', + secondary: '#6E6E6E', + hint: '#B9B9B9', }, background: { - default: "#F6F7FF", - light: "#F3F5FF", + default: '#F6F7FF', + light: '#F3F5FF', }, }, customShadows: { - widget: - "0px 3px 11px 0px #E8EAFC, 0 3px 3px -2px #B2B2B21A, 0 1px 8px 0 #9A9A9A1A", + widget: '0px 3px 11px 0px #E8EAFC, 0 3px 3px -2px #B2B2B21A, 0 1px 8px 0 #9A9A9A1A', widgetDark: - "0px 3px 18px 0px #4558A3B3, 0 3px 3px -2px #B2B2B21A, 0 1px 8px 0 #9A9A9A1A", + '0px 3px 18px 0px #4558A3B3, 0 3px 3px -2px #B2B2B21A, 0 1px 8px 0 #9A9A9A1A', widgetWide: - "0px 12px 33px 0px #E8EAFC, 0 3px 3px -2px #B2B2B21A, 0 1px 8px 0 #9A9A9A1A", + '0px 12px 33px 0px #E8EAFC, 0 3px 3px -2px #B2B2B21A, 0 1px 8px 0 #9A9A9A1A', }, overrides: { MuiBackdrop: { root: { - backgroundColor: "#4A4A4A1A", + backgroundColor: '#4A4A4A1A', }, }, MuiMenu: { paper: { boxShadow: - "0px 3px 11px 0px #E8EAFC, 0 3px 3px -2px #B2B2B21A, 0 1px 8px 0 #9A9A9A1A", + '0px 3px 11px 0px #E8EAFC, 0 3px 3px -2px #B2B2B21A, 0 1px 8px 0 #9A9A9A1A', }, }, MuiSelect: { icon: { - color: "#B9B9B9", + color: '#B9B9B9', }, }, MuiListItem: { root: { - "&$selected": { - backgroundColor: "#F3F5FF !important", - "&:focus": { - backgroundColor: "#F3F5FF", + '&$selected': { + backgroundColor: '#F3F5FF !important', + '&:focus': { + backgroundColor: '#F3F5FF', }, }, }, button: { - "&:hover, &:focus": { - backgroundColor: "#F3F5FF", + '&:hover, &:focus': { + backgroundColor: '#F3F5FF', }, }, }, MuiTouchRipple: { child: { - backgroundColor: "white", + backgroundColor: 'white', }, }, MuiTableRow: { @@ -119,13 +98,13 @@ export default { }, MuiTableCell: { root: { - borderBottom: "1px solid rgba(224, 224, 224, .5)", + borderBottom: '1px solid rgba(224, 224, 224, .5)', }, head: { - fontSize: "0.95rem", + fontSize: '0.95rem', }, body: { - fontSize: "0.95rem", + fontSize: '0.95rem', }, }, }, diff --git a/src/themes/index.js b/src/themes/index.js index 73236d2..fd3a2f3 100644 --- a/src/themes/index.js +++ b/src/themes/index.js @@ -1,26 +1,26 @@ -import defaultTheme from "./default"; +import defaultTheme from './default'; -import { createMuiTheme } from "@material-ui/core"; +import { createMuiTheme } from '@material-ui/core'; const overrides = { typography: { h1: { - fontSize: "3rem", + fontSize: '3rem', }, h2: { - fontSize: "2rem", + fontSize: '2rem', }, h3: { - fontSize: "1.64rem", + fontSize: '1.64rem', }, h4: { - fontSize: "1.5rem", + fontSize: '1.5rem', }, h5: { - fontSize: "1.285rem", + fontSize: '1.285rem', }, h6: { - fontSize: "1.142rem", + fontSize: '1.142rem', }, }, }; diff --git a/src/utils.js b/src/utils.js index 0ed0a21..678670d 100644 --- a/src/utils.js +++ b/src/utils.js @@ -1,40 +1,44 @@ export const getGatekeeperBaseUrl = () => { - return process.env.REACT_APP_IN_SYLVA_GATEKEEPER_PORT ? `${process.env.REACT_APP_IN_SYLVA_GATEKEEPER_HOST}:${process.env.REACT_APP_IN_SYLVA_GATEKEEPER_PORT}` : `${window._env_.REACT_APP_IN_SYLVA_GATEKEEPER_HOST}` -} + return process.env.REACT_APP_IN_SYLVA_GATEKEEPER_PORT + ? `${process.env.REACT_APP_IN_SYLVA_GATEKEEPER_HOST}:${process.env.REACT_APP_IN_SYLVA_GATEKEEPER_PORT}` + : `${window._env_.REACT_APP_IN_SYLVA_GATEKEEPER_HOST}`; +}; export const getLoginUrl = () => { - return process.env.REACT_APP_IN_SYLVA_LOGIN_PORT ? `${process.env.REACT_APP_IN_SYLVA_LOGIN_HOST}:${process.env.REACT_APP_IN_SYLVA_LOGIN_PORT}` : `${window._env_.REACT_APP_IN_SYLVA_LOGIN_HOST}`; -} + return process.env.REACT_APP_IN_SYLVA_LOGIN_PORT + ? `${process.env.REACT_APP_IN_SYLVA_LOGIN_HOST}:${process.env.REACT_APP_IN_SYLVA_LOGIN_PORT}` + : `${window._env_.REACT_APP_IN_SYLVA_LOGIN_HOST}`; +}; export const getUrlParams = () => { - let lets = {}; - window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) { - lets[key] = value; - }); - return lets; -} + let lets = {}; + window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) { + lets[key] = value; + }); + return lets; +}; export const getUrlParam = (parameter, defaultValue) => { - let urlParameter = defaultValue; - if (window.location.href.indexOf(parameter) > -1) { - urlParameter = getUrlParams()[parameter]; - } - return urlParameter; -} + let urlParameter = defaultValue; + if (window.location.href.indexOf(parameter) > -1) { + urlParameter = getUrlParams()[parameter]; + } + return urlParameter; +}; export const changeNameToLabel = (object) => { - object.label = object.name - delete object.name - return object -} + object.label = object.name; + delete object.name; + return object; +}; export const redirect = (url, condition = true) => { - if (condition) { - window.location.replace(url) - } -} + if (condition) { + window.location.replace(url); + } +}; export const tokenTimedOut = (validityDurationInMin) => { - const timeSinceLastRefresh = Date.now() - sessionStorage.getItem("token_refresh_time") - return timeSinceLastRefresh > (validityDurationInMin * 60000); -} + const timeSinceLastRefresh = Date.now() - sessionStorage.getItem('token_refresh_time'); + return timeSinceLastRefresh > validityDurationInMin * 60000; +}; -- GitLab From 9e7a457abbc4016535a9a1ee200582dbdbcfbb08 Mon Sep 17 00:00:00 2001 From: rbisson <remi.bisson@inrae.fr> Date: Mon, 22 Apr 2024 17:57:09 +0200 Subject: [PATCH 04/19] [src]: removed console.log --- src/actions/user.js | 12 +-- src/components/Header/HeaderView.js | 1 - src/context/InSylvaGatekeeperClient.js | 144 ++++++++----------------- src/context/UserContext.js | 2 +- src/pages/group/Group.js | 1 - src/pages/policy/Policy.js | 1 - src/pages/requests/Requests.js | 15 +-- src/pages/sources/Sources.js | 1 - src/pages/user/User.js | 3 - 9 files changed, 52 insertions(+), 128 deletions(-) diff --git a/src/actions/user.js b/src/actions/user.js index 2a21e8f..2930d86 100644 --- a/src/actions/user.js +++ b/src/actions/user.js @@ -131,8 +131,7 @@ export async function fetchRequests(store, request = igClient) { return requests; } } catch (error) { - console.log('error fetch requests'); - console.log(error); + console.error(error); } } @@ -145,8 +144,7 @@ export async function fetchPendingRequests(store, request = igClient) { return requests; } } catch (error) { - console.log('error fetch pending requests'); - console.log(error); + console.error(error); } } @@ -156,8 +154,7 @@ export async function processUserRequest(store, requestId, request = igClient) { try { await request.processUserRequest(requestId); } catch (error) { - console.log('error process user request'); - console.log(error); + console.error(error); } } @@ -167,8 +164,7 @@ export async function deleteUserRequest(store, requestId, request = igClient) { try { await request.deleteUserRequest(requestId); } catch (error) { - console.log('error delete user request'); - console.log(error); + console.error(error); } } diff --git a/src/components/Header/HeaderView.js b/src/components/Header/HeaderView.js index b137bc8..2fda854 100644 --- a/src/components/Header/HeaderView.js +++ b/src/components/Header/HeaderView.js @@ -20,7 +20,6 @@ import { } from '@material-ui/icons'; import { fade } from '@material-ui/core/styles/colorManipulator'; import classNames from 'classnames'; - import { Badge, Typography } from '../Wrappers'; import Notification from '../Notification'; import UserAvatar from '../UserAvatar'; diff --git a/src/context/InSylvaGatekeeperClient.js b/src/context/InSylvaGatekeeperClient.js index 2601b71..2d7c77e 100644 --- a/src/context/InSylvaGatekeeperClient.js +++ b/src/context/InSylvaGatekeeperClient.js @@ -12,108 +12,90 @@ class InSylvaGatekeeperClient { body: JSON.stringify(requestContent), mode: 'cors', }); - - const responseContent = await response.json(); - - return responseContent; + return await response.json(); } async createUser({ username, email, password, roleId }) { const path = `/user`; - const user = await this.post('POST', `${path}`, { + return await this.post('POST', `${path}`, { username, email, password, roleId, }); - - return user; } async kcId({ email }) { const path = `/user/kcid`; - const kcId = await this.post('POST', `${path}`, { + return await this.post('POST', `${path}`, { email, }); - - return kcId; } async updateUser({ id, firstName, lastName }) { const path = `/user/update`; - const user = await this.post('PUT', `${path}`, { + return await this.post('PUT', `${path}`, { id, firstName, lastName, }); - - return user; } async findUser() { const path = `/user/find`; - const users = await this.post('GET', `${path}`); - return users; + return await this.post('GET', `${path}`); } async findOneUser(id) { const path = `/user/findOne`; - const user = await this.post('POST', `${path}`, { + return await this.post('POST', `${path}`, { id, }); - return user; } async deleteUser({ id }) { const path = `/user/delete`; - const user = await this.post('DELETE', `${path}`, { + return await this.post('DELETE', `${path}`, { userId: id, }); - return user; } async getRequests() { const path = `/user/list-requests`; - const requests = await this.post('GET', `${path}`); - return requests; + return await this.post('GET', `${path}`); } async getPendingRequests() { const path = `/user/list-pending-requests`; - const pendingRequests = await this.post('GET', `${path}`); - return pendingRequests; + return await this.post('GET', `${path}`); } async processUserRequest(id) { const path = `/user/process-request`; - const userRequests = await this.post('POST', `${path}`, { + return await this.post('POST', `${path}`, { id, }); - return userRequests; } async deleteUserRequest(id) { - console.log('client'); const path = `/user/delete-request`; - const userRequests = await this.post('DELETE', `${path}`, { + await this.post('DELETE', `${path}`, { id, }); } async createRole({ name, description }) { const path = `/role`; - const role = await this.post('POST', `${path}`, { + return await this.post('POST', `${path}`, { name, description, }); - return role; } async findRole() { const path = `/role/find`; - const roles = await this.post('GET', `${path}`); - return roles; + return await this.post('GET', `${path}`); } async allocateRoles({ roles, users }) { @@ -135,221 +117,187 @@ class InSylvaGatekeeperClient { async allocateRolesToUser({ userId, roleId }) { const path = `/allocate-role-to-user`; - const result = await this.post('POST', `${path}`, { + return await this.post('POST', `${path}`, { kc_id: userId, role_id: roleId, }); - - return result; } async allocatedRoles(kc_id) { const path = `/allocatedRoles`; - const allocatedRoles = await this.post('POST', `${path}`, { + return await this.post('POST', `${path}`, { kc_id, }); - return allocatedRoles; } - async createPolicy({ name, sourceId, kcId }) { + async createPolicy({ name, kcId }) { const path = `/policy/add`; - const policy = await this.post('POST', `${path}`, { + return await this.post('POST', `${path}`, { name, - // sourceId, kcId, }); - return policy; } async createPolicyField({ policyId, stdFieldId }) { const path = `/policyField/add`; - const policyField = await this.post('POST', `${path}`, { + return await this.post('POST', `${path}`, { policyId, stdFieldId, }); - return policyField; } async updatePolicy({ id, name, sourceId, isDeafault }) { const path = `/policy/update`; - const policy = await this.post('PUT', `${path}`, { + return await this.post('PUT', `${path}`, { id, name, sourceId, isDeafault, }); - return policy; } async updatePolicyField({ id, policyId, stdFieldId }) { const path = `/policyField/update`; - const policyField = this.post('PUT', `${path}`, { + return this.post('PUT', `${path}`, { id, policyId, stdFieldId, }); - return policyField; } async deletePolicyField({ id }) { const path = `/policyField/delete`; - const policyField = await this.post('DELETE', `${path}`, { + return await this.post('DELETE', `${path}`, { id, }); - return policyField; } async deletePolicy({ id }) { const path = `/policy/delete`; - const policy = await this.post('DELETE', `${path}`, { + return await this.post('DELETE', `${path}`, { id, }); - return policy; } async getPolicies() { const path = `/policy/list`; - const policies = await this.post('GET', `${path}`); - return policies; + return await this.post('GET', `${path}`); } async getPoliciesByUser(kcId) { const path = `/policy/list-by-user`; - const group = await this.post('POST', `${path}`, { kcId }); - return group; + return await this.post('POST', `${path}`, { kcId }); } async getPoliciesWithSourcesByUser(kcId) { const path = `/policy/policies-with-sources-by-user`; - const group = await this.post('POST', `${path}`, { kcId }); - return group; + return await this.post('POST', `${path}`, { kcId }); } async getPoliciesWithSources() { const path = `/policy/policies-with-sources`; - const policiesWithSource = await this.post('GET', `${path}`); - return policiesWithSource; + return await this.post('GET', `${path}`); } async getPolicyFields() { const path = `/policyField/list`; - const policyFields = await this.post('GET', `${path}`, {}); - return policyFields; + return await this.post('GET', `${path}`, {}); } async getGroups() { const path = `/user/groups`; - const groups = await this.post('POST', `${path}`, {}); - return groups; + return await this.post('POST', `${path}`, {}); } async getGroupPolicies() { const path = `/user/group-policies`; - const groupsPolicies = await this.post('GET', `${path}`, {}); - return groupsPolicies; + return await this.post('GET', `${path}`, {}); } async getGroupUsers({ groupId }) { const path = `/user/group-users`; - const groupUsers = await this.post('POST', `${path}`, { groupId }); - return groupUsers; + return await this.post('POST', `${path}`, { groupId }); } async createGroup({ name, description, kcId }) { const path = `/user/add-group`; - const group = await this.post('POST', `${path}`, { name, description, kcId }); - return group; + return await this.post('POST', `${path}`, { name, description, kcId }); } async createGroupPolicy({ groupId, policyId }) { const path = `/user/add-group-policy`; - const groupPolicy = await this.post('POST', `${path}`, { groupId, policyId }); - return groupPolicy; + return await this.post('POST', `${path}`, { groupId, policyId }); } async createGroupUser({ groupId, kcId }) { const path = `/user/add-group-user`; - const groupUser = await this.post('POST', `${path}`, { groupId, kcId }); - return groupUser; + return await this.post('POST', `${path}`, { groupId, kcId }); } async updateGroup({ id, userId, name, description }) { const path = `/user/update-group`; - const group = await this.post('PUT', `${path}`, { name, description, id, userId }); - return group; + return await this.post('PUT', `${path}`, { name, description, id, userId }); } async updateGroupPolicy({ id, groupId, policyId }) { const path = `/user/update-group-policy`; - const groupPolicy = await this.post('PUT', `${path}`, { id, groupId, policyId }); - return groupPolicy; + return await this.post('PUT', `${path}`, { id, groupId, policyId }); } async updateGroupUser({ id, kcId, groupId }) { const path = `/user/update-group-user`; - const groupUser = await this.post('PUT', `${path}`, { id, kcId, groupId }); - return groupUser; + return await this.post('PUT', `${path}`, { id, kcId, groupId }); } async deleteGroup({ id }) { const path = `/user/delete-group`; - const group = await this.post('DELETE', `${path}`, { id }); - return group; + return await this.post('DELETE', `${path}`, { id }); } async deleteGroupPolicy({ id }) { const path = `/user/delete-group-policy`; - const groupPolicy = await this.post('DELETE', `${path}`, { id }); - return groupPolicy; + return await this.post('DELETE', `${path}`, { id }); } async deleteGroupUser({ groupId, userId }) { const path = `/user/delete-group-user`; - const groupUser = await this.post('DELETE', `${path}`, { groupId, userId }); - return groupUser; + return await this.post('DELETE', `${path}`, { groupId, userId }); } async getAssignedPolicies({ policyId }) { const path = `/policy/assigned-fields`; - const assignedPolicies = await this.post('POST', `${path}`, { policyId }); - return assignedPolicies; + return await this.post('POST', `${path}`, { policyId }); } async deleteRole({ id }) { const path = `/role/delete`; - const role = await this.post('DELETE', `${path}`, { id }); - return role; + return await this.post('DELETE', `${path}`, { id }); } async getAssignedUserByRole({ id }) { const path = `/user/assigned-by-role`; - const assignedUserByRole = await this.post('POST', `${path}`, { id }); - return assignedUserByRole; + return await this.post('POST', `${path}`, { id }); } async getGroupDetailsByPolicy({ policyId }) { const path = `/policy/policies-with-groups`; - const groupDetailsByPolicy = await this.post('POST', `${path}`, { policyId }); - return groupDetailsByPolicy; + return await this.post('POST', `${path}`, { policyId }); } async usersWithGroupAndRole() { const path = `/user/with-groups-and-roles`; - const usersWithGroupAndRole = await this.post('GET', `${path}`); - return usersWithGroupAndRole; + return await this.post('GET', `${path}`); } async findOneUserWithGroupAndRole(id) { const path = `/user/one-with-groups-and-roles`; - const user = await this.post('POST', `${path}`, { + return await this.post('POST', `${path}`, { id, }); - return user; } async createPolicySource({ policyId, sourceId }) { const path = `/policySource/add`; - const policySource = await this.post('POST', `${path}`, { policyId, sourceId }); - return policySource; + return await this.post('POST', `${path}`, { policyId, sourceId }); } } diff --git a/src/context/UserContext.js b/src/context/UserContext.js index 60ceb5f..8eb0ea9 100644 --- a/src/context/UserContext.js +++ b/src/context/UserContext.js @@ -85,7 +85,7 @@ async function checkUserLogin(userId, accessToken, refreshToken, roleId) { sessionStorage.setItem('token_refresh_time', Date.now()); } } else { - console.log('user not logged in'); + console.error('user not logged in'); } } diff --git a/src/pages/group/Group.js b/src/pages/group/Group.js index 252f11f..e100806 100644 --- a/src/pages/group/Group.js +++ b/src/pages/group/Group.js @@ -241,7 +241,6 @@ const Group = (props) => { group.value, user.value ); - console.log(assignedUserToGroup); } } diff --git a/src/pages/policy/Policy.js b/src/pages/policy/Policy.js index 48d761f..6fd5237 100644 --- a/src/pages/policy/Policy.js +++ b/src/pages/policy/Policy.js @@ -735,7 +735,6 @@ const Policy = (props) => { return { 'data-test-subj': `row-${id}`, className: 'customRowClass', - onClick: () => console.log(`Clicked row ${id}`), }; }; diff --git a/src/pages/requests/Requests.js b/src/pages/requests/Requests.js index e3b183e..6206546 100644 --- a/src/pages/requests/Requests.js +++ b/src/pages/requests/Requests.js @@ -1,8 +1,6 @@ -import React, { useState, useCallback, useEffect, memo, useRef } from 'react'; - +import React, { useState, useCallback, useEffect, memo } from 'react'; import store from '../../store/index'; import { ShowAlert } from '../../components/Common/Common'; - import { EuiForm, EuiPageContent, @@ -12,10 +10,6 @@ import { EuiPageContentBody, EuiTabbedContent, EuiFormRow, - EuiFieldText, - EuiFieldPassword, - EuiSelect, - EuiButton, EuiBasicTable, } from '@elastic/eui'; @@ -43,24 +37,19 @@ const Requests = (props) => { const [open, setOpen] = useState(false); const [alertMessage, setAlertMessage] = useState(''); const [severity, setSeverity] = useState('info'); - const [dual] = useState(true); const [requests, setRequests] = useState([]); const [pendingRequests, setPendingRequests] = useState([]); const loadRequests = useCallback(async () => { const requestList = await globalActions.user.fetchRequests(); - if (requestList) { - console.log(requestList); setRequests(requestList); } }, [globalActions.user]); const loadPendingRequests = useCallback(async () => { const requestList = await globalActions.user.fetchPendingRequests(); - if (requestList) { - console.log(requestList); setPendingRequests(requestList); } }, [globalActions.user]); @@ -79,7 +68,6 @@ const Requests = (props) => { const onDeleteRequest = async (request) => { if (request) { await globalActions.user.deleteUserRequest(request.id); - setOpen(true); setAlertMessage('Request was deleted succesfully!'); setSeverity('success'); @@ -91,7 +79,6 @@ const Requests = (props) => { const onProcessRequest = async (request) => { if (request) { await globalActions.user.processUserRequest(request.id); - setOpen(true); setAlertMessage('Request was deleted succesfully!'); setSeverity('success'); diff --git a/src/pages/sources/Sources.js b/src/pages/sources/Sources.js index 285ebeb..da1b11b 100644 --- a/src/pages/sources/Sources.js +++ b/src/pages/sources/Sources.js @@ -325,7 +325,6 @@ const Sources = () => { sourceDescription, selectedSources ); - console.log(result); if (result.status === 201) { setOpen(true); setAlertMessage('Sources are merged and send to elasticsearch successfully !'); diff --git a/src/pages/user/User.js b/src/pages/user/User.js index 184cbb2..daf4dc3 100644 --- a/src/pages/user/User.js +++ b/src/pages/user/User.js @@ -1,8 +1,6 @@ import React, { useState, useCallback, useEffect, memo, useRef } from 'react'; - import store from '../../store/index'; import { ShowAlert } from '../../components/Common'; - import { EuiForm, EuiPageContent, @@ -135,7 +133,6 @@ const User = (props) => { const users = await globalActions.user.usersWithGroupAndRole(); if (users) { - console.log(users); const userList = []; const userNameList = []; users.forEach((user) => { -- GitLab From ea5c06654fa0ff5030c9a721f752b267fef5ec99 Mon Sep 17 00:00:00 2001 From: rbisson <remi.bisson@inrae.fr> Date: Tue, 23 Apr 2024 10:05:40 +0200 Subject: [PATCH 05/19] [src]: removed useless variables used to return --- src/context/InSylvaGatekeeperClient.js | 4 +- src/context/InSylvaSourceManager.js | 71 ++++++++++---------------- src/context/KeycloakClient.js | 22 +++----- 3 files changed, 35 insertions(+), 62 deletions(-) diff --git a/src/context/InSylvaGatekeeperClient.js b/src/context/InSylvaGatekeeperClient.js index 2d7c77e..d1b8568 100644 --- a/src/context/InSylvaGatekeeperClient.js +++ b/src/context/InSylvaGatekeeperClient.js @@ -145,13 +145,13 @@ class InSylvaGatekeeperClient { }); } - async updatePolicy({ id, name, sourceId, isDeafault }) { + async updatePolicy({ id, name, sourceId, isDefault }) { const path = `/policy/update`; return await this.post('PUT', `${path}`, { id, name, sourceId, - isDeafault, + isDefault, }); } diff --git a/src/context/InSylvaSourceManager.js b/src/context/InSylvaSourceManager.js index b817c6c..a02e89c 100644 --- a/src/context/InSylvaSourceManager.js +++ b/src/context/InSylvaSourceManager.js @@ -12,45 +12,37 @@ class InSylvaSourceManager { body: JSON.stringify(requestContent), mode: 'cors', }); - - const responseContent = await response.json(); - - return responseContent; + return await response.json(); } async createSource(metaUrfms, name, description, kc_id) { const path = `/source`; - const result = await this.post('POST', `${path}`, { + return await this.post('POST', `${path}`, { metaUrfms, name, description, kc_id, }); - return result; } async sources(kc_id) { const path = '/sources'; - const result = await this.post('POST', `${path}`, { kc_id }); - return result; + return await this.post('POST', `${path}`, { kc_id }); } async indexedSources(kc_id) { const path = '/indexed-sources'; - const result = await this.post('POST', `${path}`, { kc_id }); - return result; + return await this.post('POST', `${path}`, { kc_id }); } async allSource() { const path = '/allSource'; - const result = await this.post('GET', `${path}`); - return result; + return await this.post('GET', `${path}`); } async allIndexedSource() { const path = '/allIndexedSource'; - const result = await this.post('GET', `${path}`); - return result; + return await this.post('GET', `${path}`); } async addStdField( @@ -61,11 +53,11 @@ class InSylvaSourceManager { field_type, cardinality, values, - ispublic, - isoptional + isPublic, + isOptional ) { const path = `/addStdField`; - const result = await this.post('POST', `${path}`, { + return await this.post('POST', `${path}`, { category, field_name, definition_and_comment, @@ -73,10 +65,9 @@ class InSylvaSourceManager { field_type, cardinality, values, - ispublic, - isoptional, + isPublic, + isOptional, }); - return result; } async addAddtlField( @@ -87,11 +78,11 @@ class InSylvaSourceManager { field_type, cardinality, values, - ispublic, - isoptional + isPublic, + isOptional ) { const path = `/addAddtlField`; - const result = await this.post('POST', `${path}`, { + return await this.post('POST', `${path}`, { category, field_name, definition_and_comment, @@ -99,10 +90,9 @@ class InSylvaSourceManager { field_type, cardinality, values, - ispublic, - isoptional, + isPublic, + isOptional, }); - return result; } async updateStdField( @@ -113,11 +103,11 @@ class InSylvaSourceManager { field_type, cardinality, values, - ispublic, - isoptional + isPublic, + isOptional ) { const path = `/updateStdField`; - const result = await this.post('POST', `${path}`, { + return await this.post('POST', `${path}`, { category, field_name, definition_and_comment, @@ -125,45 +115,38 @@ class InSylvaSourceManager { field_type, cardinality, values, - ispublic, - isoptional, + isPublic, + isOptional, }); - return result; } async updateSource(kc_id, source_id) { const path = '/update_source'; - const result = await this.post('POST', `${path}`, { kc_id, source_id }); - return result; + return await this.post('POST', `${path}`, { kc_id, source_id }); } async publicFields() { const path = `/stdFields`; - const result = this.post('GET', `${path}`); - return result; + return this.post('GET', `${path}`); } async privateFields() { const path = `/privateFieldList`; - const result = this.post('GET', `${path}`); - return result; + return this.post('GET', `${path}`); } async truncateStdField() { const path = `/stdFields/truncate`; - const result = this.post('DELETE', `${path}`); - return result; + return this.post('DELETE', `${path}`); } async deleteSource(sourceId, kc_id) { const path = `/source/delete`; - const result = this.post('POST', `${path}`, { sourceId, kc_id }); - return result; + return this.post('POST', `${path}`, { sourceId, kc_id }); } async mergeAndSendSource({ kc_id, name, description, sources }) { const path = `/source/merge-and-send`; - const result = this.post('POST', `${path}`, { kc_id, name, description, sources }); - return result; + return this.post('POST', `${path}`, { kc_id, name, description, sources }); } } diff --git a/src/context/KeycloakClient.js b/src/context/KeycloakClient.js index 34dfa8b..6f75bf5 100644 --- a/src/context/KeycloakClient.js +++ b/src/context/KeycloakClient.js @@ -12,11 +12,10 @@ class KeycloakClient { headers["Authorization"] = "Bearer " + access_token } */ - - var formBody = []; - for (var property in requestContent) { - var encodedKey = encodeURIComponent(property); - var encodedValue = encodeURIComponent(requestContent[property]); + let formBody = []; + for (const property in requestContent) { + const encodedKey = encodeURIComponent(property); + const encodedValue = encodeURIComponent(requestContent[property]); formBody.push(encodedKey + '=' + encodedValue); } formBody = formBody.join('&'); @@ -27,23 +26,16 @@ class KeycloakClient { body: formBody, mode: 'cors', }); - if (response.ok === true) { // ok } else { // throw new Error(response.status); - - const responseContent = await response.json(); - - return responseContent; + return await response.json(); } - if (response.statusText === 'No Content') { // ok } else { - const responseContent = await response.json(); - - return responseContent; + return await response.json(); } } @@ -61,7 +53,6 @@ class KeycloakClient { password, grant_type, }); - return { token }; } @@ -78,7 +69,6 @@ class KeycloakClient { grant_type, refresh_token, }); - return { token }; } -- GitLab From 6e0fc25f06b397e60c85e28a708e120e5e5ab369 Mon Sep 17 00:00:00 2001 From: rbisson <remi.bisson@inrae.fr> Date: Tue, 23 Apr 2024 11:04:06 +0200 Subject: [PATCH 06/19] [src]: converted all var to let or const --- src/components/App.js | 7 +--- src/components/Header/Header.js | 20 ++++-------- src/components/Layout/Layout.js | 4 +-- src/components/Notification/Notification.js | 4 +-- src/components/PageTitle/PageTitle.js | 2 +- src/components/Sidebar/Sidebar.js | 32 ++++++------------- src/components/Sidebar/components/Dot.js | 6 ++-- .../components/SidebarLink/SidebarLink.js | 6 ++-- src/components/UserAvatar/UserAvatar.js | 6 ++-- src/components/Widget/Widget.js | 6 ++-- src/components/Wrappers/Wrappers.js | 20 ++++++------ src/context/LayoutContext.js | 10 +++--- src/pages/charts/Charts.js | 26 +++++++-------- src/pages/charts/components/ApexHeatmap.js | 10 +++--- src/pages/charts/components/ApexLineChart.js | 2 +- src/pages/dashboard/Dashboard.js | 6 ++-- .../dashboard/components/BigStat/BigStat.js | 8 ++--- src/pages/dashboard/components/Table/Table.js | 2 +- src/pages/error/Error.js | 6 +--- src/pages/fields/Fields.js | 6 ++-- src/pages/policy/Policy.js | 3 -- 21 files changed, 81 insertions(+), 111 deletions(-) diff --git a/src/components/App.js b/src/components/App.js index bb8b8c7..1476783 100644 --- a/src/components/App.js +++ b/src/components/App.js @@ -1,20 +1,15 @@ import React from 'react'; import { HashRouter, Route, Switch, Redirect } from 'react-router-dom'; - -// components import Layout from './Layout'; - -// pages import Error from '../pages/error'; -export default function App(props) { +export default function App() { return ( <HashRouter> <Switch> <Route exact path="/" render={() => <Redirect to="/app/dashboard" />} /> <Route exact path="/app" render={() => <Redirect to="/app/dashboard" />} /> <Route path="/app" component={Layout} /> - {/* <PublicRoute path="/login" component={Login} /> */} <Route path="/Error" component={Error} /> </Switch> </HashRouter> diff --git a/src/components/Header/Header.js b/src/components/Header/Header.js index 9d73183..3ca07d7 100644 --- a/src/components/Header/Header.js +++ b/src/components/Header/Header.js @@ -6,14 +6,8 @@ import { ArrowBack as ArrowBackIcon, } from '@material-ui/icons'; import classNames from 'classnames'; - -// styles import useStyles from './styles'; - -// components import { Typography } from '../Wrappers/Wrappers'; - -// context import { useLayoutState, useLayoutDispatch, @@ -46,19 +40,19 @@ const notifications = [ */ export default function Header(props) { - var classes = useStyles(); + const classes = useStyles(); // global - var layoutState = useLayoutState(); - var layoutDispatch = useLayoutDispatch(); - var userDispatch = useUserDispatch(); + const layoutState = useLayoutState(); + const layoutDispatch = useLayoutDispatch(); + const userDispatch = useUserDispatch(); // local // var [mailMenu, setMailMenu] = useState(null); - var [profileMenu, setProfileMenu] = useState(null); + let [profileMenu, setProfileMenu] = useState(null); - var [, globalActions] = store(); - var [user, setUser] = useState({}); + let [, globalActions] = store(); + let [user, setUser] = useState({}); const loadUser = useCallback(async () => { if (sessionStorage.getItem('userId')) { diff --git a/src/components/Layout/Layout.js b/src/components/Layout/Layout.js index 2c4570d..d7ad4f1 100644 --- a/src/components/Layout/Layout.js +++ b/src/components/Layout/Layout.js @@ -23,10 +23,10 @@ import Group from '../../pages/group'; import { useLayoutState } from '../../context/LayoutContext'; function Layout(props) { - var classes = useStyles(); + const classes = useStyles(); // global - var layoutState = useLayoutState(); + const layoutState = useLayoutState(); return ( <div className={classes.root}> diff --git a/src/components/Notification/Notification.js b/src/components/Notification/Notification.js index eb34c86..c9d0724 100644 --- a/src/components/Notification/Notification.js +++ b/src/components/Notification/Notification.js @@ -42,8 +42,8 @@ const typesIcons = { }; export default function Notification({ variant, ...props }) { - var classes = useStyles(); - var theme = useTheme(); + const classes = useStyles(); + const theme = useTheme(); const icon = getIconByType(props.type); const iconWithStyles = React.cloneElement(icon, { diff --git a/src/components/PageTitle/PageTitle.js b/src/components/PageTitle/PageTitle.js index e7be74c..14e0f37 100644 --- a/src/components/PageTitle/PageTitle.js +++ b/src/components/PageTitle/PageTitle.js @@ -8,7 +8,7 @@ import useStyles from './styles'; import { Typography } from '../Wrappers'; export default function PageTitle(props) { - var classes = useStyles(); + const classes = useStyles(); return ( <div className={classes.pageTitleContainer}> diff --git a/src/components/Sidebar/Sidebar.js b/src/components/Sidebar/Sidebar.js index 57d0303..059db8a 100644 --- a/src/components/Sidebar/Sidebar.js +++ b/src/components/Sidebar/Sidebar.js @@ -1,24 +1,12 @@ import React, { useState, useEffect } from 'react'; import { Drawer, IconButton, List } from '@material-ui/core'; -import { - ArrowBack as ArrowBackIcon, - People as UserIcon, - GroupWork as GroupIcon, -} from '@material-ui/icons'; - +import { ArrowBack as ArrowBackIcon } from '@material-ui/icons'; import { EuiIcon } from '@elastic/eui'; - import { useTheme } from '@material-ui/styles'; import { withRouter } from 'react-router-dom'; import classNames from 'classnames'; - -// styles import useStyles from './styles'; - -// components import SidebarLink from './components/SidebarLink/SidebarLink'; - -// context import { useLayoutState, useLayoutDispatch, @@ -26,8 +14,8 @@ import { } from '../../context/LayoutContext'; function Sidebar({ location }) { - var classes = useStyles(); - var theme = useTheme(); + const classes = useStyles(); + const theme = useTheme(); const structures = [ { @@ -106,18 +94,18 @@ function Sidebar({ location }) { const _structures = []; for (const structure of structures) { - if (structure.roles.some((e) => e == roleId)) { + if (structure.roles.some((e) => e === roleId)) { structure.isAuthorized = true; _structures.push(structure); } } // global - var { isSidebarOpened } = useLayoutState(); - var layoutDispatch = useLayoutDispatch(); + let { isSidebarOpened } = useLayoutState(); + const layoutDispatch = useLayoutDispatch(); // local - var [isPermanent, setPermanent] = useState(true); + let [isPermanent, setPermanent] = useState(true); useEffect(function () { window.addEventListener('resize', handleWindowWidthChange); @@ -170,9 +158,9 @@ function Sidebar({ location }) { // ################################################################## function handleWindowWidthChange() { - var windowWidth = window.innerWidth; - var breakpointWidth = theme.breakpoints.values.md; - var isSmallScreen = windowWidth < breakpointWidth; + const windowWidth = window.innerWidth; + const breakpointWidth = theme.breakpoints.values.md; + const isSmallScreen = windowWidth < breakpointWidth; if (isSmallScreen && isPermanent) { setPermanent(false); diff --git a/src/components/Sidebar/components/Dot.js b/src/components/Sidebar/components/Dot.js index 73c154c..df1a1c0 100644 --- a/src/components/Sidebar/components/Dot.js +++ b/src/components/Sidebar/components/Dot.js @@ -3,7 +3,7 @@ import { makeStyles, useTheme } from '@material-ui/styles'; import classnames from 'classnames'; // styles -var useStyles = makeStyles((theme) => ({ +const useStyles = makeStyles((theme) => ({ dotBase: { width: 5, height: 5, @@ -18,8 +18,8 @@ var useStyles = makeStyles((theme) => ({ })); export default function Dot({ size, color }) { - var classes = useStyles(); - var theme = useTheme(); + const classes = useStyles(); + const theme = useTheme(); return ( <div diff --git a/src/components/Sidebar/components/SidebarLink/SidebarLink.js b/src/components/Sidebar/components/SidebarLink/SidebarLink.js index c8c9d6c..9a6feb4 100644 --- a/src/components/Sidebar/components/SidebarLink/SidebarLink.js +++ b/src/components/Sidebar/components/SidebarLink/SidebarLink.js @@ -28,11 +28,11 @@ export default function SidebarLink({ nested, type, }) { - var classes = useStyles(); + const classes = useStyles(); // local - var [isOpen, setIsOpen] = useState(false); - var isLinkActive = + let [isOpen, setIsOpen] = useState(false); + const isLinkActive = link && (location.pathname === link || location.pathname.indexOf(link) !== -1); if (type === 'title') diff --git a/src/components/UserAvatar/UserAvatar.js b/src/components/UserAvatar/UserAvatar.js index 6394591..e0e5e34 100644 --- a/src/components/UserAvatar/UserAvatar.js +++ b/src/components/UserAvatar/UserAvatar.js @@ -8,10 +8,10 @@ import useStyles from './styles'; import { Typography } from '../Wrappers'; export default function UserAvatar({ color = 'primary', ...props }) { - var classes = useStyles(); - var theme = useTheme(); + const classes = useStyles(); + const theme = useTheme(); - var letters = props.name + const letters = props.name .split(' ') .map((word) => word[0]) .join(''); diff --git a/src/components/Widget/Widget.js b/src/components/Widget/Widget.js index 4aa1b3d..84b4c21 100644 --- a/src/components/Widget/Widget.js +++ b/src/components/Widget/Widget.js @@ -15,11 +15,11 @@ export default function Widget({ header, ...props }) { - var classes = useStyles(); + const classes = useStyles(); // local - var [moreButtonRef, setMoreButtonRef] = useState(null); - var [isMoreMenuOpen, setMoreMenuOpen] = useState(false); + let [moreButtonRef, setMoreButtonRef] = useState(null); + let [isMoreMenuOpen, setMoreMenuOpen] = useState(false); return ( <div className={classes.widgetWrapper}> diff --git a/src/components/Wrappers/Wrappers.js b/src/components/Wrappers/Wrappers.js index e1ea9bb..6442f8c 100644 --- a/src/components/Wrappers/Wrappers.js +++ b/src/components/Wrappers/Wrappers.js @@ -9,7 +9,7 @@ import { useTheme, makeStyles } from '@material-ui/styles'; import classnames from 'classnames'; // styles -var useStyles = makeStyles((theme) => ({ +const useStyles = makeStyles((theme) => ({ badge: { fontWeight: 600, height: 16, @@ -18,9 +18,9 @@ var useStyles = makeStyles((theme) => ({ })); function Badge({ children, colorBrightness, color, ...props }) { - var classes = useStyles(); - var theme = useTheme(); - var Styled = createStyled({ + const classes = useStyles(); + const theme = useTheme(); + const Styled = createStyled({ badge: { backgroundColor: getColor(color, theme, colorBrightness), }, @@ -43,7 +43,7 @@ function Badge({ children, colorBrightness, color, ...props }) { } function Typography({ children, weight, size, colorBrightness, color, ...props }) { - var theme = useTheme(); + const theme = useTheme(); return ( <TypographyBase @@ -60,9 +60,9 @@ function Typography({ children, weight, size, colorBrightness, color, ...props } } function Button({ children, color, ...props }) { - var theme = useTheme(); + const theme = useTheme(); - var Styled = createStyled({ + const Styled = createStyled({ button: { backgroundColor: getColor(color, theme), boxShadow: theme.customShadows.widget, @@ -109,7 +109,7 @@ function getFontWeight(style) { } function getFontSize(size, variant = '', theme) { - var multiplier; + let multiplier; switch (size) { case 'sm': @@ -129,7 +129,7 @@ function getFontSize(size, variant = '', theme) { break; } - var defaultSize = + const defaultSize = variant && theme.typography[variant] ? theme.typography[variant].fontSize : theme.typography.fontSize + 'px'; @@ -138,7 +138,7 @@ function getFontSize(size, variant = '', theme) { } function createStyled(styles, options) { - var Styled = function (props) { + const Styled = function (props) { const { children, ...other } = props; return children(other); }; diff --git a/src/context/LayoutContext.js b/src/context/LayoutContext.js index d4207ff..3c739c6 100644 --- a/src/context/LayoutContext.js +++ b/src/context/LayoutContext.js @@ -1,7 +1,7 @@ import React from 'react'; -var LayoutStateContext = React.createContext(); -var LayoutDispatchContext = React.createContext(); +const LayoutStateContext = React.createContext(); +const LayoutDispatchContext = React.createContext(); function layoutReducer(state, action) { switch (action.type) { @@ -14,7 +14,7 @@ function layoutReducer(state, action) { } function LayoutProvider({ children }) { - var [state, dispatch] = React.useReducer(layoutReducer, { + let [state, dispatch] = React.useReducer(layoutReducer, { isSidebarOpened: true, }); return ( @@ -27,7 +27,7 @@ function LayoutProvider({ children }) { } function useLayoutState() { - var context = React.useContext(LayoutStateContext); + const context = React.useContext(LayoutStateContext); if (context === undefined) { throw new Error('useLayoutState must be used within a LayoutProvider'); } @@ -35,7 +35,7 @@ function useLayoutState() { } function useLayoutDispatch() { - var context = React.useContext(LayoutDispatchContext); + const context = React.useContext(LayoutDispatchContext); if (context === undefined) { throw new Error('useLayoutDispatch must be used within a LayoutProvider'); } diff --git a/src/pages/charts/Charts.js b/src/pages/charts/Charts.js index db19851..99793bc 100644 --- a/src/pages/charts/Charts.js +++ b/src/pages/charts/Charts.js @@ -74,10 +74,10 @@ const pieChartData = [ ]; export default function Charts(props) { - var theme = useTheme(); + const theme = useTheme(); // local - var [activeIndex, setActiveIndexId] = useState(0); + let [activeIndex, setActiveIndexId] = useState(0); return ( <> @@ -155,8 +155,8 @@ export default function Charts(props) { // ################################################################ function renderActiveShape(props) { - var RADIAN = Math.PI / 180; - var { + const RADIAN = Math.PI / 180; + let { cx, cy, midAngle, @@ -169,15 +169,15 @@ function renderActiveShape(props) { percent, value, } = props; - var sin = Math.sin(-RADIAN * midAngle); - var cos = Math.cos(-RADIAN * midAngle); - var sx = cx + (outerRadius + 10) * cos; - var sy = cy + (outerRadius + 10) * sin; - var mx = cx + (outerRadius + 30) * cos; - var my = cy + (outerRadius + 30) * sin; - var ex = mx + (cos >= 0 ? 1 : -1) * 22; - var ey = my; - var textAnchor = cos >= 0 ? 'start' : 'end'; + const sin = Math.sin(-RADIAN * midAngle); + const cos = Math.cos(-RADIAN * midAngle); + const sx = cx + (outerRadius + 10) * cos; + const sy = cy + (outerRadius + 10) * sin; + const mx = cx + (outerRadius + 30) * cos; + const my = cy + (outerRadius + 30) * sin; + const ex = mx + (cos >= 0 ? 1 : -1) * 22; + const ey = my; + const textAnchor = cos >= 0 ? 'start' : 'end'; return ( <g> diff --git a/src/pages/charts/components/ApexHeatmap.js b/src/pages/charts/components/ApexHeatmap.js index ebd119f..64594bb 100644 --- a/src/pages/charts/components/ApexHeatmap.js +++ b/src/pages/charts/components/ApexHeatmap.js @@ -69,7 +69,7 @@ const series = [ ]; export default function ApexLineChart() { - var theme = useTheme(); + const theme = useTheme(); return ( <ApexCharts @@ -83,11 +83,11 @@ export default function ApexLineChart() { // ################################################################## function generateData(count, yrange) { - var i = 0; - var series = []; + let i = 0; + const series = []; while (i < count) { - var x = 'w' + (i + 1).toString(); - var y = Math.floor(Math.random() * (yrange.max - yrange.min + 1)) + yrange.min; + const x = 'w' + (i + 1).toString(); + const y = Math.floor(Math.random() * (yrange.max - yrange.min + 1)) + yrange.min; series.push({ x: x, diff --git a/src/pages/charts/components/ApexLineChart.js b/src/pages/charts/components/ApexLineChart.js index 14d212a..da684f0 100644 --- a/src/pages/charts/components/ApexLineChart.js +++ b/src/pages/charts/components/ApexLineChart.js @@ -14,7 +14,7 @@ const series = [ ]; export default function ApexLineChart() { - var theme = useTheme(); + const theme = useTheme(); return ( <ApexCharts options={themeOptions(theme)} series={series} type="area" height={350} /> diff --git a/src/pages/dashboard/Dashboard.js b/src/pages/dashboard/Dashboard.js index 054205f..c1b7466 100644 --- a/src/pages/dashboard/Dashboard.js +++ b/src/pages/dashboard/Dashboard.js @@ -74,8 +74,8 @@ urlMaps.set( ); export default function Dashboard(props) { - var classes = useStyles(); - var theme = useTheme(); + const classes = useStyles(); + const theme = useTheme(); // local // var [mainChartState, setMainChartState] = useState("monthly"); @@ -448,7 +448,7 @@ export default function Dashboard(props) { // ####################################################################### function getRandomData(length, min, max, multiplier = 10, maxDiff = 10) { - var array = new Array(length).fill(); + const array = new Array(length).fill(); let lastValue; return array.map((item, index) => { diff --git a/src/pages/dashboard/components/BigStat/BigStat.js b/src/pages/dashboard/components/BigStat/BigStat.js index 0ebcfab..45a95bb 100644 --- a/src/pages/dashboard/components/BigStat/BigStat.js +++ b/src/pages/dashboard/components/BigStat/BigStat.js @@ -13,12 +13,12 @@ import Widget from '../../../../components/Widget'; import { Typography } from '../../../../components/Wrappers'; export default function BigStat(props) { - var { product, total, color, registrations, bounce } = props; - var classes = useStyles(); - var theme = useTheme(); + let { product, total, color, registrations, bounce } = props; + const classes = useStyles(); + const theme = useTheme(); // local - var [value, setValue] = useState('daily'); + let [value, setValue] = useState('daily'); return ( <Widget diff --git a/src/pages/dashboard/components/Table/Table.js b/src/pages/dashboard/components/Table/Table.js index de752a8..3a9f58d 100644 --- a/src/pages/dashboard/components/Table/Table.js +++ b/src/pages/dashboard/components/Table/Table.js @@ -11,7 +11,7 @@ const states = { }; export default function TableComponent({ data }) { - var keys = Object.keys(data[0]).map((i) => i.toUpperCase()); + const keys = Object.keys(data[0]).map((i) => i.toUpperCase()); keys.shift(); // delete "id" key return ( diff --git a/src/pages/error/Error.js b/src/pages/error/Error.js index fde6b95..e466863 100644 --- a/src/pages/error/Error.js +++ b/src/pages/error/Error.js @@ -2,15 +2,11 @@ import React from 'react'; import { Grid, Paper, Typography, Button } from '@material-ui/core'; import { Link } from 'react-router-dom'; import classnames from 'classnames'; - -// styles import useStyles from './styles'; - -// logo import logo from './logo.png'; export default function Error() { - var classes = useStyles(); + const classes = useStyles(); return ( <Grid container className={classes.container}> diff --git a/src/pages/fields/Fields.js b/src/pages/fields/Fields.js index 57045b9..24630d8 100644 --- a/src/pages/fields/Fields.js +++ b/src/pages/fields/Fields.js @@ -217,11 +217,11 @@ const Fields = (props) => { const handleData = (file) => { if (file) { - var result = Papa.parse(file, { header: true }); - var columns = []; + const result = Papa.parse(file, { header: true }); + const columns = []; const rows = []; result.meta.fields.forEach((item) => { - var column = { + const column = { name: item, options: { display: true, diff --git a/src/pages/policy/Policy.js b/src/pages/policy/Policy.js index 6fd5237..dd3595d 100644 --- a/src/pages/policy/Policy.js +++ b/src/pages/policy/Policy.js @@ -1,6 +1,5 @@ import React, { useState, Fragment, useCallback, useEffect, memo } from 'react'; import store from '../../store/index'; - import { EuiForm, EuiPageContent, @@ -11,7 +10,6 @@ import { EuiTabbedContent, EuiFormRow, EuiFieldText, - EuiSwitch, EuiFlexGroup, EuiFlexItem, EuiSpacer, @@ -20,7 +18,6 @@ import { EuiSelectable, EuiComboBox, } from '@elastic/eui'; - import { ShowAlert } from '../../components/Common'; const NewPolicyForm = memo( -- GitLab From e97501a7c49ca98d0bda166c7cbcb29aabb61d6d Mon Sep 17 00:00:00 2001 From: rbisson <remi.bisson@inrae.fr> Date: Tue, 23 Apr 2024 13:48:29 +0200 Subject: [PATCH 07/19] [public]: removed commented script about google recaptcha --- public/index.html | 11 +--------- src/images/google.svg | 47 ------------------------------------------- 2 files changed, 1 insertion(+), 57 deletions(-) delete mode 100644 src/images/google.svg diff --git a/public/index.html b/public/index.html index e102354..708d670 100755 --- a/public/index.html +++ b/public/index.html @@ -22,15 +22,6 @@ --> <title>INRA PACA IN-SYLVA</title> <script src="%PUBLIC_URL%/env-config.js"></script> - <!-- - <script src="https://www.google.com/recaptcha/api.js?render=6LfAtbwUAAAAAPcZewkqYxf7Z7Q9TE7QXMEeQr-e"></script> - <script> - grecaptcha.ready(function () { - grecaptcha.execute('6LfAtbwUAAAAAPcZewkqYxf7Z7Q9TE7QXMEeQr-e', { action: 'homepage' }).then(function (token) { - }); - }); - </script> - --> </head> <body style="font-family: 'Roboto', sans-serif;"> @@ -48,4 +39,4 @@ --> </body> -</html> \ No newline at end of file +</html> diff --git a/src/images/google.svg b/src/images/google.svg deleted file mode 100644 index e2fce99..0000000 --- a/src/images/google.svg +++ /dev/null @@ -1,47 +0,0 @@ -<?xml version="1.0" encoding="iso-8859-1"?> -<!-- Generator: Adobe Illustrator 19.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) --> -<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" - viewBox="0 0 512 512" style="enable-background:new 0 0 512 512;" xml:space="preserve"> -<path style="fill:#FBBB00;" d="M113.47,309.408L95.648,375.94l-65.139,1.378C11.042,341.211,0,299.9,0,256 - c0-42.451,10.324-82.483,28.624-117.732h0.014l57.992,10.632l25.404,57.644c-5.317,15.501-8.215,32.141-8.215,49.456 - C103.821,274.792,107.225,292.797,113.47,309.408z"/> -<path style="fill:#518EF8;" d="M507.527,208.176C510.467,223.662,512,239.655,512,256c0,18.328-1.927,36.206-5.598,53.451 - c-12.462,58.683-45.025,109.925-90.134,146.187l-0.014-0.014l-73.044-3.727l-10.338-64.535 - c29.932-17.554,53.324-45.025,65.646-77.911h-136.89V208.176h138.887L507.527,208.176L507.527,208.176z"/> -<path style="fill:#28B446;" d="M416.253,455.624l0.014,0.014C372.396,490.901,316.666,512,256,512 - c-97.491,0-182.252-54.491-225.491-134.681l82.961-67.91c21.619,57.698,77.278,98.771,142.53,98.771 - c28.047,0,54.323-7.582,76.87-20.818L416.253,455.624z"/> -<path style="fill:#F14336;" d="M419.404,58.936l-82.933,67.896c-23.335-14.586-50.919-23.012-80.471-23.012 - c-66.729,0-123.429,42.957-143.965,102.724l-83.397-68.276h-0.014C71.23,56.123,157.06,0,256,0 - C318.115,0,375.068,22.126,419.404,58.936z"/> -<g> -</g> -<g> -</g> -<g> -</g> -<g> -</g> -<g> -</g> -<g> -</g> -<g> -</g> -<g> -</g> -<g> -</g> -<g> -</g> -<g> -</g> -<g> -</g> -<g> -</g> -<g> -</g> -<g> -</g> -</svg> -- GitLab From a21de7d65714ea7698eb174d443f41737d968319 Mon Sep 17 00:00:00 2001 From: rbisson <remi.bisson@inrae.fr> Date: Tue, 23 Apr 2024 16:26:06 +0200 Subject: [PATCH 08/19] [src]: removed useless comments and corrected some errors and warnings --- src/components/Layout/Layout.js | 10 -- src/components/Sidebar/Sidebar.js | 160 +++++------------- .../components/SidebarLink/SidebarLink.js | 6 - src/components/Widget/Widget.js | 7 +- src/components/Widget/WidgetView.js | 2 +- src/context/KeycloakClient.js | 7 - src/pages/charts/Charts.js | 8 +- src/pages/dashboard/Dashboard.js | 59 +------ .../dashboard/components/BigStat/BigStat.js | 15 +- src/pages/group/Group.js | 9 +- src/pages/policy/Policy.js | 15 +- src/pages/requests/Requests.js | 2 +- src/pages/roles/Role.js | 13 +- src/pages/sources/Sources.js | 19 +-- src/pages/user/User.js | 7 +- src/utils.js | 103 +++++++++-- 16 files changed, 157 insertions(+), 285 deletions(-) diff --git a/src/components/Layout/Layout.js b/src/components/Layout/Layout.js index d7ad4f1..23d1182 100644 --- a/src/components/Layout/Layout.js +++ b/src/components/Layout/Layout.js @@ -1,15 +1,9 @@ import React from 'react'; import { Route, Switch, withRouter } from 'react-router-dom'; import classnames from 'classnames'; - -// styles import useStyles from './styles'; - -// components import Header from '../Header'; import Sidebar from '../Sidebar'; - -// pages import Dashboard from '../../pages/dashboard'; import User from '../../pages/user'; import Role from '../../pages/roles'; @@ -18,14 +12,10 @@ import Sources from '../../pages/sources/Sources'; import Fields from '../../pages/fields'; import Policy from '../../pages/policy'; import Group from '../../pages/group'; - -// context import { useLayoutState } from '../../context/LayoutContext'; function Layout(props) { const classes = useStyles(); - - // global const layoutState = useLayoutState(); return ( diff --git a/src/components/Sidebar/Sidebar.js b/src/components/Sidebar/Sidebar.js index 059db8a..dc3b4e6 100644 --- a/src/components/Sidebar/Sidebar.js +++ b/src/components/Sidebar/Sidebar.js @@ -1,7 +1,6 @@ import React, { useState, useEffect } from 'react'; import { Drawer, IconButton, List } from '@material-ui/core'; import { ArrowBack as ArrowBackIcon } from '@material-ui/icons'; -import { EuiIcon } from '@elastic/eui'; import { useTheme } from '@material-ui/styles'; import { withRouter } from 'react-router-dom'; import classNames from 'classnames'; @@ -12,108 +11,54 @@ import { useLayoutDispatch, toggleSidebar, } from '../../context/LayoutContext'; +import { getSideBarItems, getUserRoleId } from '../../utils'; -function Sidebar({ location }) { +const Sidebar = ({ location }) => { const classes = useStyles(); const theme = useTheme(); - - const structures = [ - { - id: 0, - label: 'Dashboard', - link: '/app/dashboard', - roles: [1], - isAuthorized: true, - icon: <EuiIcon type="dashboardApp" size="l" />, - }, - { - id: 1, - label: 'User', - link: '/app/user', - roles: [1], - isAuthorized: true, - icon: <EuiIcon type="user" size="l" />, - }, - { - id: 2, - label: 'Roles', - link: '/app/role', - roles: [1], - isAuthorized: true, - icon: <EuiIcon type="usersRolesApp" size="l" />, - }, - { - id: 3, - label: 'Groups', - link: '/app/groups', - roles: [1], - isAuthorized: true, - icon: <EuiIcon type="users" size="l" />, - }, - { - id: 4, - label: 'Requests', - link: '/app/requests', - roles: [1], - isAuthorized: true, - icon: <EuiIcon type="email" size="l" />, - }, - { - id: 5, - label: 'Policies', - link: '/app/policies', - roles: [1, 2], - isAuthorized: true, - icon: <EuiIcon type="lockOpen" size="l" />, - }, - { - id: 6, - label: 'Sources', - link: '/app/sources', - roles: [1, 2], - isAuthorized: true, - icon: <EuiIcon type="indexManagementApp" size="l" />, - }, - { - id: 7, - label: 'Fields', - link: '/app/fields', - roles: [1], - isAuthorized: true, - icon: <EuiIcon type="visTable" size="l" />, - }, - { id: 8, type: 'divider', roles: [0] }, - ]; - - let roleId = 0; - if (sessionStorage.getItem('roleId').split('#')[0]) { - roleId = sessionStorage.getItem('roleId').split('#')[0]; - } else { - roleId = sessionStorage.getItem('roleId'); - } - - const _structures = []; - for (const structure of structures) { - if (structure.roles.some((e) => e === roleId)) { - structure.isAuthorized = true; - _structures.push(structure); - } - } - - // global let { isSidebarOpened } = useLayoutState(); const layoutDispatch = useLayoutDispatch(); - - // local let [isPermanent, setPermanent] = useState(true); + const [sidebarItems, setSidebarItems] = useState([]); + const [userRoleId, setUserRoleId] = useState(0); + + useEffect(() => { + setSidebarItems(getSideBarItems()); + setUserRoleId(getUserRoleId()); + const handleWindowWidthChange = () => { + const windowWidth = window.innerWidth; + const breakpointWidth = theme.breakpoints.values.md; + const isSmallScreen = windowWidth < breakpointWidth; - useEffect(function () { + if (isSmallScreen && isPermanent) { + setPermanent(false); + } else if (!isSmallScreen && !isPermanent) { + setPermanent(true); + } + }; window.addEventListener('resize', handleWindowWidthChange); handleWindowWidthChange(); return function cleanup() { window.removeEventListener('resize', handleWindowWidthChange); }; - }); + }, [setSidebarItems, setUserRoleId, isPermanent, theme]); + + const buildSidebarItems = () => { + return sidebarItems.map((item) => { + if (item.roles.some((authorizedRoleId) => authorizedRoleId === userRoleId)) { + return ( + <SidebarLink + key={item.id} + location={location} + isSidebarOpened={isSidebarOpened} + {...item} + /> + ); + } else { + return null; + } + }); + }; return ( <Drawer @@ -134,40 +79,13 @@ function Sidebar({ location }) { <div className={classes.mobileBackButton}> <IconButton onClick={() => toggleSidebar(layoutDispatch)}> <ArrowBackIcon - classes={{ - root: classNames(classes.headerIcon, classes.headerIconCollapse), - }} + classes={{ root: classNames(classes.headerIcon, classes.headerIconCollapse) }} /> </IconButton> </div> - <List className={classes.sidebarList}> - {_structures.map( - (link) => - link.isAuthorized && ( - <SidebarLink - key={link.id} - location={location} - isSidebarOpened={isSidebarOpened} - {...link} - /> - ) - )} - </List> + <List className={classes.sidebarList}>{buildSidebarItems()}</List> </Drawer> ); - - // ################################################################## - function handleWindowWidthChange() { - const windowWidth = window.innerWidth; - const breakpointWidth = theme.breakpoints.values.md; - const isSmallScreen = windowWidth < breakpointWidth; - - if (isSmallScreen && isPermanent) { - setPermanent(false); - } else if (!isSmallScreen && !isPermanent) { - setPermanent(true); - } - } -} +}; export default withRouter(Sidebar); diff --git a/src/components/Sidebar/components/SidebarLink/SidebarLink.js b/src/components/Sidebar/components/SidebarLink/SidebarLink.js index 9a6feb4..183c9e0 100644 --- a/src/components/Sidebar/components/SidebarLink/SidebarLink.js +++ b/src/components/Sidebar/components/SidebarLink/SidebarLink.js @@ -11,11 +11,7 @@ import { import { Inbox as InboxIcon } from '@material-ui/icons'; import { Link } from 'react-router-dom'; import classnames from 'classnames'; - -// styles import useStyles from './styles'; - -// components import Dot from '../Dot'; export default function SidebarLink({ @@ -133,8 +129,6 @@ export default function SidebarLink({ </> ); - // ########################################################### - function toggleCollapse(e) { if (isSidebarOpened) { e.preventDefault(); diff --git a/src/components/Widget/Widget.js b/src/components/Widget/Widget.js index 84b4c21..1b236d5 100644 --- a/src/components/Widget/Widget.js +++ b/src/components/Widget/Widget.js @@ -2,8 +2,6 @@ import React, { useState } from 'react'; import { Paper, IconButton, Menu, MenuItem, Typography } from '@material-ui/core'; import { MoreVert as MoreIcon } from '@material-ui/icons'; import classnames from 'classnames'; - -// styles import useStyles from './styles'; export default function Widget({ @@ -13,11 +11,8 @@ export default function Widget({ bodyClass, disableWidgetMenu, header, - ...props }) { const classes = useStyles(); - - // local let [moreButtonRef, setMoreButtonRef] = useState(null); let [isMoreMenuOpen, setMoreMenuOpen] = useState(false); @@ -39,7 +34,7 @@ export default function Widget({ aria-owns="widget-menu" aria-haspopup="true" onClick={() => setMoreMenuOpen(true)} - buttonRef={setMoreButtonRef} + ref={setMoreButtonRef} > <MoreIcon /> </IconButton> diff --git a/src/components/Widget/WidgetView.js b/src/components/Widget/WidgetView.js index 6e39dce..c4da6cc 100644 --- a/src/components/Widget/WidgetView.js +++ b/src/components/Widget/WidgetView.js @@ -31,7 +31,7 @@ const Widget = ({ aria-owns="widget-menu" aria-haspopup="true" onClick={() => props.setMoreMenuOpen(true)} - buttonRef={props.setMoreButtonRef} + ref={props.setMoreButtonRef} > <MoreIcon /> </IconButton> diff --git a/src/context/KeycloakClient.js b/src/context/KeycloakClient.js index 6f75bf5..1dcd055 100644 --- a/src/context/KeycloakClient.js +++ b/src/context/KeycloakClient.js @@ -1,17 +1,10 @@ class KeycloakClient { async post(path, requestContent) { - // const access_token = sessionStorage.getItem("access_token"); - const headers = { 'Content-Type': 'application/x-www-form-urlencoded', // "Access-Control-Allow-Methods": "GET,HEAD,PUT,PATCH,POST,DELETE", // "Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept, Authorization" }; - /* - if (access_token) { - headers["Authorization"] = "Bearer " + access_token - } - */ let formBody = []; for (const property in requestContent) { const encodedKey = encodeURIComponent(property); diff --git a/src/pages/charts/Charts.js b/src/pages/charts/Charts.js index 99793bc..28b3152 100644 --- a/src/pages/charts/Charts.js +++ b/src/pages/charts/Charts.js @@ -14,8 +14,6 @@ import { XAxis, YAxis, } from 'recharts'; - -// components import Widget from '../../components/Widget/Widget'; import ApexLineChart from './components/ApexLineChart'; import ApexHeatmap from './components/ApexHeatmap'; @@ -73,10 +71,8 @@ const pieChartData = [ { name: 'Group D', value: 200 }, ]; -export default function Charts(props) { +export default function Charts() { const theme = useTheme(); - - // local let [activeIndex, setActiveIndexId] = useState(0); return ( @@ -152,8 +148,6 @@ export default function Charts(props) { ); } -// ################################################################ - function renderActiveShape(props) { const RADIAN = Math.PI / 180; let { diff --git a/src/pages/dashboard/Dashboard.js b/src/pages/dashboard/Dashboard.js index c1b7466..1e6745f 100644 --- a/src/pages/dashboard/Dashboard.js +++ b/src/pages/dashboard/Dashboard.js @@ -1,7 +1,6 @@ import React from 'react'; import { Grid, LinearProgress } from '@material-ui/core'; import { useTheme } from '@material-ui/styles'; - import keycloakLogo from '../../images/Keycloak_Logo.svg'; import { ResponsiveContainer, @@ -13,7 +12,6 @@ import { Pie, Cell, } from 'recharts'; - import { EuiButton, EuiCard, @@ -22,20 +20,16 @@ import { EuiFlexItem, EuiSpacer, } from '@elastic/eui'; - -// styles import useStyles from './styles'; - -// components import Widget from '../../components/Widget'; import { Typography } from '../../components/Wrappers'; import Dot from '../../components/Sidebar/components/Dot'; +import { getRandomData } from '../../utils'; const PieChartData = [ { name: 'Super User', value: 400, color: 'primary' }, { name: 'Source Manager', value: 300, color: 'secondary' }, { name: 'Standard User', value: 300, color: 'warning' }, - // { name: "Group D", value: 200, color: "success" }, ]; const urlMaps = new Map(); @@ -73,13 +67,10 @@ urlMaps.set( : 'http://localhost:9000/#/init/admin' ); -export default function Dashboard(props) { +export default function Dashboard() { const classes = useStyles(); const theme = useTheme(); - // local - // var [mainChartState, setMainChartState] = useState("monthly"); - return ( <> <EuiFlexGroup gutterSize="l"> @@ -238,7 +229,12 @@ export default function Dashboard(props) { /> </LineChart> </div> - <Grid container direction="row" justify="space-between" alignItems="center"> + <Grid + container + direction="row" + justifyContent="space-between" + alignItems="center" + > <Grid item> <Typography color="text" colorBrightness="secondary"> Registrations @@ -445,42 +441,3 @@ export default function Dashboard(props) { </> ); } - -// ####################################################################### -function getRandomData(length, min, max, multiplier = 10, maxDiff = 10) { - const array = new Array(length).fill(); - let lastValue; - - return array.map((item, index) => { - let randomValue = Math.floor(Math.random() * multiplier + 1); - - while ( - randomValue <= min || - randomValue >= max || - (lastValue && randomValue - lastValue > maxDiff) - ) { - randomValue = Math.floor(Math.random() * multiplier + 1); - } - - lastValue = randomValue; - - return { value: randomValue }; - }); -} -/* -function getMainChartData() { - var resultArray = []; - var tablet = getRandomData(31, 3500, 6500, 7500, 1000); - var desktop = getRandomData(31, 1500, 7500, 7500, 1500); - var mobile = getRandomData(31, 1500, 7500, 7500, 1500); - - for (let i = 0; i < tablet.length; i++) { - resultArray.push({ - tablet: tablet[i].value, - desktop: desktop[i].value, - mobile: mobile[i].value, - }); - } - - return resultArray; -}*/ diff --git a/src/pages/dashboard/components/BigStat/BigStat.js b/src/pages/dashboard/components/BigStat/BigStat.js index 45a95bb..adf5a81 100644 --- a/src/pages/dashboard/components/BigStat/BigStat.js +++ b/src/pages/dashboard/components/BigStat/BigStat.js @@ -4,13 +4,10 @@ import { ArrowForward as ArrowForwardIcon } from '@material-ui/icons'; import { useTheme } from '@material-ui/styles'; import { BarChart, Bar } from 'recharts'; import classnames from 'classnames'; - -// styles import useStyles from './styles'; - -// components import Widget from '../../../../components/Widget'; import { Typography } from '../../../../components/Wrappers'; +import { getRandomData } from '../../../../utils'; export default function BigStat(props) { let { product, total, color, registrations, bounce } = props; @@ -50,7 +47,7 @@ export default function BigStat(props) { {total.percent.value}% </Typography> </div> - <BarChart width={150} height={70} data={getRandomData()}> + <BarChart width={150} height={70} data={getRandomData(7)}> <Bar dataKey="value" fill={theme.palette[color].main} @@ -103,11 +100,3 @@ export default function BigStat(props) { </Widget> ); } - -// ####################################################################### - -function getRandomData() { - return Array(7) - .fill() - .map(() => ({ value: Math.floor(Math.random() * 10) + 1 })); -} diff --git a/src/pages/group/Group.js b/src/pages/group/Group.js index e100806..1761b44 100644 --- a/src/pages/group/Group.js +++ b/src/pages/group/Group.js @@ -74,7 +74,7 @@ const GroupAssignment = memo( <EuiFormRow label="Groups" fullWidth> <EuiSelectable searchable - singleSelection={{ asPlainText: true }} + singleSelection={true} options={groups} onChange={(newOptions) => setGroups(newOptions)} > @@ -152,7 +152,7 @@ const AssignedGroups = memo( } ); -const Group = (props) => { +const Group = () => { const [selectedTabNumber, setSelectedTabNumber] = useState(0); const [globalState, globalActions] = store(); const [groupNameValue, setGroupNameValue] = useState(''); @@ -237,10 +237,7 @@ const Group = (props) => { for (const user of checkedUsers) { for (const group of checkedGroups) { - const assignedUserToGroup = await globalActions.group.createGroupUser( - group.value, - user.value - ); + await globalActions.group.createGroupUser(group.value, user.value); } } diff --git a/src/pages/policy/Policy.js b/src/pages/policy/Policy.js index dd3595d..269dfa2 100644 --- a/src/pages/policy/Policy.js +++ b/src/pages/policy/Policy.js @@ -103,7 +103,7 @@ const PolicyAssignment = memo( <EuiFormRow label="Policies" fullWidth> <EuiSelectable searchable - singleSelection={{ asPlainText: true }} + singleSelection={true} options={optPolicies} onChange={(newOptions) => setOptPolicies(newOptions)} > @@ -165,7 +165,7 @@ const PolicyGroupAssignment = memo( <EuiFormRow label="Policies" fullWidth> <EuiSelectable searchable - singleSelection={{ asPlainText: true }} + singleSelection={true} options={optPolicies} onChange={(newOptions) => setOptPolicies(newOptions)} > @@ -227,7 +227,7 @@ const PolicySourceAssignment = memo( <EuiFormRow label="Policies" fullWidth> <EuiSelectable searchable - singleSelection={{ asPlainText: true }} + singleSelection={true} options={optPolicies} onChange={(newOptions) => setOptPolicies(newOptions)} > @@ -244,7 +244,7 @@ const PolicySourceAssignment = memo( <EuiFormRow label="Sources" fullWidth> <EuiSelectable searchable - singleSelection={{ asPlainText: true }} + singleSelection={true} options={optSources} onChange={(newOptions) => setOptSources(newOptions)} > @@ -320,12 +320,11 @@ const AssignedPolicies = memo( } ); -const Policy = (props) => { +const Policy = () => { const [globalState, globalActions] = store(); const [selectedTabNumber, setSelectedTabNumber] = useState(0); const [isSwitchChecked, setIsSwitchChecked] = useState(false); const [policyName, setPolicyName] = useState(''); - const [sources, setSources] = useState([{ value: 0, text: 'select a source' }]); const [selectedSource, setSelectedSource] = useState(); const [open, setOpen] = useState(false); const [alertMessage, setAlertMessage] = useState(''); @@ -357,12 +356,9 @@ const Policy = (props) => { } if (result) { const _sources = []; - // const _sources2 = [] for (const source of result) { - //_sources.push({ value: source.id, text: source.name }) _sources.push({ value: source.id, label: source.name }); } - // setSources(prevSources => ([...prevSources, ..._sources])) setOptSources(_sources); } } @@ -763,7 +759,6 @@ const Policy = (props) => { globalState={globalState} policyName={policyName} setPolicyName={setPolicyName} - sources={sources} isSwitchChecked={isSwitchChecked} setIsSwitchChecked={setIsSwitchChecked} onSwitchChange={onSwitchChange} diff --git a/src/pages/requests/Requests.js b/src/pages/requests/Requests.js index 6206546..a2008c8 100644 --- a/src/pages/requests/Requests.js +++ b/src/pages/requests/Requests.js @@ -31,7 +31,7 @@ const RequestList = memo(({ requests, requestColumns }) => { ); }); -const Requests = (props) => { +const Requests = () => { const [globalState, globalActions] = store(); const [selectedTabNumber, setSelectedTabNumber] = useState(0); const [open, setOpen] = useState(false); diff --git a/src/pages/roles/Role.js b/src/pages/roles/Role.js index 827e5c3..ee552bd 100644 --- a/src/pages/roles/Role.js +++ b/src/pages/roles/Role.js @@ -1,8 +1,6 @@ import React, { useState, Fragment, useCallback, useEffect } from 'react'; - import store from '../../store/index'; import { ShowAlert } from '../../components/Common'; - import { EuiForm, EuiPageContent, @@ -82,7 +80,7 @@ const roleAssignment = ( <EuiFormRow label="Roles" fullWidth> <EuiSelectable searchable - singleSelection={{ asPlainText: true }} + singleSelection={true} options={roles} onChange={(newOptions) => setRoles(newOptions)} > @@ -156,7 +154,7 @@ const assignedRoles = ({ ); }; -const Role = (props) => { +const Role = () => { const [globalState, globalActions] = store(); const [selectedTabNumber, setSelectedTabNumber] = useState(0); const [roleNameValue, setRoleNameValue] = useState(); @@ -252,13 +250,6 @@ const Role = (props) => { }; const roleActions = [ - /*{ - name: 'Clone', - description: 'Clone this person', - icon: 'copy', - type: 'icon', - onClick: cloneUser, - },*/ { name: 'Delete', description: 'Delete this person', diff --git a/src/pages/sources/Sources.js b/src/pages/sources/Sources.js index da1b11b..419ad8c 100644 --- a/src/pages/sources/Sources.js +++ b/src/pages/sources/Sources.js @@ -1,4 +1,4 @@ -import React, { useState, useCallback, useEffect, memo, useRef, useReducer } from 'react'; +import React, { useState, useCallback, useEffect, memo, useRef } from 'react'; import store from '../../store/index'; import { EuiForm, @@ -184,23 +184,6 @@ const renderFiles = (files) => { } }; const Sources = () => { - const initialState = { - nameValue: '', - descriptionValue: '', - metaUrfms: [], - }; - - const reducer = (state, action) => { - if (action.type === 'reset') { - return initialState; - } - const result = { ...state }; - result[action.type] = action.value; - return result; - }; - - const [state, dispatch] = useReducer(reducer, initialState); - const [metaUrfms, setMetaUrfms] = useState([]); // const [metaUrfmsCol, setMetaUrfmsCol] = useState([]) const [selectedTabNumber, setSelectedTabNumber] = useState(0); diff --git a/src/pages/user/User.js b/src/pages/user/User.js index daf4dc3..b967b84 100644 --- a/src/pages/user/User.js +++ b/src/pages/user/User.js @@ -98,7 +98,7 @@ const UserList = memo( } ); -const User = (props) => { +const User = () => { const [globalState, globalActions] = store(); const [selectedTabNumber, setSelectedTabNumber] = useState(0); const [open, setOpen] = useState(false); @@ -116,7 +116,6 @@ const User = (props) => { const tableRef = useRef(); const [pageIndex, setPageIndex] = useState(0); const [pageSize, setPageSize] = useState(5); - const [selectedUsers, setSetSelectedUsers] = useState([]); const loadRoles = useCallback(async () => { const _roles = []; @@ -209,10 +208,6 @@ const User = (props) => { }; const totalItemCount = typeof USERS === typeof undefined ? 0 : users.length; - const onSelectionChange = (selectedItems) => { - setSetSelectedUsers(selectedItems); - }; - const pagination = { pageIndex: pageIndex, pageSize: pageSize, diff --git a/src/utils.js b/src/utils.js index 678670d..c3c0fa8 100644 --- a/src/utils.js +++ b/src/utils.js @@ -1,3 +1,6 @@ +import { EuiIcon } from '@elastic/eui'; +import React from 'react'; + export const getGatekeeperBaseUrl = () => { return process.env.REACT_APP_IN_SYLVA_GATEKEEPER_PORT ? `${process.env.REACT_APP_IN_SYLVA_GATEKEEPER_HOST}:${process.env.REACT_APP_IN_SYLVA_GATEKEEPER_PORT}` @@ -10,6 +13,20 @@ export const getLoginUrl = () => { : `${window._env_.REACT_APP_IN_SYLVA_LOGIN_HOST}`; }; +export const redirect = (url, condition = true) => { + if (condition) { + window.location.replace(url); + } +}; + +export const getUrlParam = (parameter, defaultValue) => { + let urlParameter = defaultValue; + if (window.location.href.indexOf(parameter) > -1) { + urlParameter = getUrlParams()[parameter]; + } + return urlParameter; +}; + export const getUrlParams = () => { let lets = {}; window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) { @@ -18,12 +35,82 @@ export const getUrlParams = () => { return lets; }; -export const getUrlParam = (parameter, defaultValue) => { - let urlParameter = defaultValue; - if (window.location.href.indexOf(parameter) > -1) { - urlParameter = getUrlParams()[parameter]; +// Function used to mock statistics for dashboard page +export const getRandomData = (arrayLength) => { + return Array(arrayLength) + .fill() + .map(() => { + return { value: Math.floor(Math.random() * 10) + 1 }; + }); +}; + +export const getUserRoleId = () => { + if (sessionStorage.getItem('roleId').split('#')[0]) { + return parseInt(sessionStorage.getItem('roleId').split('#')[0]); + } else { + return parseInt(sessionStorage.getItem('roleId')); } - return urlParameter; +}; + +export const getSideBarItems = () => { + return [ + { + id: 0, + label: 'Dashboard', + link: '/app/dashboard', + roles: [1], + icon: <EuiIcon type="dashboardApp" size="l" />, + }, + { + id: 1, + label: 'User', + link: '/app/user', + roles: [1], + icon: <EuiIcon type="user" size="l" />, + }, + { + id: 2, + label: 'Roles', + link: '/app/role', + roles: [1], + icon: <EuiIcon type="usersRolesApp" size="l" />, + }, + { + id: 3, + label: 'Groups', + link: '/app/groups', + roles: [1], + icon: <EuiIcon type="users" size="l" />, + }, + { + id: 4, + label: 'Requests', + link: '/app/requests', + roles: [1], + icon: <EuiIcon type="email" size="l" />, + }, + { + id: 5, + label: 'Policies', + link: '/app/policies', + roles: [1, 2], + icon: <EuiIcon type="lockOpen" size="l" />, + }, + { + id: 6, + label: 'Sources', + link: '/app/sources', + roles: [1, 2], + icon: <EuiIcon type="indexManagementApp" size="l" />, + }, + { + id: 7, + label: 'Fields', + link: '/app/fields', + roles: [1], + icon: <EuiIcon type="visTable" size="l" />, + }, + ]; }; export const changeNameToLabel = (object) => { @@ -32,12 +119,6 @@ export const changeNameToLabel = (object) => { return object; }; -export const redirect = (url, condition = true) => { - if (condition) { - window.location.replace(url); - } -}; - export const tokenTimedOut = (validityDurationInMin) => { const timeSinceLastRefresh = Date.now() - sessionStorage.getItem('token_refresh_time'); return timeSinceLastRefresh > validityDurationInMin * 60000; -- GitLab From 59f8e52887263b5da24365007e7e24e7c471f15c Mon Sep 17 00:00:00 2001 From: rbisson <remi.bisson@inrae.fr> Date: Wed, 24 Apr 2024 11:08:38 +0200 Subject: [PATCH 09/19] corrected console errors from MUI themes --- src/components/Header/HeaderView.js | 8 ++++---- src/components/Header/styles.js | 8 ++++---- src/themes/index.js | 4 ++-- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/components/Header/HeaderView.js b/src/components/Header/HeaderView.js index 2fda854..cefee12 100644 --- a/src/components/Header/HeaderView.js +++ b/src/components/Header/HeaderView.js @@ -18,7 +18,7 @@ import { Send as SendIcon, ArrowBack as ArrowBackIcon, } from '@material-ui/icons'; -import { fade } from '@material-ui/core/styles/colorManipulator'; +import { alpha } from '@material-ui/core/styles'; import classNames from 'classnames'; import { Badge, Typography } from '../Wrappers'; import Notification from '../Notification'; @@ -308,15 +308,15 @@ const styles = (theme) => ({ borderRadius: 25, paddingLeft: theme.spacing.unit * 2.5, width: 36, - backgroundColor: fade(theme.palette.common.black, 0), + backgroundColor: alpha(theme.palette.common.black, 0), transition: theme.transitions.create(['background-color', 'width']), '&:hover': { cursor: 'pointer', - backgroundColor: fade(theme.palette.common.black, 0.08), + backgroundColor: alpha(theme.palette.common.black, 0.08), }, }, searchFocused: { - backgroundColor: fade(theme.palette.common.black, 0.08), + backgroundColor: alpha(theme.palette.common.black, 0.08), width: '100%', [theme.breakpoints.up('md')]: { width: 250, diff --git a/src/components/Header/styles.js b/src/components/Header/styles.js index 6bb8a0c..a9a48e8 100644 --- a/src/components/Header/styles.js +++ b/src/components/Header/styles.js @@ -1,5 +1,5 @@ import { makeStyles } from '@material-ui/styles'; -import { fade } from '@material-ui/core/styles/colorManipulator'; +import { alpha } from '@material-ui/core/styles'; export default makeStyles((theme) => ({ logotype: { @@ -36,15 +36,15 @@ export default makeStyles((theme) => ({ borderRadius: 25, paddingLeft: theme.spacing(2.5), width: 36, - backgroundColor: fade(theme.palette.common.black, 0), + backgroundColor: alpha(theme.palette.common.black, 0), transition: theme.transitions.create(['background-color', 'width']), '&:hover': { cursor: 'pointer', - backgroundColor: fade(theme.palette.common.black, 0.08), + backgroundColor: alpha(theme.palette.common.black, 0.08), }, }, searchFocused: { - backgroundColor: fade(theme.palette.common.black, 0.08), + backgroundColor: alpha(theme.palette.common.black, 0.08), width: '100%', [theme.breakpoints.up('md')]: { width: 250, diff --git a/src/themes/index.js b/src/themes/index.js index fd3a2f3..9869367 100644 --- a/src/themes/index.js +++ b/src/themes/index.js @@ -1,6 +1,6 @@ import defaultTheme from './default'; -import { createMuiTheme } from '@material-ui/core'; +import { createTheme } from '@material-ui/core'; const overrides = { typography: { @@ -26,5 +26,5 @@ const overrides = { }; export default { - default: createMuiTheme({ ...defaultTheme, ...overrides }), + default: createTheme({ ...defaultTheme, ...overrides }), }; -- GitLab From 1974e80288da25d7573aba211355161a1b38569d Mon Sep 17 00:00:00 2001 From: rbisson <remi.bisson@inrae.fr> Date: Wed, 24 Apr 2024 11:36:47 +0200 Subject: [PATCH 10/19] removed unused file --- src/components/Sidebar/SidebarView.js | 155 -------------------------- 1 file changed, 155 deletions(-) delete mode 100644 src/components/Sidebar/SidebarView.js diff --git a/src/components/Sidebar/SidebarView.js b/src/components/Sidebar/SidebarView.js deleted file mode 100644 index 5a39146..0000000 --- a/src/components/Sidebar/SidebarView.js +++ /dev/null @@ -1,155 +0,0 @@ -import React from 'react'; -import { Drawer, IconButton, List, withStyles } from '@material-ui/core'; -import { - Home as HomeIcon, - NotificationsNone as NotificationsIcon, - FormatSize as TypographyIcon, - FilterNone as UIElementsIcon, - BorderAll as TableIcon, - QuestionAnswer as SupportIcon, - LibraryBooks as LibraryIcon, - HelpOutline as FAQIcon, - ArrowBack as ArrowBackIcon, -} from '@material-ui/icons'; -import classNames from 'classnames'; - -import SidebarLink from './components/SidebarLink/SidebarLinkContainer'; -import Dot from './components/Dot'; - -const structure = [ - { id: 0, label: 'Dashboard', link: '/app/dashboard', icon: <HomeIcon /> }, - { id: 1, label: 'Typography', link: '/app/typography', icon: <TypographyIcon /> }, - { id: 2, label: 'Tables', link: '/app/tables', icon: <TableIcon /> }, - { - id: 3, - label: 'Notifications', - link: '/app/notifications', - icon: <NotificationsIcon />, - }, - { - id: 4, - label: 'UI Elements', - link: '/app/ui', - icon: <UIElementsIcon />, - children: [ - { label: 'Icons', link: '/app/ui/icons' }, - { label: 'Charts', link: '/app/ui/charts' }, - { label: 'Maps', link: '/app/ui/maps' }, - ], - }, - { id: 5, type: 'divider' }, - { id: 6, type: 'title', label: 'HELP' }, - { id: 7, label: 'Library', link: '', icon: <LibraryIcon /> }, - { id: 8, label: 'Support', link: '', icon: <SupportIcon /> }, - { id: 9, label: 'FAQ', link: '', icon: <FAQIcon /> }, - { id: 10, type: 'divider' }, - { id: 11, type: 'title', label: 'PROJECTS' }, - { id: 12, label: 'My recent', link: '', icon: <Dot size="large" color="secondary" /> }, - { id: 13, label: 'Starred', link: '', icon: <Dot size="large" color="primary" /> }, - { id: 14, label: 'Background', link: '', icon: <Dot size="large" color="secondary" /> }, -]; - -const SidebarView = ({ - classes, - theme, - toggleSidebar, - isSidebarOpened, - isPermanent, - location, -}) => { - return ( - <Drawer - variant={isPermanent ? 'permanent' : 'temporary'} - className={classNames(classes.drawer, { - [classes.drawerOpen]: isSidebarOpened, - [classes.drawerClose]: !isSidebarOpened, - })} - classes={{ - paper: classNames(classes.drawer, { - [classes.drawerOpen]: isSidebarOpened, - [classes.drawerClose]: !isSidebarOpened, - }), - }} - open={isSidebarOpened} - > - <div className={classes.mobileBackButton}> - <IconButton onClick={toggleSidebar}> - <ArrowBackIcon - classes={{ root: classNames(classes.headerIcon, classes.headerIconCollapse) }} - /> - </IconButton> - </div> - <List className={classes.sidebarList}> - {structure.map((link) => ( - <SidebarLink - key={link.id} - location={location} - isSidebarOpened={isSidebarOpened} - {...link} - /> - ))} - </List> - </Drawer> - ); -}; - -const drawerWidth = 240; - -const styles = (theme) => ({ - menuButton: { - marginLeft: 12, - marginRight: 36, - }, - hide: { - display: 'none', - }, - drawer: { - width: drawerWidth, - flexShrink: 0, - whiteSpace: 'nowrap', - top: theme.spacing.unit * 8, - [theme.breakpoints.down('sm')]: { - top: 0, - }, - }, - drawerOpen: { - width: drawerWidth, - transition: theme.transitions.create('width', { - easing: theme.transitions.easing.sharp, - duration: theme.transitions.duration.enteringScreen, - }), - }, - drawerClose: { - transition: theme.transitions.create('width', { - easing: theme.transitions.easing.sharp, - duration: theme.transitions.duration.leavingScreen, - }), - overflowX: 'hidden', - width: theme.spacing.unit * 7 + 40, - [theme.breakpoints.down('sm')]: { - width: drawerWidth, - }, - }, - toolbar: { - ...theme.mixins.toolbar, - [theme.breakpoints.down('sm')]: { - display: 'none', - }, - }, - content: { - flexGrow: 1, - padding: theme.spacing.unit * 3, - }, - mobileBackButton: { - marginTop: theme.spacing.unit * 0.5, - marginLeft: theme.spacing.unit * 3, - [theme.breakpoints.only('sm')]: { - marginTop: theme.spacing.unit * 0.625, - }, - [theme.breakpoints.up('md')]: { - display: 'none', - }, - }, -}); - -export default withStyles(styles, { withTheme: true })(SidebarView); -- GitLab From c8258f9dafa7facc193872831e68579f2a765df3 Mon Sep 17 00:00:00 2001 From: rbisson <remi.bisson@inrae.fr> Date: Wed, 24 Apr 2024 11:56:20 +0200 Subject: [PATCH 11/19] removed unused HeaderView component --- src/components/Header/HeaderView.js | 433 ---------------------------- 1 file changed, 433 deletions(-) delete mode 100644 src/components/Header/HeaderView.js diff --git a/src/components/Header/HeaderView.js b/src/components/Header/HeaderView.js deleted file mode 100644 index cefee12..0000000 --- a/src/components/Header/HeaderView.js +++ /dev/null @@ -1,433 +0,0 @@ -import React from 'react'; -import { - AppBar, - Toolbar, - IconButton, - InputBase, - Menu, - MenuItem, - Fab, - withStyles, -} from '@material-ui/core'; -import { - Menu as MenuIcon, - MailOutline as MailIcon, - NotificationsNone as NotificationsIcon, - Person as AccountIcon, - Search as SearchIcon, - Send as SendIcon, - ArrowBack as ArrowBackIcon, -} from '@material-ui/icons'; -import { alpha } from '@material-ui/core/styles'; -import classNames from 'classnames'; -import { Badge, Typography } from '../Wrappers'; -import Notification from '../Notification'; -import UserAvatar from '../UserAvatar'; - -const messages = [ - { - id: 0, - variant: 'warning', - name: 'Jane Hew', - message: 'Hey! How is it going?', - time: '9:32', - }, - { - id: 1, - variant: 'success', - name: 'Lloyd Brown', - message: 'Check out my new Dashboard', - time: '9:18', - }, - { - id: 2, - variant: 'primary', - name: 'Mark Winstein', - message: 'I want rearrange the appointment', - time: '9:15', - }, - { - id: 3, - variant: 'secondary', - name: 'Liana Dutti', - message: 'Good news from sale department', - time: '9:09', - }, -]; - -const notifications = [ - { id: 0, color: 'warning', message: 'Check out this awesome ticket' }, - { - id: 1, - color: 'success', - type: 'info', - message: 'What is the best way to get ...', - }, - { - id: 2, - color: 'secondary', - type: 'notification', - message: 'This is just a simple notification', - }, - { - id: 3, - color: 'primary', - type: 'e-commerce', - message: '12 new orders has arrived today', - }, -]; - -const Header = ({ classes, isSidebarOpened, toggleSidebar, ...props }) => ( - <AppBar position="fixed" className={classes.appBar}> - <Toolbar className={classes.toolbar}> - <IconButton - color="inherit" - onClick={toggleSidebar} - className={classNames(classes.headerMenuButton, classes.headerMenuButtonCollapse)} - > - {isSidebarOpened ? ( - <ArrowBackIcon - classes={{ - root: classNames(classes.headerIcon, classes.headerIconCollapse), - }} - /> - ) : ( - <MenuIcon - classes={{ - root: classNames(classes.headerIcon, classes.headerIconCollapse), - }} - /> - )} - </IconButton> - <Typography variant="h6" weight="medium" className={classes.logotype}> - React Material Admin - </Typography> - <div className={classes.grow} /> - <div - className={classNames(classes.search, { - [classes.searchFocused]: props.isSearchOpen, - })} - > - <div - className={classNames(classes.searchIcon, { - [classes.searchIconOpened]: props.isSearchOpen, - })} - onClick={props.toggleSearch} - > - <SearchIcon classes={{ root: classes.headerIcon }} /> - </div> - <InputBase - placeholder="Search…" - classes={{ - root: classes.inputRoot, - input: classes.inputInput, - }} - /> - </div> - <IconButton - color="inherit" - aria-haspopup="true" - aria-controls="mail-menu" - onClick={props.openNotificationsMenu} - className={classes.headerMenuButton} - > - <Badge - badgeContent={props.isNotificationsUnread ? notifications.length : null} - colortheme="warning" - > - <NotificationsIcon classes={{ root: classes.headerIcon }} /> - </Badge> - </IconButton> - <IconButton - color="inherit" - aria-haspopup="true" - aria-controls="mail-menu" - onClick={props.openMailMenu} - className={classes.headerMenuButton} - > - <Badge - badgeContent={props.isMailsUnread ? messages.length : null} - color="secondary" - > - <MailIcon classes={{ root: classes.headerIcon }} /> - </Badge> - </IconButton> - <IconButton - aria-haspopup="true" - color="inherit" - className={classes.headerMenuButton} - aria-controls="profile-menu" - onClick={props.openProfileMenu} - > - <AccountIcon classes={{ root: classes.headerIcon }} /> - </IconButton> - <Menu - id="mail-menu" - open={Boolean(props.mailMenu)} - anchorEl={props.mailMenu} - onClose={props.closeMailMenu} - MenuListProps={{ className: classes.headerMenuList }} - className={classes.headerMenu} - classes={{ paper: classes.profileMenu }} - disableAutoFocusItem - > - <div className={classes.profileMenuUser}> - <Typography variant="h4" weight="medium"> - New Messages - </Typography> - <Typography className={classes.profileMenuLink} component="a" color="secondary"> - {messages.length} New Messages - </Typography> - </div> - {messages.map((message) => ( - <MenuItem key={message.id} className={classes.messageNotification}> - <div className={classes.messageNotificationSide}> - <UserAvatar color={message.variant} name={message.name} /> - <Typography size="sm" color="textSecondary"> - {message.time} - </Typography> - </div> - <div - className={classNames( - classes.messageNotificationSide, - classes.messageNotificationBodySide - )} - > - <Typography weight="medium" gutterBottom> - {message.name} - </Typography> - <Typography color="textSecondary">{message.message}</Typography> - </div> - </MenuItem> - ))} - <Fab - variant="extended" - color="primary" - aria-label="Add" - className={classes.sendMessageButton} - > - Send New Message - <SendIcon className={classes.sendButtonIcon} /> - </Fab> - </Menu> - <Menu - id="notifications-menu" - open={Boolean(props.notificationsMenu)} - anchorEl={props.notificationsMenu} - onClose={props.closeNotificationsMenu} - className={classes.headerMenu} - disableAutoFocusItem - > - {notifications.map((notification) => ( - <MenuItem - key={notification.id} - onClick={props.closeNotificationsMenu} - className={classes.headerMenuItem} - > - <Notification {...notification} typographyVariant="inherit" /> - </MenuItem> - ))} - </Menu> - <Menu - id="profile-menu" - open={Boolean(props.profileMenu)} - anchorEl={props.profileMenu} - onClose={props.closeProfileMenu} - className={classes.headerMenu} - classes={{ paper: classes.profileMenu }} - disableAutoFocusItem - > - <div className={classes.profileMenuUser}> - <Typography variant="h4" weight="medium"> - John Smith - </Typography> - <Typography - className={classes.profileMenuLink} - component="a" - color="primary" - href="https://flatlogic.com" - > - Flalogic.com - </Typography> - </div> - <MenuItem className={classNames(classes.profileMenuItem, classes.headerMenuItem)}> - <AccountIcon className={classes.profileMenuIcon} /> Profile - </MenuItem> - <MenuItem className={classNames(classes.profileMenuItem, classes.headerMenuItem)}> - <AccountIcon className={classes.profileMenuIcon} /> Tasks - </MenuItem> - <MenuItem className={classNames(classes.profileMenuItem, classes.headerMenuItem)}> - <AccountIcon className={classes.profileMenuIcon} /> Messages - </MenuItem> - <div className={classes.profileMenuUser}> - <Typography - className={classes.profileMenuLink} - color="primary" - onClick={props.signOut} - > - Sign Out - </Typography> - </div> - </Menu> - </Toolbar> - </AppBar> -); - -const styles = (theme) => ({ - logotype: { - color: 'white', - marginLeft: theme.spacing.unit * 2.5, - marginRight: theme.spacing.unit * 2.5, - fontWeight: 500, - fontSize: 18, - whiteSpace: 'nowrap', - [theme.breakpoints.down('xs')]: { - display: 'none', - }, - }, - appBar: { - width: '100vw', - zIndex: theme.zIndex.drawer + 1, - transition: theme.transitions.create(['margin'], { - easing: theme.transitions.easing.sharp, - duration: theme.transitions.duration.leavingScreen, - }), - }, - toolbar: { - paddingLeft: theme.spacing.unit * 2, - paddingRight: theme.spacing.unit * 2, - }, - hide: { - display: 'none', - }, - grow: { - flexGrow: 1, - }, - search: { - position: 'relative', - borderRadius: 25, - paddingLeft: theme.spacing.unit * 2.5, - width: 36, - backgroundColor: alpha(theme.palette.common.black, 0), - transition: theme.transitions.create(['background-color', 'width']), - '&:hover': { - cursor: 'pointer', - backgroundColor: alpha(theme.palette.common.black, 0.08), - }, - }, - searchFocused: { - backgroundColor: alpha(theme.palette.common.black, 0.08), - width: '100%', - [theme.breakpoints.up('md')]: { - width: 250, - }, - }, - searchIcon: { - width: 36, - right: 0, - height: '100%', - position: 'absolute', - display: 'flex', - alignItems: 'center', - justifyContent: 'center', - transition: theme.transitions.create('right'), - '&:hover': { - cursor: 'pointer', - }, - }, - searchIconOpened: { - right: theme.spacing.unit * 1.25, - }, - inputRoot: { - color: 'inherit', - width: '100%', - }, - inputInput: { - height: 36, - padding: 0, - paddingRight: 36 + theme.spacing.unit * 1.25, - width: '100%', - }, - messageContent: { - display: 'flex', - flexDirection: 'column', - }, - headerMenu: { - marginTop: theme.spacing.unit * 7, - }, - headerMenuList: { - display: 'flex', - flexDirection: 'column', - }, - headerMenuItem: { - '&:hover, &:focus': { - backgroundColor: theme.palette.primary.main, - color: 'white', - }, - }, - headerMenuButton: { - marginLeft: theme.spacing.unit * 2, - padding: theme.spacing.unit / 2, - }, - headerMenuButtonCollapse: { - marginRight: theme.spacing.unit * 2, - }, - headerIcon: { - fontSize: 28, - color: 'rgba(255, 255, 255, 0.35)', - }, - headerIconCollapse: { - color: 'white', - }, - profileMenu: { - minWidth: 265, - }, - profileMenuUser: { - display: 'flex', - flexDirection: 'column', - padding: theme.spacing.unit * 2, - }, - profileMenuItem: { - color: theme.palette.text.hint, - }, - profileMenuIcon: { - marginRight: theme.spacing.unit * 2, - color: theme.palette.text.hint, - }, - profileMenuLink: { - fontSize: 16, - textDecoration: 'none', - '&:hover': { - cursor: 'pointer', - }, - }, - messageNotification: { - height: 'auto', - display: 'flex', - alignItems: 'center', - '&:hover, &:focus': { - backgroundColor: theme.palette.background.light, - }, - }, - messageNotificationSide: { - display: 'flex', - flexDirection: 'column', - alignItems: 'center', - marginRight: theme.spacing.unit * 2, - }, - messageNotificationBodySide: { - alignItems: 'flex-start', - marginRight: 0, - }, - sendMessageButton: { - margin: theme.spacing.unit * 4, - marginTop: theme.spacing.unit * 2, - marginBottom: theme.spacing.unit * 2, - textTransform: 'none', - }, - sendButtonIcon: { - marginLeft: theme.spacing.unit * 2, - }, -}); - -export default withStyles(styles)(Header); -- GitLab From 25c60beed4d588192c89869826ffc4739ea7a478 Mon Sep 17 00:00:00 2001 From: rbisson <remi.bisson@inrae.fr> Date: Wed, 24 Apr 2024 12:22:18 +0200 Subject: [PATCH 12/19] [public/index.html]: clean file --- public/index.html | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/public/index.html b/public/index.html index 708d670..ccfa06f 100755 --- a/public/index.html +++ b/public/index.html @@ -1,15 +1,10 @@ <!DOCTYPE html> <html lang="en"> - <head> <meta charset="utf-8" /> <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.png" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <meta name="theme-color" content="#000000" /> - <!-- - manifest.json provides metadata used when your web app is installed on a - user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/ - --> <link rel="manifest" href="%PUBLIC_URL%/manifest.json" /> <!-- Notice the use of %PUBLIC_URL% in the tags above. @@ -20,10 +15,9 @@ work correctly both with client-side routing and a non-root public URL. Learn how to configure a non-root public URL by running `npm run build`. --> - <title>INRA PACA IN-SYLVA</title> + <title>INRAE PACA IN-SYLVA</title> <script src="%PUBLIC_URL%/env-config.js"></script> </head> - <body style="font-family: 'Roboto', sans-serif;"> <noscript>You need to enable JavaScript to run this app.</noscript> <div id="root"></div> @@ -38,5 +32,4 @@ To create a production bundle, use `npm run build` or `yarn build`. --> </body> - </html> -- GitLab From cf9be057176f409789862cb3aad53c03a0502ed5 Mon Sep 17 00:00:00 2001 From: rbisson <remi.bisson@inrae.fr> Date: Wed, 24 Apr 2024 12:37:04 +0200 Subject: [PATCH 13/19] [public/index.html]: clean file --- public/index.html | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/public/index.html b/public/index.html index ccfa06f..b62a88e 100755 --- a/public/index.html +++ b/public/index.html @@ -21,15 +21,5 @@ <body style="font-family: 'Roboto', sans-serif;"> <noscript>You need to enable JavaScript to run this app.</noscript> <div id="root"></div> - <!-- - This HTML file is a template. - If you open it directly in the browser, you will see an empty page. - - You can add webfonts, meta tags, or analytics to this file. - The build step will place the bundled scripts into the <body> tag. - - To begin the development, run `npm start` or `yarn start`. - To create a production bundle, use `npm run build` or `yarn build`. - --> </body> </html> -- GitLab From c6d65667a597100bff73f10bafe2e618ddbb2691 Mon Sep 17 00:00:00 2001 From: rbisson <remi.bisson@inrae.fr> Date: Wed, 24 Apr 2024 12:44:54 +0200 Subject: [PATCH 14/19] [manifest.json]: corrected project name --- public/manifest.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/public/manifest.json b/public/manifest.json index 927f0f6..6ed6763 100755 --- a/public/manifest.json +++ b/public/manifest.json @@ -1,6 +1,6 @@ { - "short_name": "IN-SILVA", - "name": "INRA - Provence-Alpes-Cote d'Azur Centre", + "short_name": "IN-SYLVA", + "name": "INRAE PACA - IN-SYLVA", "icons": [ { "src": "favicon.png", @@ -12,4 +12,4 @@ "display": "standalone", "theme_color": "#536DFE", "background_color": "#ffffff" -} \ No newline at end of file +} -- GitLab From 1253cf1890841c021dbbdb572bae89251d2590e6 Mon Sep 17 00:00:00 2001 From: rbisson <remi.bisson@inrae.fr> Date: Wed, 24 Apr 2024 15:14:53 +0200 Subject: [PATCH 15/19] removed unused components --- src/actions/policy.js | 69 +++----- src/actions/source.js | 24 +-- src/actions/user.js | 12 +- src/components/Notification/Notification.js | 115 ------------- src/components/Notification/package.json | 6 - src/components/Notification/styles.js | 47 ----- src/pages/dashboard/mock.js | 180 -------------------- 7 files changed, 46 insertions(+), 407 deletions(-) delete mode 100644 src/components/Notification/Notification.js delete mode 100644 src/components/Notification/package.json delete mode 100644 src/components/Notification/styles.js delete mode 100644 src/pages/dashboard/mock.js diff --git a/src/actions/policy.js b/src/actions/policy.js index 9e0d5d1..1cd9e24 100644 --- a/src/actions/policy.js +++ b/src/actions/policy.js @@ -9,12 +9,11 @@ export const createPolicy = async (store, name, kcId, request = igClient) => { store.setState({ isLoading: true }); request.token = sessionStorage.getItem('access_token'); - const policy = await request.createPolicy({ name, kcId }); - - if (policy) { + const result = await request.createPolicy({ name, kcId }); + if (result) { const status = 'SUCCESS'; store.setState({ status, isLoading: false }); - return policy; + return result; } } catch (error) { const isError404 = error.response && error.response.status === 404; @@ -33,12 +32,11 @@ export const createPolicyField = async ( store.setState({ isLoading: true }); request.token = sessionStorage.getItem('access_token'); - const policyField = await request.createPolicyField({ policyId, stdFieldId }); - - if (policyField) { + const result = await request.createPolicyField({ policyId, stdFieldId }); + if (result) { const status = 'SUCCESS'; store.setState({ status, isLoading: false }); - return policyField; + return result; } } catch (error) { const isError404 = error.response && error.response.status === 404; @@ -52,19 +50,18 @@ export const updatePolicy = async ( id, name, sourceId, - isDeafault, + isDefault, request = igClient ) => { try { store.setState({ isLoading: true }); request.token = sessionStorage.getItem('access_token'); - const uPolicy = await request.updatePolicy({ id, name, sourceId, isDeafault }); - - if (uPolicy) { + const result = await request.updatePolicy({ id, name, sourceId, isDefault }); + if (result) { const status = 'SUCCESS'; store.setState({ status, isLoading: false }); - return uPolicy; + return result; } } catch (error) { const isError404 = error.response && error.response.status === 404; @@ -84,12 +81,11 @@ export const updatePolicyField = async ( store.setState({ isLoading: true }); request.token = sessionStorage.getItem('access_token'); - const policyField = await request.updatePolicyField({ id, policyId, stdFieldId }); - - if (policyField) { + const result = await request.updatePolicyField({ id, policyId, stdFieldId }); + if (result) { const status = 'SUCCESS'; store.setState({ status, isLoading: false }); - return policyField; + return result; } } catch (error) { const isError404 = error.response && error.response.status === 404; @@ -104,7 +100,6 @@ export const deletePolicyField = async (store, id, request = igClient) => { request.token = sessionStorage.getItem('access_token'); const result = await request.deletePolicyField({ id }); - if (result) { const status = 'SUCCESS'; store.setState({ status, isLoading: false }); @@ -123,7 +118,6 @@ export const deletePolicy = async (store, id, request = igClient) => { request.token = sessionStorage.getItem('access_token'); const result = await request.deletePolicy({ id }); - if (result) { const status = 'SUCCESS'; store.setState({ status, isLoading: false }); @@ -141,12 +135,11 @@ export const getPolicies = async (store, request = igClient) => { store.setState({ isLoading: true }); request.token = sessionStorage.getItem('access_token'); - const policies = await request.getPolicies({}); - - if (policies) { + const result = await request.getPolicies({}); + if (result) { const status = 'SUCCESS'; store.setState({ status, isLoading: false }); - return policies; + return result; } } catch (error) { const isError404 = error.response && error.response.status === 404; @@ -161,7 +154,6 @@ export const getPoliciesByUser = async (store, kc_id, request = igClient) => { request.token = sessionStorage.getItem('access_token'); const result = await request.getPoliciesByUser(kc_id); - if (result) { const status = 'SUCCESS'; store.setState({ status, isLoading: false }); @@ -180,7 +172,6 @@ export const getPoliciesWithSourcesByUser = async (store, kc_id, request = igCli request.token = sessionStorage.getItem('access_token'); const result = await request.getPoliciesWithSourcesByUser(kc_id); - if (result) { const status = 'SUCCESS'; store.setState({ status, isLoading: false }); @@ -198,12 +189,11 @@ export const getAssignedPolicies = async (store, policyId, request = igClient) = store.setState({ isLoading: true }); request.token = sessionStorage.getItem('access_token'); - const assignedPolicies = await request.getAssignedPolicies({ policyId }); - - if (assignedPolicies) { + const result = await request.getAssignedPolicies({ policyId }); + if (result) { const status = 'SUCCESS'; store.setState({ status, isLoading: false }); - return assignedPolicies; + return result; } } catch (error) { const isError404 = error.response && error.response.status === 404; @@ -217,12 +207,11 @@ export const getPoliciesWithSources = async (store, request = igClient) => { store.setState({ isLoading: true }); request.token = sessionStorage.getItem('access_token'); - const policiesWithSources = await request.getPoliciesWithSources(); - - if (policiesWithSources) { + const result = await request.getPoliciesWithSources(); + if (result) { const status = 'SUCCESS'; store.setState({ status, isLoading: false }); - return policiesWithSources; + return result; } } catch (error) { const isError404 = error.response && error.response.status === 404; @@ -236,12 +225,11 @@ export const getGroupDetailsByPolicy = async (store, policyId, request = igClien store.setState({ isLoading: true }); request.token = sessionStorage.getItem('access_token'); - const groupDetailsByPolicy = await request.getGroupDetailsByPolicy({ policyId }); - - if (groupDetailsByPolicy) { + const result = await request.getGroupDetailsByPolicy({ policyId }); + if (result) { const status = 'SUCCESS'; store.setState({ status, isLoading: false }); - return groupDetailsByPolicy; + return result; } } catch (error) { const isError404 = error.response && error.response.status === 404; @@ -260,12 +248,11 @@ export const createPolicySource = async ( store.setState({ isLoading: true }); request.token = sessionStorage.getItem('access_token'); - const policySource = await request.createPolicySource({ policyId, sourceId }); - - if (policySource) { + const result = await request.createPolicySource({ policyId, sourceId }); + if (result) { const status = 'SUCCESS'; store.setState({ status, isLoading: false }); - return policySource; + return result; } } catch (error) { const isError404 = error.response && error.response.status === 404; diff --git a/src/actions/source.js b/src/actions/source.js index f2e1b87..cf41d7d 100644 --- a/src/actions/source.js +++ b/src/actions/source.js @@ -74,8 +74,8 @@ export const createStdField = async ( field_type, cardinality, values, - ispublic, - isoptional, + isPublic, + isOptional, request = smClient ) => { try { @@ -90,8 +90,8 @@ export const createStdField = async ( field_type, cardinality, values, - ispublic, - isoptional + isPublic, + isOptional ); if (result) { const status = 'SUCCESS'; @@ -113,8 +113,8 @@ export const createAddtlField = async ( field_type, cardinality, values, - ispublic, - isoptional, + isPublic, + isOptional, request = smClient ) => { try { @@ -129,8 +129,8 @@ export const createAddtlField = async ( field_type, cardinality, values, - ispublic, - isoptional + isPublic, + isOptional ); if (result) { const status = 'SUCCESS'; @@ -152,8 +152,8 @@ export const updateStdField = async ( field_type, cardinality, values, - ispublic, - isoptional, + isPublic, + isOptional, request = smClient ) => { try { @@ -168,8 +168,8 @@ export const updateStdField = async ( field_type, cardinality, values, - ispublic, - isoptional + isPublic, + isOptional ); if (result) { const status = 'SUCCESS'; diff --git a/src/actions/user.js b/src/actions/user.js index 2930d86..fb7f9d4 100644 --- a/src/actions/user.js +++ b/src/actions/user.js @@ -46,17 +46,17 @@ export const findUser = async (store, request = igClient) => { } }; -export const updateUser = async (store, puser, request = igClient) => { +export const updateUser = async (store, user, request = igClient) => { try { store.setState({ isLoading: true }); request.token = sessionStorage.getItem('access_token'); - const user = await request.updateUser({ - id: puser.id, - firstName: puser.firstName, - lastName: puser.lastName, + const result = await request.updateUser({ + id: user.id, + firstName: user.firstName, + lastName: user.lastName, }); - if (user) { + if (result) { const status = 'SUCCESS'; store.setState({ status, isLoading: false }); } diff --git a/src/components/Notification/Notification.js b/src/components/Notification/Notification.js deleted file mode 100644 index c9d0724..0000000 --- a/src/components/Notification/Notification.js +++ /dev/null @@ -1,115 +0,0 @@ -import React from 'react'; -import { Button } from '@material-ui/core'; -import { - NotificationsNone as NotificationsIcon, - ThumbUp as ThumbUpIcon, - ShoppingCart as ShoppingCartIcon, - LocalOffer as TicketIcon, - BusinessCenter as DeliveredIcon, - SmsFailed as FeedbackIcon, - DiscFull as DiscIcon, - Email as MessageIcon, - Report as ReportIcon, - Error as DefenceIcon, - AccountBox as CustomerIcon, - Done as ShippedIcon, - Publish as UploadIcon, -} from '@material-ui/icons'; -import { useTheme } from '@material-ui/styles'; -import classnames from 'classnames'; -import tinycolor from 'tinycolor2'; - -// styles -import useStyles from './styles'; - -// components -import { Typography } from '../Wrappers'; - -const typesIcons = { - 'e-commerce': <ShoppingCartIcon />, - notification: <NotificationsIcon />, - offer: <TicketIcon />, - info: <ThumbUpIcon />, - message: <MessageIcon />, - feedback: <FeedbackIcon />, - customer: <CustomerIcon />, - shipped: <ShippedIcon />, - delivered: <DeliveredIcon />, - defence: <DefenceIcon />, - report: <ReportIcon />, - upload: <UploadIcon />, - disc: <DiscIcon />, -}; - -export default function Notification({ variant, ...props }) { - const classes = useStyles(); - const theme = useTheme(); - - const icon = getIconByType(props.type); - const iconWithStyles = React.cloneElement(icon, { - classes: { - root: classes.notificationIcon, - }, - style: { - color: - variant !== 'contained' && - theme.palette[props.color] && - theme.palette[props.color].main, - }, - }); - - return ( - <div - className={classnames(classes.notificationContainer, props.className, { - [classes.notificationContained]: variant === 'contained', - [classes.notificationContainedShadowless]: props.shadowless, - })} - style={{ - backgroundColor: - variant === 'contained' && - theme.palette[props.color] && - theme.palette[props.color].main, - }} - > - <div - className={classnames(classes.notificationIconContainer, { - [classes.notificationIconContainerContained]: variant === 'contained', - [classes.notificationIconContainerRounded]: variant === 'rounded', - })} - style={{ - backgroundColor: - variant === 'rounded' && - theme.palette[props.color] && - tinycolor(theme.palette[props.color].main).setAlpha(0.15).toRgbString(), - }} - > - {iconWithStyles} - </div> - <div className={classes.messageContainer}> - <Typography - className={classnames({ - [classes.containedTypography]: variant === 'contained', - })} - variant={props.typographyVariant} - size={variant !== 'contained' && !props.typographyVariant && 'md'} - > - {props.message} - </Typography> - {props.extraButton && props.extraButtonClick && ( - <Button - onClick={props.extraButtonClick} - disableRipple - className={classes.extraButton} - > - {props.extraButton} - </Button> - )} - </div> - </div> - ); -} - -// #################################################################### -function getIconByType(type = 'offer') { - return typesIcons[type]; -} diff --git a/src/components/Notification/package.json b/src/components/Notification/package.json deleted file mode 100644 index d016252..0000000 --- a/src/components/Notification/package.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "name": "Notification", - "version": "0.0.0", - "private": true, - "main": "Notification.js" -} diff --git a/src/components/Notification/styles.js b/src/components/Notification/styles.js deleted file mode 100644 index 24a75ab..0000000 --- a/src/components/Notification/styles.js +++ /dev/null @@ -1,47 +0,0 @@ -import { makeStyles } from '@material-ui/styles'; - -export default makeStyles((theme) => ({ - notificationContainer: { - display: 'flex', - alignItems: 'center', - }, - notificationContained: { - borderRadius: 45, - height: 45, - boxShadow: theme.customShadows.widgetDark, - }, - notificationContainedShadowless: { - boxShadow: 'none', - }, - notificationIconContainer: { - minWidth: 45, - height: 45, - borderRadius: 45, - display: 'flex', - alignItems: 'center', - justifyContent: 'center', - fontSize: 24, - }, - notificationIconContainerContained: { - fontSize: 18, - color: '#FFFFFF80', - }, - notificationIconContainerRounded: { - marginRight: theme.spacing(2), - }, - containedTypography: { - color: 'white', - }, - messageContainer: { - display: 'flex', - alignItems: 'center', - justifyContent: 'space-between', - flexGrow: 1, - }, - extraButton: { - color: 'white', - '&:hover, &:focus': { - background: 'transparent', - }, - }, -})); diff --git a/src/pages/dashboard/mock.js b/src/pages/dashboard/mock.js deleted file mode 100644 index 2f4e484..0000000 --- a/src/pages/dashboard/mock.js +++ /dev/null @@ -1,180 +0,0 @@ -export default { - tasks: [ - { - id: 0, - type: 'Meeting', - title: 'Meeting with Andrew Piker', - time: '9:00', - }, - { - id: 1, - type: 'Call', - title: 'Call with HT Company', - time: '12:00', - }, - { - id: 2, - type: 'Meeting', - title: 'Meeting with Zoe Alison', - time: '14:00', - }, - { - id: 3, - type: 'Interview', - title: 'Interview with HR', - time: '15:00', - }, - ], - bigStat: [ - { - product: 'Light Blue', - total: { - monthly: 4232, - weekly: 1465, - daily: 199, - percent: { value: 3.7, profit: false }, - }, - color: 'primary', - registrations: { - monthly: { value: 830, profit: false }, - weekly: { value: 215, profit: true }, - daily: { value: 33, profit: true }, - }, - bounce: { - monthly: { value: 4.5, profit: false }, - weekly: { value: 3, profit: true }, - daily: { value: 3.25, profit: true }, - }, - }, - { - product: 'Sing App', - total: { - monthly: 754, - weekly: 180, - daily: 27, - percent: { value: 2.5, profit: true }, - }, - color: 'warning', - registrations: { - monthly: { value: 32, profit: true }, - weekly: { value: 8, profit: true }, - daily: { value: 2, profit: false }, - }, - bounce: { - monthly: { value: 2.5, profit: true }, - weekly: { value: 4, profit: false }, - daily: { value: 4.5, profit: false }, - }, - }, - { - product: 'RNS', - total: { - monthly: 1025, - weekly: 301, - daily: 44, - percent: { value: 3.1, profit: true }, - }, - color: 'secondary', - registrations: { - monthly: { value: 230, profit: true }, - weekly: { value: 58, profit: false }, - daily: { value: 15, profit: false }, - }, - bounce: { - monthly: { value: 21.5, profit: false }, - weekly: { value: 19.35, profit: false }, - daily: { value: 10.1, profit: true }, - }, - }, - ], - notifications: [ - { - id: 0, - icon: 'thumbs-up', - color: 'primary', - content: 'Ken <span className="fw-semi-bold">accepts</span> your invitation', - }, - { - id: 1, - icon: 'file', - color: 'success', - content: 'Report from LT Company', - }, - { - id: 2, - icon: 'envelope', - color: 'danger', - content: '4 <span className="fw-semi-bold">Private</span> Mails', - }, - { - id: 3, - icon: 'comment', - color: 'success', - content: '3 <span className="fw-semi-bold">Comments</span> to your Post', - }, - { - id: 4, - icon: 'cog', - color: 'light', - content: 'New <span className="fw-semi-bold">Version</span> of RNS app', - }, - { - id: 5, - icon: 'bell', - color: 'info', - content: '15 <span className="fw-semi-bold">Notifications</span> from Social Apps', - }, - ], - table: [ - { - id: 0, - name: 'Mark Otto', - email: 'ottoto@wxample.com', - product: 'ON the Road', - price: '$25 224.2', - date: '11 May 2017', - city: 'Otsego', - status: 'Sent', - }, - { - id: 1, - name: 'Jacob Thornton', - email: 'thornton@wxample.com', - product: 'HP Core i7', - price: '$1 254.2', - date: '4 Jun 2017', - city: 'Fivepointville', - status: 'Sent', - }, - { - id: 2, - name: 'Larry the Bird', - email: 'bird@wxample.com', - product: 'Air Pro', - price: '$1 570.0', - date: '27 Aug 2017', - city: 'Leadville North', - status: 'Pending', - }, - { - id: 3, - name: 'Joseph May', - email: 'josephmay@wxample.com', - product: 'Version Control', - price: '$5 224.5', - date: '19 Feb 2018', - city: 'Seaforth', - status: 'Declined', - }, - { - id: 4, - name: 'Peter Horadnia', - email: 'horadnia@wxample.com', - product: "Let's Dance", - price: '$43 594.7', - date: '1 Mar 2018', - city: 'Hanoverton', - status: 'Sent', - }, - ], -}; -- GitLab From f76043707a3eef09cc9d74081388fd312d024f7f Mon Sep 17 00:00:00 2001 From: rbisson <remi.bisson@inrae.fr> Date: Wed, 24 Apr 2024 15:30:18 +0200 Subject: [PATCH 16/19] removed unused components and pages --- src/components/PageTitle/PageTitle.js | 30 --- src/components/PageTitle/package.json | 6 - src/components/PageTitle/styles.js | 20 -- src/components/UserAvatar/UserAvatar.js | 27 --- src/components/UserAvatar/package.json | 6 - src/components/UserAvatar/styles.js | 15 -- src/components/Widget/WidgetView.js | 116 ---------- src/pages/charts/Charts.js | 218 ------------------- src/pages/charts/components/ApexHeatmap.js | 114 ---------- src/pages/charts/components/ApexLineChart.js | 63 ------ src/pages/charts/package.json | 6 - 11 files changed, 621 deletions(-) delete mode 100644 src/components/PageTitle/PageTitle.js delete mode 100644 src/components/PageTitle/package.json delete mode 100644 src/components/PageTitle/styles.js delete mode 100644 src/components/UserAvatar/UserAvatar.js delete mode 100644 src/components/UserAvatar/package.json delete mode 100644 src/components/UserAvatar/styles.js delete mode 100644 src/components/Widget/WidgetView.js delete mode 100644 src/pages/charts/Charts.js delete mode 100644 src/pages/charts/components/ApexHeatmap.js delete mode 100644 src/pages/charts/components/ApexLineChart.js delete mode 100644 src/pages/charts/package.json diff --git a/src/components/PageTitle/PageTitle.js b/src/components/PageTitle/PageTitle.js deleted file mode 100644 index 14e0f37..0000000 --- a/src/components/PageTitle/PageTitle.js +++ /dev/null @@ -1,30 +0,0 @@ -import React from 'react'; -import { Button } from '@material-ui/core'; - -// styles -import useStyles from './styles'; - -// components -import { Typography } from '../Wrappers'; - -export default function PageTitle(props) { - const classes = useStyles(); - - return ( - <div className={classes.pageTitleContainer}> - <Typography className={classes.typo} variant="h1" size="sm"> - {props.title} - </Typography> - {props.button && ( - <Button - classes={{ root: classes.button }} - variant="contained" - size="large" - color="secondary" - > - {props.button} - </Button> - )} - </div> - ); -} diff --git a/src/components/PageTitle/package.json b/src/components/PageTitle/package.json deleted file mode 100644 index 2bbe12c..0000000 --- a/src/components/PageTitle/package.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "name": "PageTitle", - "version": "0.0.0", - "private": true, - "main": "PageTitle.js" -} diff --git a/src/components/PageTitle/styles.js b/src/components/PageTitle/styles.js deleted file mode 100644 index 2264225..0000000 --- a/src/components/PageTitle/styles.js +++ /dev/null @@ -1,20 +0,0 @@ -import { makeStyles } from '@material-ui/styles'; - -export default makeStyles((theme) => ({ - pageTitleContainer: { - display: 'flex', - justifyContent: 'space-between', - marginBottom: theme.spacing(4), - marginTop: theme.spacing(5), - }, - typo: { - color: theme.palette.text.hint, - }, - button: { - boxShadow: theme.customShadows.widget, - textTransform: 'none', - '&:active': { - boxShadow: theme.customShadows.widgetWide, - }, - }, -})); diff --git a/src/components/UserAvatar/UserAvatar.js b/src/components/UserAvatar/UserAvatar.js deleted file mode 100644 index e0e5e34..0000000 --- a/src/components/UserAvatar/UserAvatar.js +++ /dev/null @@ -1,27 +0,0 @@ -import React from 'react'; -import { useTheme } from '@material-ui/styles'; - -// styles -import useStyles from './styles'; - -// components -import { Typography } from '../Wrappers'; - -export default function UserAvatar({ color = 'primary', ...props }) { - const classes = useStyles(); - const theme = useTheme(); - - const letters = props.name - .split(' ') - .map((word) => word[0]) - .join(''); - - return ( - <div - className={classes.avatar} - style={{ backgroundColor: theme.palette[color].main }} - > - <Typography className={classes.text}>{letters}</Typography> - </div> - ); -} diff --git a/src/components/UserAvatar/package.json b/src/components/UserAvatar/package.json deleted file mode 100644 index ed1f9d1..0000000 --- a/src/components/UserAvatar/package.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "name": "UserAvatar", - "version": "0.0.0", - "private": true, - "main": "UserAvatar.js" -} diff --git a/src/components/UserAvatar/styles.js b/src/components/UserAvatar/styles.js deleted file mode 100644 index f507e14..0000000 --- a/src/components/UserAvatar/styles.js +++ /dev/null @@ -1,15 +0,0 @@ -import { makeStyles } from '@material-ui/styles'; - -export default makeStyles(() => ({ - avatar: { - width: 30, - height: 30, - display: 'flex', - alignItems: 'center', - justifyContent: 'center', - borderRadius: '50%', - }, - text: { - color: 'white', - }, -})); diff --git a/src/components/Widget/WidgetView.js b/src/components/Widget/WidgetView.js deleted file mode 100644 index c4da6cc..0000000 --- a/src/components/Widget/WidgetView.js +++ /dev/null @@ -1,116 +0,0 @@ -import React from 'react'; -import classnames from 'classnames'; -import { Paper, IconButton, Menu, MenuItem, withStyles } from '@material-ui/core'; -import { MoreVert as MoreIcon } from '@material-ui/icons'; -import Typography from '@material-ui/core/es/Typography/Typography'; - -const Widget = ({ - classes, - children, - title, - noBodyPadding, - bodyClass, - className, - disableWidgetMenu, - ...props -}) => ( - <div className={classes.widgetWrapper}> - <Paper className={classes.paper} classes={{ root: classes.widgetRoot }}> - <div className={classes.widgetHeader}> - {props.header ? ( - props.header - ) : ( - <React.Fragment> - <Typography variant="h5" color="textSecondary"> - {title} - </Typography> - {!disableWidgetMenu && ( - <IconButton - color="primary" - classes={{ root: classes.moreButton }} - aria-owns="widget-menu" - aria-haspopup="true" - onClick={() => props.setMoreMenuOpen(true)} - ref={props.setMoreButtonRef} - > - <MoreIcon /> - </IconButton> - )} - </React.Fragment> - )} - </div> - <div - className={classnames(classes.widgetBody, { - [classes.noPadding]: noBodyPadding, - [bodyClass]: bodyClass, - })} - > - {children} - </div> - </Paper> - <Menu - id="widget-menu" - open={props.isMoreMenuOpen} - anchorEl={props.moreButtonRef} - onClose={() => props.setMoreMenuOpen(false)} - disableAutoFocusItem - > - <MenuItem> - <Typography>Edit</Typography> - </MenuItem> - <MenuItem> - <Typography>Copy</Typography> - </MenuItem> - <MenuItem> - <Typography>Delete</Typography> - </MenuItem> - <MenuItem> - <Typography>Print</Typography> - </MenuItem> - </Menu> - </div> -); - -const styles = (theme) => ({ - widgetWrapper: { - display: 'flex', - minHeight: '100%', - }, - widgetHeader: { - padding: theme.spacing.unit * 3, - paddingBottom: theme.spacing.unit, - display: 'flex', - justifyContent: 'space-between', - alignItems: 'center', - }, - widgetRoot: { - boxShadow: theme.customShadows.widget, - }, - widgetBody: { - paddingBottom: theme.spacing.unit * 3, - paddingRight: theme.spacing.unit * 3, - paddingLeft: theme.spacing.unit * 3, - }, - noPadding: { - padding: 0, - }, - paper: { - display: 'flex', - flexDirection: 'column', - flexGrow: 1, - overflow: 'hidden', - }, - moreButton: { - margin: -theme.spacing.unit, - padding: 0, - width: 40, - height: 40, - color: theme.palette.text.hint, - '&:hover': { - backgroundColor: theme.palette.primary.main, - color: 'rgba(255, 255, 255, 0.35)', - }, - }, -}); - -export default withStyles(styles, { withTheme: true })(Widget); diff --git a/src/pages/charts/Charts.js b/src/pages/charts/Charts.js deleted file mode 100644 index 28b3152..0000000 --- a/src/pages/charts/Charts.js +++ /dev/null @@ -1,218 +0,0 @@ -import React, { useState } from 'react'; -import { Grid } from '@material-ui/core'; -import { useTheme } from '@material-ui/styles'; -import { - CartesianGrid, - Legend, - Line, - LineChart, - Pie, - PieChart, - ResponsiveContainer, - Sector, - Tooltip, - XAxis, - YAxis, -} from 'recharts'; -import Widget from '../../components/Widget/Widget'; -import ApexLineChart from './components/ApexLineChart'; -import ApexHeatmap from './components/ApexHeatmap'; -import PageTitle from '../../components/PageTitle/PageTitle'; - -const lineChartData = [ - { - name: 'Page A', - uv: 4000, - pv: 2400, - amt: 2400, - }, - { - name: 'Page B', - uv: 3000, - pv: 1398, - amt: 2210, - }, - { - name: 'Page C', - uv: 2000, - pv: 9800, - amt: 2290, - }, - { - name: 'Page D', - uv: 2780, - pv: 3908, - amt: 2000, - }, - { - name: 'Page E', - uv: 1890, - pv: 4800, - amt: 2181, - }, - { - name: 'Page F', - uv: 2390, - pv: 3800, - amt: 2500, - }, - { - name: 'Page G', - uv: 3490, - pv: 4300, - amt: 2100, - }, -]; - -const pieChartData = [ - { name: 'Group A', value: 400 }, - { name: 'Group B', value: 300 }, - { name: 'Group C', value: 300 }, - { name: 'Group D', value: 200 }, -]; - -export default function Charts() { - const theme = useTheme(); - let [activeIndex, setActiveIndexId] = useState(0); - - return ( - <> - <PageTitle title="Charts Page - Data Display" button="Latest Reports" /> - <Grid container spacing={4}> - <Grid item xs={12} md={6}> - <Widget title="Apex Line Chart" upperTitle noBodyPadding> - <ApexLineChart /> - </Widget> - </Grid> - <Grid item xs={12} md={6}> - <Widget title="Apex Heatmap" upperTitle noBodyPadding> - <ApexHeatmap /> - </Widget> - </Grid> - <Grid item xs={12} md={8}> - <Widget title="Simple Line Chart" noBodyPadding upperTitle> - <ResponsiveContainer width="100%" height={350}> - <LineChart - width={500} - height={300} - data={lineChartData} - margin={{ - top: 5, - right: 30, - left: 20, - bottom: 5, - }} - > - <CartesianGrid strokeDasharray="3 3" /> - <XAxis dataKey="name" /> - <YAxis /> - <Tooltip /> - <Legend /> - <Line - type="monotone" - dataKey="pv" - stroke={theme.palette.primary.main} - activeDot={{ r: 8 }} - /> - <Line - type="monotone" - dataKey="uv" - stroke={theme.palette.secondary.main} - /> - </LineChart> - </ResponsiveContainer> - </Widget> - </Grid> - <Grid item xs={12} md={4}> - <Widget title="Pie Chart with Tooltips" noBodyPadding upperTitle> - <ResponsiveContainer width="100%" height={300}> - <PieChart width={200} height={300}> - <Pie - activeIndex={activeIndex} - activeShape={renderActiveShape} - data={pieChartData} - cx={200} - cy={150} - innerRadius={60} - outerRadius={80} - fill={theme.palette.primary.main} - dataKey="value" - onMouseEnter={(e, id) => setActiveIndexId(id)} - /> - </PieChart> - </ResponsiveContainer> - </Widget> - </Grid> - </Grid> - </> - ); -} - -function renderActiveShape(props) { - const RADIAN = Math.PI / 180; - let { - cx, - cy, - midAngle, - innerRadius, - outerRadius, - startAngle, - endAngle, - fill, - payload, - percent, - value, - } = props; - const sin = Math.sin(-RADIAN * midAngle); - const cos = Math.cos(-RADIAN * midAngle); - const sx = cx + (outerRadius + 10) * cos; - const sy = cy + (outerRadius + 10) * sin; - const mx = cx + (outerRadius + 30) * cos; - const my = cy + (outerRadius + 30) * sin; - const ex = mx + (cos >= 0 ? 1 : -1) * 22; - const ey = my; - const textAnchor = cos >= 0 ? 'start' : 'end'; - - return ( - <g> - <text x={cx} y={cy} dy={8} textAnchor="middle" fill={fill}> - {payload.name} - </text> - <Sector - cx={cx} - cy={cy} - innerRadius={innerRadius} - outerRadius={outerRadius} - startAngle={startAngle} - endAngle={endAngle} - fill={fill} - /> - <Sector - cx={cx} - cy={cy} - startAngle={startAngle} - endAngle={endAngle} - innerRadius={outerRadius + 6} - outerRadius={outerRadius + 10} - fill={fill} - /> - <path d={`M${sx},${sy}L${mx},${my}L${ex},${ey}`} stroke={fill} fill="none" /> - <circle cx={ex} cy={ey} r={2} fill={fill} stroke="none" /> - <text - x={ex + (cos >= 0 ? 1 : -1) * 12} - y={ey} - textAnchor={textAnchor} - fill="#333" - >{`PV ${value}`}</text> - <text - x={ex + (cos >= 0 ? 1 : -1) * 12} - y={ey} - dy={18} - textAnchor={textAnchor} - fill="#999" - > - {`(Rate ${(percent * 100).toFixed(2)}%)`} - </text> - </g> - ); -} diff --git a/src/pages/charts/components/ApexHeatmap.js b/src/pages/charts/components/ApexHeatmap.js deleted file mode 100644 index 64594bb..0000000 --- a/src/pages/charts/components/ApexHeatmap.js +++ /dev/null @@ -1,114 +0,0 @@ -import React from 'react'; -import { useTheme } from '@material-ui/styles'; -import ApexCharts from 'react-apexcharts'; - -const series = [ - { - name: 'Metric1', - data: generateData(18, { - min: 0, - max: 90, - }), - }, - { - name: 'Metric2', - data: generateData(18, { - min: 0, - max: 90, - }), - }, - { - name: 'Metric3', - data: generateData(18, { - min: 0, - max: 90, - }), - }, - { - name: 'Metric4', - data: generateData(18, { - min: 0, - max: 90, - }), - }, - { - name: 'Metric5', - data: generateData(18, { - min: 0, - max: 90, - }), - }, - { - name: 'Metric6', - data: generateData(18, { - min: 0, - max: 90, - }), - }, - { - name: 'Metric7', - data: generateData(18, { - min: 0, - max: 90, - }), - }, - { - name: 'Metric8', - data: generateData(18, { - min: 0, - max: 90, - }), - }, - { - name: 'Metric9', - data: generateData(18, { - min: 0, - max: 90, - }), - }, -]; - -export default function ApexLineChart() { - const theme = useTheme(); - - return ( - <ApexCharts - options={themeOptions(theme)} - series={series} - type="heatmap" - height={350} - /> - ); -} - -// ################################################################## -function generateData(count, yrange) { - let i = 0; - const series = []; - while (i < count) { - const x = 'w' + (i + 1).toString(); - const y = Math.floor(Math.random() * (yrange.max - yrange.min + 1)) + yrange.min; - - series.push({ - x: x, - y: y, - }); - i++; - } - - return series; -} - -function themeOptions(theme) { - return { - chart: { - toolbar: { - show: false, - }, - }, - dataLabels: { - enabled: false, - }, - colors: [theme.palette.primary.main], - }; -} diff --git a/src/pages/charts/components/ApexLineChart.js b/src/pages/charts/components/ApexLineChart.js deleted file mode 100644 index da684f0..0000000 --- a/src/pages/charts/components/ApexLineChart.js +++ /dev/null @@ -1,63 +0,0 @@ -import React from 'react'; -import ApexCharts from 'react-apexcharts'; -import { useTheme } from '@material-ui/styles'; - -const series = [ - { - name: 'series1', - data: [31, 40, 28, 51, 42, 109, 100], - }, - { - name: 'series2', - data: [11, 32, 45, 32, 34, 52, 41], - }, -]; - -export default function ApexLineChart() { - const theme = useTheme(); - - return ( - <ApexCharts options={themeOptions(theme)} series={series} type="area" height={350} /> - ); -} - -// ############################################################ -function themeOptions(theme) { - return { - dataLabels: { - enabled: false, - }, - stroke: { - curve: 'smooth', - }, - xaxis: { - type: 'datetime', - categories: [ - '2018-09-19T00:00:00', - '2018-09-19T01:30:00', - '2018-09-19T02:30:00', - '2018-09-19T03:30:00', - '2018-09-19T04:30:00', - '2018-09-19T05:30:00', - '2018-09-19T06:30:00', - ], - }, - tooltip: { - x: { - format: 'dd/MM/yy HH:mm', - }, - }, - fill: { - colors: [theme.palette.primary.light, theme.palette.success.light], - }, - colors: [theme.palette.primary.main, theme.palette.success.main], - chart: { - toolbar: { - show: false, - }, - }, - legend: { - show: false, - }, - }; -} diff --git a/src/pages/charts/package.json b/src/pages/charts/package.json deleted file mode 100644 index f43489f..0000000 --- a/src/pages/charts/package.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "name": "Charts", - "version": "1.0.0", - "private": true, - "main": "Charts.js" -} -- GitLab From 34a74008fcdd8f0f0e1479b0b2e39c55048874e8 Mon Sep 17 00:00:00 2001 From: rbisson <remi.bisson@inrae.fr> Date: Wed, 24 Apr 2024 15:31:55 +0200 Subject: [PATCH 17/19] [src]: corrected typos, removed warnings and unused variables --- src/components/Common/Common.js | 4 +- src/components/Wrappers/Wrappers.js | 11 ++--- src/context/LayoutContext.js | 1 - src/context/UserContext.js | 4 +- src/index.js | 3 +- .../dashboard/components/BigStat/BigStat.js | 2 - src/pages/dashboard/components/Table/Table.js | 2 - src/pages/group/Group.js | 4 +- src/pages/policy/Policy.js | 41 +++++-------------- src/pages/requests/Requests.js | 4 +- src/pages/roles/Role.js | 4 +- src/pages/sources/Sources.js | 6 +-- src/pages/user/User.js | 7 +--- 13 files changed, 31 insertions(+), 62 deletions(-) diff --git a/src/components/Common/Common.js b/src/components/Common/Common.js index c2de13a..13ff279 100644 --- a/src/components/Common/Common.js +++ b/src/components/Common/Common.js @@ -42,7 +42,7 @@ export const InputFile = (onChange, style) => { ); }; -export const ActionBar = (enabled, style, onSendClieck) => { +export const ActionBar = (enabled, style, onSendClick) => { return ( <> {enabled && ( @@ -51,7 +51,7 @@ export const ActionBar = (enabled, style, onSendClieck) => { <Button variant="contained" color="primary" - onClick={onSendClieck} + onClick={onSendClick} startIcon={<SaveIcon />} > Envoyez diff --git a/src/components/Wrappers/Wrappers.js b/src/components/Wrappers/Wrappers.js index 6442f8c..055af83 100644 --- a/src/components/Wrappers/Wrappers.js +++ b/src/components/Wrappers/Wrappers.js @@ -8,8 +8,7 @@ import { import { useTheme, makeStyles } from '@material-ui/styles'; import classnames from 'classnames'; -// styles -const useStyles = makeStyles((theme) => ({ +const useStyles = makeStyles(() => ({ badge: { fontWeight: 600, height: 16, @@ -87,11 +86,9 @@ function Button({ children, color, ...props }) { export { Badge, Typography, Button }; -// ######################################################################## - -function getColor(color, theme, brigtness = 'main') { - if (color && theme.palette[color] && theme.palette[color][brigtness]) { - return theme.palette[color][brigtness]; +function getColor(color, theme, brightness = 'main') { + if (color && theme.palette[color] && theme.palette[color][brightness]) { + return theme.palette[color][brightness]; } } diff --git a/src/context/LayoutContext.js b/src/context/LayoutContext.js index 3c739c6..20318b7 100644 --- a/src/context/LayoutContext.js +++ b/src/context/LayoutContext.js @@ -44,7 +44,6 @@ function useLayoutDispatch() { export { LayoutProvider, useLayoutState, useLayoutDispatch, toggleSidebar }; -// ########################################################### function toggleSidebar(dispatch) { dispatch({ type: 'TOGGLE_SIDEBAR', diff --git a/src/context/UserContext.js b/src/context/UserContext.js index 8eb0ea9..66c689a 100644 --- a/src/context/UserContext.js +++ b/src/context/UserContext.js @@ -1,5 +1,4 @@ import React from 'react'; - import { KeycloakClient } from './KeycloakClient'; import { InSylvaGatekeeperClient } from './InSylvaGatekeeperClient'; import { getGatekeeperBaseUrl, getLoginUrl, redirect } from '../utils.js'; @@ -80,7 +79,6 @@ async function checkUserLogin(userId, accessToken, refreshToken, roleId) { // Load the user histories from UserHistory(userId) endpoint // Load the user result filters from Result_Filter(userId) endpoints // Load the user policies from Policy(userId) endpoint - if (!sessionStorage.getItem('token_refresh_time')) { sessionStorage.setItem('token_refresh_time', Date.now()); } @@ -89,7 +87,7 @@ async function checkUserLogin(userId, accessToken, refreshToken, roleId) { } } -async function signOut(dispatch, history) { +async function signOut(dispatch) { await kcClient.logout({}); dispatch({ type: 'SIGN_OUT_SUCCESS' }); sessionStorage.removeItem('access_token'); diff --git a/src/index.js b/src/index.js index 622919b..c7ada2c 100755 --- a/src/index.js +++ b/src/index.js @@ -14,8 +14,9 @@ const accessToken = getUrlParam('accessToken', ''); const roleId = getUrlParam('roleId', ''); let refreshToken = getUrlParam('refreshToken', ''); -if (refreshToken.includes('#/app/portal')) +if (refreshToken.includes('#/app/portal')) { refreshToken = refreshToken.substring(0, refreshToken.indexOf('#')); +} checkUserLogin(userId, accessToken, refreshToken, roleId); diff --git a/src/pages/dashboard/components/BigStat/BigStat.js b/src/pages/dashboard/components/BigStat/BigStat.js index adf5a81..824e1bf 100644 --- a/src/pages/dashboard/components/BigStat/BigStat.js +++ b/src/pages/dashboard/components/BigStat/BigStat.js @@ -13,8 +13,6 @@ export default function BigStat(props) { let { product, total, color, registrations, bounce } = props; const classes = useStyles(); const theme = useTheme(); - - // local let [value, setValue] = useState('daily'); return ( diff --git a/src/pages/dashboard/components/Table/Table.js b/src/pages/dashboard/components/Table/Table.js index 3a9f58d..b724153 100644 --- a/src/pages/dashboard/components/Table/Table.js +++ b/src/pages/dashboard/components/Table/Table.js @@ -1,7 +1,5 @@ import React from 'react'; import { Table, TableRow, TableHead, TableBody, TableCell } from '@material-ui/core'; - -// components import { Button } from '../../../../components/Wrappers'; const states = { diff --git a/src/pages/group/Group.js b/src/pages/group/Group.js index 1761b44..b3fb809 100644 --- a/src/pages/group/Group.js +++ b/src/pages/group/Group.js @@ -219,7 +219,7 @@ const Group = () => { if (globalState.status === 'SUCCESS') { setOpen(true); - setAlertMessage('Group created succesfully !'); + setAlertMessage('Group created successfully!'); setSeverity('success'); } await loadGroups(); @@ -243,7 +243,7 @@ const Group = () => { if (globalState.status === 'SUCCESS') { setOpen(true); - setAlertMessage('User-Group assignment completed succesfully !'); + setAlertMessage('User-Group assignment completed successfully!'); setSeverity('success'); } }; diff --git a/src/pages/policy/Policy.js b/src/pages/policy/Policy.js index 269dfa2..5025a7f 100644 --- a/src/pages/policy/Policy.js +++ b/src/pages/policy/Policy.js @@ -277,7 +277,6 @@ const AssignedPolicies = memo( ({ policies, selectedPolicy, - setSelectedPolicy, fields, assignedPolicyColumns, getRowProps, @@ -479,7 +478,7 @@ const Policy = () => { if (globalState.status === 'SUCCESS') { loadPoliciesWithSources(); setOpen(true); - setAlertMessage('Policy-Source assignment completed succesfully !'); + setAlertMessage('Policy-Source assignment completed successfully !'); setSeverity('success'); } } @@ -498,7 +497,7 @@ const Policy = () => { if (globalState.status === 'SUCCESS') { setOpen(true); - setAlertMessage('Policy was created succesfully !'); + setAlertMessage('Policy was created successfully !'); setSeverity('success'); loadPolicies(); loadPoliciesWithSources(); @@ -524,7 +523,7 @@ const Policy = () => { if (globalState.status === 'SUCCESS') { setOpen(true); - setAlertMessage('Policy-Assignment completed succesfully !'); + setAlertMessage('Policy-Assignment completed successfully !'); setSeverity('success'); } }; @@ -546,7 +545,7 @@ const Policy = () => { } if (globalState.status === 'SUCCESS') { setOpen(true); - setAlertMessage('Policy-Group assignment completed succesfully !'); + setAlertMessage('Policy-Group assignment completed successfully !'); setSeverity('success'); } } @@ -597,19 +596,12 @@ const Policy = () => { await globalActions.policy.deletePolicyField(e.id); setOpen(true); - setAlertMessage('Policy-Field deleted succesfully !'); + setAlertMessage('Policy-Field deleted successfully !'); setSeverity('success'); } }; const assignedPolicyActions = [ - /*{ - name: 'Clone', - description: 'Clone this person', - icon: 'copy', - type: 'icon', - onClick: cloneUser, - },*/ { name: 'Delete', description: 'Delete this Policy-Field', @@ -643,40 +635,30 @@ const Policy = () => { field: 'field_type', name: 'Field Type', }, - /*{ - field: 'online', - name: 'Online', - dataType: 'boolean', - render: online => { - const color = online ? 'success' : 'danger'; - const label = online ? 'Online' : 'Offline'; - return <EuiHealth color={color}>{label}</EuiHealth>; - }, - },*/ { name: 'Actions', actions: assignedPolicyActions, }, ]; - const onAassignedPolicyGroup = async (e) => { + const onAssignedPolicyGroup = async (e) => { if (e.grouppolicyid) { await globalActions.group.deleteGroupPolicy(e.grouppolicyid); setOpen(true); - setAlertMessage('Policy-group deleted succesfully !'); + setAlertMessage('Policy-group deleted successfully !'); setSeverity('success'); } }; - const aassignedPolicyGroupActions = [ + const assignedPolicyGroupActions = [ { name: 'Delete', description: 'Delete this Policy-Group', icon: 'trash', type: 'icon', color: 'danger', - onClick: onAassignedPolicyGroup, + onClick: onAssignedPolicyGroup, }, ]; @@ -684,14 +666,14 @@ const Policy = () => { { field: 'group_name', name: 'Group Name' }, { field: 'source_name', name: 'Source Name' }, { field: 'source_description', name: 'Source Description' }, - { name: 'Actions', actions: aassignedPolicyGroupActions }, + { name: 'Actions', actions: assignedPolicyGroupActions }, ]; const onDeletePolicy = async (e) => { await globalActions.policy.deletePolicy(e.id); if (globalState.status === 'SUCCESS') { setOpen(true); - setAlertMessage('Policy deleted succesfully !'); + setAlertMessage('Policy deleted successfully !'); setSeverity('success'); loadPoliciesWithSources(); loadPolicies(); @@ -831,7 +813,6 @@ const Policy = () => { <AssignedPolicies policies={optPolicies} selectedPolicy={selectedPolicy} - setSelectedPolicy={setSelectedPolicy} fields={assignedPolicyItems} assignedPolicyColumns={assignedPolicyColumns} getRowProps={getRowProps} diff --git a/src/pages/requests/Requests.js b/src/pages/requests/Requests.js index a2008c8..eef6e18 100644 --- a/src/pages/requests/Requests.js +++ b/src/pages/requests/Requests.js @@ -69,7 +69,7 @@ const Requests = () => { if (request) { await globalActions.user.deleteUserRequest(request.id); setOpen(true); - setAlertMessage('Request was deleted succesfully!'); + setAlertMessage('Request was deleted successfully!'); setSeverity('success'); await loadRequests(); await loadPendingRequests(); @@ -80,7 +80,7 @@ const Requests = () => { if (request) { await globalActions.user.processUserRequest(request.id); setOpen(true); - setAlertMessage('Request was deleted succesfully!'); + setAlertMessage('Request was deleted successfully!'); setSeverity('success'); await loadRequests(); await loadPendingRequests(); diff --git a/src/pages/roles/Role.js b/src/pages/roles/Role.js index ee552bd..4b75f6e 100644 --- a/src/pages/roles/Role.js +++ b/src/pages/roles/Role.js @@ -221,7 +221,7 @@ const Role = () => { if (globalState.status === 'SUCCESS') { setOpen(true); - setAlertMessage('Role-Assignment completed succesfully !'); + setAlertMessage('Role-Assignment completed successfully !'); setSeverity('success'); } }; @@ -242,7 +242,7 @@ const Role = () => { await globalActions.user.deleteRole(e.id); if (globalState.status === 'SUCCESS') { setOpen(true); - setAlertMessage('Role delete succesfully !'); + setAlertMessage('Role delete successfully !'); setSeverity('success'); await globalActions.user.findRole(); diff --git a/src/pages/sources/Sources.js b/src/pages/sources/Sources.js index 419ad8c..f69da6a 100644 --- a/src/pages/sources/Sources.js +++ b/src/pages/sources/Sources.js @@ -286,7 +286,7 @@ const Sources = () => { sessionStorage.getItem('userId') ); setOpen(true); - setAlertMessage('Source is deleted succesfully'); + setAlertMessage('Source is deleted successfully'); setSeverity('success'); await loadSources(); @@ -335,7 +335,7 @@ const Sources = () => { await updateSource(kc_id, source_id); if (globalState.status === 'SUCCESS') { setOpen(true); - setAlertMessage('Source imported to elastic stack succesfully'); + setAlertMessage('Source imported to elastic stack successfully'); setSeverity('success'); await loadSources(); @@ -440,7 +440,7 @@ const Sources = () => { if (globalState.status === 'SUCCESS') { setOpen(true); - setAlertMessage('Source was created succesfully'); + setAlertMessage('Source was created successfully'); setSeverity('success'); await loadSources(); diff --git a/src/pages/user/User.js b/src/pages/user/User.js index b967b84..7662de5 100644 --- a/src/pages/user/User.js +++ b/src/pages/user/User.js @@ -26,7 +26,6 @@ const NewUserForm = memo( setPasswordValue, email, setEmail, - dual, roles, selectedRole, setSelectedRole, @@ -166,9 +165,8 @@ const User = () => { passwordValue, selectedRole ); - setOpen(true); - setAlertMessage('User is created succesfully!'); + setAlertMessage('User is created successfully!'); setSeverity('success'); loadUsers(); } @@ -177,9 +175,8 @@ const User = () => { const onDeleteUser = async (user) => { if (user) { await globalActions.user.deleteUser(user.kc_id); - setOpen(true); - setAlertMessage('User is deleted succesfully!'); + setAlertMessage('User is deleted successfully!'); setSeverity('success'); await loadUsers(); } -- GitLab From 75b4fb24d355667b2919fe31e8afd8d25eb72297 Mon Sep 17 00:00:00 2001 From: rbisson <remi.bisson@inrae.fr> Date: Wed, 24 Apr 2024 15:56:03 +0200 Subject: [PATCH 18/19] [src]: removed useless comments, added dependencies to useEffects to prevent warning --- src/components/Header/Header.js | 36 ++----------------- src/components/Sidebar/components/Dot.js | 1 - .../components/SidebarLink/SidebarLink.js | 13 ++++--- src/components/Sidebar/styles.js | 3 -- src/pages/fields/Fields.js | 1 - src/pages/policy/Policy.js | 7 ++-- src/pages/requests/Requests.js | 3 +- src/pages/sources/Sources.js | 2 +- 8 files changed, 16 insertions(+), 50 deletions(-) diff --git a/src/components/Header/Header.js b/src/components/Header/Header.js index 3ca07d7..252dda2 100644 --- a/src/components/Header/Header.js +++ b/src/components/Header/Header.js @@ -15,44 +15,15 @@ import { } from '../../context/LayoutContext'; import { useUserDispatch, signOut } from '../../context/UserContext'; import store from '../../store/index'; -/* -const notifications = [ - { id: 0, color: "warning", message: "Check out this awesome ticket" }, - { - id: 1, - color: "success", - type: "info", - message: "What is the best way to get ...", - }, - { - id: 2, - color: "secondary", - type: "notification", - message: "This is just a simple notification", - }, - { - id: 3, - color: "primary", - type: "e-commerce", - message: "12 new orders has arrived today", - }, -]; -*/ export default function Header(props) { const classes = useStyles(); - - // global + let [, globalActions] = store(); const layoutState = useLayoutState(); const layoutDispatch = useLayoutDispatch(); const userDispatch = useUserDispatch(); - - // local - // var [mailMenu, setMailMenu] = useState(null); - let [profileMenu, setProfileMenu] = useState(null); - - let [, globalActions] = store(); let [user, setUser] = useState({}); + let [profileMenu, setProfileMenu] = useState(null); const loadUser = useCallback(async () => { if (sessionStorage.getItem('userId')) { @@ -64,8 +35,7 @@ export default function Header(props) { useEffect(() => { loadUser(); - // eslint-disable-next-line react-hooks/exhaustive-deps - }, []); + }, [loadUser]); return ( <AppBar position="fixed" className={classes.appBar}> diff --git a/src/components/Sidebar/components/Dot.js b/src/components/Sidebar/components/Dot.js index df1a1c0..6cb089f 100644 --- a/src/components/Sidebar/components/Dot.js +++ b/src/components/Sidebar/components/Dot.js @@ -2,7 +2,6 @@ import React from 'react'; import { makeStyles, useTheme } from '@material-ui/styles'; import classnames from 'classnames'; -// styles const useStyles = makeStyles((theme) => ({ dotBase: { width: 5, diff --git a/src/components/Sidebar/components/SidebarLink/SidebarLink.js b/src/components/Sidebar/components/SidebarLink/SidebarLink.js index 183c9e0..f7363bc 100644 --- a/src/components/Sidebar/components/SidebarLink/SidebarLink.js +++ b/src/components/Sidebar/components/SidebarLink/SidebarLink.js @@ -25,13 +25,12 @@ export default function SidebarLink({ type, }) { const classes = useStyles(); - - // local let [isOpen, setIsOpen] = useState(false); + const isLinkActive = link && (location.pathname === link || location.pathname.indexOf(link) !== -1); - if (type === 'title') + if (type === 'title') { return ( <Typography className={classnames(classes.linkText, classes.sectionTitle, { @@ -41,10 +40,13 @@ export default function SidebarLink({ {label} </Typography> ); + } - if (type === 'divider') return <Divider className={classes.divider} />; + if (type === 'divider') { + return <Divider className={classes.divider} />; + } - if (!children) + if (!children) { return ( <ListItem button @@ -77,6 +79,7 @@ export default function SidebarLink({ /> </ListItem> ); + } return ( <> diff --git a/src/components/Sidebar/styles.js b/src/components/Sidebar/styles.js index f74ee96..fabdf1c 100644 --- a/src/components/Sidebar/styles.js +++ b/src/components/Sidebar/styles.js @@ -43,9 +43,6 @@ export default makeStyles((theme) => ({ flexGrow: 1, padding: theme.spacing(3), }, - /* sidebarList: { - marginTop: theme.spacing(6), - }, */ mobileBackButton: { marginTop: theme.spacing(0.5), marginLeft: theme.spacing(3), diff --git a/src/pages/fields/Fields.js b/src/pages/fields/Fields.js index 24630d8..ecbd5f5 100644 --- a/src/pages/fields/Fields.js +++ b/src/pages/fields/Fields.js @@ -112,7 +112,6 @@ const Fields = (props) => { const [alertMessage, setAlertMessage] = useState(''); const [severity, setSeverity] = useState('info'); const [files, setFiles] = useState(); - // const [fieldsCol, setFieldsCol] = useState([]) const [fields, setFields] = useState([]); const [stdFields, setStdFields] = useState([]); const [pageIndex, setPageIndex] = useState(0); diff --git a/src/pages/policy/Policy.js b/src/pages/policy/Policy.js index 5025a7f..8fbe356 100644 --- a/src/pages/policy/Policy.js +++ b/src/pages/policy/Policy.js @@ -361,7 +361,7 @@ const Policy = () => { setOptSources(_sources); } } - }, [globalActions.source]); + }, [globalActions.source, globalActions.user]); const loadPolicies = useCallback(async () => { if (sessionStorage.getItem('userId')) { @@ -387,7 +387,7 @@ const Policy = () => { setOptSourcePolicies(_policies); } } - }, [globalActions.policy]); + }, [globalActions.policy, globalActions.user]); const loadPoliciesWithSources = useCallback(async () => { if (sessionStorage.getItem('userId')) { @@ -418,7 +418,7 @@ const Policy = () => { setPolicies(policyList); } } - }, [globalActions.policy]); + }, [globalActions.policy, globalActions.user]); const loadStdFields = useCallback(async () => { const result = await globalActions.source.privateFields(); @@ -452,7 +452,6 @@ const Policy = () => { loadStdFields(); loadPoliciesWithSources(); loadGroups(); - // eslint-disable-next-line react-hooks/exhaustive-deps } // cancel subscription to useEffect diff --git a/src/pages/requests/Requests.js b/src/pages/requests/Requests.js index eef6e18..a87a92e 100644 --- a/src/pages/requests/Requests.js +++ b/src/pages/requests/Requests.js @@ -23,7 +23,6 @@ const RequestList = memo(({ requests, requestColumns }) => { isSelectable={true} items={requests} columns={requestColumns} - // selection={selection} /> </EuiFormRow> </EuiForm> @@ -32,7 +31,7 @@ const RequestList = memo(({ requests, requestColumns }) => { }); const Requests = () => { - const [globalState, globalActions] = store(); + const [, globalActions] = store(); const [selectedTabNumber, setSelectedTabNumber] = useState(0); const [open, setOpen] = useState(false); const [alertMessage, setAlertMessage] = useState(''); diff --git a/src/pages/sources/Sources.js b/src/pages/sources/Sources.js index f69da6a..7e7b9ce 100644 --- a/src/pages/sources/Sources.js +++ b/src/pages/sources/Sources.js @@ -468,7 +468,7 @@ const Sources = () => { setSources(result); } } - }, [globalActions.source]); + }, [globalActions.source, globalActions.user]); useEffect(() => { // clean up controller -- GitLab From a06cc266a371e0d3f9006cea9844451ef3a09af7 Mon Sep 17 00:00:00 2001 From: rbisson <remi.bisson@inrae.fr> Date: Fri, 24 May 2024 12:18:15 +0200 Subject: [PATCH 19/19] [public/index.html]: renamed page title --- public/index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/public/index.html b/public/index.html index b62a88e..e4c2254 100755 --- a/public/index.html +++ b/public/index.html @@ -15,7 +15,7 @@ work correctly both with client-side routing and a non-root public URL. Learn how to configure a non-root public URL by running `npm run build`. --> - <title>INRAE PACA IN-SYLVA</title> + <title>IN-SYLVA Portal</title> <script src="%PUBLIC_URL%/env-config.js"></script> </head> <body style="font-family: 'Roboto', sans-serif;"> -- GitLab