code quality improvements and improved file error handling

This commit is contained in:
2025-09-17 11:39:26 +01:00
parent b98e3ed85d
commit 0b7ab3b0de
20 changed files with 226 additions and 144 deletions

3
.env
View File

@@ -1,3 +1,6 @@
VITE_BASEURL=http://192.168.75.11/ VITE_BASEURL=http://192.168.75.11/
VITE_FOLKESTONE_BASE=http://100.116.253.81
VITE_TESTURL=http://100.82.205.44/SightingListRear/sightingSummary?mostRecentRef=-1 VITE_TESTURL=http://100.82.205.44/SightingListRear/sightingSummary?mostRecentRef=-1
VITE_OUTSIDE_BASEURL=http://100.82.205.44/api VITE_OUTSIDE_BASEURL=http://100.82.205.44/api
VITE_FOLKESTONE_URL=http://100.116.253.81/mergedHistory/sightingSummary?mostRecentRef=
VITE_MAV_URL=http://192.168.75.11/SightingListFront/sightingSummary?mostRecentRef=

View File

@@ -7,7 +7,8 @@
"dev": "vite", "dev": "vite",
"build": "tsc -b && vite build", "build": "tsc -b && vite build",
"lint": "eslint .", "lint": "eslint .",
"preview": "vite preview" "preview": "vite preview",
"type-check": "tsc --noEmit"
}, },
"dependencies": { "dependencies": {
"@fortawesome/fontawesome-svg-core": "^7.0.0", "@fortawesome/fontawesome-svg-core": "^7.0.0",

View File

@@ -13,9 +13,9 @@ const NPEDFields = () => {
const initialValues = user const initialValues = user
? { ? {
username: user.propUsername.value, username: user?.propUsername?.value,
password: user.propPassword.value, password: user?.propPassword?.value,
clientId: user.propClientID.value, clientId: user?.propClientID?.value,
frontId: "NPED", frontId: "NPED",
rearId: "NPED", rearId: "NPED",
} }

View File

@@ -1,13 +1,26 @@
import { Form, Formik } from "formik"; import { Form, Formik } from "formik";
import type { HotlistUploadType } from "../../../types/types"; import type { HotlistUploadType } from "../../../types/types";
import { useSystemConfig } from "../../../hooks/useSystemConfig";
const NPEDHotlist = () => { const NPEDHotlist = () => {
const { uploadSettings } = useSystemConfig();
const initialValue = { const initialValue = {
file: null, file: null,
}; };
const handleSubmit = (values: HotlistUploadType) => console.log(values.file); const handleSubmit = (values: HotlistUploadType) => {
// upload/hotlist-upload/2 const settings = {
file: values.file,
opts: {
timeoutMs: 30000,
fieldName: "upload",
uploadUrl: "http://192.168.75.11/upload/hotlist-upload/2",
},
};
uploadSettings(settings);
};
return ( return (
<Formik initialValues={initialValue} onSubmit={handleSubmit}> <Formik initialValues={initialValue} onSubmit={handleSubmit}>
{({ setFieldValue, setErrors, errors }) => { {({ setFieldValue, setErrors, errors }) => {
@@ -24,21 +37,21 @@ const NPEDHotlist = () => {
setErrors({ setErrors({
file: "This file is not a CSV, please select a different one", file: "This file is not a CSV, please select a different one",
}); });
return;
} }
setFieldValue("file", e.target.files[0]); setFieldValue("file", e.target.files[0]);
} else {
setErrors({ file: "no file" });
} }
}} }}
/> />
<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"
disabled={errors ? true : false} // disabled={errors ? true : false}
> >
Upload Upload
</button> </button>
<p>{errors && errors.file}</p> <p>{errors.file && errors.file}</p>
</Form> </Form>
); );
}} }}

View File

