added nped list functionality

This commit is contained in:
2025-08-29 14:55:37 +01:00
parent d2b8827987
commit 4fd3bd4319
15 changed files with 152 additions and 39 deletions

View File

@@ -26,7 +26,6 @@ const CameraSettingFields = () => {
const handleSubmit = (values: CameraSettingValues) => { const handleSubmit = (values: CameraSettingValues) => {
// post values to endpoint // post values to endpoint
toast("Settings Saved"); toast("Settings Saved");
console.log(values);
}; };
return ( return (

View File

@@ -8,7 +8,6 @@ export const ValuesComponent = () => {
const BearerTypeFields = () => { const BearerTypeFields = () => {
const { values } = useFormikContext(); const { values } = useFormikContext();
console.log(values);
return ( return (
<div className="flex flex-col space-y-4"> <div className="flex flex-col space-y-4">

View File

@@ -1,11 +1,8 @@
import Card from "../../UI/Card"; import Card from "../../UI/Card";
import CardHeader from "../../UI/CardHeader"; import CardHeader from "../../UI/CardHeader";
import NPEDFields from "./NPEDFields"; import NPEDFields from "./NPEDFields";
import { useNPEDContext } from "../../../context/NPEDUserContext";
const NPEDCard = () => { const NPEDCard = () => {
const { user } = useNPEDContext();
console.log(user);
return ( return (
<Card> <Card>
<CardHeader title={"NPED Config"} /> <CardHeader title={"NPED Config"} />

View File

@@ -5,14 +5,22 @@ import { useNPEDAuth } from "../../../hooks/useNPEDAuth";
import { toast } from "sonner"; import { toast } from "sonner";
const NPEDFields = () => { const NPEDFields = () => {
const { signIn } = useNPEDAuth(); const { signIn, user, signOut } = useNPEDAuth();
const initialValues = { const initialValues = user
? {
username: user.propUsername.value,
password: "",
clientId: user.propClientID.value,
frontId: "NPED",
rearId: "NPED",
}
: {
username: "", username: "",
password: "", password: "",
clientId: "", clientId: "",
frontId: "NPEDFront", frontId: "NPED",
rearId: "NPEDRear", rearId: "NPED",
}; };
const handleSubmit = (values: NPEDFieldType) => { const handleSubmit = (values: NPEDFieldType) => {
@@ -20,7 +28,7 @@ const NPEDFields = () => {
...values, ...values,
}; };
signIn(valuesToSend); signIn(valuesToSend);
toast("Signed in successfully"); toast.success("Signed in successfully");
}; };
const validateValues = (values: NPEDFieldType) => { const validateValues = (values: NPEDFieldType) => {
@@ -31,6 +39,10 @@ const NPEDFields = () => {
return errors; return errors;
}; };
const handleLogoutClick = () => {
signOut();
};
return ( return (
<Formik <Formik
initialValues={initialValues} initialValues={initialValues}
@@ -84,12 +96,22 @@ 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 ? (
<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" 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"
> >
Login Login
</button> </button>
) : (
<button
type="button"
className="w-1/4 border-red-700 bg-red-800 text-white font-small rounded-lg text-sm px-2 py-2.5 hover:cursor-pointer"
onClick={handleLogoutClick}
>
Logout
</button>
)}
</Form> </Form>
)} )}
</Formik> </Formik>

View File

@@ -23,13 +23,14 @@ const SightingOverview = () => {
setOverlayMode((m) => ((m + 1) % 3) as 0 | 1 | 2); setOverlayMode((m) => ((m + 1) % 3) as 0 | 1 | 2);
}, []); }, []);
const { effectiveSelected, side, mostRecent, noSighting } = const { effectiveSelected, side, mostRecent, noSighting, isPending } =
useSightingFeedContext(); useSightingFeedContext();
useOverviewOverlay(mostRecent, overlayMode, imgRef, canvasRef); useOverviewOverlay(mostRecent, overlayMode, imgRef, canvasRef);
const { sync } = useHiDPICanvas(imgRef, canvasRef); const { sync } = useHiDPICanvas(imgRef, canvasRef);
if (noSighting) return <p>loading</p>;
if (noSighting || isPending) return <p>loading</p>;
return ( return (
<div className="mt-2 grid gap-3"> <div className="mt-2 grid gap-3">
<div className="inline-block w-[90%] mx-auto" {...handlers}> <div className="inline-block w-[90%] mx-auto" {...handlers}>

View File

@@ -50,11 +50,12 @@ export default function SightingHistoryWidget({
{/* Rows */} {/* Rows */}
<div className="flex flex-col"> <div className="flex flex-col">
{rows?.map((obj, idx) => { {rows?.map((obj, idx) => {
console.log(obj);
const isNPEDHit = obj?.metadata?.npedJSON?.status_code === 201;
const isSelected = obj?.ref === selectedRef; const isSelected = obj?.ref === selectedRef;
const motionAway = (obj?.motion ?? "").toUpperCase() === "AWAY"; const motionAway = (obj?.motion ?? "").toUpperCase() === "AWAY";
const primaryIsColour = obj?.srcCam === 1; const primaryIsColour = obj?.srcCam === 1;
const secondaryMissing = (obj?.vrmSecondary ?? "") === ""; const secondaryMissing = (obj?.vrmSecondary ?? "") === "";
return ( return (
<div <div
key={idx} key={idx}
@@ -80,7 +81,11 @@ export default function SightingHistoryWidget({
</div> </div>
{/* Patch row */} {/* Patch row */}
<div className="flex items-center gap-3 mt-2"> <div
className={`flex items-center gap-3 mt-2
${isNPEDHit ? "border border-red-600" : ""}
`}
>
<div <div
className={`border p-1 ${ className={`border p-1 ${
primaryIsColour ? "" : "ring-2 ring-lime-400" primaryIsColour ? "" : "ring-2 ring-lime-400"

View File

@@ -0,0 +1,11 @@
import { clsx } from "clsx";
type SkeletonBoxProps = {
className: string;
};
const SkeletonBox = ({ className }: SkeletonBoxProps) => {
return <div className={clsx(...className)}></div>;
};
export default SkeletonBox;

View File

@@ -1,8 +1,8 @@
import { createContext, useContext, type SetStateAction } from "react"; import { createContext, useContext, type SetStateAction } from "react";
import type { NPEDUser } from "../types/types"; import type { NPEDCameraConfig, NPEDUser } from "../types/types";
type UserContextValue = { type UserContextValue = {
user: NPEDUser | null; user: NPEDCameraConfig | null;
setUser: React.Dispatch<SetStateAction<NPEDUser | null>>; setUser: React.Dispatch<SetStateAction<NPEDUser | null>>;
}; };

View File

@@ -4,7 +4,6 @@ import { useQuery } from "@tanstack/react-query";
const apiUrl = import.meta.env.VITE_BASEURL; const apiUrl = import.meta.env.VITE_BASEURL;
async function fetchSnapshot(cameraSide: string) { async function fetchSnapshot(cameraSide: string) {
console.log(`${apiUrl}/${cameraSide}-preview`);
const response = await fetch( const response = await fetch(
// `http://100.116.253.81/Colour-preview` // `http://100.116.253.81/Colour-preview`
`${apiUrl}/${cameraSide}-preview` `${apiUrl}/${cameraSide}-preview`

View File

@@ -3,6 +3,7 @@ import { useCallback, useEffect, useRef } from "react";
async function fetchSighting() { async function fetchSighting() {
const response = await fetch( const response = await fetch(
// `http://100.82.205.44/api`
`http://100.116.253.81/mergedHistory/sightingSummary?mostRecentRef=-1` `http://100.116.253.81/mergedHistory/sightingSummary?mostRecentRef=-1`
); );
if (!response.ok) throw new Error("Failed to fetch sighting"); if (!response.ok) throw new Error("Failed to fetch sighting");

View File

@@ -1,15 +1,22 @@
import { useMutation } 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 { useNPEDContext } from "../context/NPEDUserContext";
import { useEffect } from "react";
const base_url = import.meta.env.VITE_OUTSIDE_BASEURL; const base_url = import.meta.env.VITE_OUTSIDE_BASEURL;
async function fetchNPEDDetails() {
const fetchUrl = `${base_url}/fetch-config?id=NPED`;
const response = await fetch(fetchUrl);
if (!response.ok) throw new Error("Cannot reach fetch-config endpoint");
const data = await response.json();
console.log(data);
return response.json();
}
async function signIn(loginDetails: NPEDFieldType) { async function signIn(loginDetails: NPEDFieldType) {
const { frontId, rearId, username, password, clientId } = loginDetails; const { frontId, rearId, username, password, clientId } = loginDetails;
const NPEDLoginURLFront = `${base_url}/update-config?id=${frontId}`; const NPEDLoginURLFront = `${base_url}/update-config?id=${frontId}`;
const NPEDLoginURLRear = `${base_url}/update-config?id=${rearId}`; const NPEDLoginURLRear = `${base_url}/update-config?id=${rearId}`;
const frontCameraPayload = { const frontCameraPayload = {
id: frontId, id: frontId,
fields: [ fields: [
@@ -43,8 +50,6 @@ async function signIn(loginDetails: NPEDFieldType) {
if (!frontCameraResponse.ok) throw new Error("cannot reach NPED endpoint"); if (!frontCameraResponse.ok) throw new Error("cannot reach NPED endpoint");
if (!rearCameraResponse.ok) throw new Error("cannot reach NPED endpoint"); if (!rearCameraResponse.ok) throw new Error("cannot reach NPED endpoint");
console.log(frontCameraResponse);
console.log(rearCameraResponse);
return { return {
frontResponse: frontCameraResponse.json(), frontResponse: frontCameraResponse.json(),
rearResponse: rearCameraResponse.json(), rearResponse: rearCameraResponse.json(),
@@ -52,13 +57,28 @@ async function signIn(loginDetails: NPEDFieldType) {
} }
async function signOut() { async function signOut() {
const response = await fetch(url, { method: "POST" }); const nullPayload = {
id: "NPED",
fields: [
{ property: "propEnabled", value: false },
{ property: "propUsername", value: "" },
{ property: "propPassword", value: "" },
{ property: "propClientID", value: "" },
],
};
const NPEDLoginURLFront = `${base_url}/update-config?id=NPED`;
const response = await fetch(NPEDLoginURLFront, {
method: "POST",
body: JSON.stringify(nullPayload),
});
if (!response.ok) throw new Error("cannot reach NPED sign out endpoint"); if (!response.ok) throw new Error("cannot reach NPED sign out endpoint");
return response.json(); return response.json();
} }
export const useNPEDAuth = () => { export const useNPEDAuth = () => {
const { setUser } = useNPEDContext(); const { setUser, user } = useNPEDContext();
const signInMutation = useMutation({ const signInMutation = useMutation({
mutationKey: ["NPEDSignin"], mutationKey: ["NPEDSignin"],
@@ -69,9 +89,24 @@ export const useNPEDAuth = () => {
const signOutMutation = useMutation({ const signOutMutation = useMutation({
mutationKey: ["auth", "NPEDSignOut"], mutationKey: ["auth", "NPEDSignOut"],
mutationFn: signOut, mutationFn: signOut,
onSuccess: () => setUser(null),
}); });
const fetchdataQuery = useQuery({
queryKey: ["auth", "NPEDFetch"],
queryFn: fetchNPEDDetails,
});
useEffect(() => {
if (fetchdataQuery.isSuccess && fetchdataQuery.data) {
setUser(fetchdataQuery.data);
} else if (
!fetchdataQuery?.data?.propUsername?.value &&
!fetchdataQuery?.data?.propClientID?.value
) {
setUser(null);
}
}, [fetchdataQuery.data, fetchdataQuery.isSuccess, setUser]);
return { return {
signIn: signInMutation.mutate, signIn: signInMutation.mutate,
signInAsync: signInMutation.mutateAsync, signInAsync: signInMutation.mutateAsync,
@@ -79,7 +114,8 @@ export const useNPEDAuth = () => {
isError: signInMutation.isError, isError: signInMutation.isError,
error: signInMutation.error, error: signInMutation.error,
data: signInMutation.data, data: signInMutation.data,
user,
setUser,
signOut: signOutMutation.mutate, signOut: signOutMutation.mutate,
}; };
}; };

View File

@@ -6,6 +6,7 @@ import { useQuery } from "@tanstack/react-query";
async function fetchSighting(url: string, ref: number, signal?: AbortSignal) { async function fetchSighting(url: string, ref: number, signal?: AbortSignal) {
const dynamicUrl = `${url}${ref}`; const dynamicUrl = `${url}${ref}`;
const res = await fetch(dynamicUrl, { signal }); const res = await fetch(dynamicUrl, { signal });
if (!res.ok) throw new Error(String(res.status)); if (!res.ok) throw new Error(String(res.status));
return (await res.json()) as SightingWidgetType; return (await res.json()) as SightingWidgetType;
@@ -20,12 +21,13 @@ export function useSightingFeed(url: string) {
const [mostRecent, setMostRecent] = useState<SightingWidgetType | null>(null); const [mostRecent, setMostRecent] = useState<SightingWidgetType | null>(null);
const mostRecentRef = useRef<number>(-1); const mostRecentRef = useRef<number>(-1);
const lastSeenRef = useRef<number | null>(null); const lastSeenRef = useRef<number | null>(null);
const { data, isPending } = useQuery({ const { data, isPending } = useQuery({
queryKey: ["sighting"], queryKey: ["sighting"],
queryFn: ({ signal }) => fetchSighting(url, mostRecentRef.current, signal), queryFn: ({ signal }) => fetchSighting(url, mostRecentRef.current, signal),
refetchInterval: 200, refetchInterval: 2000,
refetchIntervalInBackground: true, refetchIntervalInBackground: true,
refetchOnWindowFocus: false, refetchOnWindowFocus: false,
staleTime: 0, staleTime: 0,

View File

@@ -9,7 +9,8 @@ const Dashboard = () => {
<div className="mx-auto grid grid-cols-1 sm:grid-cols-1 lg:grid-cols-2 gap-2 px-2 sm:px-4 lg:px-0 w-full"> <div className="mx-auto grid grid-cols-1 sm:grid-cols-1 lg:grid-cols-2 gap-2 px-2 sm:px-4 lg:px-0 w-full">
<SightingFeedProvider <SightingFeedProvider
url={ url={
"http://100.116.253.81/mergedHistory/sightingSummary?mostRecentRef=" "http://100.82.205.44/SightingListFront/sightingSummary?mostRecentRef="
// "http://100.116.253.81/mergedHistory/sightingSummary?mostRecentRef="
} }
side="Front" side="Front"
> >

View File

@@ -4,8 +4,11 @@ import NPEDCard from "../components/SettingForms/NPED/NPEDCard";
import SettingForms from "../components/SettingForms/SettingForms/SettingForms"; import SettingForms from "../components/SettingForms/SettingForms/SettingForms";
import NPEDHotlistCard from "../components/SettingForms/NPED/NPEDHotlistCard"; import NPEDHotlistCard from "../components/SettingForms/NPED/NPEDHotlistCard";
import { Toaster } from "sonner"; import { Toaster } from "sonner";
import { useNPEDAuth } from "../hooks/useNPEDAuth";
const SystemSettings = () => { const SystemSettings = () => {
const { user } = useNPEDAuth();
console.log(user);
return ( return (
<div className="m-4"> <div className="m-4">
<Tabs selectedTabClassName="bg-gray-300 text-gray-900 font-semibold border-none"> <Tabs selectedTabClassName="bg-gray-300 text-gray-900 font-semibold border-none">

View File

@@ -97,7 +97,25 @@ export type SightingWidgetType = {
plateUrlInfrared?: string; plateUrlInfrared?: string;
plateUrlColour?: string; plateUrlColour?: string;
overviewPlateRect?: [number, number, number, number]; // [x,y,w,h] normalized 0..1 overviewPlateRect?: [number, number, number, number]; // [x,y,w,h] normalized 0..1
plateTrack?: [number, number, number, number][]; // list of rects normalized 0..1 plateTrack?: [number, number, number, number][];
metadata?: Metadata;
// list of rects normalized 0..1
};
export type Metadata = {
npedJSON: NpedJSON;
"hotlist-matches": HotlistMatches;
};
export type HotlistMatches = {
Hotlist0: boolean;
Hotlist1: boolean;
Hotlist2: boolean;
};
export type NpedJSON = {
status_code: number;
reason_phrase: string;
}; };
export type NPEDUser = { export type NPEDUser = {
@@ -111,3 +129,22 @@ export type NPEDErrorValues = {
password?: string | undefined; password?: string | undefined;
clientId?: string | undefined; clientId?: string | undefined;
}; };
export type NPEDCameraConfig = {
id: string;
configHash: string;
propEnabled: Prop;
propUsername: Prop;
propPassword: Prop;
propClientID: Prop;
propConnectTimeoutSeconds: Prop;
propReadTimeoutSeconds: Prop;
propNPEDAuthTokenURL: Prop;
propNPEDLookupURL: Prop;
propVerbose: Prop;
};
export interface Prop {
value: string;
datatype: string;
}