Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Playground frequencies are now updated in DB when saved #204

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
152 changes: 124 additions & 28 deletions app/components/Map.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ import {
initializePlayground,
replacePlayground,
replaceOldPlayground,
clearToUpdatePlayground,
replaceToUpdatePlayground,
} from '../../lib/features/playground/playgroundSlice';

import {
Expand Down Expand Up @@ -139,6 +141,8 @@ export default function Map() {

const antennasData = useAppSelector((state) => state.currentAntennas.value);

const toBeUpdated = useAppSelector((state) => state.playground.toBeUpdated);

const dispatch = useAppDispatch();

useEffect(() => {
Expand All @@ -151,7 +155,7 @@ export default function Map() {
}

const responseJson = (await response.json()) as Antenna[];
console.log('Antennas Data:', responseJson);

return responseJson;
} catch (e) {
if (e instanceof Error) {
Expand Down Expand Up @@ -182,9 +186,23 @@ export default function Map() {
})
);

const playgroundAntennasData: AccessPoint[] = accessPoints.map(
(ap: Antenna) => ({
id: ap.id,
modelName: ap.modelname,
lat: ap.latitude,
lon: ap.longitude,
frequency: ap.playground_frequency || 0,
azimuth: ap.azimuth || 0,
antenna_status: ap.antenna_status || 'N/A',
cpu: ap.cpu || -1,
ram: ap.ram || -1,
})
);

if (!initialized.current) {
store.dispatch(initializeActual(antennasData));
store.dispatch(initializePlayground(antennasData));
store.dispatch(initializePlayground(playgroundAntennasData));
store.dispatch(initializeCurrent(antennasData));
initialized.current = true;
}
Expand Down Expand Up @@ -212,7 +230,8 @@ export default function Map() {
fetchDataAndSetAntennasData().catch((error) => {
console.error(error);
});
}, [store]);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

useEffect(() => {
const sectorlobesData: SectorlobeData[] = antennasData.data.map((ap) => {
Expand Down Expand Up @@ -346,6 +365,43 @@ export default function Map() {
return amount;
}, [intersections]);

const handleSavePlayground = async () => {
const url = '/api/v1/antenna/';
if (toBeUpdated.length === 0) {
alert('No changes to save');
return;
}
for (let i = 0; i < 3; i++) {
try {
const response = await fetch(url, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ dataArray: toBeUpdated }),
});
if (!response.ok) {
throw new Error(
`${response.status} error: Failed to save playground data`
);
}
dispatch(replacePlayground(antennasData.data));
dispatch(replaceOldPlayground(antennasData.data));
dispatch(clearToUpdatePlayground());
alert('Playground data saved successfully');
break;
} catch (e) {
if (e instanceof Error) {
console.error(`Attempt ${i + 1} failed: ${e.message}`);
if (i === 2) {
alert('Failed to save playground data');
}
await new Promise((resolve) => setTimeout(resolve, 1000));
}
}
}
};

return (
<>
<div className="absolute right-0 top-0 z-[1001] flex flex-col justify-center rounded-md bg-black p-2">
Expand Down Expand Up @@ -431,48 +487,88 @@ export default function Map() {
</MapContainer>
<div className="m-5 flex flex-row justify-between align-middle">
<div className="flex flex-row justify-center">
<h1 className="mx-2 p-1 align-baseline">Current mode: </h1>
<button
className="rounded-md border-[1px] border-black bg-gray-400 p-1 transition-all duration-300 ease-in-out hover:bg-gray-900"
onClick={() => {
if (antennasData.mode === 'actual') {
dispatch(
changeCurrent({
mode: 'playground',
data: playgroundData,
})
<div>
<button
className="rounded-md border-[1px] border-black bg-gray-400 p-1 transition-all duration-300 ease-in-out hover:bg-gray-900"
onClick={() => alert('Updating from NYCMesh server...')}
>
Update from Server
</button>
</div>
<div className="flex flex-row justify-center">
<h1 className="mx-2 p-1 align-baseline">Current mode: </h1>
<button
className="rounded-md border-[1px] border-black bg-gray-400 p-1 transition-all duration-300 ease-in-out hover:bg-gray-900"
onClick={() => {
if (antennasData.mode === 'actual') {
dispatch(
changeCurrent({
mode: 'playground',
data: playgroundData,
})
);
} else {
dispatch(replacePlayground(antennasData.data));
dispatch(
changeCurrent({
mode: 'actual',
data: actualData,
})
);
}
}}
>
{antennasData.mode === 'actual' ? 'Current' : 'Playground'}
</button>
</div>
</div>
{antennasData.mode === 'playground' ? (
<div>
<button
className="mx-2 rounded-md border-[1px] border-black bg-gray-400 p-1 transition-all duration-300 ease-in-out hover:bg-gray-900"
onClick={() => {
if (toBeUpdated.length > 0) {
dispatch(replaceToUpdatePlayground([]));
}
const updatedData: AccessPoint[] = actualData.filter(
(antenna) => {
return (
playgroundData.find(
(oldAntenna) =>
oldAntenna.id === antenna.id &&
oldAntenna.frequency === antenna.frequency &&
oldAntenna.azimuth === antenna.azimuth
) === undefined
);
}
);
} else {
dispatch(replacePlayground(antennasData.data));
if (updatedData.length > 0) {
dispatch(replaceToUpdatePlayground(updatedData));
}
dispatch(
changeCurrent({
mode: 'actual',
mode: 'playground',
data: actualData,
})
);
}
}}
>
{antennasData.mode === 'actual' ? 'Current' : 'Playground'}
</button>
</div>
{antennasData.mode === 'playground' ? (
<div>
}}
>
Revert All Changes
</button>
<button
className="mx-2 rounded-md border-[1px] border-black bg-gray-400 p-1 transition-all duration-300 ease-in-out hover:bg-gray-900"
onClick={() => {
dispatch(
changeCurrent({ mode: 'playground', data: oldPlaygroundData })
);
dispatch(clearToUpdatePlayground());
}}
>
Revert Changes
Revert Current Changes
</button>
<button
className="mx-2 rounded-md border-[1px] border-black bg-gray-400 p-1 transition-all duration-300 ease-in-out hover:bg-gray-900"
onClick={() => {
dispatch(replaceOldPlayground(antennasData.data));
}}
onClick={() => void handleSavePlayground()}
>
Save Changes
</button>
Expand Down
46 changes: 27 additions & 19 deletions app/components/SectorLobe.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { SectorLobeProps } from '../types';
import { useAppSelector, useAppDispatch } from '../../lib/hooks';

import { updateCurrent } from '@/lib/features/currentAntennas/currentAntennasSlice';
import { addToUpdatePlayground } from '@/lib/features/playground/playgroundSlice';

export default function SectorLobe({
key_path,
Expand Down Expand Up @@ -152,14 +153,17 @@ export default function SectorLobe({
const newAp = { ...currentAp };
newAp.azimuth = tempHeading;
newAp.frequency = tempFreq;

setCurrentAp(newAp);
if (currentMode === 'playground') {
dispatch(addToUpdatePlayground(newAp));
dispatch(updateCurrent(newAp));
}
}

function handleCancel() {
function handleCancel(
e: React.FormEvent<HTMLFormElement> | React.MouseEvent
) {
e.preventDefault();
setTempHeading(heading);
setTempFreq(freq);
}
Expand All @@ -169,14 +173,14 @@ export default function SectorLobe({
positions={sectorVertices}
color={color}
fillOpacity={0.5}
weight={1}
weight={3}
key={String(key_path)}
>
<Popup>
<form
className="flex flex-col"
id={`form ${String(key_path)}`}
onSubmit={(e) => handleCommit(e)}
// onSubmit={(e) => handleCommit(e)}
>
<p>Change Sector Lobe of {ap.id}</p>
<div className="my-2 flex flex-row">
Expand Down Expand Up @@ -217,21 +221,25 @@ export default function SectorLobe({
)}
&deg;
</div>
<div className="flex flex-row justify-between">
<button
className="rounded-md border-[1px] border-black bg-green-300 p-1 hover:bg-green-900"
onClick={(e) => handleCommit(e)}
type="submit"
>
Save
</button>
<button
className="rounded-md border-[1px] border-black bg-red-400 p-1 hover:bg-red-900"
onClick={() => handleCancel()}
>
Cancel
</button>
</div>
{currentMode === 'playground' ? (
<div className="flex flex-row justify-between">
<button
className="rounded-md border-[1px] border-black bg-green-300 p-1 hover:bg-green-900"
onClick={(e) => handleCommit(e)}
type="submit"
>
Save
</button>
<button
className="rounded-md border-[1px] border-black bg-red-400 p-1 hover:bg-red-900"
onClick={(e) => handleCancel(e)}
>
Cancel
</button>
</div>
) : (
<></>
)}
</form>
</Popup>
</Polygon>
Expand Down
44 changes: 43 additions & 1 deletion lib/features/playground/playgroundSlice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,18 @@ import { PayloadAction, createSlice } from '@reduxjs/toolkit';

import { AccessPoint } from '../../../app/types';

type PlaygroundState = { value: AccessPoint[]; old: AccessPoint[] };
type PlaygroundState = {
value: AccessPoint[];
old: AccessPoint[];
toBeUpdated: AccessPoint[];
};

export const playgroundSlice = createSlice({
name: 'playground',
initialState: {
value: [],
old: [],
toBeUpdated: [],
} satisfies PlaygroundState as PlaygroundState,
reducers: {
initializePlayground: (state, action: PayloadAction<AccessPoint[]>) => {
Expand Down Expand Up @@ -38,6 +43,39 @@ export const playgroundSlice = createSlice({
replaceOldPlayground: (state, action: PayloadAction<AccessPoint[]>) => {
return { ...state, old: action.payload };
},
addToUpdatePlayground: (state, action: PayloadAction<AccessPoint>) => {
for (let i = 0; i < state.toBeUpdated.length; i++) {
if (state.toBeUpdated[i].id === action.payload.id) {
return {
...state,
toBeUpdated: state.toBeUpdated.map((item) => {
if (item.id === action.payload.id) {
return action.payload;
}
return item;
}),
};
}
}
return { ...state, toBeUpdated: [...state.toBeUpdated, action.payload] };
},
clearToUpdatePlayground: (state) => {
return { ...state, toBeUpdated: [] };
},
removeFromUpdatePlayground: (state, action: PayloadAction<AccessPoint>) => {
return {
...state,
toBeUpdated: state.toBeUpdated.filter(
(item) => item !== action.payload
),
};
},
replaceToUpdatePlayground: (
state,
action: PayloadAction<AccessPoint[]>
) => {
return { ...state, toBeUpdated: action.payload };
},
},
});

Expand All @@ -48,6 +86,10 @@ export const {
removePlayground,
updatePlayground,
replaceOldPlayground,
addToUpdatePlayground,
clearToUpdatePlayground,
removeFromUpdatePlayground,
replaceToUpdatePlayground,
} = playgroundSlice.actions;

export default playgroundSlice.reducer;
Expand Down
Loading