temporary fix for build and remove previous auth related code

This commit is contained in:
i701 2025-04-10 22:39:38 +05:00
parent 7e49bf119a
commit e8296ae3f6
Signed by: i701
GPG Key ID: 54A0DA1E26D8E587
10 changed files with 854 additions and 800 deletions

3
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,3 @@
{
"typescript.tsdk": "node_modules/typescript/lib"
}

View File

@ -1,5 +1,4 @@
import { UsersPaymentsTable } from "@/components/admin/user-payments-table"; import { UsersPaymentsTable } from "@/components/admin/user-payments-table";
import { AdminAuthGuard } from "@/lib/auth-guard";
import React, { Suspense } from "react"; import React, { Suspense } from "react";
export default async function UserPayments({ export default async function UserPayments({
@ -12,15 +11,12 @@ export default async function UserPayments({
status: string; status: string;
}>; }>;
}) { }) {
await AdminAuthGuard();
const query = (await searchParams)?.query || ""; const query = (await searchParams)?.query || "";
return ( return (
<div> <div>
<div className="flex justify-between items-center border-[1px] rounded-md border-dashed font-bold title-bg py-4 px-2 mb-4"> <div className="flex justify-between items-center border-[1px] 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 Payments</h3>
User Payments
</h3>
</div> </div>
<Suspense key={query} fallback={"loading...."}> <Suspense key={query} fallback={"loading...."}>
<UsersPaymentsTable searchParams={searchParams} /> <UsersPaymentsTable searchParams={searchParams} />

View File

@ -1,11 +1,10 @@
import InputReadOnly from '@/components/input-read-only'; import InputReadOnly from "@/components/input-read-only";
import { Badge } from '@/components/ui/badge'; import { Badge } from "@/components/ui/badge";
import UserRejectDialog from '@/components/user/user-reject-dialog'; import UserRejectDialog from "@/components/user/user-reject-dialog";
import { UserVerifyDialog } from '@/components/user/user-verify-dialog'; import { UserVerifyDialog } from "@/components/user/user-verify-dialog";
import { getNationalPerson } from '@/lib/person'; import { getNationalPerson } from "@/lib/person";
import prisma from '@/lib/db'; import Image from "next/image";
import Image from 'next/image';
export default async function VerifyUserPage({ export default async function VerifyUserPage({
params, params,
@ -14,82 +13,164 @@ export default async function VerifyUserPage({
userId: string; userId: string;
}>; }>;
}) { }) {
const userId = (await params).userId const userId = (await params).userId;
const dbUser = await prisma.user.findUnique({ // const dbUser = await prisma.user.findUnique({
where: { // where: {
id: userId, // id: userId,
}, // },
include: { // include: {
island: { // island: {
include: { // include: {
atoll: true // atoll: true
} // }
} // }
} // }
}) // })
const nationalData = await getNationalPerson({ idCard: dbUser?.id_card ?? "" }) // const nationalData = await getNationalPerson({ idCard: dbUser?.id_card ?? "" })
return null;
// return (
// <div>
// <div className="flex items-center justify-between text-gray-500 text-2xl font-bold title-bg py-4 px-2 mb-4">
// <h3 className="text-sarLinkOrange text-2xl">Verify user</h3>
return ( // <div className="flex gap-2">
<div> // {dbUser && !dbUser?.verified && <UserVerifyDialog user={dbUser} />}
<div className='flex items-center justify-between text-gray-500 text-2xl font-bold title-bg py-4 px-2 mb-4'> // {dbUser && !dbUser?.verified && <UserRejectDialog user={dbUser} />}
<h3 className="text-sarLinkOrange text-2xl"> // {dbUser?.verified && (
Verify user // <Badge variant={"secondary"} className="bg-lime-500">
</h3> // Verified
// </Badge>
// )}
// </div>
// </div>
// <div className="grid grid-cols-1 md:grid-cols-2 gap-4 items-start justify-start">
// <div id="database-information">
// <h4 className="p-2 rounded font-semibold">Database Information</h4>
// <div className="shadow p-2 rounded-lg title-bg space-y-1 my-2 grid grid-cols-1 md:grid-cols-2 gap-2">
// <InputReadOnly
// showCheck
// checkTrue={dbUser?.id_card === nationalData.nic}
// labelClassName="text-sarLinkOrange"
// label="ID Card"
// value={dbUser?.id_card ?? ""}
// />
// <InputReadOnly
// showCheck
// checkTrue={dbUser?.name === nationalData.name_en}
// labelClassName="text-sarLinkOrange"
// label="Name"
// value={dbUser?.name ?? ""}
// />
// <InputReadOnly
// showCheck
// checkTrue={dbUser?.address === nationalData.house_name_en}
// labelClassName="text-sarLinkOrange"
// label="House Name"
// value={dbUser?.address ?? ""}
// />
// <InputReadOnly
// showCheck
// checkTrue={dbUser?.island?.name === nationalData.island_name_en}
// labelClassName="text-sarLinkOrange"
// label="Island"
// value={dbUser?.island?.name ?? ""}
// />
// <InputReadOnly
// showCheck
// checkTrue={dbUser?.island?.atoll.name === nationalData.atoll_en}
// labelClassName="text-sarLinkOrange"
// label="Atoll"
// value={dbUser?.island?.atoll.name ?? ""}
// />
<div className='flex gap-2'> // <InputReadOnly
{dbUser && !dbUser?.verified && <UserVerifyDialog user={dbUser} />} // showCheck
{dbUser && !dbUser?.verified && <UserRejectDialog user={dbUser} />} // checkTrue={
{dbUser?.verified && <Badge variant={"secondary"} className='bg-lime-500'>Verified</Badge>} // new Date(dbUser?.dob ?? "") === new Date(nationalData.dob)
</div> // }
// labelClassName="text-sarLinkOrange"
</div> // label="DOB"
<div className='grid grid-cols-1 md:grid-cols-2 gap-4 items-start justify-start'> // value={new Date(dbUser?.dob ?? "").toLocaleDateString("en-US", {
<div id="database-information"> // month: "short",
<h4 className='p-2 rounded font-semibold'>Database Information</h4> // day: "2-digit",
<div className='shadow p-2 rounded-lg title-bg space-y-1 my-2 grid grid-cols-1 md:grid-cols-2 gap-2'> // year: "numeric",
<InputReadOnly showCheck checkTrue={dbUser?.id_card === nationalData.nic} labelClassName='text-sarLinkOrange' label="ID Card" value={dbUser?.id_card ?? ""} /> // })}
<InputReadOnly showCheck checkTrue={dbUser?.name === nationalData.name_en} labelClassName='text-sarLinkOrange' label="Name" value={dbUser?.name ?? ""} /> // />
<InputReadOnly showCheck checkTrue={dbUser?.address === nationalData.house_name_en} labelClassName='text-sarLinkOrange' label="House Name" value={dbUser?.address ?? ""} /> // <InputReadOnly
<InputReadOnly showCheck checkTrue={dbUser?.island?.name === nationalData.island_name_en} labelClassName='text-sarLinkOrange' label="Island" value={dbUser?.island?.name ?? ""} /> // showCheck
<InputReadOnly showCheck checkTrue={dbUser?.island?.atoll.name === nationalData.atoll_en} labelClassName='text-sarLinkOrange' label="Atoll" value={dbUser?.island?.atoll.name ?? ""} /> // checkTrue={dbUser?.phoneNumber === nationalData.primary_contact}
// labelClassName="text-sarLinkOrange"
<InputReadOnly showCheck checkTrue={new Date(dbUser?.dob ?? "") === new Date(nationalData.dob)} labelClassName='text-sarLinkOrange' label="DOB" value={new Date(dbUser?.dob ?? "").toLocaleDateString("en-US", { // label="Phone Number"
month: "short", // value={dbUser?.phoneNumber ?? ""}
day: "2-digit", // />
year: "numeric", // </div>
})} /> // </div>
<InputReadOnly showCheck checkTrue={dbUser?.phoneNumber === nationalData.primary_contact} labelClassName='text-sarLinkOrange' label="Phone Number" value={dbUser?.phoneNumber ?? ""} /> // <div id="national-information">
</div> // <h4 className="p-2 rounded font-semibold">National Information</h4>
</div> // <div className="shadow p-2 rounded-md title-bg space-y-1 my-2 grid grid-cols-1 md:grid-cols-2 gap-2">
<div id="national-information"> // <InputReadOnly
<h4 className='p-2 rounded font-semibold'>National Information</h4> // showCheck={false}
<div className='shadow p-2 rounded-md title-bg space-y-1 my-2 grid grid-cols-1 md:grid-cols-2 gap-2'> // labelClassName="text-green-500"
<InputReadOnly showCheck={false} labelClassName='text-green-500' label="ID Card" value={nationalData?.nic ?? ""} /> // label="ID Card"
<InputReadOnly showCheck={false} labelClassName='text-green-500' label="Name" value={nationalData?.name_en ?? ""} /> // value={nationalData?.nic ?? ""}
<InputReadOnly showCheck={false} labelClassName='text-green-500' label="House Name" value={nationalData?.house_name_en ?? ""} /> // />
<InputReadOnly showCheck={false} labelClassName='text-green-500' label="Island" value={nationalData?.island_name_en ?? ""} /> // <InputReadOnly
<InputReadOnly showCheck={false} labelClassName='text-green-500' label="Atoll" value={nationalData?.atoll_en ?? ""} /> // showCheck={false}
<InputReadOnly showCheck={false} labelClassName='text-green-500' label="DOB" value={new Date(nationalData?.dob ?? "").toLocaleDateString("en-US", { // labelClassName="text-green-500"
month: "short", // label="Name"
day: "2-digit", // value={nationalData?.name_en ?? ""}
year: "numeric", // />
})} /> // <InputReadOnly
<InputReadOnly showCheck={false} labelClassName='text-green-500' label="Phone Number" value={nationalData?.primary_contact ?? ""} /> // showCheck={false}
<div className='flex flex-col col-span-2 items-center justify-center'> // labelClassName="text-green-500"
<Image // label="House Name"
src={nationalData.image_url || "https://i.pravatar.cc/300"} // value={nationalData?.house_name_en ?? ""}
height={100} // />
width={100} // <InputReadOnly
className='object-fit aspect-square rounded-full' // showCheck={false}
alt='id photo' // labelClassName="text-green-500"
/> // label="Island"
</div> // value={nationalData?.island_name_en ?? ""}
</div> // />
</div> // <InputReadOnly
</div> // showCheck={false}
// labelClassName="text-green-500"
</div> // label="Atoll"
) // value={nationalData?.atoll_en ?? ""}
// />
// <InputReadOnly
// showCheck={false}
// labelClassName="text-green-500"
// label="DOB"
// value={new Date(nationalData?.dob ?? "").toLocaleDateString(
// "en-US",
// {
// month: "short",
// day: "2-digit",
// year: "numeric",
// },
// )}
// />
// <InputReadOnly
// showCheck={false}
// labelClassName="text-green-500"
// label="Phone Number"
// value={nationalData?.primary_contact ?? ""}
// />
// <div className="flex flex-col col-span-2 items-center justify-center">
// <Image
// src={nationalData.image_url || "https://i.pravatar.cc/300"}
// height={100}
// width={100}
// className="object-fit aspect-square rounded-full"
// alt="id photo"
// />
// </div>
// </div>
// </div>
// </div>
// </div>
// );
} }

View File

@ -2,7 +2,6 @@ import { Rejectuser } from "@/actions/user-actions";
import Filter from "@/components/filter"; import Filter from "@/components/filter";
import Search from "@/components/search"; import Search from "@/components/search";
import { UsersTable } from "@/components/user-table"; import { UsersTable } from "@/components/user-table";
import { AdminAuthGuard } from "@/lib/auth-guard";
import { import {
AArrowDown, AArrowDown,
AArrowUp, AArrowUp,
@ -36,15 +35,10 @@ export default async function AdminUsers({
status: string; status: string;
}>; }>;
}) { }) {
await AdminAuthGuard();
return ( return (
<div> <div>
<div className="flex justify-between items-center border-[1px] rounded-md border-dashed font-bold title-bg py-4 px-2 mb-4"> <div className="flex justify-between items-center border-[1px] 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">Users</h3>
Users
</h3>
</div> </div>
<div <div

View File

@ -1,151 +1,151 @@
import { blockDevice } from "@/actions/omada-actions"; import { blockDevice } from "@/actions/omada-actions";
import prisma from "@/lib/db";
import { validateApiKey } from "@/lib/utils"; import { validateApiKey } from "@/lib/utils";
import { addDays, addMonths, isAfter, isWithinInterval } from "date-fns"; import { addDays, addMonths, isAfter, isWithinInterval } from "date-fns";
const lastRunTime = new Date(); const lastRunTime = new Date();
export async function GET(request: Request) { export async function GET(request: Request) {
try { return Response.json({ message: "Request received" });
// Validate API key before proceeding // try {
validateApiKey(request); // // Validate API key before proceeding
// validateApiKey(request);
const currentTime = new Date(); // const currentTime = new Date();
const hoursSinceLastRun = // const hoursSinceLastRun =
(currentTime.getTime() - lastRunTime.getTime()) / (1000 * 60 * 60); // (currentTime.getTime() - lastRunTime.getTime()) / (1000 * 60 * 60);
// Get all active and unblocked devices with their latest payment // // Get all active and unblocked devices with their latest payment
const devices = await prisma.device.findMany({ // const devices = await prisma.device.findMany({
where: { // where: {
isActive: true, // isActive: true,
blocked: false, // blocked: false,
}, // },
include: { // include: {
payments: true, // payments: true,
User: { // User: {
include: { // include: {
devices: true, // devices: true,
}, // },
}, // },
}, // },
}); // });
let devicesNeedingNotification = 0; // let devicesNeedingNotification = 0;
let devicesBlocked = 0; // let devicesBlocked = 0;
for (const device of devices) { // for (const device of devices) {
let expiryDate = new Date(); // let expiryDate = new Date();
const payment = device.payments[0]; // const payment = device.payments[0];
expiryDate = addMonths( // expiryDate = addMonths(
payment?.paidAt || new Date(), // payment?.paidAt || new Date(),
payment?.numberOfMonths || 0, // payment?.numberOfMonths || 0,
); // );
// Calculate notification threshold (5 days before expiry) // // Calculate notification threshold (5 days before expiry)
const notificationThreshold = addDays(expiryDate, -5); // const notificationThreshold = addDays(expiryDate, -5);
const currentDate = new Date(); // const currentDate = new Date();
console.log("device name -> ", device.name); // console.log("device name -> ", device.name);
console.log("paid date -> ", device.payments[0]?.paidAt); // console.log("paid date -> ", device.payments[0]?.paidAt);
console.log("no of months paid -> ", device.payments[0]?.numberOfMonths); // console.log("no of months paid -> ", device.payments[0]?.numberOfMonths);
console.log("calculated expire date -> ", expiryDate); // console.log("calculated expire date -> ", expiryDate);
console.log("notification threshold -> ", notificationThreshold); // console.log("notification threshold -> ", notificationThreshold);
console.log("current date -> ", currentDate); // console.log("current date -> ", currentDate);
// Check if device is within notification period // // Check if device is within notification period
if ( // if (
isWithinInterval(currentDate, { // isWithinInterval(currentDate, {
start: notificationThreshold, // start: notificationThreshold,
end: expiryDate, // end: expiryDate,
}) // })
) { // ) {
// Device is within 5 days of expiring // // Device is within 5 days of expiring
if (device.User?.phoneNumber) { // if (device.User?.phoneNumber) {
await sendNotifySms( // await sendNotifySms(
new Date(expiryDate), // new Date(expiryDate),
device.User?.phoneNumber ?? "", // device.User?.phoneNumber ?? "",
device.name, // device.name,
); // );
devicesNeedingNotification++; // devicesNeedingNotification++;
} // }
} // }
// Check if device has expired // // Check if device has expired
if (isAfter(currentDate, expiryDate)) { // if (isAfter(currentDate, expiryDate)) {
// Device has expired, block it // // Device has expired, block it
// TODO: add a reason for blocking // // TODO: add a reason for blocking
await blockDevice({ // await blockDevice({
macAddress: device.mac, // macAddress: device.mac,
type: "block", // type: "block",
}); // });
await prisma.device.update({ // await prisma.device.update({
where: { id: device.id }, // where: { id: device.id },
data: { // data: {
isActive: false, // isActive: false,
blocked: true, // blocked: true,
}, // },
}); // });
devicesBlocked++; // devicesBlocked++;
} // }
} // }
if (hoursSinceLastRun < 24) { // if (hoursSinceLastRun < 24) {
return Response.json({ // return Response.json({
totalActiveDevices: devices.length, // totalActiveDevices: devices.length,
devicesChecked: { // devicesChecked: {
notified: devicesNeedingNotification, // notified: devicesNeedingNotification,
blocked: devicesBlocked, // blocked: devicesBlocked,
}, // },
message: "Check was run recently", // message: "Check was run recently",
nextCheckIn: `${Math.round(24 - hoursSinceLastRun)} hours`, // nextCheckIn: `${Math.round(24 - hoursSinceLastRun)} hours`,
}); // });
} // }
return Response.json({ // return Response.json({
success: true, // success: true,
totalActiveDevices: devices.length, // totalActiveDevices: devices.length,
devicesChecked: { // devicesChecked: {
notified: devicesNeedingNotification, // notified: devicesNeedingNotification,
blocked: devicesBlocked, // blocked: devicesBlocked,
}, // },
runAt: currentTime, // runAt: currentTime,
}); // });
} catch (error) { // } catch (error) {
if (error instanceof Error) { // if (error instanceof Error) {
if (error.message === "API key is missing") { // if (error.message === "API key is missing") {
return Response.json({ error: "API key is required" }, { status: 401 }); // return Response.json({ error: "API key is required" }, { status: 401 });
} // }
if (error.message === "Invalid API key") { // if (error.message === "Invalid API key") {
return Response.json({ error: "Invalid API key" }, { status: 403 }); // return Response.json({ error: "Invalid API key" }, { status: 403 });
} // }
} // }
console.error("Error in device check:", error); // console.error("Error in device check:", error);
return Response.json({ error: "Failed to check devices" }, { status: 500 }); // return Response.json({ error: "Failed to check devices" }, { status: 500 });
} // }
} // }
// Mock function - replace with your actual SMS implementation // // Mock function - replace with your actual SMS implementation
async function sendNotifySms( // async function sendNotifySms(
expireDate: Date, // expireDate: Date,
phoneNumber: string, // phoneNumber: string,
deviceName?: string, // deviceName?: string,
) { // ) {
const respose = await fetch(`${process.env.SMS_API_BASE_URL}/api/sms`, { // const respose = await fetch(`${process.env.SMS_API_BASE_URL}/api/sms`, {
method: "POST", // method: "POST",
headers: { // headers: {
"Content-Type": "application/json", // "Content-Type": "application/json",
Authorization: `Bearer ${process.env.SMS_API_KEY}`, // Authorization: `Bearer ${process.env.SMS_API_KEY}`,
}, // },
body: JSON.stringify({ // body: JSON.stringify({
check_delivery: false, // check_delivery: false,
number: phoneNumber, // number: phoneNumber,
message: `REMINDER! Your device [${deviceName}] will expire on ${new Date(expireDate)}.`, // message: `REMINDER! Your device [${deviceName}] will expire on ${new Date(expireDate)}.`,
}), // }),
}); // });
const data = await respose.json(); // const data = await respose.json();
console.log(data); // console.log(data);
return data; // return data;
// Implement your SMS logic here //
} }

View File

@ -8,8 +8,6 @@ import {
TableHeader, TableHeader,
TableRow, TableRow,
} from "@/components/ui/table"; } from "@/components/ui/table";
import { auth } from "@/app/auth";
import prisma from "@/lib/db";
import { headers } from "next/headers"; import { headers } from "next/headers";
import Link from "next/link"; import Link from "next/link";
import BlockDeviceDialog from "../block-device-dialog"; import BlockDeviceDialog from "../block-device-dialog";
@ -27,178 +25,178 @@ export async function AdminDevicesTable({
}>; }>;
parentalControl?: boolean; parentalControl?: boolean;
}) { }) {
const session = await auth.api.getSession({ // const session = await auth.api.getSession({
headers: await headers(), // headers: await headers(),
}); // });
const isAdmin = session?.user.role === "ADMIN"; // const isAdmin = session?.user.role === "ADMIN";
const query = (await searchParams)?.query || ""; // const query = (await searchParams)?.query || "";
const page = (await searchParams)?.page; // const page = (await searchParams)?.page;
const sortBy = (await searchParams)?.sortBy || "asc"; // const sortBy = (await searchParams)?.sortBy || "asc";
const totalDevices = await prisma.device.count({ // const totalDevices = await prisma.device.count({
where: { // where: {
OR: [ // OR: [
{ // {
name: { // name: {
contains: query || "", // contains: query || "",
mode: "insensitive", // mode: "insensitive",
}, // },
}, // },
{ // {
mac: { // mac: {
contains: query || "", // contains: query || "",
mode: "insensitive", // mode: "insensitive",
}, // },
}, // },
], // ],
}, // },
}); // });
const totalPages = Math.ceil(totalDevices / 10); // const totalPages = Math.ceil(totalDevices / 10);
const limit = 10; // const limit = 10;
const offset = (Number(page) - 1) * limit || 0; // const offset = (Number(page) - 1) * limit || 0;
const devices = await prisma.device.findMany({ // const devices = await prisma.device.findMany({
where: { // where: {
OR: [ // OR: [
{ // {
name: { // name: {
contains: query || "", // contains: query || "",
mode: "insensitive", // mode: "insensitive",
}, // },
}, // },
{ // {
mac: { // mac: {
contains: query || "", // contains: query || "",
mode: "insensitive", // mode: "insensitive",
}, // },
}, // },
], // ],
}, // },
include: { // include: {
User: true, // User: true,
payments: true, // payments: true,
}, // },
skip: offset, // skip: offset,
take: limit, // take: limit,
orderBy: { // orderBy: {
name: `${sortBy}` as "asc" | "desc", // 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>
// )}
return ( // {device.blocked && (
<div> // <div className="p-2 rounded border my-2">
{devices.length === 0 ? ( // <span>Comment: </span>
<div className="h-[calc(100svh-400px)] flex flex-col items-center justify-center my-4"> // <p className="text-neutral-500">
<h3>No devices yet.</h3> // blocked because he was watching youtube
</div> // </p>
) : ( // </div>
<> // )}
<div className="hidden sm:block"> // </div>
<Table className="overflow-scroll"> // </TableCell>
<TableCaption>Table of all devices.</TableCaption> // <TableCell className="font-medium">
<TableHeader> // {device.User?.name}
<TableRow> // </TableCell>
<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 && ( // <TableCell className="font-medium">{device.mac}</TableCell>
<div className="p-2 rounded border my-2"> // <TableCell>
<span>Comment: </span> // {device.isActive ? "Active" : "Inactive"}
<p className="text-neutral-500"> // </TableCell>
blocked because he was watching youtube // <TableCell>
</p> // {device.blocked ? "Blocked" : "Not Blocked"}
</div> // </TableCell>
)} // <TableCell>
</div> // {device.blocked ? device.blockedBy : ""}
</TableCell> // </TableCell>
<TableCell className="font-medium"> // <TableCell>
{device.User?.name} // {new Date().toLocaleDateString("en-US", {
</TableCell> // month: "short",
// day: "2-digit",
<TableCell className="font-medium">{device.mac}</TableCell> // year: "numeric",
<TableCell> // })}
{device.isActive ? "Active" : "Inactive"} // </TableCell>
</TableCell> // <TableCell>
<TableCell> // <BlockDeviceDialog
{device.blocked ? "Blocked" : "Not Blocked"} // admin={isAdmin}
</TableCell> // type={device.blocked ? "unblock" : "block"}
<TableCell> // device={device}
{device.blocked ? device.blockedBy : ""} // />
</TableCell> // </TableCell>
<TableCell> // </TableRow>
{new Date().toLocaleDateString("en-US", { // ))}
month: "short", // </TableBody>
day: "2-digit", // <TableFooter>
year: "numeric", // <TableRow>
})} // <TableCell colSpan={7}>
</TableCell> // {query.length > 0 && (
<TableCell> // <p className="text-sm text-muted-foreground">
<BlockDeviceDialog // Showing {devices.length} locations for &quot;{query}
admin={isAdmin} // &quot;
type={device.blocked ? "unblock" : "block"} // </p>
device={device} // )}
/> // </TableCell>
</TableCell> // <TableCell className="text-muted-foreground">
</TableRow> // {totalDevices} devices
))} // </TableCell>
</TableBody> // </TableRow>
<TableFooter> // </TableFooter>
<TableRow> // </Table>
<TableCell colSpan={7}> // <Pagination totalPages={totalPages} currentPage={page} />
{query.length > 0 && ( // </div>
<p className="text-sm text-muted-foreground"> // <div className="sm:hidden my-4">
Showing {devices.length} locations for &quot;{query} // {devices.map((device) => (
&quot; // <DeviceCard
</p> // parentalControl={parentalControl}
)} // key={device.id}
</TableCell> // device={device}
<TableCell className="text-muted-foreground"> // />
{totalDevices} devices // ))}
</TableCell> // </div>
</TableRow> // </>
</TableFooter> // )}
</Table> // </div>
<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>
);
} }

View File

@ -11,7 +11,6 @@ import {
TableHeader, TableHeader,
TableRow, TableRow,
} from "@/components/ui/table"; } from "@/components/ui/table";
import prisma from "@/lib/db";
import Link from "next/link"; import Link from "next/link";
export async function UsersPaymentsTable({ export async function UsersPaymentsTable({
@ -27,96 +26,96 @@ export async function UsersPaymentsTable({
const query = (await searchParams)?.query || ""; const query = (await searchParams)?.query || "";
const page = (await searchParams)?.page; const page = (await searchParams)?.page;
const sortBy = (await searchParams)?.sortBy || "asc"; const sortBy = (await searchParams)?.sortBy || "asc";
const totalPayments = await prisma.payment.count({ // const totalPayments = await prisma.payment.count({
where: { // where: {
OR: [ // OR: [
{ // {
user: { // user: {
name: { // name: {
contains: query || "", // contains: query || "",
mode: "insensitive", // mode: "insensitive",
} // }
}, // },
}, // },
{ // {
user: { // user: {
phoneNumber: { // phoneNumber: {
contains: query || "", // contains: query || "",
mode: "insensitive", // mode: "insensitive",
} // }
}, // },
}, // },
{ // {
user: { // user: {
address: { // address: {
contains: query || "", // contains: query || "",
mode: "insensitive", // mode: "insensitive",
} // }
}, // },
}, // },
{ // {
user: { // user: {
id_card: { // id_card: {
contains: query || "", // contains: query || "",
mode: "insensitive", // mode: "insensitive",
} // }
}, // },
}, // },
], // ],
}, // },
}); // });
const totalPages = Math.ceil(totalPayments / 10); // const totalPages = Math.ceil(totalPayments / 10);
const limit = 10; // const limit = 10;
const offset = (Number(page) - 1) * limit || 0; // const offset = (Number(page) - 1) * limit || 0;
const payments = await prisma.payment.findMany({ // const payments = await prisma.payment.findMany({
where: { // where: {
OR: [ // OR: [
{ // {
user: { // user: {
name: { // name: {
contains: query || "", // contains: query || "",
mode: "insensitive", // mode: "insensitive",
} // }
}, // },
}, // },
{ // {
user: { // user: {
phoneNumber: { // phoneNumber: {
contains: query || "", // contains: query || "",
mode: "insensitive", // mode: "insensitive",
} // }
}, // },
}, // },
{ // {
user: { // user: {
address: { // address: {
contains: query || "", // contains: query || "",
mode: "insensitive", // mode: "insensitive",
} // }
}, // },
}, // },
{ // {
user: { // user: {
id_card: { // id_card: {
contains: query || "", // contains: query || "",
mode: "insensitive", // mode: "insensitive",
} // }
}, // },
}, // },
], // ],
}, // },
include: { // include: {
user: true, // user: true,
devices: true, // devices: true,
}, // },
skip: offset, // skip: offset,
take: limit, // take: limit,
orderBy: { // orderBy: {
id: `${sortBy}` as "asc" | "desc", // id: `${sortBy}` as "asc" | "desc",
}, // },
}); // });
// const users = await prisma.user.findMany({ // const users = await prisma.user.findMany({
// where: { // where: {
@ -127,103 +126,110 @@ export async function UsersPaymentsTable({
// island: true, // island: true,
// }, // },
// }); // });
return ( return null;
<div> // return (
{payments.length === 0 ? ( // <div>
<div className="h-[calc(100svh-400px)] flex flex-col items-center justify-center my-4"> // {payments.length === 0 ? (
<h3>No user payments yet.</h3> // <div className="h-[calc(100svh-400px)] flex flex-col items-center justify-center my-4">
</div> // <h3>No user payments yet.</h3>
) : ( // </div>
<> // ) : (
<Table className="overflow-scroll"> // <>
<TableCaption>Table of all users.</TableCaption> // <Table className="overflow-scroll">
<TableHeader> // <TableCaption>Table of all users.</TableCaption>
<TableRow> // <TableHeader>
<TableHead>Devices paid</TableHead> // <TableRow>
<TableHead>User</TableHead> // <TableHead>Devices paid</TableHead>
<TableHead>Amount</TableHead> // <TableHead>User</TableHead>
<TableHead>Duration</TableHead> // <TableHead>Amount</TableHead>
<TableHead>Payment Status</TableHead> // <TableHead>Duration</TableHead>
<TableHead>Payment Method</TableHead> // <TableHead>Payment Status</TableHead>
<TableHead>Paid At</TableHead> // <TableHead>Payment Method</TableHead>
<TableHead>Action</TableHead> // <TableHead>Paid At</TableHead>
</TableRow> // <TableHead>Action</TableHead>
</TableHeader> // </TableRow>
<TableBody className="overflow-scroll"> // </TableHeader>
{payments.map((payment) => ( // <TableBody className="overflow-scroll">
<TableRow // {payments.map((payment) => (
className={`${payment.paid && "title-bg dark:bg-black"}`} // <TableRow
key={payment.id} // className={`${payment.paid && "title-bg dark:bg-black"}`}
> // key={payment.id}
<TableCell className="font-medium"> // >
<ol className="list-disc list-inside text-sm"> // <TableCell className="font-medium">
{payment.devices.map((device) => ( // <ol className="list-disc list-inside text-sm">
<li key={device.id} className="text-sm text-muted-foreground"> // {payment.devices.map((device) => (
{device.name} // <li
</li> // key={device.id}
))} // className="text-sm text-muted-foreground"
</ol> // >
</TableCell> // {device.name}
<TableCell className="font-medium">{payment.user.id_card}</TableCell> // </li>
<TableCell>{payment.user?.name}</TableCell> // ))}
<TableCell>{payment.user?.name}</TableCell> // </ol>
<TableCell>{payment.id}</TableCell> // </TableCell>
// <TableCell className="font-medium">
// {payment.user.id_card}
// </TableCell>
// <TableCell>{payment.user?.name}</TableCell>
// <TableCell>{payment.user?.name}</TableCell>
// <TableCell>{payment.id}</TableCell>
<TableCell> // <TableCell>
{payment.paid ? ( // {payment.paid ? (
<Badge // <Badge
variant="outline" // variant="outline"
className="bg-lime-100 text-black" // className="bg-lime-100 text-black"
> // >
Verified // Verified
</Badge> // </Badge>
) : ( // ) : (
<Badge // <Badge
variant="outline" // variant="outline"
className="bg-yellow-100 text-black" // className="bg-yellow-100 text-black"
> // >
Unverified // Unverified
</Badge> // </Badge>
)} // )}
</TableCell> // </TableCell>
<TableCell> // <TableCell>
{new Date(payment.paidAt ?? "").toLocaleDateString("en-US", { // {new Date(payment.paidAt ?? "").toLocaleDateString(
month: "short", // "en-US",
day: "2-digit", // {
year: "numeric", // month: "short",
})} // day: "2-digit",
</TableCell> // year: "numeric",
// },
// )}
// </TableCell>
<TableCell>{payment.id}</TableCell> // <TableCell>{payment.id}</TableCell>
<TableCell> // <TableCell>
<Link href={`/payments/${payment.id}/verify`}> // <Link href={`/payments/${payment.id}/verify`}>
<Button> // <Button>Details</Button>
Details // </Link>
</Button> // </TableCell>
</Link> // </TableRow>
</TableCell> // ))}
</TableRow> // </TableBody>
))} // <TableFooter>
</TableBody> // <TableRow>
<TableFooter> // <TableCell colSpan={8}>
<TableRow> // {query.length > 0 && (
<TableCell colSpan={8}> // <p className="text-sm text-muted-foreground">
{query.length > 0 && ( // Showing {payments.length} locations for &quot;{query}
<p className="text-sm text-muted-foreground"> // &quot;
Showing {payments.length} locations for &quot;{query} // </p>
&quot; // )}
</p> // </TableCell>
)} // <TableCell className="text-muted-foreground">
</TableCell> // {totalPayments} payments
<TableCell className="text-muted-foreground"> // </TableCell>
{totalPayments} payments // </TableRow>
</TableCell> // </TableFooter>
</TableRow> // </Table>
</TableFooter> // <Pagination totalPages={totalPages} currentPage={page} />
</Table> // </>
<Pagination totalPages={totalPages} currentPage={page} /> // )}
</> // </div>
)} // );
</div>
);
} }

View File

@ -8,7 +8,6 @@ import {
TableHeader, TableHeader,
TableRow, TableRow,
} from "@/components/ui/table"; } from "@/components/ui/table";
import prisma from "@/lib/db";
import Link from "next/link"; import Link from "next/link";
import Pagination from "./pagination"; import Pagination from "./pagination";
import { Badge } from "./ui/badge"; import { Badge } from "./ui/badge";
@ -28,84 +27,84 @@ export async function UsersTable({
const page = (await searchParams)?.page; const page = (await searchParams)?.page;
const sortBy = (await searchParams)?.sortBy || "asc"; const sortBy = (await searchParams)?.sortBy || "asc";
const verified = (await searchParams)?.status || "all"; const verified = (await searchParams)?.status || "all";
const totalUsers = await prisma.user.count({ // const totalUsers = await prisma.user.count({
where: { // where: {
OR: [ // OR: [
{ // {
name: { // name: {
contains: query || "", // contains: query || "",
mode: "insensitive", // mode: "insensitive",
}, // },
}, // },
{ // {
phoneNumber: { // phoneNumber: {
contains: query || "", // contains: query || "",
mode: "insensitive", // mode: "insensitive",
}, // },
}, // },
{ // {
address: { // address: {
contains: query || "", // contains: query || "",
mode: "insensitive", // mode: "insensitive",
}, // },
}, // },
{ // {
id_card: { // id_card: {
contains: query || "", // contains: query || "",
mode: "insensitive", // mode: "insensitive",
}, // },
}, // },
], // ],
verified: verified === "all" ? undefined : verified === "verified", // verified: verified === "all" ? undefined : verified === "verified",
}, // },
}); // });
const totalPages = Math.ceil(totalUsers / 10); // const totalPages = Math.ceil(totalUsers / 10);
const limit = 10; // const limit = 10;
const offset = (Number(page) - 1) * limit || 0; // const offset = (Number(page) - 1) * limit || 0;
const users = await prisma.user.findMany({ // const users = await prisma.user.findMany({
where: { // where: {
OR: [ // OR: [
{ // {
name: { // name: {
contains: query || "", // contains: query || "",
mode: "insensitive", // mode: "insensitive",
}, // },
}, // },
{ // {
phoneNumber: { // phoneNumber: {
contains: query || "", // contains: query || "",
mode: "insensitive", // mode: "insensitive",
}, // },
}, // },
{ // {
address: { // address: {
contains: query || "", // contains: query || "",
mode: "insensitive", // mode: "insensitive",
}, // },
}, // },
{ // {
id_card: { // id_card: {
contains: query || "", // contains: query || "",
mode: "insensitive", // mode: "insensitive",
}, // },
}, // },
], // ],
verified: verified === "all" ? undefined : verified === "verified", // verified: verified === "all" ? undefined : verified === "verified",
}, // },
include: { // include: {
island: true, // island: true,
atoll: true, // atoll: true,
}, // },
skip: offset, // skip: offset,
take: limit, // take: limit,
orderBy: { // orderBy: {
id: `${sortBy}` as "asc" | "desc", // id: `${sortBy}` as "asc" | "desc",
}, // },
}); // });
// const users = await prisma.user.findMany({ // const users = await prisma.user.findMany({
// where: { // where: {
@ -116,96 +115,95 @@ export async function UsersTable({
// island: true, // island: true,
// }, // },
// }); // });
return ( return null;
<div> // return (
{users.length === 0 ? ( // <div>
<div className="h-[calc(100svh-400px)] flex flex-col items-center justify-center my-4"> // {users.length === 0 ? (
<h3>No Users yet.</h3> // <div className="h-[calc(100svh-400px)] flex flex-col items-center justify-center my-4">
</div> // <h3>No Users yet.</h3>
) : ( // </div>
<> // ) : (
<Table className="overflow-scroll"> // <>
<TableCaption>Table of all users.</TableCaption> // <Table className="overflow-scroll">
<TableHeader> // <TableCaption>Table of all users.</TableCaption>
<TableRow> // <TableHeader>
<TableHead>Name</TableHead> // <TableRow>
<TableHead>ID Card</TableHead> // <TableHead>Name</TableHead>
<TableHead>Atoll</TableHead> // <TableHead>ID Card</TableHead>
<TableHead>Island</TableHead> // <TableHead>Atoll</TableHead>
<TableHead>House Name</TableHead> // <TableHead>Island</TableHead>
<TableHead>Status</TableHead> // <TableHead>House Name</TableHead>
<TableHead>Dob</TableHead> // <TableHead>Status</TableHead>
<TableHead>Phone Number</TableHead> // <TableHead>Dob</TableHead>
<TableHead>Action</TableHead> // <TableHead>Phone Number</TableHead>
</TableRow> // <TableHead>Action</TableHead>
</TableHeader> // </TableRow>
<TableBody className="overflow-scroll"> // </TableHeader>
{users.map((user) => ( // <TableBody className="overflow-scroll">
<TableRow // {users.map((user) => (
className={`${user.verified && "title-bg dark:bg-black"}`} // <TableRow
key={user.id} // className={`${user.verified && "title-bg dark:bg-black"}`}
> // key={user.id}
<TableCell className="font-medium">{user.name}</TableCell> // >
<TableCell className="font-medium">{user.id_card}</TableCell> // <TableCell className="font-medium">{user.name}</TableCell>
<TableCell>{user.atoll?.name}</TableCell> // <TableCell className="font-medium">{user.id_card}</TableCell>
<TableCell>{user.island?.name}</TableCell> // <TableCell>{user.atoll?.name}</TableCell>
<TableCell>{user.address}</TableCell> // <TableCell>{user.island?.name}</TableCell>
// <TableCell>{user.address}</TableCell>
<TableCell> // <TableCell>
{user.verified ? ( // {user.verified ? (
<Badge // <Badge
variant="outline" // variant="outline"
className="bg-lime-100 text-black" // className="bg-lime-100 text-black"
> // >
Verified // Verified
</Badge> // </Badge>
) : ( // ) : (
<Badge // <Badge
variant="outline" // variant="outline"
className="bg-yellow-100 text-black" // className="bg-yellow-100 text-black"
> // >
Unverified // Unverified
</Badge> // </Badge>
)} // )}
</TableCell> // </TableCell>
<TableCell> // <TableCell>
{new Date(user.dob ?? "").toLocaleDateString("en-US", { // {new Date(user.dob ?? "").toLocaleDateString("en-US", {
month: "short", // month: "short",
day: "2-digit", // day: "2-digit",
year: "numeric", // year: "numeric",
})} // })}
</TableCell> // </TableCell>
<TableCell>{user.phoneNumber}</TableCell> // <TableCell>{user.phoneNumber}</TableCell>
<TableCell> // <TableCell>
<Link href={`/users/${user.id}/verify`}> // <Link href={`/users/${user.id}/verify`}>
<Button> // <Button>Details</Button>
Details // </Link>
</Button> // </TableCell>
</Link> // </TableRow>
</TableCell> // ))}
</TableRow> // </TableBody>
))} // <TableFooter>
</TableBody> // <TableRow>
<TableFooter> // <TableCell colSpan={8}>
<TableRow> // {query.length > 0 && (
<TableCell colSpan={8}> // <p className="text-sm text-muted-foreground">
{query.length > 0 && ( // Showing {users.length} locations for &quot;{query}
<p className="text-sm text-muted-foreground"> // &quot;
Showing {users.length} locations for &quot;{query} // </p>
&quot; // )}
</p> // </TableCell>
)} // <TableCell className="text-muted-foreground">
</TableCell> // {totalUsers} users
<TableCell className="text-muted-foreground"> // </TableCell>
{totalUsers} users // </TableRow>
</TableCell> // </TableFooter>
</TableRow> // </Table>
</TableFooter> // <Pagination totalPages={totalPages} currentPage={page} />
</Table> // </>
<Pagination totalPages={totalPages} currentPage={page} /> // )}
</> // </div>
)} // );
</div>
);
} }

View File

@ -1,8 +0,0 @@
"use server";
import prisma from "@/lib/db";
export async function useFormula() {
const formula = await prisma.billFormula.findFirst();
return formula;
}

View File

@ -1,14 +0,0 @@
"use server";
import { auth } from "@/app/auth";
import { headers } from "next/headers";
import { redirect } from "next/navigation";
export async function AdminAuthGuard() {
const session = await auth.api.getSession({
headers: await headers(),
});
if (session?.user.role !== "ADMIN") {
return redirect("/login");
}
return true;
}