@@ -139,6 +139,10 @@ const SystemConfigFields = () => {
name={"softwareUpdate"} name={"softwareUpdate"}
selectedFile={values.softwareUpdate} selectedFile={values.softwareUpdate}
/> />
<div className="border-b border-gray-600">
<p>Reboot</p>
</div>
<button <button
type="button" type="button"
className="bg-red-600 text-white px-4 py-2 rounded hover:bg-red-700 transition w-full max-w-md" className="bg-red-600 text-white px-4 py-2 rounded hover:bg-red-700 transition w-full max-w-md"

View File

@@ -14,16 +14,24 @@ const SystemFileUpload = ({ name, selectedFile }: SystemFileUploadProps) => {
const handleFileUploadClick = () => { const handleFileUploadClick = () => {
if (!selectedFile) return; if (!selectedFile) return;
uploadSettings(selectedFile, { const settings = {
file: selectedFile,
opts: {
timeoutMs: 30000, timeoutMs: 30000,
fieldName: "upload", fieldName: "upload",
}); uploadUrl: "http://192.168.75.11/upload/software-update/2'",
},
};
uploadSettings(settings);
}; };
return ( return (
<div className="py-8 w-full"> <div className="py-8 w-full">
<div className="border-b border-gray-600">
<h2>Software Update file upload</h2>
</div>
<FormGroup> <FormGroup>
<div className="flex-1 flex justify-end md:w-2/3"> <div className="flex-1 flex md:w-2/3 my-5">
<input <input
type="file" type="file"
name="softwareUpdate" name="softwareUpdate"

View File

@@ -0,0 +1,64 @@
// CORS (server missing Access-Control-Allow-* headers)??
type BlobFileUpload = {
file: File | null;
opts?: {
timeoutMs?: number;
fieldName?: string;
overrideFileName?: string;
uploadUrl: URL | string;
};
};
export async function sendBlobFileUpload({
file,
opts,
}: BlobFileUpload): Promise<string> {
if (!file) throw new Error("No file supplied");
if (!opts?.uploadUrl) throw new Error("No URL supplied");
if (file?.type !== "text/csv") {
throw new Error("This file is not supported, please upload a CSV file.");
}
const timeoutMs = opts?.timeoutMs ?? 30000;
const fieldName = opts?.fieldName ?? "upload";
const fileName = opts?.overrideFileName ?? file?.name;
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), timeoutMs);
try {
const form = new FormData();
form.append(fieldName, file, fileName);
const resp = await fetch(opts?.uploadUrl, {
method: "POST",
body: form,
signal: controller.signal,
redirect: "follow",
});
const bodyText = await resp.text();
if (!resp.ok) {
throw new Error(
`Upload failed (${resp.status} ${resp.statusText}) from ${opts.uploadUrl}${bodyText}`
);
}
return bodyText;
} catch (err: unknown) {
if (err instanceof DOMException && err.name === "AbortError") {
throw new Error(`Timeout uploading to ${opts.uploadUrl}.`);
}
// In browsers, fetch throws TypeError on network-level failures
if (err instanceof TypeError) {
throw new Error(
`HTTP error uploading to ${opts.uploadUrl}: ${err.message}`
);
}
throw new Error("HTTP method POST is not supported by this URL");
} finally {
clearTimeout(timeout);
}
}

View File

@@ -1,47 +0,0 @@
// CORS (server missing Access-Control-Allow-* headers)??
export async function sendBlobFileUpload(
file: File,
opts?: { timeoutMs?: number; fieldName?: string; overrideFileName?: string }
): Promise<string> {
const timeoutMs = opts?.timeoutMs ?? 30000;
const fieldName = opts?.fieldName ?? "upload";
const fileName = opts?.overrideFileName ?? file.name;
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), timeoutMs);
try {
const form = new FormData();
form.append(fieldName, file, fileName);
const resp = await fetch("http://192.168.75.11/upload/hotlist-upload/2", {
method: "POST",
body: form,
signal: controller.signal,
redirect: "follow",
});
const bodyText = await resp.text();
if (!resp.ok) {
// throw new Error(
// `Server returned ${resp.status}: ${resp.statusText}. Details: ${bodyText}`
// );
return `Server returned ${resp.status}: ${resp.statusText}. Details: ${bodyText}`;
}
return bodyText;
} catch (err: any) {
if (err?.name === "AbortError") {
return `Timeout uploading to /upload/software-update/2.`;
}
// In browsers, fetch throws TypeError on network-level failures
if (err instanceof TypeError) {
return `HTTP error uploading to /upload/software-update/2: ${err.message}`;
}
return `Unexpected error uploading to /upload/software-update/2: ${
err?.message ?? String(err)
} ${err?.cause ?? ""}`;
} finally {
clearTimeout(timeout);
}
}

