diff --git a/src/components/Header.tsx b/src/components/Header.tsx index 6932c7ecb9..44e4e3ad6a 100644 --- a/src/components/Header.tsx +++ b/src/components/Header.tsx @@ -6,6 +6,12 @@ import languages from "../i18n/languages"; import opencastLogo from "../img/opencast-white.svg?url"; import { setSpecificServiceFilter } from "../slices/tableFilterSlice"; import { getErrorCount, getHealthStatus } from "../selectors/healthSelectors"; +import { + getRegistrationLoaded, + getRegistration, + getAbleToRegister, + getAgreedLatestToU, +} from "../selectors/registrationSelectors"; import { getOrgProperties, getUserBasicInfo, @@ -20,6 +26,11 @@ import HotKeyCheatSheet from "./shared/HotKeyCheatSheet"; import { useHotkeys } from "react-hotkeys-hook"; import { useAppDispatch, useAppSelector } from "../store"; import { HealthStatus, fetchHealthStatus } from "../slices/healthSlice"; +import { + fetchRegistration, + fetchLatestToU, + fetchIsUpToDate, +} from "../slices/registrationSlice"; import { UserInfoState } from "../slices/userInfoSlice"; import { Tooltip } from "./shared/Tooltip"; import { HiOutlineTranslate } from "react-icons/hi"; @@ -54,7 +65,11 @@ const Header = () => { const healthStatus = useAppSelector(state => getHealthStatus(state)); const errorCounter = useAppSelector(state => getErrorCount(state)); + const isAbleToRegister = useAppSelector(state => getAbleToRegister(state)); + const agreedLatestToU = useAppSelector(state => getAgreedLatestToU(state)); const user = useAppSelector(state => getUserInformation(state)); + const registrationLoaded = useAppSelector(state => getRegistrationLoaded(state)); + const registration = useAppSelector(state => getRegistration(state)); const orgProperties = useAppSelector(state => getOrgProperties(state)); const displayTerms = (orgProperties["org.opencastproject.admin.display_terms"] || "false").toLowerCase() === "true"; @@ -66,6 +81,10 @@ const Header = () => { setMenuHelp(false); }; + const hideNotificationMenu = () => { + setMenuNotify(false); + }; + const showRegistrationModal = () => { registrationModalRef.current?.open(); }; @@ -138,18 +157,24 @@ const Header = () => { }, []); useEffect(() => { - if (!user) { return; } - - const isAdmin = user.isAdmin || user.isOrgAdmin; - const isLocalhost = window.location.hostname === "localhost"; - const lastDismissed = localStorage.getItem("adopterModalDismissed"); - const THIRTY_DAYS = 30 * 24 * 60 * 60 * 1000; - const dismissedLongEnough = !lastDismissed || Date.now() - parseInt(lastDismissed) > THIRTY_DAYS; - - if (isAdmin && !isLocalhost && dismissedLongEnough) { - showRegistrationModal(); - } - }, [user]); + dispatch(fetchRegistration()); + dispatch(fetchLatestToU()); + dispatch(fetchIsUpToDate()); + }, [dispatch]); + + useEffect(() => { + if (!user) { return; } + + const isAdmin = user.isAdmin || user.isOrgAdmin; + const isLocalhost = window.location.hostname === "localhost"; + const lastDismissed = localStorage.getItem("adopterModalDismissed"); + const THIRTY_DAYS = 30 * 24 * 60 * 60 * 1000; + const dismissedLongEnough = !lastDismissed || Date.now() - parseInt(lastDismissed) > THIRTY_DAYS; + + if (isAdmin && !isLocalhost && dismissedLongEnough && registrationLoaded && registration == null) { + showRegistrationModal(); + } + }, [user, registration, registrationLoaded]); return ( <>
@@ -214,9 +239,9 @@ const Header = () => { setMenuNotify(!displayMenuNotify)} className="nav-dd-element"> - {errorCounter !== 0 && ( + {(errorCounter !== 0 || !agreedLatestToU || !isAbleToRegister) && ( - {errorCounter} + {errorCounter + (!agreedLatestToU || !isAbleToRegister ? 1 : 0)} )} @@ -225,6 +250,10 @@ const Header = () => { {displayMenuNotify && ( )} @@ -326,9 +355,18 @@ const MenuLang = ({ handleChangeLanguage }: { handleChangeLanguage: (code: strin const MenuNotify = ({ healthStatus, + registering, + updatedToU, + showRegistrationModal, + hideNotificationMenu, }: { healthStatus: HealthStatus[], + registering: boolean, + updatedToU: boolean, + showRegistrationModal: () => void, + hideNotificationMenu: () => void, }) => { + const { t } = useTranslation(); const dispatch = useAppDispatch(); const navigate = useNavigate(); @@ -338,6 +376,13 @@ const MenuNotify = ({ navigate("/systems/services"); }; + // show Adopter Registration Modal and hide drop down + const showAdoptersRegistrationModal = () => { + showRegistrationModal(); + hideNotificationMenu(); + }; + + return (
    {/* For each service in the serviceList (Background Services) one list item */} @@ -361,6 +406,26 @@ const MenuNotify = ({ )} ))} + {!registering && +
  • + showAdoptersRegistrationModal()} + > + Registration + {t("ADOPTER_REGISTRATION.NOTIFICATION.UNREGISTERED")} + +
  • + } + {registering && !updatedToU && +
  • + showAdoptersRegistrationModal()} + > + Registration + {t("ADOPTER_REGISTRATION.NOTIFICATION.UPDATED_TOU")} + +
  • + }
); }; diff --git a/src/components/shared/RegistrationModal.tsx b/src/components/shared/RegistrationModal.tsx index 3ccda2b80d..44becd464e 100644 --- a/src/components/shared/RegistrationModal.tsx +++ b/src/components/shared/RegistrationModal.tsx @@ -1,6 +1,7 @@ import React, { useEffect, useState } from "react"; import { useTranslation } from "react-i18next"; import { Formik } from "formik"; +import { useAppDispatch, useAppSelector } from "../../store"; import { Field } from "./Field"; import TermsOfUsePage from "./modals/TermsOfUsePage"; import { countries, states, systemTypes } from "../../configs/adopterRegistrationConfig"; @@ -8,11 +9,18 @@ import cn from "classnames"; import { AdopterRegistrationSchema } from "../../utils/validate"; import { Registration, + Statistics, + fetchRegistration, + fetchStatistics, + postAdopterRegistration, deleteAdopterRegistration, - fetchAdopterRegistration, - fetchAdopterStatisticsSummary, - postRegistration, -} from "../../utils/adopterRegistrationUtils"; +} from "../../slices/registrationSlice"; +import { + getRegistrationLoaded, + getRegistration, + getStatisticsLoaded, + getStatistics, +} from "../../selectors/registrationSelectors"; import ModalContent from "./modals/ModalContent"; import { Modal, ModalHandle } from "./modals/Modal"; import { ParseKeys } from "i18next"; @@ -47,11 +55,17 @@ const RegistrationModal = ({ const RegistrationModalContent = () => { const { t } = useTranslation(); + const dispatch = useAppDispatch(); + + const registrationLoaded = useAppSelector(state => getRegistrationLoaded(state)); + const registration = useAppSelector(state => getRegistration(state)); + const statisticsLoaded = useAppSelector(state => getStatisticsLoaded(state)); + const statistics = useAppSelector(state => getStatistics(state)); // current state of the modal that is shown const [state, setState] = useState("information"); // initial values for Formik - const [initialValues, setInitialValues] = useState({ + const [initialValues, setInitialValues] = useState({ contactMe: false, systemType: "", allowsStatistics: false, @@ -66,20 +80,27 @@ const RegistrationModalContent = () => { street: "", streetNo: "", email: "", + termsVersionAgreed: "", agreedToPolicy: false, + dateModified: "", + dateCreated: "", registered: false, + statistics: null, }); - const [statisticsSummary, setStatisticsSummary] = useState<{ - general: { [key: string]: unknown }, - statistics: { [key: string]: unknown }, - }>(); + useEffect(() => { + if (!registrationLoaded) { + dispatch(fetchRegistration()); + } + if (!statisticsLoaded) { + dispatch(fetchStatistics()); + } + }, [registrationLoaded, statisticsLoaded, dispatch]); useEffect(() => { - fetchRegistrationInfos().then(r => console.log(r)); - fetchStatisticSummary(); - // eslint-disable-next-line react-hooks/exhaustive-deps - }, []); + setInitialValues(initialValues => ({ ...initialValues, ...registration, statistics: { ...statistics } })); + }, [registration, statistics]); + const onClickContinue = () => { // if state is deleteSubmit then delete infos about adaptor else show next state @@ -90,23 +111,13 @@ const RegistrationModalContent = () => { } }; - const fetchRegistrationInfos = async () => { - const registrationInfo = await fetchAdopterRegistration(); - - // merge response into initial values for formik - setInitialValues({ ...initialValues, ...registrationInfo }); - }; - - const fetchStatisticSummary = async () => { - const info = await fetchAdopterStatisticsSummary(); - - setStatisticsSummary(info); - }; const handleSubmit = (values: Registration) => { // post request for adopter information - postRegistration(values) + postAdopterRegistration(values) .then(() => { + // Refetch the registration data since otherwise what we just submitted does not show up if the user immediately returns to the modal + dispatch(fetchRegistration()); // show thank you state return setState(states[state].nextState[0] as keyof typeof states); }) @@ -616,7 +627,10 @@ const RegistrationModalContent = () => {

{t("ADOPTER_REGISTRATION.MODAL.SUMMARY_STATE.GENERAL_HEADER")}

-									{JSON.stringify(formik.values, null, "\t")}
+									{JSON.stringify(Object.fromEntries(
+										Object.entries(formik.values)
+										.filter(([key, _]) => key != "statistics"))
+									, null, "\t")}
 								

@@ -626,7 +640,7 @@ const RegistrationModalContent = () => {

{t("ADOPTER_REGISTRATION.MODAL.SUMMARY_STATE.STATS_HEADER")}

-										{JSON.stringify(statisticsSummary?.statistics, null, "\t")}
+										{JSON.stringify(formik.values.statistics, null, "\t")}
 									
diff --git a/src/i18n/org/opencastproject/adminui/languages/lang-en_US.json b/src/i18n/org/opencastproject/adminui/languages/lang-en_US.json index fc5c32404c..1adaed5865 100644 --- a/src/i18n/org/opencastproject/adminui/languages/lang-en_US.json +++ b/src/i18n/org/opencastproject/adminui/languages/lang-en_US.json @@ -479,6 +479,10 @@ "DELETE_SUBMIT_STATE": { "TEXT": "Are you sure you want to delete your registration data?" } + }, + "NOTIFICATION": { + "UNREGISTERED": "Unregistered", + "UPDATED_TOU": "Updated ToU" } }, "EVENTS": { diff --git a/src/selectors/registrationSelectors.ts b/src/selectors/registrationSelectors.ts new file mode 100644 index 0000000000..b5a912f1ad --- /dev/null +++ b/src/selectors/registrationSelectors.ts @@ -0,0 +1,19 @@ +import { RootState } from "../store"; + +/** + * This file contains selectors regarding information about the registration status + */ +export const getRegistrationLoaded = (state: RootState) => state.registration.registrationLoaded; +// Are we registered at all +export const getRegistration = (state: RootState) => state.registration.registration; + +export const getStatisticsLoaded = (state: RootState) => state.registration.statisticsLoaded; +// Gather the system statistics reportable to the registration server +export const getStatistics = (state: RootState) => state.registration.statistics; + +// Are we able to talk to register.opencast.org +export const getAbleToRegister = (state: RootState) => state.registration.registrationLoaded && + state.registration.ableToRegister; +export const getAgreedLatestToU = (state: RootState) => state.registration.registrationLoaded && + state.registration.registration != null && // this is correct because the *endpoint* returns a bare 'null' when the cluster isn't registered + state.registration.registration.termsVersionAgreed == state.registration.latestToU; diff --git a/src/slices/registrationSlice.ts b/src/slices/registrationSlice.ts new file mode 100644 index 0000000000..c553b815cb --- /dev/null +++ b/src/slices/registrationSlice.ts @@ -0,0 +1,206 @@ +import { PayloadAction, createSlice } from "@reduxjs/toolkit"; +import axios from "axios"; +import { createAppAsyncThunk } from "../createAsyncThunkWithTypes"; + +export type Registration = { + contactMe: boolean, + systemType: string, + allowsStatistics: boolean, + allowsErrorReports: boolean, + organisationName: string, + departmentName: string, + country: string, + postalCode: string, + city: string, + firstName: string, + lastName: string, + street: string, + streetNo: string, + email: string, + termsVersionAgreed: string, + agreedToPolicy: boolean, + dateModified: string, + dateCreated: string, +}; + +// FIXME: This could be expanded to have all the fields, it's missing the nested host stuff +export type Statistics = { + statistics: { + /* the linter doesn't like these, but those are the names. Should we change them? + adopter_key: string, + statistics_key: string, + ca_count: number, + event_count: number, + job_count: number, + series_count: number, + tenant_count: number, + total_minutes: number, + user_count: number, */ + version: string, + } +}; + +export type RegistrationState = { + registrationLoaded: boolean, + registration: Registration, + statisticsLoaded: boolean, + statistics: Statistics, + latestToU: string, + ableToRegister: boolean, + agreedToPolicy: boolean, + error: boolean +}; + +// Initial state of health status in redux store +const initialState: RegistrationState = { + registrationLoaded: false, + registration: { + contactMe: false, + systemType: "", + allowsStatistics: false, + allowsErrorReports: false, + organisationName: "", + departmentName: "", + country: "", + postalCode: "", + city: "", + firstName: "", + lastName: "", + street: "", + streetNo: "", + email: "", + termsVersionAgreed: "", + agreedToPolicy: false, + dateModified: "", + dateCreated: "", + }, + statisticsLoaded: false, + statistics: { + statistics: { + /* the linter doesn't like these, but those are the names. Should we change them? + adopter_key: "", + statistics_key: "string", + ca_count: -1, + event_count: -1, + job_count: -1, + series_count: -1, + tenant_count: -1, + total_minutes: -1, + user_count: -1,*/ + version: "", + }, + /* There are other keys here, like so + tobira: { + insert arbitrary stats data + }, + But these, and other keys, are not always present and depend *entirely* on local config + Thus, we omit them here + */ + }, + latestToU: "uninitialized", + ableToRegister: false, + agreedToPolicy: false, + error: false, +}; + +// This is the registration itself +export const fetchRegistration = createAppAsyncThunk("registration/fetchRegistration", async () => { + const res = await axios.get("/admin-ng/adopter/registration"); + return res.data; +}); + +// This is the latest ToU ID. It's a string like APRIL_2020. +export const fetchLatestToU = createAppAsyncThunk("registration/fetchLatestToU", async () => { + const res = await axios.get("/admin-ng/adopter/latestToU"); + return res.data; +}); + +// This is whether the core can talk to register.opencast.org. +export const fetchIsUpToDate = createAppAsyncThunk("registration/isUpToDate", async () => { + const res = await axios.get("/admin-ng/adopter/isUpToDate"); + return res.data; +}); + +// This is whether the statistics used in the registration modal. +export const fetchStatistics = createAppAsyncThunk("registration/statistics", async () => { + const res = await axios.get("/admin-ng/adopter/statistics"); + return res.data; +}); + + + // post request for adopter information + export const postAdopterRegistration = async ( + values: Registration, + ) => { + // build body + const body = new URLSearchParams(); + body.append("contactMe", values.contactMe.toString()); + body.append("systemType", values.systemType); + body.append("allowsStatistics", values.allowsStatistics.toString()); + body.append("allowsErrorReports", values.allowsErrorReports.toString()); + body.append("organisationName", values.organisationName); + body.append("departmentName", values.departmentName); + body.append("country", values.country); + body.append("postalCode", values.postalCode); + body.append("city", values.city); + body.append("firstName", values.firstName); + body.append("lastName", values.lastName); + body.append("street", values.street); + body.append("streetNo", values.streetNo); + body.append("email", values.email); + body.append("agreedToPolicy", values.agreedToPolicy.toString()); + body.append("registered", "true"); + + // save adopter information and return next state + await axios.post("/admin-ng/adopter/registration", body, { + headers: { + "Content-Type": "application/x-www-form-urlencoded", + }, + }); + }; + +// delete adopter information +export const deleteAdopterRegistration = async () => { + // delete adopter information + await axios.delete("/admin-ng/adopter/registration", { + headers: { + "Content-Type": "application/x-www-form-urlencoded", + }, + }); +}; + +const registrationSlice = createSlice({ + name: "registration", + initialState, + reducers: {}, + // These are used for thunks + extraReducers: builder => { + builder + .addCase(fetchRegistration.fulfilled, (state, action: PayloadAction< + Registration + >) => { + state.registration = action.payload; + state.registrationLoaded = true; + }) + .addCase(fetchLatestToU.fulfilled, (state, action: PayloadAction< + string + >) => { + state.latestToU = action.payload; + }) + .addCase(fetchIsUpToDate.fulfilled, (state, action: PayloadAction< + boolean + >) => { + // This is true if the core can talk to https://register.opencast.org/, false otherwise + state.ableToRegister = action.payload; + }) + .addCase(fetchStatistics.fulfilled, (state, action: PayloadAction< + Statistics + >) => { + state.statistics = action.payload; + state.statisticsLoaded = true; + }); + }, +}); + +// Export the slice reducer as the default export +export default registrationSlice.reducer; diff --git a/src/store.ts b/src/store.ts index 76a3f65d9f..0558b56bb1 100644 --- a/src/store.ts +++ b/src/store.ts @@ -15,6 +15,7 @@ import groups from "./slices/groupSlice"; import acls from "./slices/aclSlice"; import themes from "./slices/themeSlice"; import health from "./slices/healthSlice"; +import registration from "./slices/registrationSlice"; import notifications from "./slices/notificationSlice"; import workflows from "./slices/workflowSlice"; import eventDetails from "./slices/eventDetailsSlice"; @@ -64,6 +65,7 @@ const reducers = combineReducers({ acls: persistReducer(aclsPersistConfig, acls), themes: persistReducer(themesPersistConfig, themes), health, + registration, notifications, workflows, eventDetails, diff --git a/src/styles/components/_header.scss b/src/styles/components/_header.scss index e33a8e1486..d3fa5a2499 100644 --- a/src/styles/components/_header.scss +++ b/src/styles/components/_header.scss @@ -161,6 +161,9 @@ .dropdown-ul{ width: auto; right: 8px; + .wide-text{ + padding-right: 5px; + } } #error-count{ min-width: 10px; diff --git a/src/utils/adopterRegistrationUtils.ts b/src/utils/adopterRegistrationUtils.ts deleted file mode 100644 index f51aaeada5..0000000000 --- a/src/utils/adopterRegistrationUtils.ts +++ /dev/null @@ -1,108 +0,0 @@ -import axios from "axios"; - -// get information about adopter -export const fetchAdopterRegistration = async () => { - type FetchRegistration = { - contactMe: boolean, - allowsStatistics: boolean, - allowsErrorReports: boolean, - agreedToPolicy: boolean, - registered: boolean, - termsVersionAgreed: string, - deleteMe: boolean, - }; - // fetch current information about adopter - const response = await axios.get("/admin-ng/adopter/registration"); - - return response.data; -}; - -// get statistics information about adopter -export const fetchAdopterStatisticsSummary = async () => { - type FetchSummary = { - general: { - contact_me: boolean, - send_errors: boolean, - send_usage: boolean, - }, - statistics: { - job_count: number, - event_count: number, - series_count: number, - user_count: number, - ca_count: number, - total_minutes: number, - tenant_count: number, - hosts: { - cores: number, - max_load: number, - memory: number, - hostname: string, - disk_space: number, - services: string, - }[] - }, - }; - const response = await axios.get("/admin-ng/adopter/summary"); - - return response.data; -}; - -export type Registration = { - contactMe: boolean, - systemType: string, - allowsStatistics: boolean, - allowsErrorReports: boolean, - organisationName: string, - departmentName: string, - country: string, - postalCode: string, - city: string, - firstName: string, - lastName: string, - street: string, - streetNo: string, - email: string, - agreedToPolicy: boolean, -} - -// post request for adopter information -export const postRegistration = async ( - values: Registration, -) => { - // build body - const body = new URLSearchParams(); - body.append("contactMe", values.contactMe.toString()); - body.append("systemType", values.systemType); - body.append("allowsStatistics", values.allowsStatistics.toString()); - body.append("allowsErrorReports", values.allowsErrorReports.toString()); - body.append("organisationName", values.organisationName); - body.append("departmentName", values.departmentName); - body.append("country", values.country); - body.append("postalCode", values.postalCode); - body.append("city", values.city); - body.append("firstName", values.firstName); - body.append("lastName", values.lastName); - body.append("street", values.street); - body.append("streetNo", values.streetNo); - body.append("email", values.email); - body.append("agreedToPolicy", values.agreedToPolicy.toString()); - body.append("registered", "true"); - - // save adopter information and return next state - await axios.post("/admin-ng/adopter/registration", body, { - headers: { - "Content-Type": "application/x-www-form-urlencoded", - }, - }); -}; - -// delete adopter information -export const deleteAdopterRegistration = async () => { - // delete adopter information - await axios.delete("/admin-ng/adopter/registration", { - headers: { - "Content-Type": "application/x-www-form-urlencoded", - }, - }); -};