- updated form to include bof2 constants

- refactored code to make more scalable and use one form
This commit is contained in:
2025-11-04 10:24:06 +00:00
parent 933c101cbc
commit 538b623ac6
7 changed files with 237 additions and 159 deletions

View File

@@ -1,4 +1,4 @@
import { Field, Form, useFormikContext } from "formik"; import { Field, useFormikContext } from "formik";
import FormToggle from "../components/FormToggle"; import FormToggle from "../components/FormToggle";
import FormGroup from "../components/FormGroup"; import FormGroup from "../components/FormGroup";
import type { BearerTypeFieldType, InitialValuesForm } from "../../../types/types"; import type { BearerTypeFieldType, InitialValuesForm } from "../../../types/types";
@@ -9,8 +9,8 @@ type BearerTypeFieldsProps = {
const BearerTypeFields = ({ options }: BearerTypeFieldsProps) => { const BearerTypeFields = ({ options }: BearerTypeFieldsProps) => {
useFormikContext<BearerTypeFieldType & InitialValuesForm>(); useFormikContext<BearerTypeFieldType & InitialValuesForm>();
return ( return (
<Form>
<div className="flex flex-col space-y-4 px-2"> <div className="flex flex-col space-y-4 px-2">
<FormGroup> <FormGroup>
<label htmlFor="format">Format</label> <label htmlFor="format">Format</label>
@@ -33,14 +33,7 @@ const BearerTypeFields = ({ options }: BearerTypeFieldsProps) => {
<FormToggle name="verbose" label="Verbose" /> <FormToggle name="verbose" label="Verbose" />
</div> </div>
</FormGroup> </FormGroup>
{/* <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"
>
{isSubmitting || dispatcherMutation.isPending ? "Saving..." : "Save Changes"}
</button> */}
</div> </div>
</Form>
); );
}; };

View File

@@ -3,18 +3,17 @@ import Card from "../../UI/Card";
import CardHeader from "../../UI/CardHeader"; import CardHeader from "../../UI/CardHeader";
import ChannelFields from "./ChannelFields"; import ChannelFields from "./ChannelFields";
import type { BearerTypeFieldType, InitialValuesForm } from "../../../types/types"; import type { BearerTypeFieldType, InitialValuesForm } from "../../../types/types";
import { useCameraBackOfficeOutput } from "../../../hooks/useCameraBackOfficeOutput"; import { useCameraBackOfficeOutput } from "../../../hooks/useBackOfficeConfig";
import { useEffect, useMemo } from "react"; import { useEffect, useMemo } from "react";
type ChannelCardProps = { type ChannelCardProps = {
touched: FormikTouched<BearerTypeFieldType & InitialValuesForm>; touched: FormikTouched<BearerTypeFieldType & InitialValuesForm>;
isSubmitting: boolean; isSubmitting: boolean;
handleFormSubmit: (values: BearerTypeFieldType & InitialValuesForm) => Promise<void>;
}; };
const ChannelCard = ({ touched, isSubmitting, handleFormSubmit }: ChannelCardProps) => { const ChannelCard = ({ touched, isSubmitting }: ChannelCardProps) => {
const { values, resetForm } = useFormikContext<BearerTypeFieldType & InitialValuesForm>(); const { values, setFieldValue } = useFormikContext<BearerTypeFieldType & InitialValuesForm>();
const { backOfficeQuery, backOfficeMutation } = useCameraBackOfficeOutput(values?.format); const { backOfficeQuery } = useCameraBackOfficeOutput(values?.format);
const mapped = useMemo(() => { const mapped = useMemo(() => {
const d = backOfficeQuery.data; const d = backOfficeQuery.data;
@@ -29,22 +28,10 @@ const ChannelCard = ({ touched, isSubmitting, handleFormSubmit }: ChannelCardPro
useEffect(() => { useEffect(() => {
if (!backOfficeQuery.isSuccess) return; if (!backOfficeQuery.isSuccess) return;
resetForm({ values: { ...values, ...mapped } }); for (const [key, value] of Object.entries(mapped)) {
// eslint-disable-next-line react-hooks/exhaustive-deps setFieldValue(key, value);
}, [backOfficeQuery.isSuccess, mapped]); }
}, [backOfficeQuery.isSuccess, mapped, setFieldValue]);
console.log(backOfficeQuery.isFetching);
const handleSubmit = async () => {
const backOfficeData = {
format: values.format,
backOfficeURL: values.backOfficeURL,
connectTimeoutSeconds: values.connectTimeoutSeconds,
password: values.password,
readTimeoutSeconds: values.readTimeoutSeconds,
username: values.username,
};
await backOfficeMutation.mutateAsync(backOfficeData);
};
return ( return (
<Card className="p-4"> <Card className="p-4">
@@ -53,9 +40,7 @@ const ChannelCard = ({ touched, isSubmitting, handleFormSubmit }: ChannelCardPro
touched={touched} touched={touched}
isSubmitting={isSubmitting} isSubmitting={isSubmitting}
backOfficeData={backOfficeQuery} backOfficeData={backOfficeQuery}
backOfficeMutation={backOfficeMutation} format={values?.format}
handleFormSubmit={handleFormSubmit}
handleSubmit={handleSubmit}
/> />
</Card> </Card>
); );

View File

@@ -1,73 +1,24 @@
/* eslint-disable @typescript-eslint/no-explicit-any */ /* eslint-disable @typescript-eslint/no-explicit-any */
import { Field, Form, useFormikContext, type FormikTouched } from "formik"; import { Field, useFormikContext, type FormikTouched } from "formik";
import FormGroup from "../components/FormGroup"; import FormGroup from "../components/FormGroup";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
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 type { BearerTypeFieldType, InitialValuesForm, InitialValuesFormErrors } from "../../../types/types"; import type { BearerTypeFieldType, InitialValuesForm } from "../../../types/types";
import { toast } from "sonner"; import { toast } from "sonner";
import type { UseMutationResult, UseQueryResult } from "@tanstack/react-query"; import type { UseQueryResult } from "@tanstack/react-query";
type ChannelFieldsProps = { type ChannelFieldsProps = {
touched: FormikTouched<BearerTypeFieldType & InitialValuesForm>; touched: FormikTouched<BearerTypeFieldType & InitialValuesForm>;
isSubmitting: boolean; isSubmitting: boolean;
backOfficeMutation: UseMutationResult<any, Error, InitialValuesForm, unknown>;
backOfficeData: UseQueryResult<any, Error>; backOfficeData: UseQueryResult<any, Error>;
handleFormSubmit: (values: BearerTypeFieldType & InitialValuesForm) => Promise<void>; format?: string;
handleSubmit: () => void;
}; };
const ChannelFields = ({ const ChannelFields = ({ touched, isSubmitting, format }: ChannelFieldsProps) => {
touched,
isSubmitting,
backOfficeMutation,
handleFormSubmit,
handleSubmit,
}: ChannelFieldsProps) => {
const [showPwd, setShowPwd] = useState(false); const [showPwd, setShowPwd] = useState(false);
const { submitCount, isValid, values, setErrors, errors } = useFormikContext< const { submitCount, isValid, values, errors } = useFormikContext<BearerTypeFieldType & InitialValuesForm>();
BearerTypeFieldType & InitialValuesForm
>();
const validateValues = (values: InitialValuesForm): InitialValuesFormErrors => {
const errors: InitialValuesFormErrors = {};
const url = values.backOfficeURL?.trim();
const username = values.username?.trim();
const password = values.password?.trim();
if (!url) {
errors.backOfficeURL = "Required";
}
if (!username) errors.username = "Required";
if (!password) errors.password = "Required";
const read = Number(values.readTimeoutSeconds);
if (!Number.isFinite(read)) {
errors.readTimeoutSeconds = "Must be a number";
} else if (read < 0) {
errors.readTimeoutSeconds = "Must be ≥ 0";
}
const connect = Number(values.connectTimeoutSeconds);
if (!Number.isFinite(connect)) {
errors.connectTimeoutSeconds = "Must be a number";
} else if (connect < 0) {
errors.connectTimeoutSeconds = "Must be ≥ 0";
}
return errors;
};
const onSubmit = (values: BearerTypeFieldType & InitialValuesForm) => {
const validationErrors = validateValues(values);
if (Object.values(validationErrors).length > 0) {
setErrors(validationErrors);
return;
}
handleFormSubmit(values);
handleSubmit();
};
const ValidationToastOnce = () => { const ValidationToastOnce = () => {
useEffect(() => { useEffect(() => {
@@ -79,7 +30,7 @@ const ChannelFields = ({
}; };
return ( return (
<Form> <>
<div className="flex flex-col space-y-2 px-2"> <div className="flex flex-col space-y-2 px-2">
<FormGroup> <FormGroup>
<label htmlFor="backoffice" className="m-0"> <label htmlFor="backoffice" className="m-0">
@@ -152,16 +103,75 @@ const ChannelFields = ({
} rounded-lg w-full md:w-60`} } rounded-lg w-full md:w-60`}
/> />
</FormGroup> </FormGroup>
{format?.toLowerCase() === "bof2" && (
<>
<div className="border-b border-gray-500 my-3">
<h2 className="font-bold">{values.format} Constants</h2>
</div> </div>
<FormGroup>
<label htmlFor="FFID">Feed ID / Force ID</label>
<Field
name={"FFID"}
type="text"
id="FFID"
placeholder="ABC123"
className={`p-1.5 border ${
errors.readTimeoutSeconds && touched.readTimeoutSeconds ? "border-red-500" : "border-gray-400 "
} rounded-lg w-full md:w-60`}
/>
</FormGroup>
<FormGroup>
<label htmlFor="SCID">Source ID / Camera ID</label>
<Field
name={"SCID"}
type="text"
id="SCID"
placeholder="DEF345"
className={`p-1.5 border ${
errors.readTimeoutSeconds && touched.readTimeoutSeconds ? "border-red-500" : "border-gray-400 "
} rounded-lg w-full md:w-60`}
/>
</FormGroup>
<FormGroup>
<label htmlFor="timestampSource">Timestamp Source</label>
<Field
name={"timestampSource"}
as="select"
id="timestampSource"
className="p-2 border border-gray-400 rounded-lg text-white bg-[#253445] w-full md:w-60"
>
<option value="">-- Select format --</option>
<option value={"UTC"}>UTC</option>
<option value={"local"}>Local</option>
</Field>
</FormGroup>
<FormGroup>
<label htmlFor="GPSFormat">GPS Format</label>
<Field
name={"GPSFormat"}
as="select"
id="GPSFormat"
className="p-2 border border-gray-400 rounded-lg text-white bg-[#253445] w-full md:w-60"
>
<option value="">-- Select format --</option>
<option value={"Decimal degrees"}>Decimal degrees</option>
<option value={"minutes"}>Minutes</option>
</Field>
</FormGroup>
</>
)}
</div>
<button <button
type="button" type="submit"
onClick={() => onSubmit(values)}
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"
> >
{isSubmitting || backOfficeMutation.isPending ? "Saving..." : "Save Changes"} {isSubmitting ? "Saving..." : "Save Changes"}
</button> </button>
<ValidationToastOnce /> <ValidationToastOnce />
</Form> </>
); );
}; };

View File

@@ -1,14 +1,21 @@
import { Formik } from "formik"; import { Form, Formik } from "formik";
import BearerTypeCard from "../BearerType/BearerTypeCard"; import BearerTypeCard from "../BearerType/BearerTypeCard";
import ChannelCard from "../Channel1-JSON/ChannelCard"; import ChannelCard from "../Channel1-JSON/ChannelCard";
import { useCameraOutput } from "../../../hooks/useCameraOutput"; import { useCameraOutput } from "../../../hooks/useCameraOutput";
import type { BearerTypeFieldType, InitialValuesForm } from "../../../types/types"; import type {
BearerTypeFieldType,
InitialValuesForm,
InitialValuesFormErrors,
OptionalBOF2Constants,
} from "../../../types/types";
import { cleanArray } from "../../../utils/utils"; import { cleanArray } from "../../../utils/utils";
import { useQueryClient } from "@tanstack/react-query"; import { useQueryClient } from "@tanstack/react-query";
import { useUpdateBackOfficeConfig } from "../../../hooks/useBackOfficeConfig";
const SettingForms = () => { const SettingForms = () => {
const qc = useQueryClient(); const qc = useQueryClient();
const { dispatcherQuery, dispatcherMutation } = useCameraOutput(); const { dispatcherQuery, dispatcherMutation, backOfficeDispatcherMutation } = useCameraOutput();
const { backOfficeMutation } = useUpdateBackOfficeConfig();
const format = dispatcherQuery?.data?.propFormat?.value; const format = dispatcherQuery?.data?.propFormat?.value;
const rawOptions = dispatcherQuery?.data?.propFormat?.accepted; const rawOptions = dispatcherQuery?.data?.propFormat?.accepted;
@@ -17,8 +24,54 @@ const SettingForms = () => {
const options = cleanArray(rawOptions); const options = cleanArray(rawOptions);
const handleFormSubmit = async (values: BearerTypeFieldType & InitialValuesForm) => { const initialValues: BearerTypeFieldType & InitialValuesForm & OptionalBOF2Constants = {
console.log(values); format: format ?? "JSON",
enabled: enabled === "true",
verbose: verbose === "true",
backOfficeURL: "",
username: "",
password: "",
connectTimeoutSeconds: Number(5),
readTimeoutSeconds: Number(15),
// Bof2 - optional constants
FFID: "",
SCID: "",
timestampSource: "",
GPSFormat: "",
};
const validateValues = (values: InitialValuesForm): InitialValuesFormErrors => {
const errors: InitialValuesFormErrors = {};
const url = values.backOfficeURL?.trim();
const username = values.username?.trim();
const password = values.password?.trim();
if (!url) {
errors.backOfficeURL = "Required";
}
if (!username) errors.username = "Required";
if (!password) errors.password = "Required";
const read = Number(values.readTimeoutSeconds);
if (!Number.isFinite(read)) {
errors.readTimeoutSeconds = "Must be a number";
} else if (read < 0) {
errors.readTimeoutSeconds = "Must be ≥ 0";
}
const connect = Number(values.connectTimeoutSeconds);
if (!Number.isFinite(connect)) {
errors.connectTimeoutSeconds = "Must be a number";
} else if (connect < 0) {
errors.connectTimeoutSeconds = "Must be ≥ 0";
}
return errors;
};
const handleSubmit = async (values: BearerTypeFieldType & InitialValuesForm & OptionalBOF2Constants) => {
const dispatcherData = { const dispatcherData = {
format: values.format, format: values.format,
enabled: values.enabled, enabled: values.enabled,
@@ -28,37 +81,29 @@ const SettingForms = () => {
if (result?.id) { if (result?.id) {
qc.invalidateQueries({ queryKey: ["dispatcher"] }); qc.invalidateQueries({ queryKey: ["dispatcher"] });
qc.invalidateQueries({ queryKey: ["backoffice", values.format] }); qc.invalidateQueries({ queryKey: ["backoffice", values.format] });
await backOfficeMutation.mutateAsync(values);
}
if (values.format.toLowerCase() === "bof2") {
const bof2ConstantsData: OptionalBOF2Constants = {
FFID: values.FFID,
SCID: values.SCID,
timestampSource: values.timestampSource,
GPSFormat: values.GPSFormat,
};
await backOfficeDispatcherMutation.mutateAsync(bof2ConstantsData);
} }
}; };
const initialValues: BearerTypeFieldType & InitialValuesForm = {
format: format ?? "JSON",
enabled: enabled === "true",
verbose: verbose === "true",
backOfficeURL: "",
username: "",
password: "",
connectTimeoutSeconds: Number(5),
readTimeoutSeconds: Number(15),
};
const handleSubmit = async (values: BearerTypeFieldType) => {
console.log(values);
// await dispatcherMutation.mutateAsync(values);
};
return ( return (
<Formik initialValues={initialValues} onSubmit={handleSubmit} enableReinitialize> <Formik initialValues={initialValues} onSubmit={handleSubmit} validate={validateValues} enableReinitialize>
{({ isSubmitting, touched }) => ( {({ isSubmitting, touched }) => (
<Form>
<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">
<BearerTypeCard options={options} /> <BearerTypeCard options={options} />
<ChannelCard <ChannelCard touched={touched} isSubmitting={isSubmitting} />
touched={touched}
isSubmitting={isSubmitting}
// backOfficeMutation={backOfficeMutation}
handleFormSubmit={handleFormSubmit}
/>
</div> </div>
</Form>
)} )}
</Formik> </Formik>
); );

View File

@@ -36,8 +36,7 @@ const updateBackOfficeConfig = async (data: InitialValuesForm) => {
}, },
], ],
}; };
console.log(updateConfigPayload); const response = await fetch(`${CAM_BASE}/api/update-config?id=Dispatcher`, {
const response = await fetch(`${CAM_BASE}/api/update-config?id=Dispatcher-${data.format.toLowerCase()}`, {
method: "POST", method: "POST",
body: JSON.stringify(updateConfigPayload), body: JSON.stringify(updateConfigPayload),
}); });
@@ -52,6 +51,16 @@ export const useCameraBackOfficeOutput = (format: string) => {
enabled: !!format, enabled: !!format,
}); });
useEffect(() => {
if (backOfficeQuery.isError) toast.error(backOfficeQuery.error.message);
}, [backOfficeQuery?.error?.message, backOfficeQuery.isError]);
return {
backOfficeQuery,
};
};
export const useUpdateBackOfficeConfig = () => {
const backOfficeMutation = useMutation({ const backOfficeMutation = useMutation({
mutationKey: ["backOfficeUpdate"], mutationKey: ["backOfficeUpdate"],
mutationFn: updateBackOfficeConfig, mutationFn: updateBackOfficeConfig,
@@ -62,13 +71,5 @@ export const useCameraBackOfficeOutput = (format: string) => {
} }
}, },
}); });
return { backOfficeMutation };
useEffect(() => {
if (backOfficeQuery.isError) toast.error(backOfficeQuery.error.message);
}, [backOfficeQuery?.error?.message, backOfficeQuery.isError]);
return {
backOfficeQuery,
backOfficeMutation,
};
}; };

View File

@@ -2,7 +2,7 @@ import { useMutation, useQuery } from "@tanstack/react-query";
import { CAM_BASE } from "../utils/config"; import { CAM_BASE } from "../utils/config";
import { useEffect } from "react"; import { useEffect } from "react";
import { toast } from "sonner"; import { toast } from "sonner";
import type { BearerTypeFieldType } from "../types/types"; import type { BearerTypeFieldType, OptionalBOF2Constants } from "../types/types";
const getDispatcherConfig = async () => { const getDispatcherConfig = async () => {
const response = await fetch(`${CAM_BASE}/api/fetch-config?id=Dispatcher`); const response = await fetch(`${CAM_BASE}/api/fetch-config?id=Dispatcher`);
@@ -32,6 +32,37 @@ const updateDispatcherConfig = async (data: BearerTypeFieldType) => {
return response.json(); return response.json();
}; };
const updateBackOfficeDispatcher = async (data: OptionalBOF2Constants) => {
console.log(data);
const bof2ContantsPayload = {
id: "Dispatcher-bof2-constants",
fields: [
{
property: "propFeedIdentifier",
value: data?.FFID,
},
{
property: "propSourceIdentifier",
value: data?.SCID,
},
{
property: "propTimeZoneType",
value: data?.timestampSource,
},
{
property: "propGpsFormat",
value: data?.GPSFormat,
},
],
};
const response = await fetch(`${CAM_BASE}/api/update-config?id=Dispatcher-bof2-constants`, {
method: "POST",
body: JSON.stringify(bof2ContantsPayload),
});
if (!response.ok) throw new Error("Cannot update dispatcher configuration");
return response.json();
};
export const useCameraOutput = () => { export const useCameraOutput = () => {
const dispatcherQuery = useQuery({ const dispatcherQuery = useQuery({
queryKey: ["dispatcher"], queryKey: ["dispatcher"],
@@ -49,6 +80,11 @@ export const useCameraOutput = () => {
}, },
}); });
const backOfficeDispatcherMutation = useMutation({
mutationKey: ["backofficedDispatcher"],
mutationFn: updateBackOfficeDispatcher,
});
useEffect(() => { useEffect(() => {
if (dispatcherQuery.isError) toast.error(dispatcherQuery.error.message); if (dispatcherQuery.isError) toast.error(dispatcherQuery.error.message);
}, [dispatcherQuery?.error?.message, dispatcherQuery.isError]); }, [dispatcherQuery?.error?.message, dispatcherQuery.isError]);
@@ -56,5 +92,6 @@ export const useCameraOutput = () => {
return { return {
dispatcherQuery, dispatcherQuery,
dispatcherMutation, dispatcherMutation,
backOfficeDispatcherMutation,
}; };
}; };

View File

@@ -68,6 +68,13 @@ export type InitialValuesFormErrors = {
readTimeoutSeconds?: string; readTimeoutSeconds?: string;
}; };
export type OptionalBOF2Constants = {
FFID?: "";
SCID?: "";
timestampSource?: "";
GPSFormat?: "";
};
export type NPEDFieldType = { export type NPEDFieldType = {
frontId: string; frontId: string;
username: string | undefined; username: string | undefined;