mirror of
https://github.com/i701/sarlink-portal.git
synced 2025-11-06 01:36:59 +00:00
Compare commits
18 Commits
feat/devic
...
feat/user-
| Author | SHA1 | Date | |
|---|---|---|---|
| 361a01d86c | |||
| 255c03ae6a | |||
| 5809e26593 | |||
| b90a4afc73 | |||
|
|
644db022a1 | ||
| 9c1d1c5d2b | |||
| 78673e050c | |||
| a20c939c91 | |||
| d1fdcc873a | |||
| 71f48b1270 | |||
| 27a0b5d4b3 | |||
| 783d4b360d | |||
| fa12cd74d7 | |||
| 8f9b4ba2e5 | |||
| a61231cf6b | |||
| 9f9f2e4e91 | |||
|
|
3ac57a9c07 | ||
|
|
2232cdcf72 |
@@ -363,18 +363,4 @@ export async function verifyTopupPayment(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getProfile() {
|
|
||||||
const session = await getServerSession(authOptions);
|
|
||||||
const response = await fetch(
|
|
||||||
`${process.env.SARLINK_API_BASE_URL}/api/auth/profile/`,
|
|
||||||
{
|
|
||||||
method: "GET",
|
|
||||||
headers: {
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
Authorization: `Token ${session?.apiToken}`,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
return handleApiResponse<User>(response, "getProfile");
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,15 +1,20 @@
|
|||||||
"use server";
|
"use server";
|
||||||
import { VerifyUserDetails } from "@/lib/person";
|
|
||||||
import { revalidatePath } from "next/cache";
|
import { revalidatePath } from "next/cache";
|
||||||
import { redirect } from "next/navigation";
|
import { redirect } from "next/navigation";
|
||||||
import { CreateClient } from "./ninja/client";
|
import { getServerSession } from "next-auth";
|
||||||
|
import { authOptions } from "@/app/auth";
|
||||||
|
import type { RejectUserFormState } from "@/components/user/user-reject-dialog";
|
||||||
|
import type { ApiError } from "@/lib/backend-types";
|
||||||
|
import type { User, UserProfile } from "@/lib/types/user";
|
||||||
|
import { handleApiResponse } from "@/utils/tryCatch";
|
||||||
|
|
||||||
export async function VerifyUser(userId: string) {
|
export async function VerifyUser(_userId: string) {
|
||||||
// const user = await prisma.user.findUnique({
|
// const user = await prisma.user.findUnique({
|
||||||
// where: {
|
// where: {
|
||||||
// id: userId,
|
// id: userId,
|
||||||
// },
|
// },
|
||||||
// include: {
|
// include: {Rejectuser
|
||||||
// atoll: true,
|
// atoll: true,
|
||||||
// island: true,
|
// island: true,
|
||||||
// },
|
// },
|
||||||
@@ -52,72 +57,75 @@ export async function VerifyUser(userId: string) {
|
|||||||
// revalidatePath("/users");
|
// revalidatePath("/users");
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function Rejectuser({
|
export async function getProfile() {
|
||||||
userId,
|
const session = await getServerSession(authOptions);
|
||||||
reason,
|
const response = await fetch(
|
||||||
}: { userId: string; reason: string }) {
|
`${process.env.SARLINK_API_BASE_URL}/api/auth/profile/`,
|
||||||
// const user = await prisma.user.findUnique({
|
{
|
||||||
// where: {
|
method: "GET",
|
||||||
// id: userId,
|
headers: {
|
||||||
// },
|
"Content-Type": "application/json",
|
||||||
// });
|
Authorization: `Token ${session?.apiToken}`,
|
||||||
// if (!user) {
|
},
|
||||||
// throw new Error("User not found");
|
},
|
||||||
// }
|
);
|
||||||
|
|
||||||
// await SendUserRejectionDetailSMS({
|
return handleApiResponse<User>(response, "getProfile");
|
||||||
// details: reason,
|
}
|
||||||
// phoneNumber: user.phoneNumber,
|
|
||||||
// });
|
|
||||||
// await prisma.user.delete({
|
|
||||||
// where: {
|
export async function getProfileById(userId: string) {
|
||||||
// id: userId,
|
const session = await getServerSession(authOptions);
|
||||||
// },
|
const response = await fetch(
|
||||||
// });
|
`${process.env.SARLINK_API_BASE_URL}/api/auth/users/${userId}/`,
|
||||||
|
{
|
||||||
|
method: "GET",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
Authorization: `Token ${session?.apiToken}`,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
return handleApiResponse<UserProfile>(response, "getProfilebyId");
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function rejectUser(
|
||||||
|
_prevState: RejectUserFormState,
|
||||||
|
formData: FormData
|
||||||
|
): Promise<RejectUserFormState> {
|
||||||
|
const userId = formData.get("userId") as string;
|
||||||
|
const rejection_details = formData.get("rejection_details") as string;
|
||||||
|
const session = await getServerSession(authOptions);
|
||||||
|
const response = await fetch(
|
||||||
|
`${process.env.SARLINK_API_BASE_URL}/api/auth/users/${userId}/reject/`,
|
||||||
|
{
|
||||||
|
method: "DELETE",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
Authorization: `Token ${session?.apiToken}`,
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ rejection_details: rejection_details }),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const errorData = await response.json();
|
||||||
|
throw new Error(errorData.message || errorData.detail || "Failed to reject user");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle 204 No Content response (successful deletion)
|
||||||
|
if (response.status === 204) {
|
||||||
revalidatePath("/users");
|
revalidatePath("/users");
|
||||||
redirect("/users");
|
redirect("/users");
|
||||||
}
|
}
|
||||||
|
|
||||||
export const SendUserRejectionDetailSMS = async ({
|
revalidatePath("/users");
|
||||||
details,
|
const error = await response.json()
|
||||||
phoneNumber,
|
return {
|
||||||
}: {
|
message: (error as ApiError).message || (error as ApiError).detail || "An unexpected error occurred.",
|
||||||
details: string;
|
fieldErrors: {},
|
||||||
phoneNumber: string;
|
payload: formData
|
||||||
}) => {
|
|
||||||
try {
|
|
||||||
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: details,
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
const data = await respose.json();
|
|
||||||
console.log(data);
|
|
||||||
return data;
|
|
||||||
} catch (error) {
|
|
||||||
console.error(error);
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export async function AddDevice({
|
|
||||||
name,
|
|
||||||
mac_address,
|
|
||||||
user_id,
|
|
||||||
}: { name: string; mac_address: string; user_id: string }) {
|
|
||||||
// const newDevice = await prisma.device.create({
|
|
||||||
// data: {
|
|
||||||
// name: name,
|
|
||||||
// mac: mac_address,
|
|
||||||
// userId: user_id,
|
|
||||||
// },
|
|
||||||
// });
|
|
||||||
revalidatePath("/devices");
|
|
||||||
// return newDevice;
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,12 @@
|
|||||||
import { redirect } from "next/navigation";
|
import { redirect } from "next/navigation";
|
||||||
import { getPayment, getProfile } from "@/actions/payment";
|
import { getPayment } from "@/actions/payment";
|
||||||
|
import { getProfile } from "@/actions/user-actions";
|
||||||
import CancelPaymentButton from "@/components/billing/cancel-payment-button";
|
import CancelPaymentButton from "@/components/billing/cancel-payment-button";
|
||||||
import ExpiryCountDown from "@/components/billing/expiry-time-countdown";
|
import ExpiryCountDown from "@/components/billing/expiry-time-countdown";
|
||||||
import ClientErrorMessage from "@/components/client-error-message";
|
import ClientErrorMessage from "@/components/client-error-message";
|
||||||
import DevicesToPay from "@/components/devices-to-pay";
|
import DevicesToPay from "@/components/devices-to-pay";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { TextShimmer } from "@/components/ui/text-shimmer";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import { tryCatch } from "@/utils/tryCatch";
|
import { tryCatch } from "@/utils/tryCatch";
|
||||||
export default async function PaymentPage({
|
export default async function PaymentPage({
|
||||||
@@ -29,29 +31,39 @@ export default async function PaymentPage({
|
|||||||
<div className="flex justify-between items-center border rounded-md border-dashed font-bold title-bg py-4 px-4 mb-4 mx-2">
|
<div className="flex justify-between items-center border rounded-md border-dashed font-bold title-bg py-4 px-4 mb-4 mx-2">
|
||||||
<h3 className="text-sarLinkOrange text-2xl">Payment</h3>
|
<h3 className="text-sarLinkOrange text-2xl">Payment</h3>
|
||||||
<div className="flex flex-col gap-4 items-end w-full">
|
<div className="flex flex-col gap-4 items-end w-full">
|
||||||
|
{!payment.is_expired && payment.paid && payment.status !== "PENDING" && (
|
||||||
<Button
|
<Button
|
||||||
disabled
|
disabled
|
||||||
className={cn(
|
className={cn(
|
||||||
"rounded-md opacity-100! uppercase font-semibold",
|
"rounded-md opacity-100! uppercase font-semibold",
|
||||||
payment?.paid
|
payment?.paid
|
||||||
? "text-green-500 bg-green-500/20"
|
? "text-green-900 bg-green-500/20"
|
||||||
: "text-yellow-500 bg-yellow-900",
|
: "text-inherit bg-yellow-400",
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{payment?.paid ? "Paid" : "Pending"}
|
{payment.status}
|
||||||
</Button>
|
</Button>
|
||||||
{!payment.paid && (
|
)}
|
||||||
payment.is_expired ? (
|
{payment.status === "PENDING" && !payment.is_expired && (
|
||||||
|
<Button>
|
||||||
|
<TextShimmer>Payment Pending</TextShimmer>{" "}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
{!payment.paid &&
|
||||||
|
(payment.is_expired ? (
|
||||||
<Button
|
<Button
|
||||||
disabled
|
disabled
|
||||||
className="rounded-md opacity-100! uppercase font-semibold text-red-500 bg-red-500/20"
|
className="rounded-md opacity-100! uppercase font-semibold text-red-500 bg-red-500/20"
|
||||||
>
|
>
|
||||||
Payment Expired
|
Payment Expired
|
||||||
</Button>
|
</Button>
|
||||||
) : (
|
) : payment.status === "PENDING" ? (
|
||||||
<CancelPaymentButton paymentId={paymentId} />
|
<CancelPaymentButton paymentId={paymentId} />
|
||||||
)
|
) : payment.status === "CANCELLED" ? (
|
||||||
)}
|
<Button disabled>Payment Cancelled</Button>
|
||||||
|
) : (
|
||||||
|
""
|
||||||
|
))}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{!payment.paid && (
|
{!payment.paid && (
|
||||||
@@ -62,6 +74,7 @@ export default async function PaymentPage({
|
|||||||
className="pb-4 gap-4 flex sm:flex-row flex-col items-start justify-start"
|
className="pb-4 gap-4 flex sm:flex-row flex-col items-start justify-start"
|
||||||
>
|
>
|
||||||
<DevicesToPay
|
<DevicesToPay
|
||||||
|
disabled={payment.paid || payment.is_expired}
|
||||||
user={userProfile || undefined}
|
user={userProfile || undefined}
|
||||||
payment={payment || undefined}
|
payment={payment || undefined}
|
||||||
/>
|
/>
|
||||||
|
|||||||
95
app/(dashboard)/profile/page.tsx
Normal file
95
app/(dashboard)/profile/page.tsx
Normal file
@@ -0,0 +1,95 @@
|
|||||||
|
import { redirect } from "next/navigation";
|
||||||
|
import { getServerSession } from "next-auth";
|
||||||
|
import { getProfileById } from "@/actions/user-actions";
|
||||||
|
import { authOptions } from "@/app/auth";
|
||||||
|
import ClientErrorMessage from "@/components/client-error-message";
|
||||||
|
import { Badge } from "@/components/ui/badge";
|
||||||
|
import { FloatingLabelInput } from "@/components/ui/floating-label";
|
||||||
|
import { tryCatch } from "@/utils/tryCatch";
|
||||||
|
|
||||||
|
export default async function Profile() {
|
||||||
|
const session = await getServerSession(authOptions);
|
||||||
|
if (!session?.user) return redirect("/auth/signin?callbackUrl=/profile");
|
||||||
|
const [error, profile] = await tryCatch(getProfileById(session?.user.id));
|
||||||
|
if (error) {
|
||||||
|
if (error.message === "Invalid token.") redirect("/auth/signin");
|
||||||
|
return <ClientErrorMessage message={error.message} />;
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<div className="flex justify-between items-center font-bold border rounded-md border-dashed title-bg py-4 px-2 mb-4">
|
||||||
|
<h3 className="text-sarLinkOrange text-2xl">Profile</h3>
|
||||||
|
<div className="text-sarLinkOrange uppercase font-mono text-sm flex flex-col items-center rounded gap-2 py-2 px-4">
|
||||||
|
<span>Profile Status</span>
|
||||||
|
{verifiedStatus(profile?.verified ?? false)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<fieldset>
|
||||||
|
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4 max-w-4xl">
|
||||||
|
<FloatingLabelInput
|
||||||
|
id="floating-name"
|
||||||
|
label="Full Name"
|
||||||
|
value={`${profile?.first_name} ${profile?.last_name}`}
|
||||||
|
readOnly
|
||||||
|
/>
|
||||||
|
<FloatingLabelInput
|
||||||
|
id="floating-id-card"
|
||||||
|
label="ID Card"
|
||||||
|
value={`${profile?.id_card}`}
|
||||||
|
readOnly
|
||||||
|
/>
|
||||||
|
<FloatingLabelInput
|
||||||
|
id="floating-island"
|
||||||
|
label="Island"
|
||||||
|
value={`${profile?.atoll.name}. ${profile?.island.name}`}
|
||||||
|
readOnly
|
||||||
|
/>
|
||||||
|
<FloatingLabelInput
|
||||||
|
id="floating-dob"
|
||||||
|
label="Date of Birth"
|
||||||
|
value={`${new Date(
|
||||||
|
profile?.dob.toString() ?? "",
|
||||||
|
).toLocaleDateString("en-US", {
|
||||||
|
month: "short",
|
||||||
|
day: "2-digit",
|
||||||
|
year: "numeric",
|
||||||
|
})}`}
|
||||||
|
readOnly
|
||||||
|
/>
|
||||||
|
<FloatingLabelInput
|
||||||
|
id="floating-address"
|
||||||
|
label="Address"
|
||||||
|
value={`${profile?.address}`}
|
||||||
|
readOnly
|
||||||
|
/>
|
||||||
|
<FloatingLabelInput
|
||||||
|
id="floating-mobile"
|
||||||
|
label="Phone Number"
|
||||||
|
value={`${profile?.mobile}`}
|
||||||
|
readOnly
|
||||||
|
/>
|
||||||
|
<FloatingLabelInput
|
||||||
|
id="floating-account"
|
||||||
|
label="Account Number"
|
||||||
|
value={`${profile?.acc_no}`}
|
||||||
|
readOnly
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</fieldset>
|
||||||
|
{/* <Suspense key={query} fallback={"loading...."}>
|
||||||
|
<TopupsTable searchParams={searchParams} />
|
||||||
|
</Suspense> */}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function verifiedStatus(status: boolean) {
|
||||||
|
switch (status) {
|
||||||
|
case true:
|
||||||
|
return <Badge className="bg-green-500 text-white">Verified</Badge>;
|
||||||
|
case false:
|
||||||
|
return <Badge className="bg-red-500 text-white">Not Verified</Badge>;
|
||||||
|
default:
|
||||||
|
return <Badge className="bg-yellow-500 text-white">Unknown</Badge>;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -20,42 +20,48 @@ export default async function TopupPage({
|
|||||||
return <ClientErrorMessage message={error.message} />;
|
return <ClientErrorMessage message={error.message} />;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
<div className="flex justify-between items-center border rounded-md border-dashed font-bold title-bg py-4 px-4 mb-4 mx-2">
|
<div className="flex justify-between items-center border rounded-md border-dashed font-bold title-bg py-4 px-4 mb-4 mx-2">
|
||||||
<h3 className="text-sarLinkOrange text-2xl">Topup</h3>
|
<h3 className="text-sarLinkOrange text-2xl">Topup</h3>
|
||||||
<div className="flex flex-col gap-4 items-end w-full">
|
<div className="flex flex-col gap-4 items-end w-full">
|
||||||
{!topup.is_expired && (
|
{!topup.is_expired && topup.paid && topup.status !== "PENDING" && (
|
||||||
|
|
||||||
<Button
|
<Button
|
||||||
disabled
|
disabled
|
||||||
className={cn(
|
className={cn(
|
||||||
"rounded-md opacity-100! uppercase font-semibold",
|
"rounded-md opacity-100! uppercase font-semibold",
|
||||||
// topup?.paid
|
topup?.paid
|
||||||
// ? "text-green-900 bg-green-500/20"
|
? "text-green-900 bg-green-500/20"
|
||||||
// : "text-inherit bg-yellow-400",
|
: "text-inherit bg-yellow-400",
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{topup?.paid ? <span>Paid</span> : <TextShimmer>Payment Pending</TextShimmer>}
|
{topup.status}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
{topup.status === "PENDING" && !topup.is_expired && (
|
||||||
|
<Button>
|
||||||
|
<TextShimmer>Payment Pending</TextShimmer>{" "}
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{!topup.paid && (
|
{!topup.paid &&
|
||||||
topup.is_expired ? (
|
(topup.is_expired ? (
|
||||||
<Button
|
<Button
|
||||||
disabled
|
disabled
|
||||||
className="rounded-md opacity-100! uppercase font-semibold text-red-500 bg-red-500/20"
|
className="rounded-md opacity-100! uppercase font-semibold text-red-500 bg-red-500/20"
|
||||||
>
|
>
|
||||||
Topup Expired
|
Topup Expired
|
||||||
</Button>
|
</Button>
|
||||||
) : (
|
) : topup.status === "PENDING" ? (
|
||||||
<CancelTopupButton topupId={topupId} />
|
<CancelTopupButton topupId={topupId} />
|
||||||
)
|
) : topup.status === "CANCELLED" ? (
|
||||||
)}
|
<Button disabled>Topup Cancelled</Button>
|
||||||
|
) : (
|
||||||
|
""
|
||||||
|
))}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{!topup.paid && (
|
{!topup.paid && topup.status === "PENDING" && !topup.is_expired && (
|
||||||
<ExpiryCountDown expiryLabel="Top up" expiresAt={topup.expires_at} />
|
<ExpiryCountDown expiryLabel="Top up" expiresAt={topup.expires_at} />
|
||||||
)}
|
)}
|
||||||
<div
|
<div
|
||||||
@@ -63,7 +69,9 @@ export default async function TopupPage({
|
|||||||
className="pb-4 gap-4 flex sm:flex-row flex-col items-start justify-start"
|
className="pb-4 gap-4 flex sm:flex-row flex-col items-start justify-start"
|
||||||
>
|
>
|
||||||
<TopupToPay
|
<TopupToPay
|
||||||
disabled={topup.paid || topup.is_expired}
|
disabled={
|
||||||
|
topup.paid || topup.is_expired || topup.status === "CANCELLED"
|
||||||
|
}
|
||||||
topup={topup || undefined}
|
topup={topup || undefined}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
14
app/(dashboard)/users/[userId]/update/page.tsx
Normal file
14
app/(dashboard)/users/[userId]/update/page.tsx
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
|
||||||
|
export default async function UserUpdate({
|
||||||
|
params,
|
||||||
|
}: {
|
||||||
|
params: Promise<{
|
||||||
|
userId: string;
|
||||||
|
}>;
|
||||||
|
}) {
|
||||||
|
const { userId } = await params;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>UserUpdate: {userId}</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -1,3 +1,14 @@
|
|||||||
|
import Image from "next/image";
|
||||||
|
import { redirect } from "next/navigation";
|
||||||
|
import { getProfileById } from "@/actions/user-actions";
|
||||||
|
import ClientErrorMessage from "@/components/client-error-message";
|
||||||
|
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 { tryCatch } from "@/utils/tryCatch";
|
||||||
|
|
||||||
export default async function VerifyUserPage({
|
export default async function VerifyUserPage({
|
||||||
params,
|
params,
|
||||||
}: {
|
}: {
|
||||||
@@ -6,164 +17,168 @@ export default async function VerifyUserPage({
|
|||||||
}>;
|
}>;
|
||||||
}) {
|
}) {
|
||||||
const userId = (await params).userId;
|
const userId = (await params).userId;
|
||||||
console.log("userId", userId);
|
const [error, dbUser] = await tryCatch(getProfileById(userId));
|
||||||
// const dbUser = await prisma.user.findUnique({
|
|
||||||
// where: {
|
|
||||||
// id: userId,
|
|
||||||
// },
|
|
||||||
// include: {
|
|
||||||
// island: {
|
|
||||||
// include: {
|
|
||||||
// atoll: true
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// })
|
|
||||||
|
|
||||||
// const nationalData = await getNationalPerson({ idCard: dbUser?.id_card ?? "" })
|
const [nationalDataEror, nationalData] = await tryCatch(getNationalPerson({ idCard: dbUser?.id_card ?? "" }))
|
||||||
|
if (nationalDataEror) {
|
||||||
return null;
|
console.warn("Error fetching national data:", nationalDataEror);
|
||||||
// return (
|
}
|
||||||
// <div>
|
if (error) {
|
||||||
// <div className="flex items-center justify-between text-gray-500 text-2xl font-bold title-bg py-4 px-2 mb-4">
|
if (error.message === "UNAUTHORIZED") {
|
||||||
// <h3 className="text-sarLinkOrange text-2xl">Verify user</h3>
|
redirect("/auth/signin");
|
||||||
|
} else {
|
||||||
// <div className="flex gap-2">
|
return <ClientErrorMessage message={error.message} />;
|
||||||
// {dbUser && !dbUser?.verified && <UserVerifyDialog user={dbUser} />}
|
}
|
||||||
// {dbUser && !dbUser?.verified && <UserRejectDialog user={dbUser} />}
|
}
|
||||||
// {dbUser?.verified && (
|
|
||||||
// <Badge variant={"secondary"} className="bg-lime-500">
|
// return <pre>{JSON.stringify(nationalData, null, 2)}</pre>
|
||||||
// Verified
|
const fullName = `${dbUser?.first_name} ${dbUser?.last_name}`;
|
||||||
// </Badge>
|
const nationalDob = nationalData?.dob?.split("T")[0];
|
||||||
// )}
|
const dbUserDob = new Date(dbUser?.dob).toISOString().split("T")[0];
|
||||||
// </div>
|
|
||||||
// </div>
|
return (
|
||||||
// <div className="grid grid-cols-1 md:grid-cols-2 gap-4 items-start justify-start">
|
<div>
|
||||||
// <div id="database-information">
|
<div className="flex items-center justify-between text-gray-500 text-2xl font-bold title-bg py-4 px-2 mb-4">
|
||||||
// <h4 className="p-2 rounded font-semibold">Database Information</h4>
|
<h3 className="text-sarLinkOrange text-2xl">Verify user</h3>
|
||||||
// <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
|
<div className="flex gap-2">
|
||||||
// showCheck
|
{dbUser && !dbUser?.verified && <UserVerifyDialog user={dbUser} />}
|
||||||
// checkTrue={dbUser?.id_card === nationalData.nic}
|
{dbUser && !dbUser?.verified && <UserRejectDialog user={dbUser} />}
|
||||||
// labelClassName="text-sarLinkOrange"
|
{dbUser?.verified && (
|
||||||
// label="ID Card"
|
<Badge variant={"secondary"} className="bg-lime-500">
|
||||||
// value={dbUser?.id_card ?? ""}
|
Verified
|
||||||
// />
|
</Badge>
|
||||||
// <InputReadOnly
|
)}
|
||||||
// showCheck
|
</div>
|
||||||
// checkTrue={dbUser?.name === nationalData.name_en}
|
</div>
|
||||||
// labelClassName="text-sarLinkOrange"
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 items-start justify-start">
|
||||||
// label="Name"
|
<div id="database-information">
|
||||||
// value={dbUser?.name ?? ""}
|
<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
|
<InputReadOnly
|
||||||
// showCheck
|
showCheck
|
||||||
// checkTrue={dbUser?.address === nationalData.house_name_en}
|
checkTrue={dbUser?.id_card === nationalData?.nic}
|
||||||
// labelClassName="text-sarLinkOrange"
|
labelClassName="text-sarLinkOrange"
|
||||||
// label="House Name"
|
label="ID Card"
|
||||||
// value={dbUser?.address ?? ""}
|
value={dbUser?.id_card ?? ""}
|
||||||
// />
|
/>
|
||||||
// <InputReadOnly
|
<InputReadOnly
|
||||||
// showCheck
|
showCheck
|
||||||
// checkTrue={dbUser?.island?.name === nationalData.island_name_en}
|
checkTrue={fullName === nationalData?.name_en}
|
||||||
// labelClassName="text-sarLinkOrange"
|
labelClassName="text-sarLinkOrange"
|
||||||
// label="Island"
|
label="Name"
|
||||||
// value={dbUser?.island?.name ?? ""}
|
value={fullName}
|
||||||
// />
|
/>
|
||||||
// <InputReadOnly
|
<InputReadOnly
|
||||||
// showCheck
|
showCheck
|
||||||
// checkTrue={dbUser?.island?.atoll.name === nationalData.atoll_en}
|
checkTrue={dbUser?.address === nationalData?.house_name_en}
|
||||||
// labelClassName="text-sarLinkOrange"
|
labelClassName="text-sarLinkOrange"
|
||||||
// label="Atoll"
|
label="House Name"
|
||||||
// value={dbUser?.island?.atoll.name ?? ""}
|
value={dbUser?.address ?? ""}
|
||||||
// />
|
/>
|
||||||
|
<InputReadOnly
|
||||||
// <InputReadOnly
|
showCheck
|
||||||
// showCheck
|
checkTrue={dbUser?.island?.name === nationalData?.island_name_en}
|
||||||
// checkTrue={
|
labelClassName="text-sarLinkOrange"
|
||||||
// new Date(dbUser?.dob ?? "") === new Date(nationalData.dob)
|
label="Island"
|
||||||
// }
|
value={dbUser?.island?.name ?? ""}
|
||||||
// labelClassName="text-sarLinkOrange"
|
/>
|
||||||
// label="DOB"
|
<InputReadOnly
|
||||||
// value={new Date(dbUser?.dob ?? "").toLocaleDateString("en-US", {
|
showCheck
|
||||||
// month: "short",
|
checkTrue={dbUser?.atoll.name === nationalData?.atoll_en}
|
||||||
// day: "2-digit",
|
labelClassName="text-sarLinkOrange"
|
||||||
// year: "numeric",
|
label="Atoll"
|
||||||
// })}
|
value={dbUser?.island?.name ?? ""}
|
||||||
// />
|
/>
|
||||||
// <InputReadOnly
|
|
||||||
// showCheck
|
<InputReadOnly
|
||||||
// checkTrue={dbUser?.phoneNumber === nationalData.primary_contact}
|
showCheck
|
||||||
// labelClassName="text-sarLinkOrange"
|
checkTrue={
|
||||||
// label="Phone Number"
|
dbUserDob === nationalDob
|
||||||
// value={dbUser?.phoneNumber ?? ""}
|
}
|
||||||
// />
|
labelClassName="text-sarLinkOrange"
|
||||||
// </div>
|
label="DOB"
|
||||||
// </div>
|
value={new Date(dbUser?.dob ?? "").toLocaleDateString("en-US", {
|
||||||
// <div id="national-information">
|
month: "short",
|
||||||
// <h4 className="p-2 rounded font-semibold">National Information</h4>
|
day: "2-digit",
|
||||||
// <div className="shadow p-2 rounded-md title-bg space-y-1 my-2 grid grid-cols-1 md:grid-cols-2 gap-2">
|
year: "numeric",
|
||||||
// <InputReadOnly
|
})}
|
||||||
// showCheck={false}
|
/>
|
||||||
// labelClassName="text-green-500"
|
<InputReadOnly
|
||||||
// label="ID Card"
|
showCheck
|
||||||
// value={nationalData?.nic ?? ""}
|
checkTrue={dbUser?.mobile === nationalData?.primary_contact}
|
||||||
// />
|
labelClassName="text-sarLinkOrange"
|
||||||
// <InputReadOnly
|
label="Phone Number"
|
||||||
// showCheck={false}
|
value={dbUser?.mobile ?? ""}
|
||||||
// labelClassName="text-green-500"
|
/>
|
||||||
// label="Name"
|
</div>
|
||||||
// value={nationalData?.name_en ?? ""}
|
</div>
|
||||||
// />
|
{(
|
||||||
// <InputReadOnly
|
<div id="national-information">
|
||||||
// showCheck={false}
|
<h4 className="p-2 rounded font-semibold">National Information</h4>
|
||||||
// labelClassName="text-green-500"
|
<div className="shadow p-2 rounded-lg title-bg space-y-1 my-2 grid grid-cols-1 md:grid-cols-2 gap-2">
|
||||||
// label="House Name"
|
<InputReadOnly
|
||||||
// value={nationalData?.house_name_en ?? ""}
|
showCheck={false}
|
||||||
// />
|
labelClassName="text-green-500"
|
||||||
// <InputReadOnly
|
label="ID Card"
|
||||||
// showCheck={false}
|
value={nationalData?.nic ?? ""}
|
||||||
// labelClassName="text-green-500"
|
/>
|
||||||
// label="Island"
|
<InputReadOnly
|
||||||
// value={nationalData?.island_name_en ?? ""}
|
showCheck={false}
|
||||||
// />
|
labelClassName="text-green-500"
|
||||||
// <InputReadOnly
|
label="Name"
|
||||||
// showCheck={false}
|
value={nationalData?.name_en ?? ""}
|
||||||
// labelClassName="text-green-500"
|
/>
|
||||||
// label="Atoll"
|
<InputReadOnly
|
||||||
// value={nationalData?.atoll_en ?? ""}
|
showCheck={false}
|
||||||
// />
|
labelClassName="text-green-500"
|
||||||
// <InputReadOnly
|
label="House Name"
|
||||||
// showCheck={false}
|
value={nationalData?.house_name_en ?? ""}
|
||||||
// labelClassName="text-green-500"
|
/>
|
||||||
// label="DOB"
|
<InputReadOnly
|
||||||
// value={new Date(nationalData?.dob ?? "").toLocaleDateString(
|
showCheck={false}
|
||||||
// "en-US",
|
labelClassName="text-green-500"
|
||||||
// {
|
label="Island"
|
||||||
// month: "short",
|
value={nationalData?.island_name_en ?? ""}
|
||||||
// day: "2-digit",
|
/>
|
||||||
// year: "numeric",
|
<InputReadOnly
|
||||||
// },
|
showCheck={false}
|
||||||
// )}
|
labelClassName="text-green-500"
|
||||||
// />
|
label="Atoll"
|
||||||
// <InputReadOnly
|
value={nationalData?.atoll_en ?? ""}
|
||||||
// showCheck={false}
|
/>
|
||||||
// labelClassName="text-green-500"
|
<InputReadOnly
|
||||||
// label="Phone Number"
|
showCheck={false}
|
||||||
// value={nationalData?.primary_contact ?? ""}
|
labelClassName="text-green-500"
|
||||||
// />
|
label="DOB"
|
||||||
// <div className="flex flex-col col-span-2 items-center justify-center">
|
value={new Date(nationalData?.dob ?? "").toLocaleDateString(
|
||||||
// <Image
|
"en-US",
|
||||||
// src={nationalData.image_url || "https://i.pravatar.cc/300"}
|
{
|
||||||
// height={100}
|
month: "short",
|
||||||
// width={100}
|
day: "2-digit",
|
||||||
// className="object-fit aspect-square rounded-full"
|
year: "numeric",
|
||||||
// alt="id photo"
|
},
|
||||||
// />
|
)}
|
||||||
// </div>
|
/>
|
||||||
// </div>
|
<InputReadOnly
|
||||||
// </div>
|
showCheck={false}
|
||||||
// </div>
|
labelClassName="text-green-500"
|
||||||
// </div>
|
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>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
56
components/account-information.tsx
Normal file
56
components/account-information.tsx
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
"use client"
|
||||||
|
import { Clipboard, ClipboardCheck } from "lucide-react";
|
||||||
|
import { useState } from "react";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import { Button } from "./ui/button";
|
||||||
|
|
||||||
|
export function AccountInfomation({
|
||||||
|
accountNo,
|
||||||
|
accName,
|
||||||
|
}: {
|
||||||
|
accountNo: string;
|
||||||
|
accName: string;
|
||||||
|
}) {
|
||||||
|
const [accNo, setAccNo] = useState(false);
|
||||||
|
return (
|
||||||
|
<div className="justify-center items-center border my-4 flex flex-col gap-2 p-2 rounded-md">
|
||||||
|
<h6 className="title-bg uppercase p-2 border rounded w-full font-semibold">
|
||||||
|
Account Information
|
||||||
|
</h6>
|
||||||
|
<div className="border justify-center flex flex-col items-center bg-white/10 w-full p-2 rounded">
|
||||||
|
<div className="text-sm font-semibold">Account Name</div>
|
||||||
|
<span>{accName}</span>
|
||||||
|
</div>
|
||||||
|
<div className="border flex justify-between items-center gap-2 w-full p-2 rounded">
|
||||||
|
<div className="flex flex-col items-center justify-center w-full">
|
||||||
|
<p className="text-sm font-semibold">Account No</p>
|
||||||
|
<span>{accountNo}</span>
|
||||||
|
<Button
|
||||||
|
onClick={() => {
|
||||||
|
setTimeout(() => {
|
||||||
|
setAccNo(true);
|
||||||
|
navigator.clipboard.writeText(accountNo);
|
||||||
|
}, 2000);
|
||||||
|
toast.success("Account number copied!");
|
||||||
|
setAccNo((prev) => !prev);
|
||||||
|
}}
|
||||||
|
className="mt-2 w-full"
|
||||||
|
variant={"secondary"}
|
||||||
|
>
|
||||||
|
{accNo ? (
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span>Copy Account Number</span>
|
||||||
|
<Clipboard />
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span>Copy Account Number</span>
|
||||||
|
<ClipboardCheck color="green" />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,13 +1,14 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
import { Loader2, User as UserIcon } from "lucide-react";
|
||||||
|
import Link from "next/link";
|
||||||
|
import { signOut, useSession } from "next-auth/react";
|
||||||
|
import { useState } from "react";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import {
|
import {
|
||||||
Popover,
|
Popover,
|
||||||
PopoverContent,
|
PopoverContent,
|
||||||
PopoverTrigger,
|
PopoverTrigger,
|
||||||
} from "@/components/ui/popover";
|
} from "@/components/ui/popover";
|
||||||
import { Loader2, User as UserIcon } from "lucide-react";
|
|
||||||
import { signOut, useSession } from "next-auth/react";
|
|
||||||
import { useState } from "react";
|
|
||||||
|
|
||||||
export function AccountPopover() {
|
export function AccountPopover() {
|
||||||
const session = useSession();
|
const session = useSession();
|
||||||
@@ -36,6 +37,7 @@ export function AccountPopover() {
|
|||||||
<p>{session.data?.user?.mobile}</p>
|
<p>{session.data?.user?.mobile}</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<div className="flex flex-col gap-2">
|
||||||
<Button
|
<Button
|
||||||
disabled={loading}
|
disabled={loading}
|
||||||
onClick={async () => {
|
onClick={async () => {
|
||||||
@@ -46,6 +48,13 @@ export function AccountPopover() {
|
|||||||
>
|
>
|
||||||
{loading ? <Loader2 className="animate-spin" /> : "Logout"}
|
{loading ? <Loader2 className="animate-spin" /> : "Logout"}
|
||||||
</Button>
|
</Button>
|
||||||
|
<Link href="/profile" className="text-muted-foreground">
|
||||||
|
<Button variant={"secondary"} className="w-full">
|
||||||
|
View Profile
|
||||||
|
</Button>
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
</PopoverContent>
|
</PopoverContent>
|
||||||
</Popover>
|
</Popover>
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { redirect } from "next/navigation";
|
import { redirect } from "next/navigation";
|
||||||
import { getServerSession } from "next-auth";
|
import { getServerSession } from "next-auth";
|
||||||
import { NuqsAdapter } from 'nuqs/adapters/next/app'
|
import { NuqsAdapter } from 'nuqs/adapters/next/app'
|
||||||
import { getProfile } from "@/actions/payment";
|
import { getProfile } from "@/actions/user-actions";
|
||||||
import { authOptions } from "@/app/auth";
|
import { authOptions } from "@/app/auth";
|
||||||
import { DeviceCartDrawer } from "@/components/device-cart";
|
import { DeviceCartDrawer } from "@/components/device-cart";
|
||||||
import { ModeToggle } from "@/components/theme-toggle";
|
import { ModeToggle } from "@/components/theme-toggle";
|
||||||
|
|||||||
@@ -52,7 +52,6 @@ export async function DevicesTable({
|
|||||||
}
|
}
|
||||||
apiParams.limit = limit;
|
apiParams.limit = limit;
|
||||||
apiParams.offset = offset;
|
apiParams.offset = offset;
|
||||||
console.log("API Params:", apiParams);
|
|
||||||
const [error, devices] = await tryCatch(
|
const [error, devices] = await tryCatch(
|
||||||
getDevices(apiParams),
|
getDevices(apiParams),
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,12 +1,10 @@
|
|||||||
"use client";
|
"use client";
|
||||||
import {
|
import {
|
||||||
BadgeDollarSign,
|
BadgeDollarSign,
|
||||||
Clipboard,
|
|
||||||
ClipboardCheck,
|
|
||||||
Loader2,
|
Loader2,
|
||||||
Wallet,
|
Wallet
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import { useActionState, useEffect, useState } from "react";
|
import { useActionState, useEffect } from "react";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
import { type VerifyDevicePaymentState, verifyDevicePayment } from "@/actions/payment";
|
import { type VerifyDevicePaymentState, verifyDevicePayment } from "@/actions/payment";
|
||||||
import {
|
import {
|
||||||
@@ -19,6 +17,7 @@ import {
|
|||||||
} from "@/components/ui/table";
|
} from "@/components/ui/table";
|
||||||
import type { Payment } from "@/lib/backend-types";
|
import type { Payment } from "@/lib/backend-types";
|
||||||
import type { User } from "@/lib/types/user";
|
import type { User } from "@/lib/types/user";
|
||||||
|
import { AccountInfomation } from "./account-information";
|
||||||
import { Button } from "./ui/button";
|
import { Button } from "./ui/button";
|
||||||
|
|
||||||
const initialState: VerifyDevicePaymentState = {
|
const initialState: VerifyDevicePaymentState = {
|
||||||
@@ -30,7 +29,8 @@ const initialState: VerifyDevicePaymentState = {
|
|||||||
export default function DevicesToPay({
|
export default function DevicesToPay({
|
||||||
payment,
|
payment,
|
||||||
user,
|
user,
|
||||||
}: { payment?: Payment; user?: User }) {
|
disabled
|
||||||
|
}: { payment?: Payment; user?: User, disabled?: boolean }) {
|
||||||
const [state, formAction, isPending] = useActionState(verifyDevicePayment, initialState);
|
const [state, formAction, isPending] = useActionState(verifyDevicePayment, initialState);
|
||||||
|
|
||||||
// Handle toast notifications based on state changes
|
// Handle toast notifications based on state changes
|
||||||
@@ -118,7 +118,7 @@ export default function DevicesToPay({
|
|||||||
<input type="hidden" name="paymentId" value={payment?.id ?? ""} />
|
<input type="hidden" name="paymentId" value={payment?.id ?? ""} />
|
||||||
<input type="hidden" name="method" value="TRANSFER" />
|
<input type="hidden" name="method" value="TRANSFER" />
|
||||||
<Button
|
<Button
|
||||||
disabled={isPending}
|
disabled={isPending || disabled}
|
||||||
type="submit"
|
type="submit"
|
||||||
size={"lg"}
|
size={"lg"}
|
||||||
className="mb-4"
|
className="mb-4"
|
||||||
@@ -136,6 +136,19 @@ export default function DevicesToPay({
|
|||||||
</div>
|
</div>
|
||||||
</TableCaption>
|
</TableCaption>
|
||||||
<TableBody className="">
|
<TableBody className="">
|
||||||
|
<TableRow>
|
||||||
|
<TableCell>Payment created</TableCell>
|
||||||
|
<TableCell className="text-right">
|
||||||
|
{new Date(payment?.created_at ?? "").toLocaleDateString("en-US", {
|
||||||
|
month: "short",
|
||||||
|
day: "2-digit",
|
||||||
|
year: "numeric",
|
||||||
|
minute: "2-digit",
|
||||||
|
hour: "2-digit",
|
||||||
|
second: "2-digit",
|
||||||
|
})}
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
<TableRow>
|
<TableRow>
|
||||||
<TableCell>Total Devices</TableCell>
|
<TableCell>Total Devices</TableCell>
|
||||||
<TableCell className="text-right text-xl">
|
<TableCell className="text-right text-xl">
|
||||||
@@ -147,6 +160,7 @@ export default function DevicesToPay({
|
|||||||
<TableCell className="text-right text-xl">
|
<TableCell className="text-right text-xl">
|
||||||
{payment?.number_of_months} Months
|
{payment?.number_of_months} Months
|
||||||
</TableCell>
|
</TableCell>
|
||||||
|
|
||||||
</TableRow>
|
</TableRow>
|
||||||
</TableBody>
|
</TableBody>
|
||||||
<TableFooter>
|
<TableFooter>
|
||||||
@@ -163,42 +177,4 @@ export default function DevicesToPay({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function AccountInfomation({
|
|
||||||
accountNo,
|
|
||||||
accName,
|
|
||||||
}: {
|
|
||||||
accountNo: string;
|
|
||||||
accName: string;
|
|
||||||
}) {
|
|
||||||
const [accNo, setAccNo] = useState(false);
|
|
||||||
return (
|
|
||||||
<div className="justify-start items-start border my-4 flex flex-col gap-2 p-2 rounded-md">
|
|
||||||
<h6 className="title-bg uppercase p-2 border rounded w-full font-semibold">
|
|
||||||
Account Information
|
|
||||||
</h6>
|
|
||||||
<div className="border justify-start flex flex-col items-start bg-white/10 w-full p-2 rounded">
|
|
||||||
<div className="text-sm font-semibold">Account Name</div>
|
|
||||||
<span>{accName}</span>
|
|
||||||
</div>
|
|
||||||
<div className="border flex justify-between items-start gap-2 bg-white/10 w-full p-2 rounded">
|
|
||||||
<div className="flex flex-col items-start justify-start">
|
|
||||||
<p className="text-sm font-semibold">Account No</p>
|
|
||||||
<span>{accountNo}</span>
|
|
||||||
</div>
|
|
||||||
<Button
|
|
||||||
onClick={() => {
|
|
||||||
setTimeout(() => {
|
|
||||||
setAccNo(true);
|
|
||||||
navigator.clipboard.writeText(accountNo);
|
|
||||||
}, 2000);
|
|
||||||
toast.success("Account number copied!");
|
|
||||||
setAccNo((prev) => !prev);
|
|
||||||
}}
|
|
||||||
variant={"link"}
|
|
||||||
>
|
|
||||||
{accNo ? <Clipboard /> : <ClipboardCheck color="green" />}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { cn } from '@/lib/utils';
|
|
||||||
import { CheckCheck, X } from 'lucide-react';
|
import { CheckCheck, X } from 'lucide-react';
|
||||||
|
import { cn } from '@/lib/utils';
|
||||||
|
|
||||||
export default function InputReadOnly({ label, value, labelClassName, className, showCheck = true, checkTrue = false }: {
|
export default function InputReadOnly({ label, value, labelClassName, className, showCheck = true, checkTrue = false }: {
|
||||||
label: string;
|
label: string;
|
||||||
@@ -10,7 +10,7 @@ export default function InputReadOnly({ label, value, labelClassName, className,
|
|||||||
checkTrue?: boolean
|
checkTrue?: boolean
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<div className={cn("relative flex items-center justify-between rounded-lg border border-input bg-background shadow-sm shadow-black/5 transition-shadow focus-within:border-ring focus-within:outline-none focus-within:ring-[3px] focus-within:ring-ring/20 has-disabled:cursor-not-allowed has-disabled:opacity-80 [&:has(input:is(:disabled))_*]:pointer-events-none", className)}>
|
<div className={cn("relative flex items-center justify-between rounded-lg border border-input bg-background shadow-sm shadow-black/5 transition-shadow focus-within:border-ring focus-within:outline-none focus-within:ring-[3px] focus-within:ring-ring/20 has-disabled:cursor-not-allowed has-disabled:opacity-80 [&:has(input:is(:disabled))_*]:pointer-events-none col-span-2 sm:col-span-1", className)}>
|
||||||
<div>
|
<div>
|
||||||
|
|
||||||
<label htmlFor="input-33" className={cn("block px-3 pt-2 text-xs font-medium", labelClassName)}>
|
<label htmlFor="input-33" className={cn("block px-3 pt-2 text-xs font-medium", labelClassName)}>
|
||||||
|
|||||||
@@ -28,12 +28,17 @@ export async function PaymentsTable({
|
|||||||
}>;
|
}>;
|
||||||
}) {
|
}) {
|
||||||
const resolvedParams = await searchParams;
|
const resolvedParams = await searchParams;
|
||||||
|
const page = Number.parseInt(resolvedParams.page as string) || 1;
|
||||||
|
const limit = 10;
|
||||||
|
const offset = (page - 1) * limit;
|
||||||
const apiParams: Record<string, string | number | undefined> = {};
|
const apiParams: Record<string, string | number | undefined> = {};
|
||||||
for (const [key, value] of Object.entries(resolvedParams)) {
|
for (const [key, value] of Object.entries(resolvedParams)) {
|
||||||
if (value !== undefined && value !== "") {
|
if (value !== undefined && value !== "") {
|
||||||
apiParams[key] = typeof value === "number" ? value : String(value);
|
apiParams[key] = typeof value === "number" ? value : String(value);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
apiParams.limit = limit;
|
||||||
|
apiParams.offset = offset;
|
||||||
const [error, payments] = await tryCatch(getPayments(apiParams));
|
const [error, payments] = await tryCatch(getPayments(apiParams));
|
||||||
|
|
||||||
if (error) {
|
if (error) {
|
||||||
@@ -71,7 +76,9 @@ export async function PaymentsTable({
|
|||||||
className={cn(
|
className={cn(
|
||||||
"flex flex-col items-start border rounded p-2",
|
"flex flex-col items-start border rounded p-2",
|
||||||
payment?.paid
|
payment?.paid
|
||||||
? "bg-green-500/10 border-dashed border-green=500"
|
? "bg-green-500/10 border-dashed border-green-500"
|
||||||
|
: payment?.is_expired
|
||||||
|
? "bg-gray-500/10 border-dashed border-gray-500 dark:border-gray-500/50"
|
||||||
: "bg-yellow-500/10 border-dashed border-yellow-500 dark:border-yellow-500/50",
|
: "bg-yellow-500/10 border-dashed border-yellow-500 dark:border-yellow-500/50",
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
@@ -86,6 +93,7 @@ export async function PaymentsTable({
|
|||||||
year: "numeric",
|
year: "numeric",
|
||||||
minute: "2-digit",
|
minute: "2-digit",
|
||||||
hour: "2-digit",
|
hour: "2-digit",
|
||||||
|
timeZone: "Indian/Maldives", // Force consistent timezone
|
||||||
},
|
},
|
||||||
)}
|
)}
|
||||||
</span>
|
</span>
|
||||||
@@ -127,7 +135,7 @@ export async function PaymentsTable({
|
|||||||
className={cn(
|
className={cn(
|
||||||
payment.status === "PENDING"
|
payment.status === "PENDING"
|
||||||
? "bg-yellow-100 text-yellow-700 dark:bg-yellow-700 dark:text-yellow-100"
|
? "bg-yellow-100 text-yellow-700 dark:bg-yellow-700 dark:text-yellow-100"
|
||||||
: "bg-green-100 dark:bg-green-700"
|
: "bg-green-100 dark:bg-green-700",
|
||||||
)}
|
)}
|
||||||
variant="outline"
|
variant="outline"
|
||||||
>
|
>
|
||||||
@@ -151,8 +159,7 @@ export async function PaymentsTable({
|
|||||||
</TableBody>
|
</TableBody>
|
||||||
<TableFooter>
|
<TableFooter>
|
||||||
<TableRow>
|
<TableRow>
|
||||||
|
<TableCell colSpan={4} className="text-muted-foreground">
|
||||||
<TableCell colSpan={3} className="text-muted-foreground">
|
|
||||||
{meta?.total === 1 ? (
|
{meta?.total === 1 ? (
|
||||||
<p className="text-center">
|
<p className="text-center">
|
||||||
Total {meta?.total} payment.
|
Total {meta?.total} payment.
|
||||||
@@ -161,12 +168,13 @@ export async function PaymentsTable({
|
|||||||
<p className="text-center">
|
<p className="text-center">
|
||||||
Total {meta?.total} payments.
|
Total {meta?.total} payments.
|
||||||
</p>
|
</p>
|
||||||
)} </TableCell>
|
)}{" "}
|
||||||
|
</TableCell>
|
||||||
</TableRow>
|
</TableRow>
|
||||||
</TableFooter>
|
</TableFooter>
|
||||||
</Table>
|
</Table>
|
||||||
<Pagination
|
<Pagination
|
||||||
totalPages={meta.total / meta.per_page}
|
totalPages={meta.last_page}
|
||||||
currentPage={meta.current_page}
|
currentPage={meta.current_page}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
@@ -187,7 +195,9 @@ function MobilePaymentDetails({ payment }: { payment: Payment }) {
|
|||||||
className={cn(
|
className={cn(
|
||||||
"flex flex-col items-start border rounded p-2 my-2",
|
"flex flex-col items-start border rounded p-2 my-2",
|
||||||
payment?.paid
|
payment?.paid
|
||||||
? "bg-green-500/10 border-dashed border-green=500"
|
? "bg-green-500/10 border-dashed border-green-500"
|
||||||
|
: payment?.is_expired
|
||||||
|
? "bg-gray-500/10 border-dashed border-gray-500 dark:border-gray-500/50"
|
||||||
: "bg-yellow-500/10 border-dashed border-yellow-500 dark:border-yellow-500/50",
|
: "bg-yellow-500/10 border-dashed border-yellow-500 dark:border-yellow-500/50",
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
@@ -200,6 +210,7 @@ function MobilePaymentDetails({ payment }: { payment: Payment }) {
|
|||||||
year: "numeric",
|
year: "numeric",
|
||||||
minute: "2-digit",
|
minute: "2-digit",
|
||||||
hour: "2-digit",
|
hour: "2-digit",
|
||||||
|
timeZone: "Indian/Maldives", // Force consistent timezone
|
||||||
})}
|
})}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
@@ -241,7 +252,7 @@ function MobilePaymentDetails({ payment }: { payment: Payment }) {
|
|||||||
className={cn(
|
className={cn(
|
||||||
payment.status === "PENDING"
|
payment.status === "PENDING"
|
||||||
? "bg-yellow-100 text-yellow-700 dark:bg-yellow-700 dark:text-yellow-100"
|
? "bg-yellow-100 text-yellow-700 dark:bg-yellow-700 dark:text-yellow-100"
|
||||||
: "bg-green-100 dark:bg-green-700"
|
: "bg-green-100 dark:bg-green-700",
|
||||||
)}
|
)}
|
||||||
variant="outline"
|
variant="outline"
|
||||||
>
|
>
|
||||||
|
|||||||
@@ -1,13 +1,14 @@
|
|||||||
"use client";
|
"use client";
|
||||||
import {
|
import {
|
||||||
BadgeDollarSign,
|
BadgeDollarSign,
|
||||||
Clipboard,
|
Loader2
|
||||||
ClipboardCheck,
|
|
||||||
Loader2,
|
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import { useActionState, useEffect, useState } from "react";
|
import { useActionState, useEffect } from "react";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
import { type VerifyTopupPaymentState, verifyTopupPayment } from "@/actions/payment";
|
import {
|
||||||
|
type VerifyTopupPaymentState,
|
||||||
|
verifyTopupPayment,
|
||||||
|
} from "@/actions/payment";
|
||||||
import {
|
import {
|
||||||
Table,
|
Table,
|
||||||
TableBody,
|
TableBody,
|
||||||
@@ -17,17 +18,25 @@ import {
|
|||||||
TableRow,
|
TableRow,
|
||||||
} from "@/components/ui/table";
|
} from "@/components/ui/table";
|
||||||
import type { Topup } from "@/lib/backend-types";
|
import type { Topup } from "@/lib/backend-types";
|
||||||
|
import { AccountInfomation } from "./account-information";
|
||||||
import { Button } from "./ui/button";
|
import { Button } from "./ui/button";
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
const initialState: VerifyTopupPaymentState = {
|
const initialState: VerifyTopupPaymentState = {
|
||||||
message: "",
|
message: "",
|
||||||
success: false,
|
success: false,
|
||||||
fieldErrors: {},
|
fieldErrors: {},
|
||||||
};
|
};
|
||||||
export default function TopupToPay({ topup, disabled }: { topup?: Topup, disabled?: boolean }) {
|
export default function TopupToPay({
|
||||||
const [state, formAction, isPending] = useActionState(verifyTopupPayment, initialState);
|
topup,
|
||||||
|
disabled,
|
||||||
|
}: {
|
||||||
|
topup?: Topup;
|
||||||
|
disabled?: boolean;
|
||||||
|
}) {
|
||||||
|
const [state, formAction, isPending] = useActionState(
|
||||||
|
verifyTopupPayment,
|
||||||
|
initialState,
|
||||||
|
);
|
||||||
|
|
||||||
// Handle toast notifications based on state changes
|
// Handle toast notifications based on state changes
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -38,7 +47,11 @@ export default function TopupToPay({ topup, disabled }: { topup?: Topup, disable
|
|||||||
? `Your topup payment has been verified successfully using ${state.transaction.sourceBank} bank transfer on ${state.transaction.trxDate}.`
|
? `Your topup payment has been verified successfully using ${state.transaction.sourceBank} bank transfer on ${state.transaction.trxDate}.`
|
||||||
: state.message,
|
: state.message,
|
||||||
});
|
});
|
||||||
} else if (!state.success && state.message && state.message !== initialState.message) {
|
} else if (
|
||||||
|
!state.success &&
|
||||||
|
state.message &&
|
||||||
|
state.message !== initialState.message
|
||||||
|
) {
|
||||||
toast.error("Topup Payment Verification Failed", {
|
toast.error("Topup Payment Verification Failed", {
|
||||||
closeButton: true,
|
closeButton: true,
|
||||||
description: state.message,
|
description: state.message,
|
||||||
@@ -69,16 +82,18 @@ export default function TopupToPay({ topup, disabled }: { topup?: Topup, disable
|
|||||||
) : (
|
) : (
|
||||||
<div className="flex flex-col gap-2">
|
<div className="flex flex-col gap-2">
|
||||||
<form action={formAction}>
|
<form action={formAction}>
|
||||||
<input type="hidden" name="topupId" value={topup?.id ?? ""} />
|
<input
|
||||||
|
type="hidden"
|
||||||
|
name="topupId"
|
||||||
|
value={topup?.id ?? ""}
|
||||||
|
/>
|
||||||
<Button
|
<Button
|
||||||
disabled={disabled || isPending}
|
disabled={disabled || isPending}
|
||||||
type="submit"
|
type="submit"
|
||||||
size={"lg"}
|
size={"lg"}
|
||||||
className="mb-4"
|
className="mb-4 w-full"
|
||||||
>
|
>
|
||||||
{isPending
|
{isPending ? "Processing payment..." : "I have paid"}
|
||||||
? "Processing payment..."
|
|
||||||
: "I have paid"}
|
|
||||||
{isPending ? (
|
{isPending ? (
|
||||||
<Loader2 className="animate-spin" />
|
<Loader2 className="animate-spin" />
|
||||||
) : (
|
) : (
|
||||||
@@ -86,7 +101,6 @@ export default function TopupToPay({ topup, disabled }: { topup?: Topup, disable
|
|||||||
)}
|
)}
|
||||||
</Button>
|
</Button>
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
@@ -141,42 +155,4 @@ export default function TopupToPay({ topup, disabled }: { topup?: Topup, disable
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function AccountInfomation({
|
|
||||||
accountNo,
|
|
||||||
accName,
|
|
||||||
}: {
|
|
||||||
accountNo: string;
|
|
||||||
accName: string;
|
|
||||||
}) {
|
|
||||||
const [accNo, setAccNo] = useState(false);
|
|
||||||
return (
|
|
||||||
<div className="justify-start items-start border my-4 flex flex-col gap-2 p-2 rounded-md">
|
|
||||||
<h6 className="title-bg uppercase p-2 border rounded w-full font-semibold">
|
|
||||||
Account Information
|
|
||||||
</h6>
|
|
||||||
<div className="border justify-start flex flex-col items-start bg-white/10 w-full p-2 rounded">
|
|
||||||
<div className="text-sm font-semibold">Account Name</div>
|
|
||||||
<span>{accName}</span>
|
|
||||||
</div>
|
|
||||||
<div className="border flex justify-between items-start gap-2 bg-white/10 w-full p-2 rounded">
|
|
||||||
<div className="flex flex-col items-start justify-start">
|
|
||||||
<p className="text-sm font-semibold">Account No</p>
|
|
||||||
<span>{accountNo}</span>
|
|
||||||
</div>
|
|
||||||
<Button
|
|
||||||
onClick={() => {
|
|
||||||
setTimeout(() => {
|
|
||||||
setAccNo(true);
|
|
||||||
navigator.clipboard.writeText(accountNo);
|
|
||||||
}, 2000);
|
|
||||||
toast.success("Account number copied!");
|
|
||||||
setAccNo((prev) => !prev);
|
|
||||||
}}
|
|
||||||
variant={"link"}
|
|
||||||
>
|
|
||||||
{accNo ? <Clipboard /> : <ClipboardCheck color="green" />}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -27,7 +27,9 @@ export async function TopupsTable({
|
|||||||
}>;
|
}>;
|
||||||
}) {
|
}) {
|
||||||
const resolvedParams = await searchParams;
|
const resolvedParams = await searchParams;
|
||||||
|
const page = Number.parseInt(resolvedParams.page as string) || 1;
|
||||||
|
const limit = 10;
|
||||||
|
const offset = (page - 1) * limit;
|
||||||
// Build params object
|
// Build params object
|
||||||
const apiParams: Record<string, string | number | undefined> = {};
|
const apiParams: Record<string, string | number | undefined> = {};
|
||||||
for (const [key, value] of Object.entries(resolvedParams)) {
|
for (const [key, value] of Object.entries(resolvedParams)) {
|
||||||
@@ -35,7 +37,8 @@ export async function TopupsTable({
|
|||||||
apiParams[key] = typeof value === "number" ? value : String(value);
|
apiParams[key] = typeof value === "number" ? value : String(value);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
apiParams.limit = limit;
|
||||||
|
apiParams.offset = offset;
|
||||||
const [error, topups] = await tryCatch(getTopups(apiParams));
|
const [error, topups] = await tryCatch(getTopups(apiParams));
|
||||||
|
|
||||||
if (error) {
|
if (error) {
|
||||||
@@ -151,8 +154,8 @@ export async function TopupsTable({
|
|||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
<Pagination
|
<Pagination
|
||||||
totalPages={meta.total / meta.per_page}
|
totalPages={meta?.last_page}
|
||||||
currentPage={meta.current_page}
|
currentPage={meta?.current_page}
|
||||||
/>
|
/>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -1,130 +1,145 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
import { AlertDialog as AlertDialogPrimitive } from "radix-ui"
|
import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog"
|
||||||
import * as React from "react"
|
import * as React from "react"
|
||||||
|
|
||||||
import { buttonVariants } from "@/components/ui/button"
|
import { buttonVariants } from "@/components/ui/button"
|
||||||
import { cn } from "@/lib/utils"
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
const AlertDialog = AlertDialogPrimitive.Root
|
function AlertDialog({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof AlertDialogPrimitive.Root>) {
|
||||||
|
return <AlertDialogPrimitive.Root data-slot="alert-dialog" {...props} />
|
||||||
|
}
|
||||||
|
|
||||||
const AlertDialogTrigger = AlertDialogPrimitive.Trigger
|
function AlertDialogTrigger({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof AlertDialogPrimitive.Trigger>) {
|
||||||
|
return (
|
||||||
|
<AlertDialogPrimitive.Trigger data-slot="alert-dialog-trigger" {...props} />
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
const AlertDialogPortal = AlertDialogPrimitive.Portal
|
function AlertDialogPortal({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof AlertDialogPrimitive.Portal>) {
|
||||||
|
return (
|
||||||
|
<AlertDialogPrimitive.Portal data-slot="alert-dialog-portal" {...props} />
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
const AlertDialogOverlay = React.forwardRef<
|
function AlertDialogOverlay({
|
||||||
React.ElementRef<typeof AlertDialogPrimitive.Overlay>,
|
className,
|
||||||
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Overlay>
|
...props
|
||||||
>(({ className, ...props }, ref) => (
|
}: React.ComponentProps<typeof AlertDialogPrimitive.Overlay>) {
|
||||||
|
return (
|
||||||
<AlertDialogPrimitive.Overlay
|
<AlertDialogPrimitive.Overlay
|
||||||
|
data-slot="alert-dialog-overlay"
|
||||||
className={cn(
|
className={cn(
|
||||||
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
|
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
|
||||||
className
|
className
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
ref={ref}
|
|
||||||
/>
|
/>
|
||||||
))
|
)
|
||||||
AlertDialogOverlay.displayName = AlertDialogPrimitive.Overlay.displayName
|
}
|
||||||
|
|
||||||
const AlertDialogContent = React.forwardRef<
|
function AlertDialogContent({
|
||||||
React.ElementRef<typeof AlertDialogPrimitive.Content>,
|
className,
|
||||||
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Content>
|
...props
|
||||||
>(({ className, ...props }, ref) => (
|
}: React.ComponentProps<typeof AlertDialogPrimitive.Content>) {
|
||||||
|
return (
|
||||||
<AlertDialogPortal>
|
<AlertDialogPortal>
|
||||||
<AlertDialogOverlay />
|
<AlertDialogOverlay />
|
||||||
<AlertDialogPrimitive.Content
|
<AlertDialogPrimitive.Content
|
||||||
ref={ref}
|
data-slot="alert-dialog-content"
|
||||||
className={cn(
|
className={cn(
|
||||||
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 [data-[state=closed]:slide-out-to-top-[48%]] data-[state=open]:slide-in-from-left-1/2 [data-[state=open]:slide-in-from-top-[48%]] sm:rounded-lg",
|
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
|
||||||
className
|
className
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
</AlertDialogPortal>
|
</AlertDialogPortal>
|
||||||
))
|
)
|
||||||
AlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName
|
}
|
||||||
|
|
||||||
const AlertDialogHeader = ({
|
function AlertDialogHeader({
|
||||||
className,
|
className,
|
||||||
...props
|
...props
|
||||||
}: React.HTMLAttributes<HTMLDivElement>) => (
|
}: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
<div
|
<div
|
||||||
|
data-slot="alert-dialog-header"
|
||||||
|
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function AlertDialogFooter({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="alert-dialog-footer"
|
||||||
className={cn(
|
className={cn(
|
||||||
"flex flex-col space-y-2 text-center sm:text-left",
|
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
|
||||||
className
|
className
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
)
|
||||||
AlertDialogHeader.displayName = "AlertDialogHeader"
|
}
|
||||||
|
|
||||||
const AlertDialogFooter = ({
|
function AlertDialogTitle({
|
||||||
className,
|
className,
|
||||||
...props
|
...props
|
||||||
}: React.HTMLAttributes<HTMLDivElement>) => (
|
}: React.ComponentProps<typeof AlertDialogPrimitive.Title>) {
|
||||||
<div
|
return (
|
||||||
className={cn(
|
|
||||||
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
AlertDialogFooter.displayName = "AlertDialogFooter"
|
|
||||||
|
|
||||||
const AlertDialogTitle = React.forwardRef<
|
|
||||||
React.ElementRef<typeof AlertDialogPrimitive.Title>,
|
|
||||||
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Title>
|
|
||||||
>(({ className, ...props }, ref) => (
|
|
||||||
<AlertDialogPrimitive.Title
|
<AlertDialogPrimitive.Title
|
||||||
ref={ref}
|
data-slot="alert-dialog-title"
|
||||||
className={cn("text-lg font-semibold", className)}
|
className={cn("text-lg font-semibold", className)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
))
|
)
|
||||||
AlertDialogTitle.displayName = AlertDialogPrimitive.Title.displayName
|
}
|
||||||
|
|
||||||
const AlertDialogDescription = React.forwardRef<
|
function AlertDialogDescription({
|
||||||
React.ElementRef<typeof AlertDialogPrimitive.Description>,
|
className,
|
||||||
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Description>
|
...props
|
||||||
>(({ className, ...props }, ref) => (
|
}: React.ComponentProps<typeof AlertDialogPrimitive.Description>) {
|
||||||
|
return (
|
||||||
<AlertDialogPrimitive.Description
|
<AlertDialogPrimitive.Description
|
||||||
ref={ref}
|
data-slot="alert-dialog-description"
|
||||||
className={cn("text-sm text-muted-foreground", className)}
|
className={cn("text-muted-foreground text-sm", className)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
))
|
)
|
||||||
AlertDialogDescription.displayName =
|
}
|
||||||
AlertDialogPrimitive.Description.displayName
|
|
||||||
|
|
||||||
const AlertDialogAction = React.forwardRef<
|
function AlertDialogAction({
|
||||||
React.ElementRef<typeof AlertDialogPrimitive.Action>,
|
className,
|
||||||
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Action>
|
...props
|
||||||
>(({ className, ...props }, ref) => (
|
}: React.ComponentProps<typeof AlertDialogPrimitive.Action>) {
|
||||||
|
return (
|
||||||
<AlertDialogPrimitive.Action
|
<AlertDialogPrimitive.Action
|
||||||
ref={ref}
|
|
||||||
className={cn(buttonVariants(), className)}
|
className={cn(buttonVariants(), className)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
))
|
)
|
||||||
AlertDialogAction.displayName = AlertDialogPrimitive.Action.displayName
|
}
|
||||||
|
|
||||||
const AlertDialogCancel = React.forwardRef<
|
function AlertDialogCancel({
|
||||||
React.ElementRef<typeof AlertDialogPrimitive.Cancel>,
|
className,
|
||||||
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Cancel>
|
...props
|
||||||
>(({ className, ...props }, ref) => (
|
}: React.ComponentProps<typeof AlertDialogPrimitive.Cancel>) {
|
||||||
|
return (
|
||||||
<AlertDialogPrimitive.Cancel
|
<AlertDialogPrimitive.Cancel
|
||||||
ref={ref}
|
className={cn(buttonVariants({ variant: "outline" }), className)}
|
||||||
className={cn(
|
|
||||||
buttonVariants({ variant: "outline" }),
|
|
||||||
"mt-2 sm:mt-0",
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
))
|
)
|
||||||
AlertDialogCancel.displayName = AlertDialogPrimitive.Cancel.displayName
|
}
|
||||||
|
|
||||||
export {
|
export {
|
||||||
AlertDialog,
|
AlertDialog,
|
||||||
|
|||||||
45
components/ui/floating-label.tsx
Normal file
45
components/ui/floating-label.tsx
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
import * as React from 'react';
|
||||||
|
import { Input } from '@/components/ui/input';
|
||||||
|
import { Label } from '@/components/ui/label';
|
||||||
|
import { cn } from '@/lib/utils';
|
||||||
|
|
||||||
|
const FloatingInput = React.forwardRef<HTMLInputElement, React.InputHTMLAttributes<HTMLInputElement>>(
|
||||||
|
({ className, ...props }, ref) => {
|
||||||
|
return <Input placeholder=" " className={cn('peer', className)} ref={ref} {...props} />;
|
||||||
|
},
|
||||||
|
);
|
||||||
|
FloatingInput.displayName = 'FloatingInput';
|
||||||
|
|
||||||
|
const FloatingLabel = React.forwardRef<
|
||||||
|
React.ElementRef<typeof Label>,
|
||||||
|
React.ComponentPropsWithoutRef<typeof Label>
|
||||||
|
>(({ className, ...props }, ref) => {
|
||||||
|
return (
|
||||||
|
<Label
|
||||||
|
className={cn(
|
||||||
|
'peer-focus:secondary peer-focus:dark:secondary absolute start-2 top-2 z-10 origin-[0] -translate-y-4 scale-75 transform bg-background px-2 text-sm text-gray-500 duration-300 peer-placeholder-shown:top-1/2 peer-placeholder-shown:-translate-y-1/2 peer-placeholder-shown:scale-100 peer-focus:top-2 peer-focus:-translate-y-4 peer-focus:scale-75 peer-focus:px-2 dark:bg-background rtl:peer-focus:left-auto rtl:peer-focus:translate-x-1/4 cursor-text',
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
ref={ref}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
});
|
||||||
|
FloatingLabel.displayName = 'FloatingLabel';
|
||||||
|
|
||||||
|
type FloatingLabelInputProps = React.InputHTMLAttributes<HTMLInputElement> & { label?: string };
|
||||||
|
|
||||||
|
const FloatingLabelInput = React.forwardRef<
|
||||||
|
React.ElementRef<typeof FloatingInput>,
|
||||||
|
React.PropsWithoutRef<FloatingLabelInputProps>
|
||||||
|
>(({ id, label, ...props }, ref) => {
|
||||||
|
return (
|
||||||
|
<div className="relative">
|
||||||
|
<FloatingInput ref={ref} id={id} {...props} />
|
||||||
|
<FloatingLabel htmlFor={id}>{label}</FloatingLabel>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
});
|
||||||
|
FloatingLabelInput.displayName = 'FloatingLabelInput';
|
||||||
|
|
||||||
|
export { FloatingInput, FloatingLabel, FloatingLabelInput };
|
||||||
@@ -2,21 +2,17 @@ import * as React from "react"
|
|||||||
|
|
||||||
import { cn } from "@/lib/utils"
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
const Textarea = React.forwardRef<
|
function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
|
||||||
HTMLTextAreaElement,
|
|
||||||
React.ComponentProps<"textarea">
|
|
||||||
>(({ className, ...props }, ref) => {
|
|
||||||
return (
|
return (
|
||||||
<textarea
|
<textarea
|
||||||
|
data-slot="textarea"
|
||||||
className={cn(
|
className={cn(
|
||||||
"flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-base shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
"border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-md border bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||||
className
|
className
|
||||||
)}
|
)}
|
||||||
ref={ref}
|
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
)
|
||||||
})
|
}
|
||||||
Textarea.displayName = "Textarea"
|
|
||||||
|
|
||||||
export { Textarea }
|
export { Textarea }
|
||||||
|
|||||||
@@ -1,6 +1,10 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { Rejectuser } from "@/actions/user-actions";
|
import { UserX } from "lucide-react";
|
||||||
|
import { useActionState, useEffect, useState } from "react";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import { rejectUser } from "@/actions/user-actions";
|
||||||
|
// import { Rejectuser } from "@/actions/user-actions";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import {
|
import {
|
||||||
Dialog,
|
Dialog,
|
||||||
@@ -12,68 +16,55 @@ import {
|
|||||||
DialogTrigger,
|
DialogTrigger,
|
||||||
} from "@/components/ui/dialog";
|
} from "@/components/ui/dialog";
|
||||||
import { Label } from "@/components/ui/label";
|
import { Label } from "@/components/ui/label";
|
||||||
import type { User } from "@/lib/types/user";
|
import type { UserProfile } from "@/lib/types/user";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import { zodResolver } from "@hookform/resolvers/zod";
|
|
||||||
import { UserX } from "lucide-react";
|
|
||||||
import { useState } from "react";
|
|
||||||
import { type SubmitHandler, useForm } from "react-hook-form";
|
|
||||||
import { toast } from "sonner";
|
|
||||||
import { z } from "zod";
|
|
||||||
import { Textarea } from "../ui/textarea";
|
import { Textarea } from "../ui/textarea";
|
||||||
|
|
||||||
const validationSchema = z.object({
|
|
||||||
reason: z.string().min(5, { message: "Reason is required" }),
|
|
||||||
});
|
|
||||||
|
|
||||||
export default function UserRejectDialog({ user }: { user: User }) {
|
export type RejectUserFormState = {
|
||||||
const [disabled, setDisabled] = useState(false);
|
message: string;
|
||||||
const [open, setOpen] = useState(false);
|
fieldErrors?: {
|
||||||
const {
|
rejection_details?: string[];
|
||||||
register,
|
|
||||||
handleSubmit,
|
|
||||||
formState: { errors },
|
|
||||||
} = useForm<z.infer<typeof validationSchema>>({
|
|
||||||
resolver: zodResolver(validationSchema),
|
|
||||||
});
|
|
||||||
|
|
||||||
const onSubmit: SubmitHandler<z.infer<typeof validationSchema>> = (data) => {
|
|
||||||
setDisabled(true);
|
|
||||||
console.log(data);
|
|
||||||
toast.promise(
|
|
||||||
Rejectuser({
|
|
||||||
userId: String(user.id),
|
|
||||||
reason: data.reason,
|
|
||||||
}),
|
|
||||||
{
|
|
||||||
loading: "Rejecting...",
|
|
||||||
success: () => {
|
|
||||||
setDisabled(false);
|
|
||||||
setOpen((prev) => !prev);
|
|
||||||
return "Rejected!";
|
|
||||||
},
|
|
||||||
error: (error) => {
|
|
||||||
setDisabled(false);
|
|
||||||
return error.message || "Something went wrong";
|
|
||||||
},
|
|
||||||
},
|
|
||||||
);
|
|
||||||
setDisabled(false);
|
|
||||||
};
|
};
|
||||||
|
payload?: FormData;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const initialState: RejectUserFormState = {
|
||||||
|
message: "",
|
||||||
|
fieldErrors: {},
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function UserRejectDialog({ user }: { user: UserProfile }) {
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
|
||||||
|
const [state, formAction, isPending] = useActionState(rejectUser, initialState);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (state.message && state !== initialState) {
|
||||||
|
if (state.fieldErrors && Object.keys(state.fieldErrors).length > 0) {
|
||||||
|
toast.error(state.message);
|
||||||
|
} else if (!state.fieldErrors) {
|
||||||
|
toast.success("User rejected successfully!");
|
||||||
|
setOpen(false);
|
||||||
|
} else {
|
||||||
|
toast.error(state.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, [state]);
|
||||||
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Dialog open={open} onOpenChange={setOpen}>
|
<Dialog open={open} onOpenChange={setOpen}>
|
||||||
<DialogTrigger asChild>
|
<DialogTrigger asChild>
|
||||||
<Button disabled={disabled} variant="destructive">
|
<Button disabled={isPending} variant="destructive">
|
||||||
<UserX />
|
<UserX />
|
||||||
Reject
|
Reject
|
||||||
</Button>
|
</Button>
|
||||||
</DialogTrigger>
|
</DialogTrigger>
|
||||||
<DialogContent className="sm:max-w-[425px]">
|
<DialogContent className="sm:max-w-[425px]">
|
||||||
<DialogHeader>
|
<DialogHeader>
|
||||||
<DialogTitle>
|
<DialogTitle className="text-muted-foreground">
|
||||||
Are you sure you want to{" "}
|
Are you sure?
|
||||||
<span className="text-red-500">reject</span> this user?
|
|
||||||
</DialogTitle>
|
</DialogTitle>
|
||||||
<DialogDescription className="py-2">
|
<DialogDescription className="py-2">
|
||||||
<li>
|
<li>
|
||||||
@@ -92,28 +83,30 @@ export default function UserRejectDialog({ user }: { user: User }) {
|
|||||||
<li>Phone Number: {user.mobile}</li>
|
<li>Phone Number: {user.mobile}</li>
|
||||||
</DialogDescription>
|
</DialogDescription>
|
||||||
</DialogHeader>
|
</DialogHeader>
|
||||||
<form onSubmit={handleSubmit(onSubmit)}>
|
<form action={formAction}>
|
||||||
<div className="grid gap-4 py-4">
|
<div className="grid gap-4 py-4">
|
||||||
<div className="flex flex-col items-start gap-1">
|
<div className="flex flex-col items-start gap-2">
|
||||||
<Label htmlFor="reason" className="text-right">
|
<input type="hidden" name="userId" value={user.id} />
|
||||||
|
<Label htmlFor="reason" className="text-right text-muted-foreground">
|
||||||
Rejection details
|
Rejection details
|
||||||
</Label>
|
</Label>
|
||||||
<Textarea
|
<Textarea
|
||||||
rows={10}
|
rows={10}
|
||||||
{...register("reason")}
|
name="rejection_details"
|
||||||
id="reason"
|
id="reason"
|
||||||
|
defaultValue={state.payload?.get("rejection_details") as string}
|
||||||
className={cn(
|
className={cn(
|
||||||
"col-span-5",
|
"col-span-5",
|
||||||
errors.reason && "ring-2 ring-red-500",
|
state.fieldErrors?.rejection_details && "ring-2 ring-red-500",
|
||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
<span className="text-sm text-red-500">
|
<span className="text-sm text-red-500">
|
||||||
{errors.reason?.message}
|
{state.fieldErrors?.rejection_details?.[0]}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<DialogFooter>
|
<DialogFooter>
|
||||||
<Button variant={"destructive"} disabled={disabled} type="submit">
|
<Button variant={"destructive"} disabled={isPending} type="submit">
|
||||||
Reject
|
Reject
|
||||||
</Button>
|
</Button>
|
||||||
</DialogFooter>
|
</DialogFooter>
|
||||||
|
|||||||
@@ -1,4 +1,7 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
import { Check, CheckCheck } from "lucide-react";
|
||||||
|
import { useState } from "react";
|
||||||
|
import { toast } from "sonner";
|
||||||
import { VerifyUser } from "@/actions/user-actions";
|
import { VerifyUser } from "@/actions/user-actions";
|
||||||
import {
|
import {
|
||||||
AlertDialog,
|
AlertDialog,
|
||||||
@@ -12,12 +15,9 @@ import {
|
|||||||
AlertDialogTrigger,
|
AlertDialogTrigger,
|
||||||
} from "@/components/ui/alert-dialog";
|
} from "@/components/ui/alert-dialog";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import type { User } from "@/lib/types/user";
|
import type { UserProfile } from "@/lib/types/user";
|
||||||
import { Check, CheckCheck } from "lucide-react";
|
|
||||||
import { useState } from "react";
|
|
||||||
import { toast } from "sonner";
|
|
||||||
|
|
||||||
export function UserVerifyDialog({ user }: { user: User }) {
|
export function UserVerifyDialog({ user }: { user: UserProfile }) {
|
||||||
const userId = user.id;
|
const userId = user.id;
|
||||||
const [disabled, setDisabled] = useState(false);
|
const [disabled, setDisabled] = useState(false);
|
||||||
return (
|
return (
|
||||||
@@ -33,7 +33,7 @@ export function UserVerifyDialog({ user }: { user: User }) {
|
|||||||
</AlertDialogTrigger>
|
</AlertDialogTrigger>
|
||||||
<AlertDialogContent>
|
<AlertDialogContent>
|
||||||
<AlertDialogHeader>
|
<AlertDialogHeader>
|
||||||
<AlertDialogTitle>Are you sure?</AlertDialogTitle>
|
<AlertDialogTitle className="text-muted-foreground">Verify User</AlertDialogTitle>
|
||||||
<AlertDialogDescription>
|
<AlertDialogDescription>
|
||||||
Are you sure you want to verify the following user?
|
Are you sure you want to verify the following user?
|
||||||
<span className="inline-block my-4">
|
<span className="inline-block my-4">
|
||||||
|
|||||||
@@ -1,12 +1,11 @@
|
|||||||
"use server";
|
"use server";
|
||||||
import type { TNationalPerson } from "@/lib/types";
|
import type { TNationalPerson } from "@/lib/types";
|
||||||
import type { User } from "./types/user";
|
|
||||||
|
|
||||||
export async function getNationalPerson({
|
export async function getNationalPerson({
|
||||||
idCard,
|
idCard,
|
||||||
}: { idCard: string }): Promise<TNationalPerson> {
|
}: { idCard: string }): Promise<TNationalPerson> {
|
||||||
const nationalInformation = await fetch(
|
const nationalInformation = await fetch(
|
||||||
`${process.env.PERSON_VERIFY_API_BASE}/api/person/${idCard}`,
|
`${process.env.PERSON_VERIFY_BASE_URL}/api/person/${idCard}`,
|
||||||
{
|
{
|
||||||
next: {
|
next: {
|
||||||
revalidate: 60,
|
revalidate: 60,
|
||||||
@@ -17,28 +16,4 @@ export async function getNationalPerson({
|
|||||||
return nationalData;
|
return nationalData;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function VerifyUserDetails({ user }: { user: User }) {
|
|
||||||
console.log(user);
|
|
||||||
// const phoneNumber = String(user.phoneNumber).slice(4);
|
|
||||||
// console.log({ phoneNumber });
|
|
||||||
// const nationalData = await getNationalPerson({ idCard: user.id_card ?? "" });
|
|
||||||
// const dob = new Date(nationalData.dob);
|
|
||||||
// const age = new Date().getFullYear() - dob.getFullYear();
|
|
||||||
|
|
||||||
// console.log("ID card", user.id_card === nationalData.nic);
|
|
||||||
// console.log("name", user.name === nationalData.name_en);
|
|
||||||
// console.log("house", user.address === nationalData.house_name_en);
|
|
||||||
// console.log("phone", phoneNumber === nationalData.primary_contact);
|
|
||||||
// console.log("db phone", phoneNumber);
|
|
||||||
// console.log("national phone", nationalData.primary_contact);
|
|
||||||
|
|
||||||
// if (
|
|
||||||
// user.id_card === nationalData.nic &&
|
|
||||||
// user.name === nationalData.name_en &&
|
|
||||||
// user.address === nationalData.house_name_en &&
|
|
||||||
// age >= 18
|
|
||||||
// ) {
|
|
||||||
// return true;
|
|
||||||
// }
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import type { ISODateString } from "next-auth";
|
import type { ISODateString } from "next-auth";
|
||||||
|
import type { Atoll, Island } from "../backend-types";
|
||||||
|
|
||||||
export interface Permission {
|
export interface Permission {
|
||||||
id: number;
|
id: number;
|
||||||
@@ -30,6 +31,22 @@ export interface User {
|
|||||||
last_login: string;
|
last_login: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface UserProfile {
|
||||||
|
id: number;
|
||||||
|
email: string;
|
||||||
|
first_name: string;
|
||||||
|
last_name: string;
|
||||||
|
atoll: Atoll;
|
||||||
|
island: Island;
|
||||||
|
dob: string;
|
||||||
|
verified: boolean;
|
||||||
|
username: string;
|
||||||
|
mobile: string;
|
||||||
|
address: string;
|
||||||
|
acc_no: string;
|
||||||
|
id_card: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface Session {
|
export interface Session {
|
||||||
user?: {
|
user?: {
|
||||||
token?: string;
|
token?: string;
|
||||||
|
|||||||
31
queries/users.ts
Normal file
31
queries/users.ts
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
'use server'
|
||||||
|
import { getServerSession } from "next-auth";
|
||||||
|
import { authOptions } from "@/app/auth";
|
||||||
|
import type { ApiResponse } from "@/lib/backend-types";
|
||||||
|
import type { UserProfile } from "@/lib/types/user";
|
||||||
|
import { handleApiResponse } from "@/utils/tryCatch";
|
||||||
|
|
||||||
|
|
||||||
|
type ParamProps = {
|
||||||
|
[key: string]: string | number | undefined;
|
||||||
|
};
|
||||||
|
export async function getUsers(params: ParamProps) {
|
||||||
|
const session = await getServerSession(authOptions);
|
||||||
|
|
||||||
|
const query = Object.entries(params)
|
||||||
|
.filter(([_, value]) => value !== undefined && value !== "")
|
||||||
|
.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`)
|
||||||
|
.join("&");
|
||||||
|
const response = await fetch(
|
||||||
|
`${process.env.SARLINK_API_BASE_URL}/api/auth/users/?${query}`,
|
||||||
|
{
|
||||||
|
method: "GET",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
Authorization: `Token ${session?.apiToken}`,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
return handleApiResponse<ApiResponse<UserProfile>>(response, "getUsers");
|
||||||
|
}
|
||||||
@@ -11,7 +11,7 @@ export async function handleApiResponse<T>(
|
|||||||
response: Response,
|
response: Response,
|
||||||
fnName?: string,
|
fnName?: string,
|
||||||
) {
|
) {
|
||||||
const responseData = await response.json();
|
const responseData = await response.json()
|
||||||
if (response.status === 401) {
|
if (response.status === 401) {
|
||||||
console.log('response data', responseData)
|
console.log('response data', responseData)
|
||||||
throw new Error("UNAUTHORIZED");
|
throw new Error("UNAUTHORIZED");
|
||||||
@@ -32,7 +32,7 @@ export async function handleApiResponse<T>(
|
|||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
console.log(`API Error Response from ${fnName}:`, responseData);
|
console.log(`API Error Response from ${fnName}:`, responseData);
|
||||||
throw new Error(responseData.message || "Something went wrong.");
|
throw new Error(responseData.message || responseData.detail || "Something went wrong.");
|
||||||
}
|
}
|
||||||
|
|
||||||
return responseData as T;
|
return responseData as T;
|
||||||
|
|||||||
Reference in New Issue
Block a user