mirror of
https://github.com/i701/sarlink-portal.git
synced 2025-04-20 03:50:20 +00:00
refactor: add tryCatch utility for error handling, update device-related components and types, and clean up unused code in payment actions
Some checks failed
Build and Push Docker Images / Build and Push Docker Images (push) Failing after 13m55s
Some checks failed
Build and Push Docker Images / Build and Push Docker Images (push) Failing after 13m55s
This commit is contained in:
parent
dbdc1df7d5
commit
aa18484475
@ -1,31 +1,29 @@
|
||||
"use server";
|
||||
|
||||
import prisma from "@/lib/db";
|
||||
import type { PaymentType } from "@/lib/types";
|
||||
import { formatMacAddress } from "@/lib/utils";
|
||||
import type { Prisma } from "@prisma/client";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { redirect } from "next/navigation";
|
||||
import { addDevicesToGroup } from "./omada-actions";
|
||||
|
||||
export async function createPayment(data: PaymentType) {
|
||||
console.log("data", data);
|
||||
const payment = await prisma.payment.create({
|
||||
data: {
|
||||
amount: data.amount,
|
||||
numberOfMonths: data.numberOfMonths,
|
||||
paid: data.paid,
|
||||
userId: data.userId,
|
||||
devices: {
|
||||
connect: data.deviceIds.map((id) => {
|
||||
return {
|
||||
id,
|
||||
};
|
||||
}),
|
||||
},
|
||||
},
|
||||
});
|
||||
redirect(`/payments/${payment.id}`);
|
||||
// const payment = await prisma.payment.create({
|
||||
// data: {
|
||||
// amount: data.amount,
|
||||
// numberOfMonths: data.numberOfMonths,
|
||||
// paid: data.paid,
|
||||
// userId: data.userId,
|
||||
// devices: {
|
||||
// connect: data.deviceIds.map((id) => {
|
||||
// return {
|
||||
// id,
|
||||
// };
|
||||
// }),
|
||||
// },
|
||||
// },
|
||||
// });
|
||||
// redirect(`/payments/${payment.id}`);
|
||||
}
|
||||
|
||||
type VerifyPaymentType = {
|
||||
@ -38,12 +36,6 @@ type VerifyPaymentType = {
|
||||
type?: "TRANSFER" | "WALLET";
|
||||
};
|
||||
|
||||
type PaymentWithDevices = Prisma.PaymentGetPayload<{
|
||||
include: {
|
||||
devices: true;
|
||||
};
|
||||
}>;
|
||||
|
||||
class InsufficientFundsError extends Error {
|
||||
constructor() {
|
||||
super("Insufficient funds in wallet");
|
||||
|
@ -1,12 +1,10 @@
|
||||
import DevicesForPayment from '@/components/devices-for-payment'
|
||||
import prisma from '@/lib/db';
|
||||
import React from 'react'
|
||||
import DevicesForPayment from "@/components/devices-for-payment";
|
||||
import React from "react";
|
||||
|
||||
export default async function DevicesToPay() {
|
||||
const billFormula = await prisma.billFormula.findFirst();
|
||||
return (
|
||||
<div>
|
||||
<DevicesForPayment billFormula={billFormula ?? undefined} />
|
||||
<DevicesForPayment />
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
@ -1,22 +1,17 @@
|
||||
import prisma from '@/lib/db'
|
||||
import React from 'react'
|
||||
import React from "react";
|
||||
|
||||
export default async function DeviceDetails({ params }: {
|
||||
params: Promise<{ deviceId: string }>
|
||||
export default async function DeviceDetails({
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{ deviceId: string }>;
|
||||
}) {
|
||||
const deviceId = (await params)?.deviceId
|
||||
const device = await prisma.device.findUnique({
|
||||
where: {
|
||||
id: deviceId,
|
||||
},
|
||||
const deviceId = (await params)?.deviceId;
|
||||
|
||||
})
|
||||
return null;
|
||||
return (
|
||||
<div>
|
||||
<div className="flex flex-col justify-between items-start text-gray-500 title-bg py-4 px-2 mb-4">
|
||||
<h3 className='text-2xl font-bold'>
|
||||
{device?.name}
|
||||
</h3>
|
||||
<h3 className="text-2xl font-bold">{device?.name}</h3>
|
||||
<span>{device?.mac}</span>
|
||||
</div>
|
||||
|
||||
@ -35,5 +30,5 @@ export default async function DeviceDetails({ params }: {
|
||||
<DevicesTable searchParams={searchParams} />
|
||||
</Suspense> */}
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
@ -23,8 +23,6 @@ export default async function Devices({
|
||||
<h3 className="text-sarLinkOrange text-2xl">My Devices</h3>
|
||||
<AddDeviceDialogForm user_id={session?.user?.id} />
|
||||
</div>
|
||||
<pre>{JSON.stringify(session, null, 2)}</pre>
|
||||
|
||||
<div
|
||||
id="user-filters"
|
||||
className=" pb-4 gap-4 flex sm:flex-row flex-col items-start justify-start"
|
||||
|
12
next-auth.d.ts → app/next-auth.d.ts
vendored
12
next-auth.d.ts → app/next-auth.d.ts
vendored
@ -1,6 +1,5 @@
|
||||
import NextAuth, { DefaultSession } from "next-auth";
|
||||
import NextAuth, { DefaultSession, type User } from "next-auth";
|
||||
import { Session } from "next-auth";
|
||||
import type { User } from "./userTypes";
|
||||
declare module "next-auth" {
|
||||
/**
|
||||
* Returned by `useSession`, `getSession` and received as a prop on the `SessionProvider` React Context
|
||||
@ -13,6 +12,15 @@ declare module "next-auth" {
|
||||
image?: string | null;
|
||||
user?: User & {
|
||||
expiry?: string;
|
||||
id?: number;
|
||||
username?: string;
|
||||
user_permissions?: { id: number; name: string }[];
|
||||
id_card?: string;
|
||||
first_name?: string;
|
||||
last_name?: string;
|
||||
last_login?: string;
|
||||
date_joined?: string;
|
||||
is_superuser?: boolean;
|
||||
};
|
||||
expires: ISODateString;
|
||||
}
|
@ -34,7 +34,7 @@ export function AccountPopover() {
|
||||
{session.data?.user?.name}
|
||||
</h4>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{session.data?.user?.phoneNumber}
|
||||
{session.data?.user?.id_card}
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
|
@ -12,7 +12,7 @@ import {
|
||||
SidebarTrigger,
|
||||
} from "@/components/ui/sidebar";
|
||||
import { getServerSession } from "next-auth";
|
||||
import { headers } from "next/headers";
|
||||
import { redirect } from "next/navigation";
|
||||
import { AccountPopover } from "./account-popver";
|
||||
|
||||
export async function ApplicationLayout({
|
||||
@ -20,20 +20,22 @@ export async function ApplicationLayout({
|
||||
}: { children: React.ReactNode }) {
|
||||
const session = await getServerSession(authOptions);
|
||||
|
||||
if (!session) return redirect("/auth/signin");
|
||||
return (
|
||||
<SidebarProvider>
|
||||
<AppSidebar role={"admin"} />
|
||||
{/* <DeviceCartDrawer billFormula={billFormula || null} /> */}
|
||||
<AppSidebar />
|
||||
<DeviceCartDrawer />
|
||||
<SidebarInset>
|
||||
<header className="flex justify-between sticky top-0 bg-background h-16 shrink-0 items-center gap-2 border-b px-4 z-10">
|
||||
<div className="flex items-center gap-2 ">
|
||||
<SidebarTrigger className="-ml-1" />
|
||||
<Separator orientation="vertical" className="mr-2 h-4" />
|
||||
{session?.user.role === "ADMIN" && (
|
||||
<span className="text-sm font-mono px-2 p-1 rounded-md bg-green-500/10 text-green-900 dark:text-green-400">
|
||||
Welcome back {session?.user.name}
|
||||
<div className="text-sm font-mono px-2 p-1 rounded-md bg-green-500/10 text-green-900 dark:text-green-400">
|
||||
Welcome back,{" "}
|
||||
<span className="font-semibold">
|
||||
{session?.user?.first_name} {session?.user?.last_name}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
|
@ -1,34 +1,32 @@
|
||||
"use client";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
deviceCartAtom
|
||||
} from "@/lib/atoms";
|
||||
import { authClient } from "@/lib/auth-client";
|
||||
import { deviceCartAtom } from "@/lib/atoms";
|
||||
import { useAtomValue } from "jotai";
|
||||
import {
|
||||
MonitorSmartphone
|
||||
} from "lucide-react";
|
||||
import { MonitorSmartphone } from "lucide-react";
|
||||
import { usePathname, useRouter } from "next/navigation";
|
||||
|
||||
|
||||
export function DeviceCartDrawer() {
|
||||
const pathname = usePathname();
|
||||
const devices = useAtomValue(deviceCartAtom);
|
||||
const router = useRouter();
|
||||
|
||||
|
||||
if (pathname === "/payment" || pathname === "/devices-to-pay") {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
|
||||
if (devices.length === 0) return null
|
||||
return <Button size={"lg"} className="bg-sarLinkOrange absolute bottom-10 w-fit z-20 left-1/2 transform -translate-x-1/2" onClick={() => router.push("/devices-to-pay")} variant="outline">
|
||||
if (devices.length === 0) return null;
|
||||
return (
|
||||
<Button
|
||||
size={"lg"}
|
||||
className="bg-sarLinkOrange absolute bottom-10 w-fit z-20 left-1/2 transform -translate-x-1/2"
|
||||
onClick={() => router.push("/devices-to-pay")}
|
||||
variant="outline"
|
||||
>
|
||||
<MonitorSmartphone />
|
||||
Pay {devices.length > 0 && `(${devices.length})`} Device
|
||||
</Button>
|
||||
);
|
||||
|
||||
// <>
|
||||
// <Drawer open={isOpen} onOpenChange={setIsOpen}>
|
||||
@ -120,5 +118,3 @@ export function DeviceCartDrawer() {
|
||||
|
||||
// );
|
||||
}
|
||||
|
||||
|
||||
|
@ -1,32 +1,20 @@
|
||||
|
||||
"use client";
|
||||
|
||||
import { createPayment } from "@/actions/payment";
|
||||
import DeviceCard from "@/components/device-card";
|
||||
import NumberInput from "@/components/number-input";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
deviceCartAtom,
|
||||
numberOfMonths
|
||||
} from "@/lib/atoms";
|
||||
import { authClient } from "@/lib/auth-client";
|
||||
import { deviceCartAtom, numberOfMonths } from "@/lib/atoms";
|
||||
import type { PaymentType } from "@/lib/types";
|
||||
import type { BillFormula } from "@prisma/client";
|
||||
import { useAtom, useAtomValue, useSetAtom } from "jotai";
|
||||
import {
|
||||
CircleDollarSign,
|
||||
Loader2
|
||||
} from "lucide-react";
|
||||
import { CircleDollarSign, Loader2 } from "lucide-react";
|
||||
import { useSession } from "next-auth/react";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { useEffect, useState } from "react";
|
||||
export default function DevicesForPayment({
|
||||
billFormula,
|
||||
}: {
|
||||
billFormula?: BillFormula;
|
||||
}) {
|
||||
const baseAmount = billFormula?.baseAmount || 100;
|
||||
const discountPercentage = billFormula?.discountPercentage || 75;
|
||||
const session = authClient.useSession();
|
||||
export default function DevicesForPayment() {
|
||||
const baseAmount = 100;
|
||||
const discountPercentage = 75;
|
||||
const session = useSession();
|
||||
const pathname = usePathname();
|
||||
const devices = useAtomValue(deviceCartAtom);
|
||||
const setDeviceCart = useSetAtom(deviceCartAtom);
|
||||
@ -42,8 +30,8 @@ export default function DevicesForPayment({
|
||||
} else {
|
||||
setMessage("");
|
||||
}
|
||||
setTotal(baseAmount + ((devices.length + 1) - 1) * discountPercentage);
|
||||
}, [months, devices.length, baseAmount, discountPercentage]);
|
||||
setTotal(baseAmount + (devices.length + 1 - 1) * discountPercentage);
|
||||
}, [months, devices.length]);
|
||||
|
||||
if (pathname === "/payment") {
|
||||
return null;
|
||||
@ -51,7 +39,7 @@ export default function DevicesForPayment({
|
||||
|
||||
const data: PaymentType = {
|
||||
numberOfMonths: months,
|
||||
userId: session?.data?.user.id ?? "",
|
||||
userId: session?.data?.user?.id ?? "",
|
||||
deviceIds: devices.map((device) => device.id),
|
||||
amount: Number.parseFloat(total.toFixed(2)),
|
||||
paid: false,
|
||||
@ -85,7 +73,6 @@ export default function DevicesForPayment({
|
||||
setDeviceCart([]);
|
||||
setMonths(1);
|
||||
setDisabled(false);
|
||||
|
||||
}}
|
||||
className="w-full"
|
||||
disabled={devices.length === 0 || disabled}
|
||||
@ -101,7 +88,6 @@ export default function DevicesForPayment({
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
@ -9,6 +9,8 @@ import {
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
import { getDevices } from "@/queries/devices";
|
||||
import { tryCatch } from "@/utils/tryCatch";
|
||||
import { getServerSession } from "next-auth";
|
||||
import ClickableRow from "./clickable-row";
|
||||
import DeviceCard from "./device-card";
|
||||
@ -26,86 +28,17 @@ export async function DevicesTable({
|
||||
parentalControl?: boolean;
|
||||
}) {
|
||||
const session = await getServerSession(authOptions);
|
||||
const isAdmin = session?.user;
|
||||
const isAdmin = session?.user?.is_superuser;
|
||||
const query = (await searchParams)?.query || "";
|
||||
const page = (await searchParams)?.page;
|
||||
const sortBy = (await searchParams)?.sortBy || "asc";
|
||||
// const totalDevices = await prisma.device.count({
|
||||
// where: {
|
||||
// userId: isAdmin ? undefined : session?.session.userId,
|
||||
// OR: [
|
||||
// {
|
||||
// name: {
|
||||
// contains: query || "",
|
||||
// mode: "insensitive",
|
||||
// },
|
||||
// },
|
||||
// {
|
||||
// mac: {
|
||||
// contains: query || "",
|
||||
// mode: "insensitive",
|
||||
// },
|
||||
// },
|
||||
// ],
|
||||
// NOT: {
|
||||
// payments: {
|
||||
// some: {
|
||||
// paid: false,
|
||||
// },
|
||||
// },
|
||||
// },
|
||||
// isActive: isAdmin ? undefined : parentalControl,
|
||||
// blocked: isAdmin
|
||||
// ? undefined
|
||||
// : parentalControl !== undefined
|
||||
// ? undefined
|
||||
// : false,
|
||||
// },
|
||||
// });
|
||||
|
||||
// const totalPages = Math.ceil(totalDevices / 10);
|
||||
const limit = 10;
|
||||
const offset = (Number(page) - 1) * limit || 0;
|
||||
|
||||
// const devices = await prisma.device.findMany({
|
||||
// where: {
|
||||
// userId: session?.session.userId,
|
||||
// OR: [
|
||||
// {
|
||||
// name: {
|
||||
// contains: query || "",
|
||||
// mode: "insensitive",
|
||||
// },
|
||||
// },
|
||||
// {
|
||||
// mac: {
|
||||
// contains: query || "",
|
||||
// mode: "insensitive",
|
||||
// },
|
||||
// },
|
||||
// ],
|
||||
// NOT: {
|
||||
// payments: {
|
||||
// some: {
|
||||
// paid: false,
|
||||
// },
|
||||
// },
|
||||
// },
|
||||
// isActive: parentalControl,
|
||||
// blocked: parentalControl !== undefined ? undefined : false,
|
||||
// },
|
||||
|
||||
// skip: offset,
|
||||
// take: limit,
|
||||
// orderBy: {
|
||||
// name: `${sortBy}` as "asc" | "desc",
|
||||
// },
|
||||
// });
|
||||
|
||||
return null;
|
||||
const [error, devices] = await tryCatch(getDevices({ query: query }));
|
||||
if (error) {
|
||||
return <pre>{JSON.stringify(error, null, 2)}</pre>;
|
||||
}
|
||||
const { meta, links, data } = devices;
|
||||
return (
|
||||
<div>
|
||||
{devices.length === 0 ? (
|
||||
{data.length === 0 ? (
|
||||
<div className="h-[calc(100svh-400px)] flex flex-col items-center justify-center my-4">
|
||||
<h3>No devices yet.</h3>
|
||||
</div>
|
||||
@ -122,7 +55,7 @@ export async function DevicesTable({
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody className="overflow-scroll">
|
||||
{devices.map((device) => (
|
||||
{data.map((device) => (
|
||||
// <TableRow key={device.id}>
|
||||
// <TableCell>
|
||||
// <div className="flex flex-col items-start">
|
||||
@ -173,21 +106,25 @@ export async function DevicesTable({
|
||||
<TableCell colSpan={2}>
|
||||
{query.length > 0 && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Showing {devices.length} locations for "{query}
|
||||
Showing {meta.total} locations for "{query}
|
||||
"
|
||||
</p>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell className="text-muted-foreground">
|
||||
{totalDevices} devices
|
||||
{meta.total} devices
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableFooter>
|
||||
</Table>
|
||||
<Pagination totalPages={totalPages} currentPage={page} />
|
||||
<Pagination
|
||||
totalPages={meta.total / meta.per_page}
|
||||
currentPage={meta.current_page}
|
||||
/>
|
||||
<pre>{JSON.stringify(meta, null, 2)}</pre>
|
||||
</div>
|
||||
<div className="sm:hidden my-4">
|
||||
{devices.map((device) => (
|
||||
{data.map((device) => (
|
||||
<DeviceCard
|
||||
parentalControl={parentalControl}
|
||||
key={device.id}
|
||||
|
@ -8,25 +8,15 @@ import {
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
import prisma from "@/lib/db";
|
||||
import Link from "next/link";
|
||||
|
||||
import { auth } from "@/app/auth";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { Prisma } from "@prisma/client";
|
||||
import { Calendar } from "lucide-react";
|
||||
import { headers } from "next/headers";
|
||||
import Pagination from "./pagination";
|
||||
import { Badge } from "./ui/badge";
|
||||
import { Button } from "./ui/button";
|
||||
import { Separator } from "./ui/separator";
|
||||
|
||||
type PaymentWithDevices = Prisma.PaymentGetPayload<{
|
||||
include: {
|
||||
devices: true;
|
||||
};
|
||||
}>;
|
||||
|
||||
export async function PaymentsTable({
|
||||
searchParams,
|
||||
}: {
|
||||
@ -36,60 +26,61 @@ export async function PaymentsTable({
|
||||
sortBy: string;
|
||||
}>;
|
||||
}) {
|
||||
const session = await auth.api.getSession({
|
||||
headers: await headers(),
|
||||
});
|
||||
const query = (await searchParams)?.query || "";
|
||||
const page = (await searchParams)?.page;
|
||||
const totalPayments = await prisma.payment.count({
|
||||
where: {
|
||||
userId: session?.session.userId,
|
||||
OR: [
|
||||
{
|
||||
devices: {
|
||||
every: {
|
||||
name: {
|
||||
contains: query || "",
|
||||
mode: "insensitive",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
// const session = await auth.api.getSession({
|
||||
// headers: await headers(),
|
||||
// });
|
||||
// const query = (await searchParams)?.query || "";
|
||||
// const page = (await searchParams)?.page;
|
||||
// const totalPayments = await prisma.payment.count({
|
||||
// where: {
|
||||
// userId: session?.session.userId,
|
||||
// OR: [
|
||||
// {
|
||||
// devices: {
|
||||
// every: {
|
||||
// name: {
|
||||
// contains: query || "",
|
||||
// mode: "insensitive",
|
||||
// },
|
||||
// },
|
||||
// },
|
||||
// },
|
||||
// ],
|
||||
// },
|
||||
// });
|
||||
|
||||
const totalPages = Math.ceil(totalPayments / 10);
|
||||
const limit = 10;
|
||||
const offset = (Number(page) - 1) * limit || 0;
|
||||
// const totalPages = Math.ceil(totalPayments / 10);
|
||||
// const limit = 10;
|
||||
// const offset = (Number(page) - 1) * limit || 0;
|
||||
|
||||
const payments = await prisma.payment.findMany({
|
||||
where: {
|
||||
userId: session?.session.userId,
|
||||
OR: [
|
||||
{
|
||||
devices: {
|
||||
every: {
|
||||
name: {
|
||||
contains: query || "",
|
||||
mode: "insensitive",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
include: {
|
||||
devices: true,
|
||||
},
|
||||
// const payments = await prisma.payment.findMany({
|
||||
// where: {
|
||||
// userId: session?.session.userId,
|
||||
// OR: [
|
||||
// {
|
||||
// devices: {
|
||||
// every: {
|
||||
// name: {
|
||||
// contains: query || "",
|
||||
// mode: "insensitive",
|
||||
// },
|
||||
// },
|
||||
// },
|
||||
// },
|
||||
// ],
|
||||
// },
|
||||
// include: {
|
||||
// devices: true,
|
||||
// },
|
||||
|
||||
skip: offset,
|
||||
take: limit,
|
||||
orderBy: {
|
||||
createdAt: "desc",
|
||||
},
|
||||
});
|
||||
// skip: offset,
|
||||
// take: limit,
|
||||
// orderBy: {
|
||||
// createdAt: "desc",
|
||||
// },
|
||||
// });
|
||||
|
||||
return null;
|
||||
return (
|
||||
<div>
|
||||
{payments.length === 0 ? (
|
||||
|
@ -10,6 +10,7 @@ import {
|
||||
Wallet2Icon,
|
||||
} from "lucide-react";
|
||||
|
||||
import { authOptions } from "@/app/auth";
|
||||
import {
|
||||
Collapsible,
|
||||
CollapsibleContent,
|
||||
@ -27,76 +28,130 @@ import {
|
||||
SidebarMenuItem,
|
||||
SidebarRail,
|
||||
} from "@/components/ui/sidebar";
|
||||
import { getServerSession } from "next-auth";
|
||||
import Link from "next/link";
|
||||
|
||||
const data = {
|
||||
navMain: [
|
||||
type Permission = {
|
||||
id: number;
|
||||
name: string;
|
||||
};
|
||||
|
||||
type Categories = {
|
||||
id: string;
|
||||
children: (
|
||||
| {
|
||||
title: string;
|
||||
link: string;
|
||||
perm_identifier: string;
|
||||
icon: React.JSX.Element;
|
||||
}
|
||||
| {
|
||||
title: string;
|
||||
link: string;
|
||||
icon: React.JSX.Element;
|
||||
perm_identifier?: undefined;
|
||||
}
|
||||
)[];
|
||||
}[];
|
||||
|
||||
export async function AppSidebar({
|
||||
role,
|
||||
...props
|
||||
}: React.ComponentProps<typeof Sidebar>) {
|
||||
const categories = [
|
||||
{
|
||||
title: "MENU",
|
||||
id: "MENU",
|
||||
url: "#",
|
||||
requiredRoles: ["ADMIN", "USER"],
|
||||
items: [
|
||||
children: [
|
||||
{
|
||||
title: "Devices",
|
||||
url: "/devices",
|
||||
link: "/devices",
|
||||
perm_identifier: "device",
|
||||
icon: <Smartphone size={16} />,
|
||||
},
|
||||
{
|
||||
title: "Payments",
|
||||
url: "/payments",
|
||||
link: "/payments",
|
||||
icon: <CreditCard size={16} />,
|
||||
perm_identifier: "payment",
|
||||
},
|
||||
{
|
||||
title: "Parental Control",
|
||||
url: "/parental-control",
|
||||
link: "/parental-control",
|
||||
icon: <CreditCard size={16} />,
|
||||
perm_identifier: "device",
|
||||
},
|
||||
{
|
||||
title: "Agreements",
|
||||
url: "/agreements",
|
||||
link: "/agreements",
|
||||
icon: <Handshake size={16} />,
|
||||
perm_identifier: "device",
|
||||
},
|
||||
{
|
||||
title: "Wallet",
|
||||
url: "/wallet",
|
||||
link: "/wallet",
|
||||
icon: <Wallet2Icon size={16} />,
|
||||
perm_identifier: "wallet",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "ADMIN CONTROL",
|
||||
id: "ADMIN CONTROL",
|
||||
url: "#",
|
||||
requiredRoles: ["ADMIN"],
|
||||
items: [
|
||||
children: [
|
||||
{
|
||||
title: "Users",
|
||||
url: "/users",
|
||||
link: "/users",
|
||||
icon: <UsersRound size={16} />,
|
||||
perm_identifier: "device",
|
||||
},
|
||||
{
|
||||
title: "User Devices",
|
||||
url: "/user-devices",
|
||||
link: "/user-devices",
|
||||
icon: <MonitorSpeaker size={16} />,
|
||||
perm_identifier: "device",
|
||||
},
|
||||
{
|
||||
title: "User Payments",
|
||||
url: "/user-payments",
|
||||
link: "/user-payments",
|
||||
icon: <Coins size={16} />,
|
||||
perm_identifier: "payment",
|
||||
},
|
||||
{
|
||||
title: "Price Calculator",
|
||||
url: "/price-calculator",
|
||||
link: "/price-calculator",
|
||||
icon: <Calculator size={16} />,
|
||||
perm_identifier: "device",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
];
|
||||
|
||||
const session = await getServerSession(authOptions);
|
||||
|
||||
const filteredCategories = categories.map((category) => {
|
||||
const filteredChildren = category.children.filter((child) => {
|
||||
const permIdentifier = child.perm_identifier;
|
||||
return session?.user?.user_permissions?.some((permission: Permission) => {
|
||||
const permissionParts = permission.name.split(" ");
|
||||
const modelNameFromPermission = permissionParts.slice(2).join(" ");
|
||||
return modelNameFromPermission === permIdentifier;
|
||||
});
|
||||
});
|
||||
|
||||
return { ...category, children: filteredChildren };
|
||||
});
|
||||
const filteredCategoriesWithChildren = filteredCategories.filter(
|
||||
(category) => category.children.length > 0,
|
||||
);
|
||||
|
||||
let CATEGORIES: Categories;
|
||||
if (session?.user?.is_superuser) {
|
||||
CATEGORIES = categories;
|
||||
} else {
|
||||
CATEGORIES = filteredCategoriesWithChildren;
|
||||
}
|
||||
|
||||
export function AppSidebar({
|
||||
role,
|
||||
...props
|
||||
}: React.ComponentProps<typeof Sidebar> & { role: string }) {
|
||||
return (
|
||||
<Sidebar {...props} className="z-50">
|
||||
<SidebarHeader>
|
||||
@ -105,17 +160,11 @@ export function AppSidebar({
|
||||
</h4>
|
||||
</SidebarHeader>
|
||||
<SidebarContent className="gap-0">
|
||||
{data.navMain
|
||||
.filter(
|
||||
(item) =>
|
||||
!item.requiredRoles || item.requiredRoles.includes(role || ""),
|
||||
)
|
||||
.map((item) => {
|
||||
if (item.requiredRoles?.includes(role)) {
|
||||
{CATEGORIES.map((item) => {
|
||||
return (
|
||||
<Collapsible
|
||||
key={item.title}
|
||||
title={item.title}
|
||||
key={item.id}
|
||||
title={item.id}
|
||||
defaultOpen
|
||||
className="group/collapsible"
|
||||
>
|
||||
@ -125,17 +174,17 @@ export function AppSidebar({
|
||||
className="group/label text-sm text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground"
|
||||
>
|
||||
<CollapsibleTrigger>
|
||||
{item.title}{" "}
|
||||
{item.id}{" "}
|
||||
<ChevronRight className="ml-auto transition-transform group-data-[state=open]/collapsible:rotate-90" />
|
||||
</CollapsibleTrigger>
|
||||
</SidebarGroupLabel>
|
||||
<CollapsibleContent>
|
||||
<SidebarGroupContent>
|
||||
<SidebarMenu>
|
||||
{item.items.map((item) => (
|
||||
{item.children.map((item) => (
|
||||
<SidebarMenuItem key={item.title}>
|
||||
<SidebarMenuButton className="py-6" asChild>
|
||||
<Link className="text-md" href={item.url}>
|
||||
<Link className="text-md" href={item.link}>
|
||||
{item.icon}
|
||||
<span className="opacity-70 ml-2">
|
||||
{item.title}
|
||||
@ -150,7 +199,6 @@ export function AppSidebar({
|
||||
</SidebarGroup>
|
||||
</Collapsible>
|
||||
);
|
||||
}
|
||||
})}
|
||||
</SidebarContent>
|
||||
<SidebarRail />
|
||||
|
@ -1,6 +1,5 @@
|
||||
"use client";
|
||||
|
||||
import { AddDevice } from "@/actions/user-actions";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
import {
|
||||
@ -14,6 +13,8 @@ import {
|
||||
} from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { addDevice } from "@/queries/devices";
|
||||
import { tryCatch } from "@/utils/tryCatch";
|
||||
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { Loader2, Plus } from "lucide-react";
|
||||
@ -23,7 +24,6 @@ import { toast } from "sonner";
|
||||
import { z } from "zod";
|
||||
|
||||
export default function AddDeviceDialogForm({ user_id }: { user_id?: string }) {
|
||||
|
||||
const formSchema = z.object({
|
||||
name: z.string().min(2, { message: "Name is required." }),
|
||||
mac_address: z
|
||||
@ -46,28 +46,28 @@ export default function AddDeviceDialogForm({ user_id }: { user_id?: string }) {
|
||||
});
|
||||
|
||||
if (!user_id) {
|
||||
return null
|
||||
return null;
|
||||
}
|
||||
|
||||
const onSubmit: SubmitHandler<z.infer<typeof formSchema>> = (data) => {
|
||||
const onSubmit: SubmitHandler<z.infer<typeof formSchema>> = async (data) => {
|
||||
console.log(data);
|
||||
setDisabled(true)
|
||||
toast.promise(AddDevice({ mac_address: data.mac_address, name: data.name, user_id: user_id }), {
|
||||
loading: 'Adding new device...',
|
||||
success: () => {
|
||||
setDisabled(false)
|
||||
setOpen((prev) => !prev)
|
||||
return 'Device successfully added!'
|
||||
},
|
||||
error: (error) => {
|
||||
setDisabled(false)
|
||||
return error || 'Something went wrong.'
|
||||
},
|
||||
})
|
||||
setDisabled(true);
|
||||
const [error, response] = await tryCatch(
|
||||
addDevice({
|
||||
mac: data.mac_address,
|
||||
name: data.name,
|
||||
}),
|
||||
);
|
||||
if (error) {
|
||||
toast.error(error.message || "Something went wrong.");
|
||||
setDisabled(false);
|
||||
} else {
|
||||
setOpen(false);
|
||||
setDisabled(false);
|
||||
toast.success("Device successfully added!");
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
@ -84,7 +84,8 @@ export default function AddDeviceDialogForm({ user_id }: { user_id?: string }) {
|
||||
<DialogHeader>
|
||||
<DialogTitle>New Device</DialogTitle>
|
||||
<DialogDescription>
|
||||
To add a new device, enter the device name and mac address below. Click save when you are done.
|
||||
To add a new device, enter the device name and mac address below.
|
||||
Click save when you are done.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<form onSubmit={handleSubmit(onSubmit)}>
|
||||
|
@ -29,3 +29,24 @@ export interface Island {
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface Device {
|
||||
id: number;
|
||||
name: string;
|
||||
mac: string;
|
||||
reason_for_blocking: string | null;
|
||||
is_active: boolean;
|
||||
registered: boolean;
|
||||
blocked: boolean;
|
||||
blocked_by: string;
|
||||
expiry_date: string | null;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
user: number;
|
||||
}
|
||||
|
||||
export interface Api400Error {
|
||||
data: {
|
||||
message: string;
|
||||
};
|
||||
}
|
||||
|
61
queries/devices.ts
Normal file
61
queries/devices.ts
Normal file
@ -0,0 +1,61 @@
|
||||
"use server";
|
||||
|
||||
import { authOptions } from "@/app/auth";
|
||||
import type { Api400Error, ApiResponse, Device } from "@/lib/backend-types";
|
||||
import { getServerSession } from "next-auth";
|
||||
import { revalidatePath } from "next/cache";
|
||||
|
||||
type GetDevicesProps = {
|
||||
query?: string;
|
||||
page?: number;
|
||||
sortBy?: string;
|
||||
status?: string;
|
||||
};
|
||||
export async function getDevices({ query }: GetDevicesProps) {
|
||||
const session = await getServerSession(authOptions);
|
||||
const respose = await fetch(
|
||||
`${process.env.SARLINK_API_BASE_URL}/api/devices/?name=${query}`,
|
||||
{
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Token ${session?.apiToken}`,
|
||||
},
|
||||
},
|
||||
);
|
||||
const data = (await respose.json()) as ApiResponse<Device>;
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function addDevice({
|
||||
name,
|
||||
mac,
|
||||
}: {
|
||||
name: string;
|
||||
mac: string;
|
||||
}) {
|
||||
type SingleDevice = Pick<Device, "name" | "mac">;
|
||||
const session = await getServerSession(authOptions);
|
||||
const response = await fetch(
|
||||
`${process.env.SARLINK_API_BASE_URL}/api/devices/`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Token ${session?.apiToken}`,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
name: name,
|
||||
mac: mac,
|
||||
}),
|
||||
},
|
||||
);
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json();
|
||||
// Throw an error with the message from the API
|
||||
throw new Error(errorData.message || "Something went wrong.");
|
||||
}
|
||||
const data = (await response.json()) as SingleDevice;
|
||||
revalidatePath("/devices");
|
||||
return data;
|
||||
}
|
8
utils/tryCatch.ts
Normal file
8
utils/tryCatch.ts
Normal file
@ -0,0 +1,8 @@
|
||||
export async function tryCatch<T, E = Error>(promise: T | Promise<T>) {
|
||||
try {
|
||||
const data = await promise;
|
||||
return [null, data] as const;
|
||||
} catch (error) {
|
||||
return [error as E, null] as const;
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user