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

5
.env
View File

@@ -1,3 +1,6 @@
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_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",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview"
"preview": "vite preview",
"type-check": "tsc --noEmit"
},
"dependencies": {
"@fortawesome/fontawesome-svg-core": "^7.0.0",

View File

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

View File

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

View File

@@ -139,6 +139,10 @@ const SystemConfigFields = () => {
name={"softwareUpdate"}
selectedFile={values.softwareUpdate}
/>
<div className="border-b border-gray-600">
<p>Reboot</p>
</div>
<button
type="button"
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 = () => {
if (!selectedFile) return;
uploadSettings(selectedFile, {
timeoutMs: 30000,
fieldName: "upload",
});
const settings = {
file: selectedFile,
opts: {
timeoutMs: 30000,
fieldName: "upload",
uploadUrl: "http://192.168.75.11/upload/software-update/2'",
},
};
uploadSettings(settings);
};
return (
<div className="py-8 w-full">
<div className="border-b border-gray-600">
<h2>Software Update file upload</h2>
</div>
<FormGroup>
<div className="flex-1 flex justify-end md:w-2/3">
<div className="flex-1 flex md:w-2/3 my-5">
<input
type="file"
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 (
<Card className="mb-4">
<CardHeader title={"WiFi"} />
<div className="flex flex-col gap-4">
<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
id="ssid"
name="ssid"
@@ -21,11 +27,16 @@ const WiFiCard = () => {
className="p-2 border border-gray-400 rounded-lg flex-1 md:w-2/3"
placeholder="Enter SSID"
value={ssid}
onChange={e => setSsid(e.target.value)}
onChange={(e) => setSsid(e.target.value)}
/>
</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
id="password"
name="password"
@@ -33,17 +44,22 @@ const WiFiCard = () => {
className="p-2 border border-gray-400 rounded-lg flex-1 md:w-2/3"
placeholder="Enter Password"
value={password}
onChange={e => setPassword(e.target.value)}
onChange={(e) => setPassword(e.target.value)}
/>
</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
id="encryption"
name="encryption"
className="p-2 border border-gray-400 rounded-lg text-white bg-[#253445] flex-1 md:w-2/3"
value={encryption}
onChange={e => setEncryption(e.target.value)}
onChange={(e) => setEncryption(e.target.value)}
>
<option value="WPA2">WPA2</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"
/>
<div className="flex items-center gap-3">
<div className="flex flex-col md:flex-row items-center gap-3">
<img
src={sighting?.plateUrlColour}
alt="plate patch"

View File

@@ -16,13 +16,15 @@ const SightingOverview = () => {
setOverlayMode((m) => ((m + 1) % 3) as 0 | 1 | 2);
}, []);
const { side, mostRecent } = useSightingFeedContext();
const { side, mostRecent, isError, isLoading } = useSightingFeedContext();
useOverviewOverlay(mostRecent, overlayMode, 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 (
<div className="flex flex-col">

View File

@@ -16,7 +16,7 @@ const ModalComponent = ({
<Modal
isOpen={isModalOpen}
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"
>
{children}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -4,15 +4,12 @@ import SightingHistoryWidget from "../components/SightingsWidget/SightingWidget"
import { SightingFeedProvider } from "../context/providers/SightingFeedProvider";
const Dashboard = () => {
const folkestoneUrl = import.meta.env.VITE_FOLKESTONE_URL;
const outsideCamUrl = import.meta.env.VITE_MAV_URL;
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">
<SightingFeedProvider
url={
// "http://100.116.253.81/mergedHistory/sightingSummary?mostRecentRef="
"http://192.168.75.11/SightingListFront/sightingSummary?mostRecentRef="
}
side="Front"
>
<SightingFeedProvider url={folkestoneUrl} side="Front">
<FrontCameraOverviewCard className="order-1" />
<SightingHistoryWidget
className="order-3"
@@ -20,13 +17,7 @@ const Dashboard = () => {
/>
</SightingFeedProvider>
<SightingFeedProvider
url={
// "http://100.116.253.81/mergedHistory/sightingSummary?mostRecentRef="
"http://192.168.75.11/SightingListRear/sightingSummary?mostRecentRef="
}
side="Rear"
>
<SightingFeedProvider url={outsideCamUrl} side="Rear">
<RearCameraOverviewCard className="order-2" />
<SightingHistoryWidget
className="order-4"

View File

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