Merge pull request #4 from i701/feat/admin-devices-table
Some checks failed
Build and Push Docker Images / Build and Push Docker Images (push) Failing after 2m34s

feature/admin devices table 
This commit is contained in:
Abdulla Aidhaan
2025-06-30 23:23:37 +05:00
committed by GitHub
9 changed files with 285 additions and 311 deletions

View File

@ -1,8 +1,8 @@
"use server"; "use server";
import { revalidatePath } from "next/cache";
import type { GroupProfile, MacAddress, OmadaResponse } from "@/lib/types"; import type { GroupProfile, MacAddress, OmadaResponse } from "@/lib/types";
import { formatMacAddress } from "@/lib/utils"; import { formatMacAddress } from "@/lib/utils";
import { revalidatePath } from "next/cache";
async function fetchOmadaGroupProfiles(siteId: string): Promise<OmadaResponse> { async function fetchOmadaGroupProfiles(siteId: string): Promise<OmadaResponse> {
if (!siteId) { if (!siteId) {

View File

@ -18,7 +18,6 @@ export default async function Devices({
const query = (await searchParams)?.query || ""; const query = (await searchParams)?.query || "";
const page = (await searchParams)?.page || 1; const page = (await searchParams)?.page || 1;
const session = await getServerSession(authOptions); const session = await getServerSession(authOptions);
if (session?.user?.is_admin) return redirect("/user-devices");
return ( return (
<div> <div>
<div className="flex justify-between items-center border rounded-md border-dashed font-bold title-bg py-4 px-2 mb-4"> <div className="flex justify-between items-center border rounded-md border-dashed font-bold title-bg py-4 px-2 mb-4">
@ -51,13 +50,6 @@ export default async function Devices({
label: "Vendor", label: "Vendor",
type: "string", type: "string",
placeholder: "Enter vendor name", placeholder: "Enter vendor name",
}, {
label: "Amount of Devices",
name: "amount",
type: "dual-range-slider",
min: 1,
max: 100,
sliderLabel: "MVR"
} }
]} ]}
/> />

View File

@ -1,9 +1,6 @@
import { AdminDevicesTable } from "@/components/admin/admin-devices-table";
import Search from "@/components/search";
import { Suspense } from "react"; import { Suspense } from "react";
import { AdminDevicesTable } from "@/components/admin/admin-devices-table";
import DynamicFilter from "@/components/generic-filter";
export default async function UserDevices({ export default async function UserDevices({
searchParams, searchParams,
@ -19,17 +16,43 @@ export default async function UserDevices({
return ( return (
<div> <div>
<div className="flex justify-between items-center border rounded-md border-dashed font-bold title-bg py-4 px-2 mb-4"> <div className="flex justify-between items-center border rounded-md border-dashed font-bold title-bg py-4 px-2 mb-4">
<h3 className="text-sarLinkOrange text-2xl"> <h3 className="text-sarLinkOrange text-2xl">User Devices</h3>
User Devices
</h3>
</div> </div>
<div <div
id="user-filters" id="user-filters"
className=" pb-4 gap-4 flex sm:flex-row flex-col items-start justify-start" className=" pb-4 gap-4 flex sm:flex-row flex-col items-start justify-start"
> >
<Search /> <DynamicFilter
description="Filter devices by name, MAC address, or vendor."
title="Device Filter"
inputs={[
{
name: "name",
label: "Device Name",
type: "string",
placeholder: "Enter device name",
},
{
name: "mac",
label: "MAC Address",
type: "string",
placeholder: "Enter device MAC address",
},
{
name: "vendor",
label: "Vendor",
type: "string",
placeholder: "Enter device vendor name",
},
{
name: "user",
label: "Device User",
type: "string",
placeholder: "User name or id card",
}
]}
/>
</div> </div>
<Suspense key={query} fallback={"loading...."}> <Suspense key={query} fallback={"loading...."}>
<AdminDevicesTable parentalControl={true} searchParams={searchParams} /> <AdminDevicesTable parentalControl={true} searchParams={searchParams} />

View File

@ -1,204 +1,188 @@
// import { import { HandCoins } from "lucide-react";
// Table, import Link from "next/link";
// TableBody, import { redirect } from "next/navigation";
// TableCaption, import { getServerSession } from "next-auth";
// TableCell, import { authOptions } from "@/app/auth";
// TableFooter, import {
// TableHead, Table,
// TableHeader, TableBody,
// TableRow, TableCaption,
// } from "@/components/ui/table"; TableCell,
// import { headers } from "next/headers"; TableFooter,
// import Link from "next/link"; TableHead,
// import BlockDeviceDialog from "../block-device-dialog"; TableHeader,
// import DeviceCard from "../device-card"; TableRow,
// import Pagination from "../pagination"; } from "@/components/ui/table";
import { cn } from "@/lib/utils";
import { getDevices } from "@/queries/devices";
import { tryCatch } from "@/utils/tryCatch";
import BlockDeviceDialog from "../block-device-dialog";
import ClientErrorMessage from "../client-error-message";
import DeviceCard from "../device-card";
import Pagination from "../pagination";
export async function AdminDevicesTable({ export async function AdminDevicesTable({
searchParams, searchParams,
parentalControl, parentalControl,
}: { }: {
searchParams: Promise<{ searchParams: Promise<{
query: string; [key: string]: unknown;
page: number;
sortBy: string;
}>; }>;
parentalControl?: boolean; parentalControl?: boolean;
}) { }) {
console.log(parentalControl); const resolvedParams = await searchParams;
// const session = await auth.api.getSession({ const session = await getServerSession(authOptions);
// headers: await headers(), const isAdmin = session?.user?.is_superuser;
// });
// const isAdmin = session?.user.role === "ADMIN";
const query = (await searchParams)?.query || "";
const page = (await searchParams)?.page;
console.log(query, page);
// const sortBy = (await searchParams)?.sortBy || "asc";
// const totalDevices = await prisma.device.count({
// where: {
// OR: [
// {
// name: {
// contains: query || "",
// mode: "insensitive",
// },
// },
// {
// mac: {
// contains: query || "",
// mode: "insensitive",
// },
// },
// ],
// },
// });
// const totalPages = Math.ceil(totalDevices / 10); const page = Number.parseInt(resolvedParams.page as string) || 1;
// const limit = 10; const limit = 10;
// const offset = (Number(page) - 1) * limit || 0; const offset = (page - 1) * limit;
// const devices = await prisma.device.findMany({ // Build params object for getDevices
// where: { const apiParams: Record<string, string | number | undefined> = {};
// OR: [ for (const [key, value] of Object.entries(resolvedParams)) {
// { if (value !== undefined && value !== "") {
// name: { apiParams[key] = typeof value === "number" ? value : String(value);
// contains: query || "", }
// mode: "insensitive", }
// }, apiParams.limit = limit;
// }, apiParams.offset = offset;
// {
// mac: {
// contains: query || "",
// mode: "insensitive",
// },
// },
// ],
// },
// include: {
// User: true,
// payments: true,
// },
// skip: offset,
// take: limit,
// orderBy: {
// name: `${sortBy}` as "asc" | "desc",
// },
// });
return null;
// return (
// <div>
// {devices.length === 0 ? (
// <div className="h-[calc(100svh-400px)] flex flex-col items-center justify-center my-4">
// <h3>No devices yet.</h3>
// </div>
// ) : (
// <>
// <div className="hidden sm:block">
// <Table className="overflow-scroll">
// <TableCaption>Table of all devices.</TableCaption>
// <TableHeader>
// <TableRow>
// <TableHead>Device Name</TableHead>
// <TableHead>User</TableHead>
// <TableHead>MAC Address</TableHead>
// <TableHead>isActive</TableHead>
// <TableHead>blocked</TableHead>
// <TableHead>blockedBy</TableHead>
// <TableHead>expiryDate</TableHead>
// </TableRow>
// </TableHeader>
// <TableBody className="overflow-scroll">
// {devices.map((device) => (
// <TableRow key={device.id}>
// <TableCell>
// <div className="flex flex-col items-start">
// <Link
// className="font-medium hover:underline"
// href={`/devices/${device.id}`}
// >
// {device.name}
// </Link>
// {device.isActive && (
// <span className="text-muted-foreground">
// Active until{" "}
// {new Date().toLocaleDateString("en-US", {
// month: "short",
// day: "2-digit",
// year: "numeric",
// })}
// </span>
// )}
// {device.blocked && ( const [error, devices] = await tryCatch(
// <div className="p-2 rounded border my-2"> getDevices(apiParams, true),
// <span>Comment: </span> );
// <p className="text-neutral-500"> if (error) {
// blocked because he was watching youtube if (error.message === "UNAUTHORIZED") {
// </p> redirect("/auth/signin");
// </div> } else {
// )} return <ClientErrorMessage message={error.message} />;
// </div> }
// </TableCell> }
// <TableCell className="font-medium"> const { meta, data } = devices;
// {device.User?.name} return (
// </TableCell> <div>
{data?.length === 0 ? (
<div className="h-[calc(100svh-400px)] text-muted-foreground flex flex-col items-center justify-center my-4">
<h3>No devices.</h3>
</div>
) : (
<>
<div className="hidden sm:block">
<Table className="overflow-scroll">
<TableCaption>Table of all devices.</TableCaption>
<TableHeader>
<TableRow>
<TableHead>Device Name</TableHead>
<TableHead>User</TableHead>
<TableHead>MAC Address</TableHead>
<TableHead>Vendor</TableHead>
<TableHead>#</TableHead>
</TableRow>
</TableHeader>
<TableBody className="overflow-scroll">
{data?.map((device) => (
<TableRow
key={device.id}
>
<TableCell>
<div className="flex flex-col items-start">
<Link
className={cn(
"hover:underline font-semibold",
device.is_active ? "text-green-600" : "",
)}
href={`/devices/${device.id}`}
>
{device.name}
</Link>
{device.is_active ? (
<div className="text-muted-foreground">
Active until{" "}
<span className="font-semibold">
{new Date(device.expiry_date || "").toLocaleDateString(
"en-US",
{
month: "short",
day: "2-digit",
year: "numeric",
},
)}
</span>
</div>
) : (
<p className="text-muted-foreground">Device Inactive</p>
)}
{device.has_a_pending_payment && (
<Link href={`/payments/${device.pending_payment_id}`}>
<span className="bg-muted rounded px-2 p-1 mt-2 flex hover:underline items-center justify-center gap-2 text-muted-foreground">
Payment Pending{" "}
<HandCoins className="animate-pulse" size={14} />
</span>
</Link>
)}
// <TableCell className="font-medium">{device.mac}</TableCell> {device.blocked_by === "ADMIN" && device.blocked && (
// <TableCell> <div className="p-2 rounded border my-2 bg-white dark:bg-neutral-800 shadow">
// {device.isActive ? "Active" : "Inactive"} <span className="font-semibold">Comment</span>
// </TableCell> <p className="text-neutral-400">{device?.reason_for_blocking}</p>
// <TableCell> </div>
// {device.blocked ? "Blocked" : "Not Blocked"} )}
// </TableCell> </div>
// <TableCell> </TableCell>
// {device.blocked ? device.blockedBy : ""} <TableCell className="font-medium">
// </TableCell> <div className="flex flex-col items-start">
// <TableCell> {device?.user?.name}
// {new Date().toLocaleDateString("en-US", { <span className="text-muted-foreground">{device?.user?.id_card}</span>
// month: "short", </div>
// day: "2-digit",
// year: "numeric", </TableCell>
// })} <TableCell className="font-medium">{device.mac}</TableCell>
// </TableCell> <TableCell className="font-medium">{device?.vendor}</TableCell>
// <TableCell> <TableCell>
// <BlockDeviceDialog {!device.has_a_pending_payment && (
// admin={isAdmin} <BlockDeviceDialog
// type={device.blocked ? "unblock" : "block"} admin={isAdmin}
// device={device} type={device.blocked ? "unblock" : "block"}
// /> device={device}
// </TableCell> />
// </TableRow> )}
// ))} </TableCell>
// </TableBody> </TableRow>
// <TableFooter> ))}
// <TableRow> </TableBody>
// <TableCell colSpan={7}> <TableFooter>
// {query.length > 0 && ( <TableRow>
// <p className="text-sm text-muted-foreground"> <TableCell colSpan={5} className="text-muted-foreground">
// Showing {devices.length} locations for &quot;{query} {meta?.total === 1 ? (
// &quot; <p className="text-center">
// </p> Total {meta?.total} device.
// )} </p>
// </TableCell> ) : (
// <TableCell className="text-muted-foreground"> <p className="text-center">
// {totalDevices} devices Total {meta?.total} devices.
// </TableCell> </p>
// </TableRow> )}
// </TableFooter> </TableCell>
// </Table> </TableRow>
// <Pagination totalPages={totalPages} currentPage={page} /> </TableFooter>
// </div> </Table>
// <div className="sm:hidden my-4"> </div>
// {devices.map((device) => ( <div className="sm:hidden my-4">
// <DeviceCard {data?.map((device) => (
// parentalControl={parentalControl} <DeviceCard
// key={device.id} parentalControl={parentalControl}
// device={device} key={device.id}
// /> device={device}
// ))} />
// </div> ))}
// </> </div>
// )} <Pagination
// </div> totalPages={meta?.last_page}
// ); currentPage={meta?.current_page}
/>
</>
)
}
</div >
);
} }

View File

@ -1,5 +1,12 @@
"use client"; "use client";
import { zodResolver } from "@hookform/resolvers/zod";
import { OctagonX } from "lucide-react";
import { useState } from "react";
import { type SubmitHandler, useForm } from "react-hook-form";
import { toast } from "sonner";
import { z } from "zod";
import { blockDevice as BlockDeviceFromOmada } from "@/actions/omada-actions"; import { blockDevice as BlockDeviceFromOmada } from "@/actions/omada-actions";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { import {
@ -14,13 +21,6 @@ import { Label } from "@/components/ui/label";
import type { Device } from "@/lib/backend-types"; import type { Device } from "@/lib/backend-types";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { blockDevice } from "@/queries/devices"; import { blockDevice } from "@/queries/devices";
import { zodResolver } from "@hookform/resolvers/zod";
import { OctagonX } from "lucide-react";
import { useState } from "react";
import { type SubmitHandler, useForm } from "react-hook-form";
import { toast } from "sonner";
import { z } from "zod";
import { TextShimmer } from "./ui/text-shimmer"; import { TextShimmer } from "./ui/text-shimmer";
import { Textarea } from "./ui/textarea"; import { Textarea } from "./ui/textarea";
@ -44,7 +44,7 @@ export default function BlockDeviceDialog({
const onSubmit: SubmitHandler<z.infer<typeof validationSchema>> = (data) => { const onSubmit: SubmitHandler<z.infer<typeof validationSchema>> = (data) => {
setDisabled(true); setDisabled(true);
console.log(data); console.log("data in block device dialog", data);
toast.promise( toast.promise(
blockDevice({ blockDevice({
deviceId: String(device.id), deviceId: String(device.id),
@ -59,8 +59,9 @@ export default function BlockDeviceDialog({
return "Blocked!"; return "Blocked!";
}, },
error: (error) => { error: (error) => {
console.error("Error blocking device:", error);
setDisabled(false); setDisabled(false);
return error || "Something went wrong"; return error.message || "Something went wrong";
}, },
}, },
); );
@ -74,10 +75,10 @@ export default function BlockDeviceDialog({
onClick={() => { onClick={() => {
setDisabled(true); setDisabled(true);
toast.promise( toast.promise(
BlockDeviceFromOmada({ blockDevice({
macAddress: device.mac, blocked_by: "ADMIN",
type: "unblock", deviceId: String(device.id),
reason: "", reason_for_blocking: "",
}), }),
{ {
loading: "unblockinig...", loading: "unblockinig...",
@ -85,9 +86,9 @@ export default function BlockDeviceDialog({
setDisabled(false); setDisabled(false);
return "Unblocked!"; return "Unblocked!";
}, },
error: () => { error: (error) => {
setDisabled(false); setDisabled(false);
return "Something went wrong"; return error.message || "Something went wrong";
}, },
}, },
); );
@ -96,84 +97,53 @@ export default function BlockDeviceDialog({
{disabled ? <TextShimmer>Unblocking</TextShimmer> : "Unblock"} {disabled ? <TextShimmer>Unblocking</TextShimmer> : "Unblock"}
</Button> </Button>
) : ( ) : (
<> <div>
{!admin ? ( <Dialog open={open} onOpenChange={setOpen}>
<Button <DialogTrigger asChild>
variant={"destructive"} <Button disabled={disabled} variant="destructive">
onClick={() => { <OctagonX />
setDisabled(true); Block
toast.promise( </Button>
BlockDeviceFromOmada({ </DialogTrigger>
macAddress: device.mac, <DialogContent className="sm:max-w-[425px]">
type: "block", <DialogHeader>
reason: "", <DialogTitle className="text-muted-foreground">
blockedBy: "PARENT", Reason for blocking this device 🚫
}), </DialogTitle>
{ </DialogHeader>
loading: "blocking...", <form onSubmit={handleSubmit(onSubmit)}>
success: () => { <div className="grid gap-2 py-2">
setDisabled(false); <div className="flex flex-col items-start gap-4">
return "blocked!"; <Label htmlFor="reason" className="text-right text-muted-foreground">
}, Reason for blocking
error: () => { </Label>
setDisabled(false); <Textarea
return "Something went wrong"; rows={10}
}, {...register("reasonForBlocking")}
}, id="reasonForBlocking"
); className={cn(
}} "col-span-5",
> errors.reasonForBlocking && "ring-2 ring-red-500",
<OctagonX /> )}
{disabled ? <TextShimmer>Blocking</TextShimmer> : "Block"} />
</Button> <span className="text-sm text-red-500">
) : ( {errors.reasonForBlocking?.message}
<Dialog open={open} onOpenChange={setOpen}> </span>
<DialogTrigger asChild>
<Button disabled={disabled} variant="destructive">
<OctagonX />
Block
</Button>
</DialogTrigger>
<DialogContent className="sm:max-w-[425px]">
<DialogHeader>
<DialogTitle>
Please provide a reason for blocking this device.
</DialogTitle>
</DialogHeader>
<form onSubmit={handleSubmit(onSubmit)}>
<div className="grid gap-4 py-4">
<div className="flex flex-col items-start gap-1">
<Label htmlFor="reason" className="text-right">
Reason for blocking
</Label>
<Textarea
rows={10}
{...register("reasonForBlocking")}
id="reasonForBlocking"
className={cn(
"col-span-5",
errors.reasonForBlocking && "ring-2 ring-red-500",
)}
/>
<span className="text-sm text-red-500">
{errors.reasonForBlocking?.message}
</span>
</div>
</div> </div>
<DialogFooter> </div>
<Button <DialogFooter>
variant={"destructive"} <Button
disabled={disabled} variant={"destructive"}
type="submit" disabled={disabled}
> type="submit"
Block >
</Button> Block
</DialogFooter> </Button>
</form> </DialogFooter>
</DialogContent> </form>
</Dialog> </DialogContent>
)} </Dialog>
</> </div>
)} )}
</div> </div>
); );

View File

@ -1,11 +1,11 @@
"use client"; "use client";
import { useAtom } from "jotai";
import { HandCoins } from "lucide-react";
import Link from "next/link";
import { TableCell, TableRow } from "@/components/ui/table"; import { TableCell, TableRow } from "@/components/ui/table";
import { deviceCartAtom } from "@/lib/atoms"; import { deviceCartAtom } from "@/lib/atoms";
import type { Device } from "@/lib/backend-types"; import type { Device } from "@/lib/backend-types";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { useAtom } from "jotai";
import { HandCoins } from "lucide-react";
import Link from "next/link";
import AddDevicesToCartButton from "./add-devices-to-cart-button"; import AddDevicesToCartButton from "./add-devices-to-cart-button";
import BlockDeviceDialog from "./block-device-dialog"; import BlockDeviceDialog from "./block-device-dialog";
export default function ClickableRow({ export default function ClickableRow({

View File

@ -1,3 +1,5 @@
import { redirect } from "next/navigation";
import { getServerSession } from "next-auth";
import { authOptions } from "@/app/auth"; import { authOptions } from "@/app/auth";
import { import {
Table, Table,
@ -11,8 +13,6 @@ import {
} from "@/components/ui/table"; } from "@/components/ui/table";
import { getDevices } from "@/queries/devices"; import { getDevices } from "@/queries/devices";
import { tryCatch } from "@/utils/tryCatch"; import { tryCatch } from "@/utils/tryCatch";
import { getServerSession } from "next-auth";
import { redirect } from "next/navigation";
import ClickableRow from "./clickable-row"; import ClickableRow from "./clickable-row";
import ClientErrorMessage from "./client-error-message"; import ClientErrorMessage from "./client-error-message";
import DeviceCard from "./device-card"; import DeviceCard from "./device-card";

View File

@ -1,3 +1,5 @@
import { User } from "./types/user";
export interface Links { export interface Links {
next_page: string | null; next_page: string | null;
previous_page: string | null; previous_page: string | null;
@ -45,7 +47,9 @@ export interface Device {
expiry_date: string | null; expiry_date: string | null;
created_at: string; created_at: string;
updated_at: string; updated_at: string;
user: number; user: Pick<User, "id" | "id_card" | "mobile"> & {
name: string;
};
} }
export interface ApiError { export interface ApiError {

View File

@ -1,12 +1,12 @@
"use server"; "use server";
import { revalidatePath } from "next/cache";
import { getServerSession } from "next-auth";
import { authOptions } from "@/app/auth"; import { authOptions } from "@/app/auth";
import type { AddDeviceFormState, initialState } from "@/components/user/add-device-dialog"; import type { AddDeviceFormState, initialState } from "@/components/user/add-device-dialog";
import type { ApiError, ApiResponse, Device } from "@/lib/backend-types"; import type { ApiError, ApiResponse, Device } from "@/lib/backend-types";
import { checkSession } from "@/utils/session"; import { checkSession } from "@/utils/session";
import { handleApiResponse } from "@/utils/tryCatch"; import { handleApiResponse } from "@/utils/tryCatch";
import { getServerSession } from "next-auth";
import { revalidatePath } from "next/cache";
type GetDevicesProps = { type GetDevicesProps = {
name?: string; name?: string;
@ -17,7 +17,7 @@ type GetDevicesProps = {
status?: string; status?: string;
[key: string]: string | number | undefined; // Allow additional properties for flexibility [key: string]: string | number | undefined; // Allow additional properties for flexibility
}; };
export async function getDevices(params: GetDevicesProps) { export async function getDevices(params: GetDevicesProps, allDevices = false) {
const session = await checkSession(); const session = await checkSession();
// Build query string from all defined params // Build query string from all defined params
@ -27,7 +27,7 @@ export async function getDevices(params: GetDevicesProps) {
.join("&"); .join("&");
const response = await fetch( const response = await fetch(
`${process.env.SARLINK_API_BASE_URL}/api/devices/?${query}`, `${process.env.SARLINK_API_BASE_URL}/api/devices/?${query}&all_devices=${allDevices}`,
{ {
method: "GET", method: "GET",
headers: { headers: {
@ -123,6 +123,7 @@ export async function blockDevice({
reason_for_blocking: string; reason_for_blocking: string;
blocked_by: "ADMIN" | "PARENT"; blocked_by: "ADMIN" | "PARENT";
}) { }) {
console.log("Blocking device:", deviceId, reason_for_blocking, blocked_by);
const session = await getServerSession(authOptions); const session = await getServerSession(authOptions);
const response = await fetch( const response = await fetch(
`${process.env.SARLINK_API_BASE_URL}/api/devices/${deviceId}/block/`, `${process.env.SARLINK_API_BASE_URL}/api/devices/${deviceId}/block/`,