- refactored NPED Login & logout

This commit is contained in:
2025-10-27 09:35:59 +00:00
parent 18534ceb2c
commit 251a2f5e7b
11 changed files with 76 additions and 76 deletions

View File

@@ -5,7 +5,7 @@ import FrontCamera from "./pages/FrontCamera";
import RearCamera from "./pages/RearCamera"; import RearCamera from "./pages/RearCamera";
import SystemSettings from "./pages/SystemSettings"; import SystemSettings from "./pages/SystemSettings";
import Session from "./pages/Session"; import Session from "./pages/Session";
import { NPEDUserProvider } from "./context/providers/NPEDUserContextProvider"; import { IntegrationsProvider } from "./context/providers/IntegrationsContextProvider";
import { AlertHitProvider } from "./context/providers/AlertHitProvider"; import { AlertHitProvider } from "./context/providers/AlertHitProvider";
import { SoundProvider } from "react-sounds"; import { SoundProvider } from "react-sounds";
import SoundContextProvider from "./context/providers/SoundContextProvider"; import SoundContextProvider from "./context/providers/SoundContextProvider";
@@ -14,7 +14,7 @@ function App() {
return ( return (
<SoundContextProvider> <SoundContextProvider>
<SoundProvider initialEnabled={true}> <SoundProvider initialEnabled={true}>
<NPEDUserProvider> <IntegrationsProvider>
<AlertHitProvider> <AlertHitProvider>
<Routes> <Routes>
<Route path="/" element={<Container />}> <Route path="/" element={<Container />}>
@@ -27,7 +27,7 @@ function App() {
</Route> </Route>
</Routes> </Routes>
</AlertHitProvider> </AlertHitProvider>
</NPEDUserProvider> </IntegrationsProvider>
</SoundProvider> </SoundProvider>
</SoundContextProvider> </SoundContextProvider>
); );

View File

@@ -1,6 +1,6 @@
import Card from "../UI/Card"; import Card from "../UI/Card";
import CardHeader from "../UI/CardHeader"; import CardHeader from "../UI/CardHeader";
import { useNPEDContext } from "../../context/NPEDUserContext"; import { useIntegrationsContext } from "../../context/IntegrationsContext";
import type { ReducedSightingType } from "../../types/types"; import type { ReducedSightingType } from "../../types/types";
import { toast } from "sonner"; import { toast } from "sonner";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
@@ -10,7 +10,7 @@ import { useCameraBlackboard } from "../../hooks/useCameraBlackboard";
const SessionCard = () => { const SessionCard = () => {
const { sessionStarted, setSessionStarted, sessionList, setSessionPaused, sessionPaused, savedSightings } = const { sessionStarted, setSessionStarted, sessionList, setSessionPaused, sessionPaused, savedSightings } =
useNPEDContext(); useIntegrationsContext();
const { mutation } = useCameraBlackboard(); const { mutation } = useCameraBlackboard();
const sightings = [...new Map(sessionList.map((vehicle) => [vehicle.vrm, vehicle]))]; const sightings = [...new Map(sessionList.map((vehicle) => [vehicle.vrm, vehicle]))];

View File

@@ -6,16 +6,18 @@ import { toast } from "sonner";
import { faEyeSlash, faEye } from "@fortawesome/free-solid-svg-icons"; import { faEyeSlash, faEye } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useState } from "react"; import { useState } from "react";
import { useIntegrationsContext } from "../../../context/IntegrationsContext";
const NPEDFields = () => { const NPEDFields = () => {
const { state } = useIntegrationsContext();
const [showPwd, setShowPwd] = useState(false); const [showPwd, setShowPwd] = useState(false);
const { signIn, user, signOut } = useNPEDAuth(); const { signIn, signOut } = useNPEDAuth();
const initialValues = user const initialValues = state.npedUser
? { ? {
username: user?.propUsername?.value, username: state.npedUser?.propUsername?.value,
password: user?.propPassword?.value, password: state.npedUser?.propPassword?.value,
clientId: user?.propClientID?.value, clientId: state.npedUser?.propClientID?.value,
frontId: "NPED", frontId: "NPED",
rearId: "NPED", rearId: "NPED",
} }
@@ -48,20 +50,13 @@ const NPEDFields = () => {
}; };
return ( return (
<Formik <Formik initialValues={initialValues} onSubmit={handleSubmit} validate={validateValues} enableReinitialize>
initialValues={initialValues}
onSubmit={handleSubmit}
validate={validateValues}
enableReinitialize
>
{({ errors, touched, isSubmitting }) => ( {({ errors, touched, isSubmitting }) => (
<Form className="flex flex-col space-y-5 px-2"> <Form className="flex flex-col space-y-5 px-2">
<FormGroup> <FormGroup>
<label htmlFor="username">Username</label> <label htmlFor="username">Username</label>
{touched.username && errors.username && ( {touched.username && errors.username && (
<small className="absolute right-0 -top-5 text-red-500"> <small className="absolute right-0 -top-5 text-red-500">{errors.username}</small>
{errors.username}
</small>
)} )}
<Field <Field
name="username" name="username"
@@ -82,9 +77,7 @@ const NPEDFields = () => {
className="p-2 border border-gray-400 rounded-lg w-full" className="p-2 border border-gray-400 rounded-lg w-full"
/> />
{touched.password && errors.password && ( {touched.password && errors.password && (
<small className="absolute right-0 -top-5 text-red-500"> <small className="absolute right-0 -top-5 text-red-500">{errors.password}</small>
{errors.password}
</small>
)} )}
<FontAwesomeIcon <FontAwesomeIcon
type="button" type="button"
@@ -97,9 +90,7 @@ const NPEDFields = () => {
<FormGroup> <FormGroup>
<label htmlFor="clientId">Client ID</label> <label htmlFor="clientId">Client ID</label>
{touched.clientId && errors.clientId && ( {touched.clientId && errors.clientId && (
<small className="absolute right-0 -top-5 text-red-500"> <small className="absolute right-0 -top-5 text-red-500">{errors.clientId}</small>
{errors.clientId}
</small>
)} )}
<Field <Field
name="clientId" name="clientId"
@@ -109,7 +100,7 @@ const NPEDFields = () => {
className="p-1.5 border border-gray-400 rounded-lg" className="p-1.5 border border-gray-400 rounded-lg"
/> />
</FormGroup> </FormGroup>
{!user?.propClientID?.value ? ( {!state.npedUser?.propClientID?.value ? (
<button <button
type="submit" type="submit"
className="w-1/4 text-white bg-green-700 hover:bg-green-800 font-small rounded-lg text-sm px-2 py-2.5 hover:cursor-pointer" className="w-1/4 text-white bg-green-700 hover:bg-green-800 font-small rounded-lg text-sm px-2 py-2.5 hover:cursor-pointer"

View File

@@ -15,7 +15,7 @@ import NPED_CAT_C from "/NPED_Cat_C.svg";
import popup from "../../assets/sounds/ui/popup_open.mp3"; import popup from "../../assets/sounds/ui/popup_open.mp3";
import notification from "../../assets/sounds/ui/notification.mp3"; import notification from "../../assets/sounds/ui/notification.mp3";
import { useSound } from "react-sounds"; import { useSound } from "react-sounds";
import { useNPEDContext } from "../../context/NPEDUserContext"; import { useIntegrationsContext } from "../../context/IntegrationsContext";
import { useSoundContext } from "../../context/SoundContext"; import { useSoundContext } from "../../context/SoundContext";
import Loading from "../UI/Loading"; import Loading from "../UI/Loading";
import { checkIsHotListHit, getNPEDCategory } from "../../utils/utils"; import { checkIsHotListHit, getNPEDCategory } from "../../utils/utils";
@@ -70,9 +70,9 @@ export default function SightingHistoryWidget({ className, title }: SightingHist
mostRecent, mostRecent,
isLoading, isLoading,
} = useSightingFeedContext(); } = useSightingFeedContext();
console.log(sightings);
const { dispatch } = useAlertHitContext(); const { dispatch } = useAlertHitContext();
const { sessionStarted, setSessionList, sessionList, sessionPaused } = useNPEDContext(); const { sessionStarted, setSessionList, sessionList, sessionPaused } = useIntegrationsContext();
const processedRefs = useRef<Set<number | string>>(new Set()); const processedRefs = useRef<Set<number | string>>(new Set());

View File

@@ -4,11 +4,11 @@ import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faGear, faHome, faListCheck, faMaximize, faMinimize, faRotate } from "@fortawesome/free-solid-svg-icons"; import { faGear, faHome, faListCheck, faMaximize, faMinimize, faRotate } from "@fortawesome/free-solid-svg-icons";
import { useState } from "react"; import { useState } from "react";
import SoundBtn from "./SoundBtn"; import SoundBtn from "./SoundBtn";
import { useNPEDContext } from "../../context/NPEDUserContext"; import { useIntegrationsContext } from "../../context/IntegrationsContext";
export default function Header() { export default function Header() {
const [isFullscreen, setIsFullscreen] = useState(false); const [isFullscreen, setIsFullscreen] = useState(false);
const { sessionStarted, sessionPaused } = useNPEDContext(); const { sessionStarted, sessionPaused } = useIntegrationsContext();
const toggleFullscreen = () => { const toggleFullscreen = () => {
if (!document.fullscreenElement) { if (!document.fullscreenElement) {

View File

@@ -0,0 +1,22 @@
import { createContext, useContext, type ActionDispatch, type SetStateAction } from "react";
import type { DedupedSightings, NPEDACTION, NPEDSTATE, ReducedSightingType } from "../types/types";
type IntegrationsValue = {
sessionStarted: boolean;
sessionPaused: boolean;
setSessionPaused: React.Dispatch<SetStateAction<boolean>>;
setSessionStarted: React.Dispatch<SetStateAction<boolean>>;
sessionList: ReducedSightingType[];
setSessionList: React.Dispatch<SetStateAction<ReducedSightingType[]>>;
savedSightings: DedupedSightings;
setSavedSightings: React.Dispatch<SetStateAction<DedupedSightings>>;
state: NPEDSTATE;
dispatch: ActionDispatch<[action: NPEDACTION]>;
};
export const IntegrationsContext = createContext<IntegrationsValue | undefined>(undefined);
export const useIntegrationsContext = () => {
const ctx = useContext(IntegrationsContext);
if (!ctx) throw new Error("useNPEDContext must be used within <IntegrationsProvider>");
return ctx;
};

View File

@@ -1,22 +0,0 @@
import { createContext, useContext, type SetStateAction } from "react";
import type { DedupedSightings, NPEDUser, ReducedSightingType } from "../types/types";
type UserContextValue = {
user: NPEDUser | null;
setUser: React.Dispatch<SetStateAction<NPEDUser | null>>;
sessionStarted: boolean;
sessionPaused: boolean;
setSessionPaused: React.Dispatch<SetStateAction<boolean>>;
setSessionStarted: React.Dispatch<SetStateAction<boolean>>;
sessionList: ReducedSightingType[];
setSessionList: React.Dispatch<SetStateAction<ReducedSightingType[]>>;
savedSightings: DedupedSightings;
setSavedSightings: React.Dispatch<SetStateAction<DedupedSightings>>;
};
export const NPEDUserContext = createContext<UserContextValue | undefined>(undefined);
export const useNPEDContext = () => {
const ctx = useContext(NPEDUserContext);
if (!ctx) throw new Error("useNPEDContext must be used within <NPEDUserProvider>");
return ctx;
};

View File

@@ -1,17 +1,16 @@
import { useEffect, useReducer, useState, type ReactNode } from "react"; import { useEffect, useReducer, useState, type ReactNode } from "react";
import type { DedupedSightings, NPEDUser, ReducedSightingType } from "../../types/types"; import type { DedupedSightings, ReducedSightingType } from "../../types/types";
import { NPEDUserContext } from "../NPEDUserContext"; import { IntegrationsContext } from "../IntegrationsContext";
import { useCameraBlackboard } from "../../hooks/useCameraBlackboard"; import { useCameraBlackboard } from "../../hooks/useCameraBlackboard";
import { initialState, reducer } from "../reducers/NPEDContextReducer"; import { initialState, reducer } from "../reducers/IntegrationsContextReducer";
type NPEDUserProviderType = { type IntegrationsProviderType = {
children: ReactNode; children: ReactNode;
}; };
export const NPEDUserProvider = ({ children }: NPEDUserProviderType) => { export const IntegrationsProvider = ({ children }: IntegrationsProviderType) => {
const [state, dispatch] = useReducer(reducer, initialState); const [state, dispatch] = useReducer(reducer, initialState);
const { mutation } = useCameraBlackboard(); const { mutation } = useCameraBlackboard();
const [user, setUser] = useState<NPEDUser | null>(null);
const [sessionStarted, setSessionStarted] = useState(false); const [sessionStarted, setSessionStarted] = useState(false);
const [sessionList, setSessionList] = useState<ReducedSightingType[]>([]); const [sessionList, setSessionList] = useState<ReducedSightingType[]>([]);
const [sessionPaused, setSessionPaused] = useState(false); const [sessionPaused, setSessionPaused] = useState(false);
@@ -28,12 +27,10 @@ export const NPEDUserProvider = ({ children }: NPEDUserProviderType) => {
}; };
fetchData(); fetchData();
}, []); }, []);
console.log(savedSightings);
return ( return (
<NPEDUserContext.Provider <IntegrationsContext.Provider
value={{ value={{
user,
setUser,
setSessionStarted, setSessionStarted,
sessionStarted, sessionStarted,
sessionList, sessionList,
@@ -42,9 +39,11 @@ export const NPEDUserProvider = ({ children }: NPEDUserProviderType) => {
setSessionPaused, setSessionPaused,
savedSightings, savedSightings,
setSavedSightings, setSavedSightings,
state,
dispatch,
}} }}
> >
{children} {children}
</NPEDUserContext.Provider> </IntegrationsContext.Provider>
); );
}; };

View File

@@ -5,15 +5,26 @@ export const initialState = {
sessionList: [], sessionList: [],
sessionPaused: false, sessionPaused: false,
savedSightings: [], savedSightings: [],
npedUser: null,
}; };
export function reducer(state: NPEDSTATE, action: NPEDACTION) { export function reducer(state: NPEDSTATE, action: NPEDACTION) {
switch (action.type) { switch (action.type) {
case "SESSION": case "SESSIONSTART":
return { return {
...state, ...state,
sessionStarted: action.payload, sessionStarted: action.payload,
}; };
case "LOGIN":
return {
...state,
npedUser: action.payload,
};
case "LOGOUT":
return {
...state,
npedUser: action.payload,
};
default: default:
return { ...state }; return { ...state };
} }

View File

@@ -1,6 +1,6 @@
import { useMutation, useQuery } from "@tanstack/react-query"; import { useMutation, useQuery } from "@tanstack/react-query";
import type { NPEDFieldType } from "../types/types"; import type { NPEDFieldType } from "../types/types";
import { useNPEDContext } from "../context/NPEDUserContext"; import { useIntegrationsContext } from "../context/IntegrationsContext";
import { useEffect } from "react"; import { useEffect } from "react";
import { CAM_BASE } from "../utils/config"; import { CAM_BASE } from "../utils/config";
import { toast } from "sonner"; import { toast } from "sonner";
@@ -42,8 +42,7 @@ async function signIn(loginDetails: NPEDFieldType) {
}), }),
]); ]);
if (!frontRes.ok || !rearRes.ok) if (!frontRes.ok || !rearRes.ok) throw new Error("Cannot reach NPED endpoint");
throw new Error("Cannot reach NPED endpoint");
return { return {
frontResponse: frontRes.json(), frontResponse: frontRes.json(),
@@ -73,7 +72,7 @@ async function signOut() {
} }
export const useNPEDAuth = () => { export const useNPEDAuth = () => {
const { setUser, user } = useNPEDContext(); const { dispatch } = useIntegrationsContext();
const signInMutation = useMutation({ const signInMutation = useMutation({
mutationKey: ["NPEDSignin"], mutationKey: ["NPEDSignin"],
@@ -84,7 +83,8 @@ export const useNPEDAuth = () => {
onSuccess: async (data) => { onSuccess: async (data) => {
toast.dismiss(); toast.dismiss();
toast.success("Signed in successfully!"); toast.success("Signed in successfully!");
setUser(await data.frontResponse);
dispatch({ type: "LOGIN", payload: await data.frontResponse });
}, },
onError: (error) => { onError: (error) => {
toast.dismiss(); toast.dismiss();
@@ -101,7 +101,7 @@ export const useNPEDAuth = () => {
mutationFn: signOut, mutationFn: signOut,
onSuccess: () => { onSuccess: () => {
toast.success("Signed out successfully"); toast.success("Signed out successfully");
setUser(null); dispatch({ type: "LOGOUT", payload: null });
}, },
onError: (error) => { onError: (error) => {
toast.error(`Sign-out failed: ${error.message}`); toast.error(`Sign-out failed: ${error.message}`);
@@ -115,11 +115,11 @@ export const useNPEDAuth = () => {
useEffect(() => { useEffect(() => {
if (fetchdataQuery.isSuccess && fetchdataQuery.data) { if (fetchdataQuery.isSuccess && fetchdataQuery.data) {
setUser(fetchdataQuery.data); dispatch({ type: "LOGIN", payload: fetchdataQuery.data });
} else { } else {
setUser(null); dispatch({ type: "LOGOUT", payload: null });
} }
}, [fetchdataQuery.data, fetchdataQuery.isSuccess, setUser]); }, [dispatch, fetchdataQuery.data, fetchdataQuery.isSuccess]);
useEffect(() => { useEffect(() => {
if (fetchdataQuery.isError) toast.error(fetchdataQuery.error.message); if (fetchdataQuery.isError) toast.error(fetchdataQuery.error.message);
@@ -134,8 +134,6 @@ export const useNPEDAuth = () => {
data: signInMutation.data, data: signInMutation.data,
fetchdataQueryError: fetchdataQuery.error, fetchdataQueryError: fetchdataQuery.error,
fetchdataQueryLoading: fetchdataQuery.isLoading, fetchdataQueryLoading: fetchdataQuery.isLoading,
user,
setUser,
signOut: signOutMutation.mutate, signOut: signOutMutation.mutate,
}; };
}; };

View File

@@ -387,6 +387,7 @@ export type NPEDSTATE = {
sessionList: ReducedSightingType[]; sessionList: ReducedSightingType[];
sessionPaused: boolean; sessionPaused: boolean;
savedSightings: DedupedSightings; savedSightings: DedupedSightings;
npedUser: NPEDUser;
}; };
export type NPEDACTION = { export type NPEDACTION = {