mirror of
https://github.com/i701/sarlink-portal.git
synced 2025-11-05 19:27:19 +00:00
Compare commits
5 Commits
feat/cance
...
feat/admin
| Author | SHA1 | Date | |
|---|---|---|---|
| 8051b00dcf | |||
| 3cd3bbad16 | |||
| 01b064aee7 | |||
| 0157eccd57 | |||
|
|
4b116df3c0 |
@@ -9,9 +9,10 @@ This is a web portal for SAR Link customers.
|
||||
- [x] Add all the filters for devices table (mobile responsive)
|
||||
- [x] Add cancel feature to selected devices floating button
|
||||
|
||||
### Payments
|
||||
### Payments1
|
||||
- [x] Show payments table
|
||||
- [x] Add all the filters for payment table (mobile responsive)
|
||||
- [x] add slider range filter
|
||||
- [ ] Fix bill formula linking for generated payments
|
||||
|
||||
### Parental Control
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import type { GroupProfile, MacAddress, OmadaResponse } from "@/lib/types";
|
||||
import { formatMacAddress } from "@/lib/utils";
|
||||
import { revalidatePath } from "next/cache";
|
||||
|
||||
async function fetchOmadaGroupProfiles(siteId: string): Promise<OmadaResponse> {
|
||||
if (!siteId) {
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
import { getServerSession } from "next-auth";
|
||||
import { Suspense } from "react";
|
||||
import { authOptions } from "@/app/auth";
|
||||
import { DevicesTable } from "@/components/devices-table";
|
||||
import DynamicFilter from "@/components/generic-filter";
|
||||
import AddDeviceDialogForm from "@/components/user/add-device-dialog";
|
||||
import { getServerSession } from "next-auth";
|
||||
import { redirect } from "next/navigation";
|
||||
import { Suspense } from "react";
|
||||
import DevicesTableSkeleton from "./device-table-skeleton";
|
||||
|
||||
export default async function Devices({
|
||||
@@ -18,7 +17,6 @@ export default async function Devices({
|
||||
const query = (await searchParams)?.query || "";
|
||||
const page = (await searchParams)?.page || 1;
|
||||
const session = await getServerSession(authOptions);
|
||||
if (session?.user?.is_admin) return redirect("/user-devices");
|
||||
return (
|
||||
<div>
|
||||
<div className="flex justify-between items-center border rounded-md border-dashed font-bold title-bg py-4 px-2 mb-4">
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
import { AdminDevicesTable } from "@/components/admin/admin-devices-table";
|
||||
import Search from "@/components/search";
|
||||
import { Suspense } from "react";
|
||||
|
||||
|
||||
|
||||
import { AdminDevicesTable } from "@/components/admin/admin-devices-table";
|
||||
import DynamicFilter from "@/components/generic-filter";
|
||||
|
||||
export default async function UserDevices({
|
||||
searchParams,
|
||||
@@ -19,17 +16,43 @@ export default async function UserDevices({
|
||||
return (
|
||||
<div>
|
||||
<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">
|
||||
User Devices
|
||||
</h3>
|
||||
<h3 className="text-sarLinkOrange text-2xl">User Devices</h3>
|
||||
</div>
|
||||
|
||||
<div
|
||||
id="user-filters"
|
||||
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>
|
||||
<Suspense key={query} fallback={"loading...."}>
|
||||
<AdminDevicesTable parentalControl={true} searchParams={searchParams} />
|
||||
|
||||
@@ -1,204 +1,188 @@
|
||||
// import {
|
||||
// Table,
|
||||
// TableBody,
|
||||
// TableCaption,
|
||||
// TableCell,
|
||||
// TableFooter,
|
||||
// TableHead,
|
||||
// TableHeader,
|
||||
// TableRow,
|
||||
// } from "@/components/ui/table";
|
||||
// import { headers } from "next/headers";
|
||||
// import Link from "next/link";
|
||||
// import BlockDeviceDialog from "../block-device-dialog";
|
||||
// import DeviceCard from "../device-card";
|
||||
// import Pagination from "../pagination";
|
||||
import { HandCoins } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { redirect } from "next/navigation";
|
||||
import { getServerSession } from "next-auth";
|
||||
import { authOptions } from "@/app/auth";
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCaption,
|
||||
TableCell,
|
||||
TableFooter,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} 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({
|
||||
searchParams,
|
||||
parentalControl,
|
||||
}: {
|
||||
searchParams: Promise<{
|
||||
query: string;
|
||||
page: number;
|
||||
sortBy: string;
|
||||
[key: string]: unknown;
|
||||
}>;
|
||||
parentalControl?: boolean;
|
||||
}) {
|
||||
console.log(parentalControl);
|
||||
// const session = await auth.api.getSession({
|
||||
// headers: await headers(),
|
||||
// });
|
||||
// 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 resolvedParams = await searchParams;
|
||||
const session = await getServerSession(authOptions);
|
||||
const isAdmin = session?.user?.is_superuser;
|
||||
|
||||
// const totalPages = Math.ceil(totalDevices / 10);
|
||||
// const limit = 10;
|
||||
// const offset = (Number(page) - 1) * limit || 0;
|
||||
const page = Number.parseInt(resolvedParams.page as string) || 1;
|
||||
const limit = 10;
|
||||
const offset = (page - 1) * limit;
|
||||
|
||||
// const devices = await prisma.device.findMany({
|
||||
// where: {
|
||||
// OR: [
|
||||
// {
|
||||
// name: {
|
||||
// contains: query || "",
|
||||
// mode: "insensitive",
|
||||
// },
|
||||
// },
|
||||
// {
|
||||
// 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 && (
|
||||
// <div className="p-2 rounded border my-2">
|
||||
// <span>Comment: </span>
|
||||
// <p className="text-neutral-500">
|
||||
// blocked because he was watching youtube
|
||||
// </p>
|
||||
// </div>
|
||||
// )}
|
||||
// </div>
|
||||
// </TableCell>
|
||||
// <TableCell className="font-medium">
|
||||
// {device.User?.name}
|
||||
// </TableCell>
|
||||
|
||||
// <TableCell className="font-medium">{device.mac}</TableCell>
|
||||
// <TableCell>
|
||||
// {device.isActive ? "Active" : "Inactive"}
|
||||
// </TableCell>
|
||||
// <TableCell>
|
||||
// {device.blocked ? "Blocked" : "Not Blocked"}
|
||||
// </TableCell>
|
||||
// <TableCell>
|
||||
// {device.blocked ? device.blockedBy : ""}
|
||||
// </TableCell>
|
||||
// <TableCell>
|
||||
// {new Date().toLocaleDateString("en-US", {
|
||||
// month: "short",
|
||||
// day: "2-digit",
|
||||
// year: "numeric",
|
||||
// })}
|
||||
// </TableCell>
|
||||
// <TableCell>
|
||||
// <BlockDeviceDialog
|
||||
// admin={isAdmin}
|
||||
// type={device.blocked ? "unblock" : "block"}
|
||||
// device={device}
|
||||
// />
|
||||
// </TableCell>
|
||||
// </TableRow>
|
||||
// ))}
|
||||
// </TableBody>
|
||||
// <TableFooter>
|
||||
// <TableRow>
|
||||
// <TableCell colSpan={7}>
|
||||
// {query.length > 0 && (
|
||||
// <p className="text-sm text-muted-foreground">
|
||||
// Showing {devices.length} locations for "{query}
|
||||
// "
|
||||
// </p>
|
||||
// )}
|
||||
// </TableCell>
|
||||
// <TableCell className="text-muted-foreground">
|
||||
// {totalDevices} devices
|
||||
// </TableCell>
|
||||
// </TableRow>
|
||||
// </TableFooter>
|
||||
// </Table>
|
||||
// <Pagination totalPages={totalPages} currentPage={page} />
|
||||
// </div>
|
||||
// <div className="sm:hidden my-4">
|
||||
// {devices.map((device) => (
|
||||
// <DeviceCard
|
||||
// parentalControl={parentalControl}
|
||||
// key={device.id}
|
||||
// device={device}
|
||||
// />
|
||||
// ))}
|
||||
// </div>
|
||||
// </>
|
||||
// )}
|
||||
// </div>
|
||||
// );
|
||||
// Build params object for getDevices
|
||||
const apiParams: Record<string, string | number | undefined> = {};
|
||||
for (const [key, value] of Object.entries(resolvedParams)) {
|
||||
if (value !== undefined && value !== "") {
|
||||
apiParams[key] = typeof value === "number" ? value : String(value);
|
||||
}
|
||||
}
|
||||
apiParams.limit = limit;
|
||||
apiParams.offset = offset;
|
||||
|
||||
const [error, devices] = await tryCatch(
|
||||
getDevices(apiParams, true),
|
||||
);
|
||||
if (error) {
|
||||
if (error.message === "UNAUTHORIZED") {
|
||||
redirect("/auth/signin");
|
||||
} else {
|
||||
return <ClientErrorMessage message={error.message} />;
|
||||
}
|
||||
}
|
||||
const { meta, data } = devices;
|
||||
return (
|
||||
<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>
|
||||
)}
|
||||
|
||||
{device.blocked_by === "ADMIN" && device.blocked && (
|
||||
<div className="p-2 rounded border my-2 bg-white dark:bg-neutral-800 shadow">
|
||||
<span className="font-semibold">Comment</span>
|
||||
<p className="text-neutral-400">{device?.reason_for_blocking}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="font-medium">
|
||||
<div className="flex flex-col items-start">
|
||||
{device?.user?.name}
|
||||
<span className="text-muted-foreground">{device?.user?.id_card}</span>
|
||||
</div>
|
||||
|
||||
</TableCell>
|
||||
<TableCell className="font-medium">{device.mac}</TableCell>
|
||||
<TableCell className="font-medium">{device?.vendor}</TableCell>
|
||||
<TableCell>
|
||||
{!device.has_a_pending_payment && (
|
||||
<BlockDeviceDialog
|
||||
admin={isAdmin}
|
||||
type={device.blocked ? "unblock" : "block"}
|
||||
device={device}
|
||||
/>
|
||||
)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
<TableFooter>
|
||||
<TableRow>
|
||||
<TableCell colSpan={5} className="text-muted-foreground">
|
||||
{meta?.total === 1 ? (
|
||||
<p className="text-center">
|
||||
Total {meta?.total} device.
|
||||
</p>
|
||||
) : (
|
||||
<p className="text-center">
|
||||
Total {meta?.total} devices.
|
||||
</p>
|
||||
)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableFooter>
|
||||
</Table>
|
||||
</div>
|
||||
<div className="sm:hidden my-4">
|
||||
{data?.map((device) => (
|
||||
<DeviceCard
|
||||
parentalControl={parentalControl}
|
||||
key={device.id}
|
||||
device={device}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<Pagination
|
||||
totalPages={meta?.last_page}
|
||||
currentPage={meta?.current_page}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
</div >
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
"use client";
|
||||
|
||||
import { blockDevice as BlockDeviceFromOmada } from "@/actions/omada-actions";
|
||||
|
||||
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 { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
@@ -14,13 +20,6 @@ import { Label } from "@/components/ui/label";
|
||||
import type { Device } from "@/lib/backend-types";
|
||||
import { cn } from "@/lib/utils";
|
||||
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 { Textarea } from "./ui/textarea";
|
||||
|
||||
@@ -44,7 +43,7 @@ export default function BlockDeviceDialog({
|
||||
|
||||
const onSubmit: SubmitHandler<z.infer<typeof validationSchema>> = (data) => {
|
||||
setDisabled(true);
|
||||
console.log(data);
|
||||
console.log("data in block device dialog", data);
|
||||
toast.promise(
|
||||
blockDevice({
|
||||
deviceId: String(device.id),
|
||||
@@ -59,8 +58,9 @@ export default function BlockDeviceDialog({
|
||||
return "Blocked!";
|
||||
},
|
||||
error: (error) => {
|
||||
console.error("Error blocking device:", error);
|
||||
setDisabled(false);
|
||||
return error || "Something went wrong";
|
||||
return error.message || "Something went wrong";
|
||||
},
|
||||
},
|
||||
);
|
||||
@@ -69,15 +69,15 @@ export default function BlockDeviceDialog({
|
||||
|
||||
return (
|
||||
<div>
|
||||
{device.blocked ? (
|
||||
{device.blocked && !admin ? (
|
||||
<Button
|
||||
onClick={() => {
|
||||
setDisabled(true);
|
||||
toast.promise(
|
||||
BlockDeviceFromOmada({
|
||||
macAddress: device.mac,
|
||||
type: "unblock",
|
||||
reason: "",
|
||||
blockDevice({
|
||||
blocked_by: "ADMIN",
|
||||
deviceId: String(device.id),
|
||||
reason_for_blocking: "",
|
||||
}),
|
||||
{
|
||||
loading: "unblockinig...",
|
||||
@@ -85,9 +85,9 @@ export default function BlockDeviceDialog({
|
||||
setDisabled(false);
|
||||
return "Unblocked!";
|
||||
},
|
||||
error: () => {
|
||||
error: (error) => {
|
||||
setDisabled(false);
|
||||
return "Something went wrong";
|
||||
return error.message || "Something went wrong";
|
||||
},
|
||||
},
|
||||
);
|
||||
@@ -96,37 +96,7 @@ export default function BlockDeviceDialog({
|
||||
{disabled ? <TextShimmer>Unblocking</TextShimmer> : "Unblock"}
|
||||
</Button>
|
||||
) : (
|
||||
<>
|
||||
{!admin ? (
|
||||
<Button
|
||||
variant={"destructive"}
|
||||
onClick={() => {
|
||||
setDisabled(true);
|
||||
toast.promise(
|
||||
BlockDeviceFromOmada({
|
||||
macAddress: device.mac,
|
||||
type: "block",
|
||||
reason: "",
|
||||
blockedBy: "PARENT",
|
||||
}),
|
||||
{
|
||||
loading: "blocking...",
|
||||
success: () => {
|
||||
setDisabled(false);
|
||||
return "blocked!";
|
||||
},
|
||||
error: () => {
|
||||
setDisabled(false);
|
||||
return "Something went wrong";
|
||||
},
|
||||
},
|
||||
);
|
||||
}}
|
||||
>
|
||||
<OctagonX />
|
||||
{disabled ? <TextShimmer>Blocking</TextShimmer> : "Block"}
|
||||
</Button>
|
||||
) : (
|
||||
<div>
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button disabled={disabled} variant="destructive">
|
||||
@@ -136,14 +106,14 @@ export default function BlockDeviceDialog({
|
||||
</DialogTrigger>
|
||||
<DialogContent className="sm:max-w-[425px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
Please provide a reason for blocking this device.
|
||||
<DialogTitle className="text-muted-foreground">
|
||||
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">
|
||||
<div className="grid gap-2 py-2">
|
||||
<div className="flex flex-col items-start gap-4">
|
||||
<Label htmlFor="reason" className="text-right text-muted-foreground">
|
||||
Reason for blocking
|
||||
</Label>
|
||||
<Textarea
|
||||
@@ -172,8 +142,7 @@ export default function BlockDeviceDialog({
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)}
|
||||
</>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
"use client";
|
||||
import { useAtom } from "jotai";
|
||||
import { HandCoins } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { TableCell, TableRow } from "@/components/ui/table";
|
||||
import { deviceCartAtom } from "@/lib/atoms";
|
||||
import type { Device } from "@/lib/backend-types";
|
||||
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 BlockDeviceDialog from "./block-device-dialog";
|
||||
export default function ClickableRow({
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { redirect } from "next/navigation";
|
||||
import { getServerSession } from "next-auth";
|
||||
import { authOptions } from "@/app/auth";
|
||||
import {
|
||||
Table,
|
||||
@@ -11,8 +13,6 @@ import {
|
||||
} from "@/components/ui/table";
|
||||
import { getDevices } from "@/queries/devices";
|
||||
import { tryCatch } from "@/utils/tryCatch";
|
||||
import { getServerSession } from "next-auth";
|
||||
import { redirect } from "next/navigation";
|
||||
import ClickableRow from "./clickable-row";
|
||||
import ClientErrorMessage from "./client-error-message";
|
||||
import DeviceCard from "./device-card";
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
DrawerTitle,
|
||||
DrawerTrigger,
|
||||
} from "@/components/ui/drawer";
|
||||
import { DualRangeSlider } from "@/components/ui/dual-range-slider";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { cn } from "@/lib/utils";
|
||||
@@ -89,6 +90,16 @@ type FilterInputConfig<TKey extends string> =
|
||||
label: string;
|
||||
type: "radio-group";
|
||||
options: FilterOption[];
|
||||
}
|
||||
| {
|
||||
name: TKey;
|
||||
label: string;
|
||||
type: "dual-range-slider";
|
||||
min: number;
|
||||
max: number;
|
||||
step?: number;
|
||||
sliderLabel?: string;
|
||||
formatLabel?: (value: number | undefined) => React.ReactNode;
|
||||
};
|
||||
|
||||
// Utility type to extract the config for a specific key from the array
|
||||
@@ -112,6 +123,8 @@ type FilterValues<
|
||||
? string[]
|
||||
: GetConfigForKey<K, TInputs> extends { type: "radio-group" }
|
||||
? string
|
||||
: GetConfigForKey<K, TInputs> extends { type: "dual-range-slider" }
|
||||
? number[]
|
||||
: string;
|
||||
};
|
||||
|
||||
@@ -163,6 +176,16 @@ export default function DynamicFilter<
|
||||
TFilterKeys,
|
||||
TInputs
|
||||
>[typeof input.name];
|
||||
} else if (input.type === "dual-range-slider") {
|
||||
const minValue = searchParams.get(`${input.name}_min`);
|
||||
const maxValue = searchParams.get(`${input.name}_max`);
|
||||
const parsedMin = minValue ? Number(minValue) : input.min;
|
||||
const parsedMax = maxValue ? Number(maxValue) : input.max;
|
||||
(initialState as FilterValues<TFilterKeys, TInputs>)[input.name] =
|
||||
[parsedMin, parsedMax] as FilterValues<
|
||||
TFilterKeys,
|
||||
TInputs
|
||||
>[typeof input.name];
|
||||
} else {
|
||||
(initialState as FilterValues<TFilterKeys, TInputs>)[input.name] =
|
||||
(urlValue || "") as FilterValues<
|
||||
@@ -203,6 +226,15 @@ export default function DynamicFilter<
|
||||
}));
|
||||
};
|
||||
|
||||
// Handler for dual range slider changes
|
||||
const handleDualRangeChange =
|
||||
(name: TFilterKeys) => (values: number[]) => {
|
||||
setInputValues((prev) => ({
|
||||
...prev,
|
||||
[name]: values,
|
||||
}));
|
||||
};
|
||||
|
||||
// Handles applying all filters
|
||||
const handleApplyFilters = () => {
|
||||
const newParams = new URLSearchParams(currentParams.toString()); // Start fresh with current params
|
||||
@@ -218,6 +250,16 @@ export default function DynamicFilter<
|
||||
} else {
|
||||
newParams.delete(input.name);
|
||||
}
|
||||
} else if (input.type === "dual-range-slider") {
|
||||
const rangeValues = value as number[];
|
||||
// Only set params if values are different from the default min/max
|
||||
if (rangeValues.length === 2 && (rangeValues[0] !== input.min || rangeValues[1] !== input.max)) {
|
||||
newParams.set(`${input.name}_min`, rangeValues[0].toString());
|
||||
newParams.set(`${input.name}_max`, rangeValues[1].toString());
|
||||
} else {
|
||||
newParams.delete(`${input.name}_min`);
|
||||
newParams.delete(`${input.name}_max`);
|
||||
}
|
||||
} else {
|
||||
// String/Number inputs
|
||||
if (value) {
|
||||
@@ -245,6 +287,10 @@ export default function DynamicFilter<
|
||||
(clearedInputState as FilterValues<TFilterKeys, TInputs>)[
|
||||
input.name as TFilterKeys
|
||||
] = [] as FilterValues<TFilterKeys, TInputs>[typeof input.name];
|
||||
} else if (input.type === "dual-range-slider") {
|
||||
(clearedInputState as FilterValues<TFilterKeys, TInputs>)[
|
||||
input.name as TFilterKeys
|
||||
] = [input.min, input.max] as FilterValues<TFilterKeys, TInputs>[typeof input.name];
|
||||
} else if (input.type === "radio-group" || input.type === "string" || input.type === "number") {
|
||||
(clearedInputState as FilterValues<TFilterKeys, TInputs>)[
|
||||
input.name as TFilterKeys
|
||||
@@ -263,7 +309,7 @@ export default function DynamicFilter<
|
||||
const appliedFilters = useMemo(() => {
|
||||
const filters: Array<{
|
||||
key: TFilterKeys;
|
||||
value: string | string[];
|
||||
value: string | string[] | number[];
|
||||
label: string;
|
||||
config: FilterInputConfig<TFilterKeys>;
|
||||
}> = [];
|
||||
@@ -282,6 +328,19 @@ export default function DynamicFilter<
|
||||
config: input,
|
||||
});
|
||||
}
|
||||
} else if (input.type === "dual-range-slider") {
|
||||
const minValue = searchParams.get(`${input.name}_min`);
|
||||
const maxValue = searchParams.get(`${input.name}_max`);
|
||||
if (minValue && maxValue) {
|
||||
const parsedMin = Number(minValue);
|
||||
const parsedMax = Number(maxValue);
|
||||
filters.push({
|
||||
key: input.name,
|
||||
value: [parsedMin, parsedMax],
|
||||
label: input.label,
|
||||
config: input,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
filters.push({
|
||||
key: input.name,
|
||||
@@ -298,7 +357,7 @@ export default function DynamicFilter<
|
||||
// Dynamic `prettyPrintFilter` for badges
|
||||
const prettyPrintFilter = (
|
||||
_key: TFilterKeys,
|
||||
value: string | string[],
|
||||
value: string | string[] | number[],
|
||||
config: FilterInputConfig<TFilterKeys>,
|
||||
) => {
|
||||
if (config.type === "checkbox-group") {
|
||||
@@ -312,6 +371,18 @@ export default function DynamicFilter<
|
||||
</p>
|
||||
);
|
||||
}
|
||||
if (config.type === "dual-range-slider") {
|
||||
const rangeValues = value as number[];
|
||||
const formatLabel = config.formatLabel || ((val: number | undefined) => val?.toString() || "");
|
||||
return (
|
||||
<p>
|
||||
{config.label}:{" "}
|
||||
<span className="text-muted-foreground">
|
||||
{formatLabel(rangeValues[0])} - {formatLabel(rangeValues[1])}
|
||||
</span>
|
||||
</p>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<p>
|
||||
{config.label}: <span className="text-muted-foreground">{value}</span>
|
||||
@@ -322,15 +393,26 @@ export default function DynamicFilter<
|
||||
// Handles removing an individual filter
|
||||
const handleRemoveFilter = (keyToRemove: TFilterKeys) => {
|
||||
const newParams = new URLSearchParams(currentParams.toString());
|
||||
newParams.delete(keyToRemove);
|
||||
newParams.set("page", "1"); // Reset page after removing a filter
|
||||
|
||||
// Clear the specific input's local state
|
||||
const inputConfig = inputs.find((input) => input.name === keyToRemove);
|
||||
|
||||
if (inputConfig?.type === "dual-range-slider") {
|
||||
newParams.delete(`${keyToRemove}_min`);
|
||||
newParams.delete(`${keyToRemove}_max`);
|
||||
setInputValues((prev) => ({
|
||||
...prev,
|
||||
[keyToRemove]: [inputConfig.min, inputConfig.max],
|
||||
}));
|
||||
} else {
|
||||
newParams.delete(keyToRemove);
|
||||
setInputValues((prev) => ({
|
||||
...prev,
|
||||
[keyToRemove]: inputConfig?.type === "checkbox-group" ? [] : "",
|
||||
}));
|
||||
}
|
||||
|
||||
newParams.set("page", "1"); // Reset page after removing a filter
|
||||
|
||||
startTransition(() => {
|
||||
replace(`${pathname}?${newParams.toString()}`);
|
||||
@@ -384,6 +466,27 @@ export default function DynamicFilter<
|
||||
onChange={handleCheckboxGroupChange(input.name)}
|
||||
/>
|
||||
);
|
||||
case "dual-range-slider":
|
||||
return (
|
||||
<div
|
||||
key={input.name}
|
||||
className="px-2 w-full flex flex-col gap-2 p-2 border rounded-md"
|
||||
>
|
||||
<Label className="font-semibold text-sm">
|
||||
{input.label}
|
||||
</Label>
|
||||
<div className="px-3 py-2 mt-5">
|
||||
<DualRangeSlider
|
||||
label={(value) => <span className="text-xs">{value}{input.sliderLabel}</span>}
|
||||
value={inputValues[input.name] as number[]}
|
||||
onValueChange={handleDualRangeChange(input.name)}
|
||||
min={input.min}
|
||||
max={input.max}
|
||||
step={input.step || 1}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
case "radio-group":
|
||||
return (
|
||||
<div
|
||||
|
||||
50
components/ui/dual-range-slider.tsx
Normal file
50
components/ui/dual-range-slider.tsx
Normal file
@@ -0,0 +1,50 @@
|
||||
'use client';
|
||||
|
||||
import * as SliderPrimitive from '@radix-ui/react-slider';
|
||||
import * as React from 'react';
|
||||
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface DualRangeSliderProps extends React.ComponentProps<typeof SliderPrimitive.Root> {
|
||||
labelPosition?: 'top' | 'bottom';
|
||||
label?: (value: number | undefined) => React.ReactNode;
|
||||
}
|
||||
|
||||
const DualRangeSlider = React.forwardRef<
|
||||
React.ElementRef<typeof SliderPrimitive.Root>,
|
||||
DualRangeSliderProps
|
||||
>(({ className, label, labelPosition = 'top', ...props }, ref) => {
|
||||
const initialValue = Array.isArray(props.value) ? props.value : [props.min, props.max];
|
||||
|
||||
return (
|
||||
<SliderPrimitive.Root
|
||||
ref={ref}
|
||||
className={cn('relative flex w-full touch-none select-none items-center', className)}
|
||||
{...props}
|
||||
>
|
||||
<SliderPrimitive.Track className="relative h-2 w-full grow overflow-hidden rounded-full bg-secondary">
|
||||
<SliderPrimitive.Range className="absolute h-full bg-primary" />
|
||||
</SliderPrimitive.Track>
|
||||
{initialValue.map((value, index) => (
|
||||
<React.Fragment key={`${index + 1}`}>
|
||||
<SliderPrimitive.Thumb className="relative block h-4 w-4 rounded-full border-2 border-primary bg-background ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50">
|
||||
{label && (
|
||||
<span
|
||||
className={cn(
|
||||
'absolute flex w-full justify-center',
|
||||
labelPosition === 'top' && '-top-7',
|
||||
labelPosition === 'bottom' && 'top-4',
|
||||
)}
|
||||
>
|
||||
{label(value)}
|
||||
</span>
|
||||
)}
|
||||
</SliderPrimitive.Thumb>
|
||||
</React.Fragment>
|
||||
))}
|
||||
</SliderPrimitive.Root>
|
||||
);
|
||||
});
|
||||
DualRangeSlider.displayName = 'DualRangeSlider';
|
||||
|
||||
export { DualRangeSlider };
|
||||
@@ -1,3 +1,5 @@
|
||||
import { User } from "./types/user";
|
||||
|
||||
export interface Links {
|
||||
next_page: string | null;
|
||||
previous_page: string | null;
|
||||
@@ -45,7 +47,9 @@ export interface Device {
|
||||
expiry_date: string | null;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
user: number;
|
||||
user: Pick<User, "id" | "id_card" | "mobile"> & {
|
||||
name: string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface ApiError {
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { getServerSession } from "next-auth";
|
||||
import { authOptions } from "@/app/auth";
|
||||
import type { AddDeviceFormState, initialState } from "@/components/user/add-device-dialog";
|
||||
import type { ApiError, ApiResponse, Device } from "@/lib/backend-types";
|
||||
import { checkSession } from "@/utils/session";
|
||||
import { handleApiResponse } from "@/utils/tryCatch";
|
||||
import { getServerSession } from "next-auth";
|
||||
import { revalidatePath } from "next/cache";
|
||||
|
||||
type GetDevicesProps = {
|
||||
name?: string;
|
||||
@@ -17,7 +17,7 @@ type GetDevicesProps = {
|
||||
status?: string;
|
||||
[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();
|
||||
|
||||
// Build query string from all defined params
|
||||
@@ -27,7 +27,7 @@ export async function getDevices(params: GetDevicesProps) {
|
||||
.join("&");
|
||||
|
||||
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",
|
||||
headers: {
|
||||
@@ -123,6 +123,7 @@ export async function blockDevice({
|
||||
reason_for_blocking: string;
|
||||
blocked_by: "ADMIN" | "PARENT";
|
||||
}) {
|
||||
console.log("Blocking device:", deviceId, reason_for_blocking, blocked_by);
|
||||
const session = await getServerSession(authOptions);
|
||||
const response = await fetch(
|
||||
`${process.env.SARLINK_API_BASE_URL}/api/devices/${deviceId}/block/`,
|
||||
|
||||
Reference in New Issue
Block a user