temporary fix for build and remove previous auth related code

This commit is contained in:
2025-04-10 22:39:38 +05:00
parent 7e49bf119a
commit e8296ae3f6
10 changed files with 854 additions and 800 deletions

View File

@ -1,5 +1,4 @@
import { UsersPaymentsTable } from "@/components/admin/user-payments-table";
import { AdminAuthGuard } from "@/lib/auth-guard";
import React, { Suspense } from "react";
export default async function UserPayments({
@ -12,15 +11,12 @@ export default async function UserPayments({
status: string;
}>;
}) {
await AdminAuthGuard();
const query = (await searchParams)?.query || "";
return (
<div>
<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">
User Payments
</h3>
<h3 className="text-sarLinkOrange text-2xl">User Payments</h3>
</div>
<Suspense key={query} fallback={"loading...."}>
<UsersPaymentsTable searchParams={searchParams} />

View File

@ -1,95 +1,176 @@
import InputReadOnly from '@/components/input-read-only';
import { Badge } from '@/components/ui/badge';
import UserRejectDialog from '@/components/user/user-reject-dialog';
import { UserVerifyDialog } from '@/components/user/user-verify-dialog';
import { getNationalPerson } from '@/lib/person';
import InputReadOnly from "@/components/input-read-only";
import { Badge } from "@/components/ui/badge";
import UserRejectDialog from "@/components/user/user-reject-dialog";
import { UserVerifyDialog } from "@/components/user/user-verify-dialog";
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({
params,
params,
}: {
params: Promise<{
userId: string;
}>;
params: Promise<{
userId: string;
}>;
}) {
const userId = (await params).userId
const dbUser = await prisma.user.findUnique({
where: {
id: userId,
},
include: {
island: {
include: {
atoll: true
}
}
}
})
const userId = (await params).userId;
// const dbUser = await prisma.user.findUnique({
// where: {
// id: userId,
// },
// include: {
// island: {
// include: {
// 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>
<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>
// <div className="flex gap-2">
// {dbUser && !dbUser?.verified && <UserVerifyDialog user={dbUser} />}
// {dbUser && !dbUser?.verified && <UserRejectDialog user={dbUser} />}
// {dbUser?.verified && (
// <Badge variant={"secondary"} className="bg-lime-500">
// 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'>
{dbUser && !dbUser?.verified && <UserVerifyDialog user={dbUser} />}
{dbUser && !dbUser?.verified && <UserRejectDialog user={dbUser} />}
{dbUser?.verified && <Badge variant={"secondary"} className='bg-lime-500'>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 ?? ""} />
<InputReadOnly showCheck checkTrue={new Date(dbUser?.dob ?? "") === new Date(nationalData.dob)} labelClassName='text-sarLinkOrange' label="DOB" value={new Date(dbUser?.dob ?? "").toLocaleDateString("en-US", {
month: "short",
day: "2-digit",
year: "numeric",
})} />
<InputReadOnly showCheck checkTrue={dbUser?.phoneNumber === nationalData.primary_contact} labelClassName='text-sarLinkOrange' label="Phone Number" value={dbUser?.phoneNumber ?? ""} />
</div>
</div>
<div id="national-information">
<h4 className='p-2 rounded font-semibold'>National Information</h4>
<div className='shadow p-2 rounded-md title-bg space-y-1 my-2 grid grid-cols-1 md:grid-cols-2 gap-2'>
<InputReadOnly showCheck={false} labelClassName='text-green-500' label="ID Card" value={nationalData?.nic ?? ""} />
<InputReadOnly showCheck={false} labelClassName='text-green-500' label="Name" value={nationalData?.name_en ?? ""} />
<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 showCheck={false} labelClassName='text-green-500' 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>
)
// <InputReadOnly
// showCheck
// checkTrue={
// new Date(dbUser?.dob ?? "") === new Date(nationalData.dob)
// }
// labelClassName="text-sarLinkOrange"
// label="DOB"
// value={new Date(dbUser?.dob ?? "").toLocaleDateString("en-US", {
// month: "short",
// day: "2-digit",
// year: "numeric",
// })}
// />
// <InputReadOnly
// showCheck
// checkTrue={dbUser?.phoneNumber === nationalData.primary_contact}
// labelClassName="text-sarLinkOrange"
// label="Phone Number"
// value={dbUser?.phoneNumber ?? ""}
// />
// </div>
// </div>
// <div id="national-information">
// <h4 className="p-2 rounded font-semibold">National Information</h4>
// <div className="shadow p-2 rounded-md title-bg space-y-1 my-2 grid grid-cols-1 md:grid-cols-2 gap-2">
// <InputReadOnly
// showCheck={false}
// labelClassName="text-green-500"
// label="ID Card"
// value={nationalData?.nic ?? ""}
// />
// <InputReadOnly
// showCheck={false}
// labelClassName="text-green-500"
// label="Name"
// value={nationalData?.name_en ?? ""}
// />
// <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
// showCheck={false}
// labelClassName="text-green-500"
// 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 Search from "@/components/search";
import { UsersTable } from "@/components/user-table";
import { AdminAuthGuard } from "@/lib/auth-guard";
import {
AArrowDown,
AArrowUp,
@ -36,15 +35,10 @@ export default async function AdminUsers({
status: string;
}>;
}) {
await AdminAuthGuard();
return (
<div>
<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">
Users
</h3>
<h3 className="text-sarLinkOrange text-2xl">Users</h3>
</div>
<div

View File

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