View File

@@ -11,9 +11,15 @@ const WiFiCard = () => {
return ( return (
<Card className="mb-4"> <Card className="mb-4">
<CardHeader title={"WiFi"} /> <CardHeader title={"WiFi"} />
<div className="flex flex-col gap-4"> <div className="flex flex-col gap-4">
<FormGroup> <FormGroup>
<label htmlFor="ssid" className="font-medium whitespace-nowrap md:w-2/3">SSID</label> <label
htmlFor="ssid"
className="font-medium whitespace-nowrap md:w-2/3"
>
SSID
</label>
<input <input
id="ssid" id="ssid"
name="ssid" name="ssid"
@@ -21,11 +27,16 @@ const WiFiCard = () => {
className="p-2 border border-gray-400 rounded-lg flex-1 md:w-2/3" className="p-2 border border-gray-400 rounded-lg flex-1 md:w-2/3"
placeholder="Enter SSID" placeholder="Enter SSID"
value={ssid} value={ssid}
onChange={e => setSsid(e.target.value)} onChange={(e) => setSsid(e.target.value)}
/> />
</FormGroup> </FormGroup>
<FormGroup> <FormGroup>
<label htmlFor="password" className="font-medium whitespace-nowrap md:w-2/3">Password</label> <label
htmlFor="password"
className="font-medium whitespace-nowrap md:w-2/3"
>
Password
</label>
<input <input
id="password" id="password"
name="password" name="password"
@@ -33,17 +44,22 @@ const WiFiCard = () => {
className="p-2 border border-gray-400 rounded-lg flex-1 md:w-2/3" className="p-2 border border-gray-400 rounded-lg flex-1 md:w-2/3"
placeholder="Enter Password" placeholder="Enter Password"
value={password} value={password}
onChange={e => setPassword(e.target.value)} onChange={(e) => setPassword(e.target.value)}
/> />
</FormGroup> </FormGroup>
<FormGroup> <FormGroup>
<label htmlFor="encryption" className="font-medium whitespace-nowrap md:w-2/3">WPA/Encryption Type</label> <label
htmlFor="encryption"
className="font-medium whitespace-nowrap md:w-2/3"
>
WPA/Encryption Type
</label>
<select <select
id="encryption" id="encryption"
name="encryption" name="encryption"
className="p-2 border border-gray-400 rounded-lg text-white bg-[#253445] flex-1 md:w-2/3" className="p-2 border border-gray-400 rounded-lg text-white bg-[#253445] flex-1 md:w-2/3"
value={encryption} value={encryption}
onChange={e => setEncryption(e.target.value)} onChange={(e) => setEncryption(e.target.value)}
> >
<option value="WPA2">WPA2</option> <option value="WPA2">WPA2</option>
<option value="WPA3">WPA3</option> <option value="WPA3">WPA3</option>

View File

@@ -36,7 +36,7 @@ const SightingModal = ({
className="w-full h-56 sm:h-72 md:h-96 rounded-lg object-cover border border-gray-700" className="w-full h-56 sm:h-72 md:h-96 rounded-lg object-cover border border-gray-700"
/> />
<div className="flex items-center gap-3"> <div className="flex flex-col md:flex-row items-center gap-3">
<img <img
src={sighting?.plateUrlColour} src={sighting?.plateUrlColour}
alt="plate patch" alt="plate patch"

View File

@@ -16,13 +16,15 @@ const SightingOverview = () => {
setOverlayMode((m) => ((m + 1) % 3) as 0 | 1 | 2); setOverlayMode((m) => ((m + 1) % 3) as 0 | 1 | 2);
}, []); }, []);
const { side, mostRecent } = useSightingFeedContext(); const { side, mostRecent, isError, isLoading } = useSightingFeedContext();
useOverviewOverlay(mostRecent, overlayMode, imgRef, canvasRef); useOverviewOverlay(mostRecent, overlayMode, imgRef, canvasRef);
const { sync } = useHiDPICanvas(imgRef, canvasRef); const { sync } = useHiDPICanvas(imgRef, canvasRef);
// if (noSighting || isPending) return <p>loading</p>; if (isLoading) return <p>Loading</p>;
if (isError) return <p>An error occurred, Cannot display footage</p>;
return ( return (
<div className="flex flex-col"> <div className="flex flex-col">

View File

@@ -16,7 +16,7 @@ const ModalComponent = ({
<Modal <Modal
isOpen={isModalOpen} isOpen={isModalOpen}
onRequestClose={close} onRequestClose={close}
className="bg-[#1e2a38] p-6 rounded-lg shadow-lg max-w-[90%] mx-auto mt-20 md:w-[70%] md:h-[80%] z-100" className="bg-[#1e2a38] p-6 rounded-lg shadow-lg max-w-[90%] mx-auto mt-[1%] md:w-[70%] md:h-[90%] z-[100] overflow-y-auto max-h-screen"
overlayClassName="fixed inset-0 bg-[#1e2a38]/70 flex justify-center items-start z-100" overlayClassName="fixed inset-0 bg-[#1e2a38]/70 flex justify-center items-start z-100"
> >
{children} {children}

View File

@@ -12,6 +12,8 @@ type SightingFeedContextType = {
setSelectedSighting: (sighting: SightingType | SightingType | null) => void; setSelectedSighting: (sighting: SightingType | SightingType | null) => void;
setSightingModalOpen: (isSightingModalOpen: boolean) => void; setSightingModalOpen: (isSightingModalOpen: boolean) => void;
isSightingModalOpen: boolean; isSightingModalOpen: boolean;
isError: boolean;
isLoading: boolean;
}; };
export const SightingFeedContext = createContext< export const SightingFeedContext = createContext<

View File

@@ -17,11 +17,14 @@ export const SightingFeedProvider = ({
sightings, sightings,
selectedRef, selectedRef,
setSelectedRef, setSelectedRef,
// effectiveSelected,
isLoading,
isError,
setSelectedSighting, setSelectedSighting,
selectedSighting, selectedSighting,
mostRecent, mostRecent,
} = useSightingFeed(url); } = useSightingFeed(url);
const [isSightingModalOpen, setSightingModalOpen] = useState(false); const [isSightingModalOpen, setSightingModalOpen] = useState(false);
return ( return (
@@ -34,8 +37,9 @@ export const SightingFeedProvider = ({
selectedSighting, selectedSighting,
setSightingModalOpen, setSightingModalOpen,
isSightingModalOpen, isSightingModalOpen,
// effectiveSelected,
mostRecent, mostRecent,
isError,
isLoading,
side, side,
}} }}
> >

View File

@@ -2,10 +2,11 @@ import { useRef, useCallback, useEffect } from "react";
import { useQuery } from "@tanstack/react-query"; import { useQuery } from "@tanstack/react-query";
const apiUrl = import.meta.env.VITE_BASEURL; const apiUrl = import.meta.env.VITE_BASEURL;
const folkstoneUrl = import.meta.env.VITE_FOLKESTONE_BASE;
async function fetchSnapshot(cameraSide: string) { async function fetchSnapshot(cameraSide: string) {
console.log(`${folkstoneUrl}/${cameraSide}-preview`);
const response = await fetch( const response = await fetch(
// `http://100.116.253.81/Colour-preview` // `${folkstoneUrl}/Colour-preview`
`${apiUrl}/${cameraSide}-preview` `${apiUrl}/${cameraSide}-preview`
); );
if (!response.ok) { if (!response.ok) {

View File

@@ -2,8 +2,6 @@ import { useQuery } from "@tanstack/react-query";
import { useRef } from "react"; import { useRef } from "react";
const apiUrl = import.meta.env.VITE_BASEURL; const apiUrl = import.meta.env.VITE_BASEURL;
const FAST_MS = 200; // tab visible
const SLOW_MS = 2000; // tab hidden
async function fetchOverviewImage(cameraSide: string) { async function fetchOverviewImage(cameraSide: string) {
const response = await fetch(`${apiUrl}${cameraSide}-preview`); const response = await fetch(`${apiUrl}${cameraSide}-preview`);

View File

@@ -1,75 +1,97 @@
import { useEffect, useRef, useState } from "react"; import { useEffect, useRef, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import type { SightingType } from "../types/types"; import type { SightingType } from "../types/types";
async function fetchSighting(url: string, ref: number): Promise<SightingType> { async function fetchSighting(url: string, ref: number): Promise<SightingType> {
const res = await fetch(`${url}${ref}`); const res = await fetch(`${url}${ref}`);
if (!res.ok) throw new Error(String(res.status)); if (!res.ok) throw new Error(String(res.status));
return await res.json(); return res.json();
} }
export function useSightingFeed(url: string) { export function useSightingFeed(url: string) {
const [sightings, setSightings] = useState<SightingType[]>([]); const [sightings, setSightings] = useState<SightingType[]>([]);
const [selectedRef, setSelectedRef] = useState<number | null>(null); const [selectedRef, setSelectedRef] = useState<number | null>(null);
const [mostRecent, setMostRecent] = useState<SightingType | null>(null); const mostRecent = sightings[0] ?? null;
const [selectedSighting, setSelectedSighting] = useState<SightingType | null>( const [selectedSighting, setSelectedSighting] = useState<SightingType | null>(
null null
); );
const currentRef = useRef<number>(-1); const currentRef = useRef<number>(-1);
const pollingTimeout = useRef<ReturnType<typeof setTimeout> | null>(null);
const lastValidTimestamp = useRef<number>(Date.now()); const lastValidTimestamp = useRef<number>(Date.now());
const query = useQuery({
queryKey: ["sighting-feed", url],
enabled: !!url,
queryFn: () => fetchSighting(url, currentRef.current),
refetchInterval: (q) => {
const data = q.state.data as SightingType | undefined;
const now = Date.now();
if (data && data.ref !== -1) {
lastValidTimestamp.current = now;
return 100;
}
if (now - lastValidTimestamp.current > 60_000) {
currentRef.current = -1;
lastValidTimestamp.current = now;
}
return 400;
},
refetchIntervalInBackground: true,
refetchOnWindowFocus: false,
retry: false,
staleTime: 0,
});
useEffect(() => { useEffect(() => {
const poll = async () => { const data = query.data;
try { if (!data) return;
const data = await fetchSighting(url, currentRef.current);
const now = Date.now(); const now = Date.now();
if (data.ref === -1) { if (data.ref === -1) {
if (now - lastValidTimestamp.current > 60000) { // setSightings((prev) => {
console.warn("No valid sighting in over a minute. Restarting..."); // if (prev[0]?.ref === data.ref) return prev;
currentRef.current = -1; // const dedupPrev = prev.filter((s) => s.ref !== data.ref);
lastValidTimestamp.current = now; // return [data, ...dedupPrev].slice(0, 7);
// });
return;
} }
pollingTimeout.current = setTimeout(poll, 400);
} else {
currentRef.current = data.ref; currentRef.current = data.ref;
lastValidTimestamp.current = now; lastValidTimestamp.current = now;
setSightings((prev) => { setSightings((prev) => {
const updated = [data, ...prev].slice(0, 7); if (prev[0]?.ref === data.ref) return prev;
return updated; const dedupPrev = prev.filter((s) => s.ref !== data.ref);
return [data, ...dedupPrev].slice(0, 7);
}); });
setMostRecent(data);
setSelectedRef(data.ref); setSelectedRef(data.ref);
}, [query.data]);
pollingTimeout.current = setTimeout(poll, 100); useEffect(() => {
if (query.error) {
// you can add logging/telemetry here
// console.error("Sighting feed error:", query.error);
} }
} catch (err) { }, [query.error]);
console.error("Polling error:", err);
pollingTimeout.current = setTimeout(poll, 100);
}
};
poll();
return () => {
if (pollingTimeout.current) clearTimeout(pollingTimeout.current);
};
}, [url]);
// const selected = sightings.find(s => s?.ref === selectedRef) ?? mostRecent;
return { return {
sightings, sightings,
selectedRef, selectedRef,
setSelectedRef, setSelectedRef,
mostRecent, mostRecent,
setSelectedSighting,
selectedSighting, selectedSighting,
// effectiveSelected: selected, setSelectedSighting,
data: query.data,
isLoading: query.isLoading,
isFetching: query.isFetching,
isError: query.isError,
error: query.error as Error | null,
refetch: query.refetch,
}; };
} }

View File

@@ -10,8 +10,8 @@ export const useSystemConfig = () => {
const uploadSettingsMutation = useMutation({ const uploadSettingsMutation = useMutation({
mutationKey: ["uploadSettings"], mutationKey: ["uploadSettings"],
mutationFn: sendBlobFileUpload, mutationFn: sendBlobFileUpload,
onError: () => console.log("upload failed"), onError: (error) => toast.error(error.message),
onSuccess: (test) => console.log(test), onSuccess: (test) => toast(test),
}); });
const saveSystemSettings = useMutation({ const saveSystemSettings = useMutation({

View File

@@ -4,15 +4,12 @@ import SightingHistoryWidget from "../components/SightingsWidget/SightingWidget"
import { SightingFeedProvider } from "../context/providers/SightingFeedProvider"; import { SightingFeedProvider } from "../context/providers/SightingFeedProvider";
const Dashboard = () => { const Dashboard = () => {
const folkestoneUrl = import.meta.env.VITE_FOLKESTONE_URL;
const outsideCamUrl = import.meta.env.VITE_MAV_URL;
return ( return (
<div className="mx-auto grid grid-cols-1 sm:grid-cols-1 lg:grid-cols-2 gap-2 px-1 sm:px-2 lg:px-0 w-full"> <div className="mx-auto grid grid-cols-1 sm:grid-cols-1 lg:grid-cols-2 gap-2 px-1 sm:px-2 lg:px-0 w-full">
<SightingFeedProvider <SightingFeedProvider url={folkestoneUrl} side="Front">
url={
// "http://100.116.253.81/mergedHistory/sightingSummary?mostRecentRef="
"http://192.168.75.11/SightingListFront/sightingSummary?mostRecentRef="
}
side="Front"
>
<FrontCameraOverviewCard className="order-1" /> <FrontCameraOverviewCard className="order-1" />
<SightingHistoryWidget <SightingHistoryWidget
className="order-3" className="order-3"
@@ -20,13 +17,7 @@ const Dashboard = () => {
/> />
</SightingFeedProvider> </SightingFeedProvider>
<SightingFeedProvider <SightingFeedProvider url={outsideCamUrl} side="Rear">
url={
// "http://100.116.253.81/mergedHistory/sightingSummary?mostRecentRef="
"http://192.168.75.11/SightingListRear/sightingSummary?mostRecentRef="
}
side="Rear"
>
<RearCameraOverviewCard className="order-2" /> <RearCameraOverviewCard className="order-2" />
<SightingHistoryWidget <SightingHistoryWidget
className="order-4" className="order-4"

View File

@@ -61,14 +61,14 @@ export type InitialValuesForm = {
export type NPEDFieldType = { export type NPEDFieldType = {
frontId: string; frontId: string;
username: string; username: string | undefined;
password: string; password: string | undefined;
clientId: string; clientId: string | undefined;
rearId: string; rearId: string;
}; };
export type HotlistUploadType = { export type HotlistUploadType = {
file: string | null; file: File | null;
}; };
export type VersionFieldType = { export type VersionFieldType = {
@@ -99,9 +99,9 @@ export type NpedJSON = {
}; };
export type NPEDUser = { export type NPEDUser = {
username: string; propUsername?: Prop;
clientId: string; propClientID?: Prop;
password?: string; propPassword?: Prop;
}; };
export type NPEDErrorValues = { export type NPEDErrorValues = {