diff --git a/client/app/dashboard/page.tsx b/client/app/dashboard/page.tsx index 5fc879a..4fe6014 100644 --- a/client/app/dashboard/page.tsx +++ b/client/app/dashboard/page.tsx @@ -8,17 +8,18 @@ import MainSection from "../../components/dashboard-componenets/mainContent/main import { useRouter } from "next/navigation"; import { getCookie } from "@/lib/cookieFunctions"; import { curActive, role } from "@/data/cookieNames"; +import { set } from "react-hook-form"; export default function Dashboard() { - const curRole = getCookie(role) || ""; - const [currentActive, setCurrentActive] = useState(getCookie(curActive) || ""); + const [curRole, setCurrentRole] = useState(""); + const [currentActive, setCurrentActive] = useState(""); const router = useRouter(); - - if(curRole === ""){ - alert('Please login first'); - router.push('/auth/login'); - } + + useEffect(() => { + setCurrentRole(getCookie(role)); + setCurrentActive(getCookie(curActive)); + }, []); console.log('Role: ' + curRole + ' Current Active: ' + currentActive); diff --git a/client/components/dashboard-componenets/mainContent/systemAdminContents/System.tsx b/client/components/dashboard-componenets/mainContent/systemAdminContents/System.tsx index 66f8eb3..a2888b0 100644 --- a/client/components/dashboard-componenets/mainContent/systemAdminContents/System.tsx +++ b/client/components/dashboard-componenets/mainContent/systemAdminContents/System.tsx @@ -1,9 +1,11 @@ import { Button } from "@/components/ui/button"; import EmptyFillContainer from "../../cards/EmptyFillContainer"; import { Plus, Truck } from "lucide-react"; -import { StsCreateModal } from "../../../modals/StsModal" +import { StsCreateModal } from "../../../modals/StsModal"; import { VehicleCreateModal } from "@/components/modals/VehicleModal"; -import { LandfillCreateModal } from "@/components/modals/LandfillModal"; +import { LandfillCreateModal } from "@/components/modals/LandfillModal"; +import UserListTable from "@/components/dataTables/UserList"; +import STSListTable from "@/components/dataTables/STSList"; export default function AdminSystemDataPanel() { return ( @@ -13,29 +15,41 @@ export default function AdminSystemDataPanel() {
- + - + - +
- STS LIST +
VEICLE LIST diff --git a/client/components/dataTables/STSList.tsx b/client/components/dataTables/STSList.tsx new file mode 100644 index 0000000..e97343d --- /dev/null +++ b/client/components/dataTables/STSList.tsx @@ -0,0 +1,292 @@ +"use client"; + +import * as React from "react"; +import { + CaretSortIcon, + ChevronDownIcon, + DotsHorizontalIcon, +} from "@radix-ui/react-icons"; + +import { Button } from "@/components/ui/button"; + +import { + ColumnDef, + ColumnFiltersState, + SortingState, + VisibilityState, + flexRender, + getCoreRowModel, + getFilteredRowModel, + getPaginationRowModel, + getSortedRowModel, + useReactTable, +} from "@tanstack/react-table"; + +import { + DropdownMenu, + DropdownMenuCheckboxItem, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuLabel, + DropdownMenuSeparator, + DropdownMenuTrigger, +} from "@/components/ui/dropdown-menu"; +import { Input } from "@/components/ui/input"; +import { + Table, + TableBody, + TableCell, + TableHead, + TableHeader, + TableRow, +} from "@/components/ui/table"; +import useGetAllUser from "@/hooks/user_data/useGetAllUser"; +import { DeleteUserModal } from "../modals/DeleteUserModal"; +import { Copy, EditIcon } from "lucide-react"; +import { EditUserModal } from "../modals/EditUserInfoModal"; +import gettAllRoles from "@/hooks/user_data/useGetAllRole"; +import { roleList } from "@/data/roles"; +import useGetAllSTS from "@/hooks/dataQuery/useGetAllSTS"; +import { EditSTSInfoModal } from "../modals/EditSTSInfoModal"; +import { DeleteSTSModal } from "../modals/DeleteSTSModal"; + +export type STS = { + id: string; + name: string; + wardNumber: string; + capacity: string; + latitude: string; + longitude: string; +}; + +export const columns: ColumnDef[] = [ + { + accessorKey: "name", + header: ({ column }) => { + return ( +
+ +
+ ); + }, + cell: ({ row }) => ( +
{row.getValue("name")}
+ ), + }, + { + accessorKey: "wardNumber", + header: ({ column }) => { + return ( +
+ +
+ ); + }, + cell: ({ row }) => ( +
+ {row.getValue("wardNumber")} +
+ ), + }, + { + accessorKey: "capacity", + header: ({ column }) => { + return ( +
+ +
+ ); + }, + cell: ({ row }) => ( +
{row.getValue("capacity")}
+ ), + }, + { + id: "actions", + enableHiding: false, + cell: ({ row }) => { + const sts: STS = row.original; + + return ( +
+ + +
+ ); + }, + }, +]; + +export default function STSListTable() { + const [data, setData] = React.useState([]); + const { fetchAllSTS, stsData } = useGetAllSTS(); + const [sorting, setSorting] = React.useState([]); + const [columnFilters, setColumnFilters] = React.useState( + [] + ); + const [columnVisibility, setColumnVisibility] = + React.useState({}); + const [rowSelection, setRowSelection] = React.useState({}); + + React.useEffect(() => { + fetchAllSTS(); + }, []); + + React.useEffect(() => { + setData(stsData); + }, [stsData]); + + const table = useReactTable({ + data, + columns, + onSortingChange: setSorting, + onColumnFiltersChange: setColumnFilters, + getCoreRowModel: getCoreRowModel(), + getPaginationRowModel: getPaginationRowModel(), + getSortedRowModel: getSortedRowModel(), + getFilteredRowModel: getFilteredRowModel(), + onColumnVisibilityChange: setColumnVisibility, + onRowSelectionChange: setRowSelection, + state: { + sorting, + columnFilters, + columnVisibility, + rowSelection, + }, + }); + return ( + <> +
+ + table.getColumn("name")?.setFilterValue(event.target.value) + } + className="max-w-sm" + /> + + + + + + {table + .getAllColumns() + .filter((column) => column.getCanHide()) + .map((column) => { + return ( + + column.toggleVisibility(!!value) + } + > + {column.id} + + ); + })} + + +
+
+ + + {table.getHeaderGroups().map((headerGroup) => ( + + {headerGroup.headers.map((header) => { + return ( + + {header.isPlaceholder + ? null + : flexRender( + header.column.columnDef.header, + header.getContext() + )} + + ); + })} + + ))} + + + {table.getRowModel().rows?.length ? ( + table.getRowModel().rows.map((row) => ( + + {row.getVisibleCells().map((cell) => ( + + {flexRender( + cell.column.columnDef.cell, + cell.getContext() + )} + + ))} + + )) + ) : ( + + + No results. + + + )} + +
+
+
+
+ {table.getFilteredSelectedRowModel().rows.length} of{" "} + {table.getFilteredRowModel().rows.length} row(s) selected. +
+
+ + +
+
+ + ); +} diff --git a/client/components/maps/SetZone.tsx b/client/components/maps/SetZone.tsx index d92e476..764ca1c 100644 --- a/client/components/maps/SetZone.tsx +++ b/client/components/maps/SetZone.tsx @@ -1,74 +1,107 @@ // pages/index.tsx -import { useEffect, useRef, useState } from 'react'; +import { useEffect, useRef, useState } from "react"; +import { Input } from "../ui/input"; +import { Label } from "../ui/label"; interface CoordinateProps { - - setLatitude: React.Dispatch>; - setLongitude: React.Dispatch>; - } - + setLatitude: React.Dispatch>; + setLongitude: React.Dispatch>; +} -const SetZone : React.FC = ({ setLatitude, setLongitude }) => { - const locationInputRef = useRef(null); - const latInputRef = useRef(null); - const longInputRef = useRef(null); - const placeNameRef = useRef(null); +const SetZone: React.FC = ({ setLatitude, setLongitude }) => { + const locationInputRef = useRef(null); + const latInputRef = useRef(null); + const longInputRef = useRef(null); + const placeNameRef = useRef(null); - useEffect(() => { - const loadScript = (url: string, callback: () => void) => { - const script = document.createElement('script'); - script.type = 'text/javascript'; - script.src = url; - script.onload = callback; - document.head.appendChild(script); - }; - const apiKey: string = process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY || ''; + useEffect(() => { + const loadScript = (url: string, callback: () => void) => { + const script = document.createElement("script"); + script.type = "text/javascript"; + script.src = url; + script.onload = callback; + document.head.appendChild(script); + }; + const apiKey: string = process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY || ""; - loadScript('https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js', () => { - loadScript( - `https://maps.googleapis.com/maps/api/js?key=${apiKey}&libraries=places`, - initializeAutocomplete - ); - }); - }, []); + loadScript( + "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js", + () => { + loadScript( + `https://maps.googleapis.com/maps/api/js?key=${apiKey}&libraries=places`, + initializeAutocomplete + ); + } + ); + }, []); - const initializeAutocomplete = () => { - const autocomplete = new google.maps.places.Autocomplete(locationInputRef.current!, { - types: ['geocode'] - }); + const initializeAutocomplete = () => { + const autocomplete = new google.maps.places.Autocomplete( + locationInputRef.current!, + { + types: ["geocode"], + } + ); - google.maps.event.addListener(autocomplete, 'place_changed', () => { - const place = autocomplete.getPlace(); - if (!place.geometry) { - return; - } - const lat = place.geometry.location.lat(); - const lng = place.geometry.location.lng(); - latInputRef.current!.value = lat.toString(); - longInputRef.current!.value = lng.toString(); - // placeNameRef.current!.value = place.name.toString(); - setLatitude(latInputRef.current!.value); - setLongitude(longInputRef.current!.value); + google.maps.event.addListener(autocomplete, "place_changed", () => { + const place = autocomplete.getPlace(); + if (!place.geometry) { + return; + } + const lat = place.geometry.location?.lat(); + const lng = place.geometry.location?.lng(); + latInputRef.current!.value = lat?.toString() || ""; + longInputRef.current!.value = lng?.toString() || ""; + // placeNameRef.current!.value = place.name.toString(); + setLatitude(latInputRef.current!.value); + setLongitude(longInputRef.current!.value); + }); + }; + const handleLatitudeChange = (event: React.ChangeEvent) => { + setLatitude(event.target.value); + }; - }); - }; - const handleLatitudeChange = (event: React.ChangeEvent) => { - setLatitude(event.target.value); - }; - - const handleLongitudeChange = (event: React.ChangeEvent) => { - setLongitude(event.target.value); - }; + const handleLongitudeChange = ( + event: React.ChangeEvent + ) => { + setLongitude(event.target.value); + }; - return ( -
- - - - {/* */} -
- ); + return ( + <> + + + +
+ + +
+ {/* */} + + ); }; export default SetZone; diff --git a/client/components/modals/DeleteSTSModal.tsx b/client/components/modals/DeleteSTSModal.tsx new file mode 100644 index 0000000..d7c6420 --- /dev/null +++ b/client/components/modals/DeleteSTSModal.tsx @@ -0,0 +1,97 @@ +import { Button } from "@/components/ui/button"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, + DialogTrigger, +} from "@/components/ui/dialog"; + +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import React, { useState } from "react"; +import { Trash } from "lucide-react"; +import deleteUser from "@/hooks/user_data/deleteUser"; +import deleteSTS from "@/hooks/entityCreation/deleteSTS"; + +export type STS = { + id: string; + name: string; + wardNumber: string; + capacity: string; + latitude: string; + longitude: string; + }; + +export const DeleteSTSModal = ({ stsInfo }: { stsInfo: STS }) => { + const [confirmText, setConfirmText] = useState(""); + return ( + + + + + + + + Confirm Delete STS? + + +
+

+ ID: + {stsInfo.id} +

+

+ Name: + {stsInfo.name} +

+

+ Ward: + {stsInfo.wardNumber} +

+

+ Capacity: + {stsInfo.capacity} +

+
+
+
+
+
+
+ + setConfirmText(e.target.value)} + required + /> +
+
+ + + +
+
+
+ ); +}; diff --git a/client/components/modals/EditSTSInfoModal.tsx b/client/components/modals/EditSTSInfoModal.tsx new file mode 100644 index 0000000..f6a9733 --- /dev/null +++ b/client/components/modals/EditSTSInfoModal.tsx @@ -0,0 +1,180 @@ +import { Button } from "@/components/ui/button"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, + DialogTrigger, +} from "@/components/ui/dialog"; + +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import React, { use, useEffect, useState } from "react"; +import { EditIcon, Trash } from "lucide-react"; +import deleteUser from "@/hooks/user_data/deleteUser"; +import { + Select, + SelectTrigger, + SelectValue, + SelectContent, + SelectGroup, + SelectLabel, + SelectItem, +} from "../ui/select"; +import editUser from "@/hooks/user_data/editUser"; +import gettAllRoles from "@/hooks/user_data/useGetAllRole"; +import { number } from "prop-types"; +import { admin, landfillManager, stsManager, unassigned } from "@/data/roles"; +import editSTS from "@/hooks/entityCreation/editSTS"; +import getUserByRole from "@/hooks/user_data/getUserByRole"; + +export type STS = { + id: string; + name: string; + wardNumber: string; + capacity: string; + latitude: string; + longitude: string; +}; + +type STSManager = { + id: string; + username: string; +}; + +export const EditSTSInfoModal = ({ stsInfo }: { stsInfo: STS }) => { + const [stsData, setSTSData] = useState(stsInfo); + const [stsManagerData, setSTSManagerData] = useState(); + const [stsManagerList, setSTSManagerList] = useState([]); + + const getManagerList = async () => { + const result = await getUserByRole(stsManager); + if (result) await setSTSManagerList(result); + }; + + useEffect(() => { + getManagerList(); + }, []); + + return ( + + + + + + + + Edit STS Details + + +
+

+ ID: + {stsData.id} +

+

+ Name: + {stsData.name} +

+

+ Capacity: + {stsData.capacity} +

+

+ Ward: + {stsData.wardNumber} +

+
+
+
+
+
+
+ + + setSTSData({ ...stsData, name: e.target.value }) + } + className="col-span-3" + required + /> +
+
+ + + setSTSData({ ...stsData, capacity: e.target.value }) + } + className="col-span-3" + required + /> +
+
+ + + setSTSData({ ...stsData, wardNumber: e.target.value }) + } + className="col-span-3" + required + /> +
+
+ + +
+
+ + + +
+
+
+ ); +}; diff --git a/client/components/modals/LandfillModal.tsx b/client/components/modals/LandfillModal.tsx index 0b6c995..aae67c1 100644 --- a/client/components/modals/LandfillModal.tsx +++ b/client/components/modals/LandfillModal.tsx @@ -7,13 +7,16 @@ import { DialogHeader, DialogTitle, DialogTrigger, - DialogClose + DialogClose, } from "@/components/ui/dialog"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; -import React , {useState} from "react"; +import React, { useState } from "react"; import SetZone from "../maps/SetZone"; +import useCreateLandFill, { + LandFill, +} from "@/hooks/entityCreation/useCreateLandfill"; interface DialogWrapperProps { children: React.ReactNode; @@ -22,29 +25,22 @@ interface DialogWrapperProps { export const LandfillCreateModal: React.FC = ({ children, }) => { - const [landfillName, setLandfill] = useState(""); - const [capacity, setCapacity] = useState(""); - const [latitude, setLatitude] = useState(""); - const [longitude, setLongitude] = useState(""); - - + const [landfillName, setLandfill] = useState(""); + const [capacity, setCapacity] = useState(""); + const [latitude, setLatitude] = useState(""); + const [longitude, setLongitude] = useState(""); + const { createLandfill } = useCreateLandFill(); - - - - - - const handleSaveChanges = () => { - // console.log("Vehicle Number:", vehicleNumber); - // console.log("Vehicle Type:", vehicleType); - // console.log("Capacity:", capacity); - console.log(landfillName); - console.log(capacity); - console.log(latitude); - console.log(longitude); + const handleSaveChanges = async () => { + const data: LandFill = { + name: landfillName, + capacity: parseInt(capacity), + latitude: parseFloat(latitude), + longitude: parseFloat(longitude), + }; + alert((await createLandfill(data)) || "Landfill data invalid"); }; - return ( @@ -71,7 +67,7 @@ export const LandfillCreateModal: React.FC = ({ onChange={(e) => setLandfill(e.target.value)} />
- +
- - +
- - - + + + - ); diff --git a/client/components/modals/StsModal.tsx b/client/components/modals/StsModal.tsx index e7ad8ca..4079349 100644 --- a/client/components/modals/StsModal.tsx +++ b/client/components/modals/StsModal.tsx @@ -15,6 +15,7 @@ import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import React , {useState} from "react"; import SetZone from "../maps/SetZone"; +import useCreateSTS, { STS } from "@/hooks/entityCreation/useCreateSTS"; interface DialogWrapperProps { children: React.ReactNode; @@ -28,35 +29,23 @@ export const StsCreateModal: React.FC = ({ const [capacity, setCapacity] = useState(""); const [latitude, setLatitude] = useState(""); const [longitude, setLongitude] = useState(""); - - + const {createSTS } = useCreateSTS(); - - - - - - const handleSaveChanges = () => { - // console.log("Vehicle Number:", vehicleNumber); - // console.log("Vehicle Type:", vehicleType); - // console.log("Capacity:", capacity); - console.log(stsName); - console.log(wardNumber); - console.log(capacity); - console.log(latitude); - console.log(longitude); + const handleSaveChanges = async () => { + const data:STS = {name: stsName, wardNumber , capacity: parseInt(capacity), latitude: parseFloat(latitude), longitude: parseFloat(longitude)}; + console.log(data); + alert(await createSTS(data) || "STS data invalid"); }; return ( - - {/* */} + {children} - Add New STS + ADD NEW STS Add new STS here. Click save when you're done. @@ -68,7 +57,7 @@ export const StsCreateModal: React.FC = ({ setStsName(e.target.value)} @@ -100,12 +89,10 @@ export const StsCreateModal: React.FC = ({ />
- - + + + +
diff --git a/client/data/apiRoutes.ts b/client/data/apiRoutes.ts index 9170d37..1b0051b 100644 --- a/client/data/apiRoutes.ts +++ b/client/data/apiRoutes.ts @@ -11,4 +11,22 @@ export const apiRoutes = { delete: `${baseUrl}/users/`, edit: `${baseUrl}/users/`, }, + sts: { + create: `${baseUrl}/sts/create`, + getAll: `${baseUrl}/sts`, + delete: `${baseUrl}/sts/`, + edit: `${baseUrl}/sts/`, + }, + landfill: { + create: `${baseUrl}/landfills/create`, + getAll: `${baseUrl}/landfills`, + delete: `${baseUrl}/landfills/`, + edit: `${baseUrl}/landfills/`, + }, + rbac: { + create: `${baseUrl}/rbac/create`, + getByRole: `${baseUrl}/rbac/roles/`, + delete: `${baseUrl}/rbac/`, + edit: `${baseUrl}/rbac/`, + }, } \ No newline at end of file diff --git a/client/data/mainContentElements/InvalidState.tsx b/client/data/mainContentElements/InvalidState.tsx index 67b70f4..58e9228 100644 --- a/client/data/mainContentElements/InvalidState.tsx +++ b/client/data/mainContentElements/InvalidState.tsx @@ -2,11 +2,11 @@ export default function InvalidSate() { return (
- Logo + Logo

- INVALID STATE + PLEASE WAIT

- The state you are trying to access is invalid. + Proper access data is not loaded yet.
); diff --git a/client/hooks/dataQuery/useGetAllSTS.tsx b/client/hooks/dataQuery/useGetAllSTS.tsx new file mode 100644 index 0000000..d1ffcb6 --- /dev/null +++ b/client/hooks/dataQuery/useGetAllSTS.tsx @@ -0,0 +1,51 @@ +"use client"; +import { apiRoutes } from "@/data/apiRoutes"; +import { jwtToken } from "@/data/cookieNames"; +import { admin, landfillManager, stsManager, unassigned } from "@/data/roles"; +import { getCookie } from "@/lib/cookieFunctions"; +import axios from "axios"; +import { useState, useEffect, use } from "react"; + +export type STS = { + id: string; + name: string; + wardNumber: string; + capacity: string; + latitude: string; + longitude: string; + }; + +export default function useGetAllSTS() { + const [stsData, setSTSData] = useState([]); + + async function fetchAllSTS() { + try { + const res = await axios.get(apiRoutes.sts.getAll, { + headers: { + Authorization: `Bearer ${await getCookie(jwtToken)}`, + }, + }); + const stsList = res.data.map((sts: any) => { + return { + id: sts.id, + name: sts.name, + wardNumber: sts.wardNumber, + capacity: sts.capacity, + latitude: sts.latitude, + longitude: sts.longitude, + }; + }); + await setSTSData(stsList); + console.log(stsList); + } catch (error: any) { + alert("Error fetching sts data... Are you authorized?"); + console.log(error.message); + } + } + + useEffect(() => { + fetchAllSTS(); + }, []); + + return {fetchAllSTS, stsData}; +} diff --git a/client/hooks/entityCreation/deleteSTS.ts b/client/hooks/entityCreation/deleteSTS.ts new file mode 100644 index 0000000..6464169 --- /dev/null +++ b/client/hooks/entityCreation/deleteSTS.ts @@ -0,0 +1,22 @@ +import { apiRoutes } from "@/data/apiRoutes"; +import { jwtToken } from "@/data/cookieNames"; +import { admin, landfillManager, stsManager, unassigned } from "@/data/roles"; +import { getCookie } from "@/lib/cookieFunctions"; +import axios from "axios"; + +export default async function deleteSTS(stsId: string) { + if (stsId) { + try { + const res = await axios.delete(apiRoutes.sts.delete + stsId, { + headers: { + Authorization: `Bearer ${await getCookie(jwtToken)}`, + }, + }); + return "sts deleted successfully"; + } catch (error: any) { + return error.message?.toString() || "error deleteing sts"; + } + } + + return null; +} diff --git a/client/hooks/entityCreation/editSTS.ts b/client/hooks/entityCreation/editSTS.ts new file mode 100644 index 0000000..e9e4b73 --- /dev/null +++ b/client/hooks/entityCreation/editSTS.ts @@ -0,0 +1,44 @@ +import { User } from "@/components/dataTables/UserList"; +import { apiRoutes } from "@/data/apiRoutes"; +import { jwtToken } from "@/data/cookieNames"; +import { admin, landfillManager, stsManager, unassigned } from "@/data/roles"; +import { getCookie } from "@/lib/cookieFunctions"; +import axios from "axios"; +import { STS } from "@/components/modals/EditSTSInfoModal"; + +export default async function editSTS(stsData: STS, manager: string) { + if (stsData && manager) { + try { + const res1 = await axios.put( + apiRoutes.user.edit + manager, + { + stsId: stsData.id, + }, + { + headers: { + Authorization: `Bearer ${await getCookie(jwtToken)}`, + }, + } + ); + const res2 = await axios.put( + apiRoutes.sts.edit + stsData.id, + { + ...stsData, + }, + { + headers: { + Authorization: `Bearer ${await getCookie(jwtToken)}`, + }, + } + ); + return "sts updated successfully"; + } catch (error: any) { + return ( + error.message?.toString() || + "error updating sts. You may not have the required permissions." + ); + } + } + + return null; +} diff --git a/client/hooks/entityCreation/useCreateLandfill.tsx b/client/hooks/entityCreation/useCreateLandfill.tsx new file mode 100644 index 0000000..79c2cbb --- /dev/null +++ b/client/hooks/entityCreation/useCreateLandfill.tsx @@ -0,0 +1,45 @@ +"use client"; +import { apiRoutes } from "@/data/apiRoutes"; +import { jwtToken } from "@/data/cookieNames"; +import { admin, landfillManager, stsManager, unassigned } from "@/data/roles"; +import { getCookie } from "@/lib/cookieFunctions"; +import axios from "axios"; +export type LandFill = { + name: string; + capacity: number; + latitude: number; + longitude: number; +}; + +export default function useCreateLandFill() { +// const [landfillData, setlandfillData] = useState(); + + function isValid(landfillData: LandFill) { + + return ( + landfillData.name.length > 0 && + landfillData.capacity > 0 && + landfillData.latitude !== null && + landfillData.longitude !== null + ); + } + + async function createLandfill(landfillData: LandFill) { + if (landfillData && isValid(landfillData)) { + try { + const res = await axios.post(apiRoutes.landfill.create, landfillData, { + headers: { + Authorization: `Bearer ${await getCookie(jwtToken)}`, + }, + }); + return "Landfill Aadded successfully"; + } catch (error: any) { + return error.message?.toString() || "Error creating Landfill"; + } + } + + return null; + } + + return { createLandfill }; +} diff --git a/client/hooks/entityCreation/useCreateSTS.tsx b/client/hooks/entityCreation/useCreateSTS.tsx new file mode 100644 index 0000000..f57dcb3 --- /dev/null +++ b/client/hooks/entityCreation/useCreateSTS.tsx @@ -0,0 +1,47 @@ +"use client"; +import { apiRoutes } from "@/data/apiRoutes"; +import { jwtToken } from "@/data/cookieNames"; +import { admin, landfillManager, stsManager, unassigned } from "@/data/roles"; +import { getCookie } from "@/lib/cookieFunctions"; +import axios from "axios"; +export type STS = { + name: string; + wardNumber: string; + capacity: number; + latitude: number; + longitude: number; +}; + +export default function useCreateSTS() { +// const [stsData, setStsData] = useState(); + + function isValid(stsData: STS) { + + return ( + stsData.name.length > 0 && + stsData.wardNumber.length > 0 && + stsData.capacity > 0 && + stsData.latitude !== null && + stsData.longitude !== null + ); + } + + async function createSTS(stsData: STS) { + if (stsData && isValid(stsData)) { + try { + const res = await axios.post(apiRoutes.sts.create, stsData, { + headers: { + Authorization: `Bearer ${await getCookie(jwtToken)}`, + }, + }); + return "STS Aadded successfully"; + } catch (error: any) { + return error.message?.toString() || "Error creating STS"; + } + } + + return null; + } + + return { createSTS }; +} diff --git a/client/hooks/user_data/getUserByRole.ts b/client/hooks/user_data/getUserByRole.ts new file mode 100644 index 0000000..25a119c --- /dev/null +++ b/client/hooks/user_data/getUserByRole.ts @@ -0,0 +1,39 @@ +"use client"; +import { UserData } from "@/components/graphs/Data"; +import { apiRoutes } from "@/data/apiRoutes"; +import { jwtToken } from "@/data/cookieNames"; +import { admin, landfillManager, stsManager, unassigned } from "@/data/roles"; +import { getCookie } from "@/lib/cookieFunctions"; +import axios from "axios"; +import { useState, useEffect, use } from "react"; + +type User = { + id: string; + username: string; + email: string; + role: string; +}; + +export default async function getUserByRole(roleName: string) { + + try { + const res = await axios.get(apiRoutes.rbac.getByRole + roleName, { + headers: { + Authorization: `Bearer ${await getCookie(jwtToken)}`, + }, + }); + const userList = res.data.map((user: any) => { + return { + id: user.id, + username: user.username, + }; + }); + console.log(userList); + return userList; + } catch (error: any) { + alert("Error fetching user data... Are you authorized?"); + console.log(error.message); + } + + return []; +} diff --git a/client/lib/cookieFunctions.ts b/client/lib/cookieFunctions.ts index 7c13c5d..0c3b693 100644 --- a/client/lib/cookieFunctions.ts +++ b/client/lib/cookieFunctions.ts @@ -40,7 +40,7 @@ export function setCookie(name: string, value: string, days: number) { } export function getCookie(name: string, context?: any) { - if (process.browser) { + if (typeof window !== 'undefined') { // Client-side var nameEQ = name + "="; var ca = document.cookie.split(';'); @@ -66,7 +66,7 @@ export function getCookie(name: string, context?: any) { } export function eraseCookie(name: string) { - if (process.browser) { + if (typeof window !== 'undefined') { // Client-side document.cookie = name +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;'; } else {