chore: add skeletons to tables and loading.tsx files for routes and run formatting ♻️
All checks were successful
Build and Push Docker Images / Build and Push Docker Images (push) Successful in 12m20s

This commit is contained in:
2025-09-20 20:42:14 +05:00
parent 5277c13fb7
commit a60e9a9c85
45 changed files with 3539 additions and 3041 deletions

View File

@@ -4,226 +4,226 @@ import { redirect } from "next/navigation";
import { z } from "zod"; import { z } from "zod";
import { signUpFormSchema } from "@/lib/schemas"; import { signUpFormSchema } from "@/lib/schemas";
import { import {
backendRegister, backendRegister,
checkIdOrPhone, checkIdOrPhone,
checkTempIdOrPhone, checkTempIdOrPhone,
} from "@/queries/authentication"; } from "@/queries/authentication";
import { handleApiResponse, tryCatch } from "@/utils/tryCatch"; import { handleApiResponse, tryCatch } from "@/utils/tryCatch";
const formSchema = z.object({ const formSchema = z.object({
phoneNumber: z phoneNumber: z
.string() .string()
.regex(/^[7|9][0-9]{2}-[0-9]{4}$/, "Please enter a valid phone number"), .regex(/^[7|9][0-9]{2}-[0-9]{4}$/, "Please enter a valid phone number"),
}); });
export type FilterUserResponse = { export type FilterUserResponse = {
ok: boolean; ok: boolean;
verified: boolean; verified: boolean;
}; };
export type FilterTempUserResponse = { export type FilterTempUserResponse = {
ok: boolean; ok: boolean;
otp_verified: boolean; otp_verified: boolean;
t_verified: boolean; t_verified: boolean;
}; };
export async function signin(_previousState: ActionState, formData: FormData) { export async function signin(_previousState: ActionState, formData: FormData) {
const phoneNumber = formData.get("phoneNumber") as string; const phoneNumber = formData.get("phoneNumber") as string;
const result = formSchema.safeParse({ phoneNumber }); const result = formSchema.safeParse({ phoneNumber });
console.log(phoneNumber); console.log(phoneNumber);
if (!result.success) { if (!result.success) {
return { return {
message: result.error.errors[0].message, // Get the error message from Zod message: result.error.errors[0].message, // Get the error message from Zod
status: "error", status: "error",
}; };
} }
if (!phoneNumber) { if (!phoneNumber) {
return { return {
message: "Please enter a phone number", message: "Please enter a phone number",
status: "error", status: "error",
}; };
} }
const FORMATTED_MOBILE_NUMBER: string = `${phoneNumber.split("-").join("")}`; const FORMATTED_MOBILE_NUMBER: string = `${phoneNumber.split("-").join("")}`;
console.log({ FORMATTED_MOBILE_NUMBER }); console.log({ FORMATTED_MOBILE_NUMBER });
const user = await fetch( const user = await fetch(
`${process.env.SARLINK_API_BASE_URL}/api/auth/users/filter/?mobile=${FORMATTED_MOBILE_NUMBER}`, `${process.env.SARLINK_API_BASE_URL}/api/auth/users/filter/?mobile=${FORMATTED_MOBILE_NUMBER}`,
{ {
method: "GET", method: "GET",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
}, },
}, },
); );
const userData = (await user.json()) as FilterUserResponse; const userData = (await user.json()) as FilterUserResponse;
console.log({ userData }); console.log({ userData });
if (!userData.ok) { if (!userData.ok) {
redirect(`/auth/signup?phone_number=${phoneNumber}`); redirect(`/auth/signup?phone_number=${phoneNumber}`);
} }
if (!userData.verified) { if (!userData.verified) {
return { return {
message: message:
"Your account is on pending verification. Please wait for a response from admin or contact shihaam.", "Your account is on pending verification. Please wait for a response from admin or contact shihaam.",
status: "error", status: "error",
}; };
} }
const sendOTPResponse = await fetch( const sendOTPResponse = await fetch(
`${process.env.SARLINK_API_BASE_URL}/auth/mobile/`, `${process.env.SARLINK_API_BASE_URL}/auth/mobile/`,
{ {
method: "POST", method: "POST",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
}, },
body: JSON.stringify({ body: JSON.stringify({
mobile: FORMATTED_MOBILE_NUMBER, mobile: FORMATTED_MOBILE_NUMBER,
}), }),
}, },
); );
const otpResponse = await sendOTPResponse.json(); const otpResponse = await sendOTPResponse.json();
console.log("otpResponse", otpResponse); console.log("otpResponse", otpResponse);
redirect(`/auth/verify-otp?phone_number=${FORMATTED_MOBILE_NUMBER}`); redirect(`/auth/verify-otp?phone_number=${FORMATTED_MOBILE_NUMBER}`);
} }
export type ActionState = { export type ActionState = {
status?: string; status?: string;
payload?: FormData; payload?: FormData;
errors?: z.typeToFlattenedError< errors?: z.typeToFlattenedError<
{ {
id_card: string; id_card: string;
phone_number: string; phone_number: string;
name: string; name: string;
atoll_id: string; atoll_id: string;
island_id: string; island_id: string;
address: string; address: string;
dob: Date; dob: Date;
terms: string; terms: string;
policy: string; policy: string;
accNo: string; accNo: string;
}, },
string string
>; >;
db_error?: string; db_error?: string;
error?: string; error?: string;
}; };
export async function signup(_actionState: ActionState, formData: FormData) { export async function signup(_actionState: ActionState, formData: FormData) {
const data = Object.fromEntries(formData.entries()); const data = Object.fromEntries(formData.entries());
const parsedData = signUpFormSchema.safeParse(data); const parsedData = signUpFormSchema.safeParse(data);
// get phone number from /signup?phone_number=999-1231 // get phone number from /signup?phone_number=999-1231
console.log("DATA ON SERVER SIDE", data); console.log("DATA ON SERVER SIDE", data);
if (!parsedData.success) { if (!parsedData.success) {
return { return {
message: "Invalid form data", message: "Invalid form data",
payload: formData, payload: formData,
errors: parsedData.error.flatten(), errors: parsedData.error.flatten(),
}; };
} }
const age = const age =
new Date().getFullYear() - new Date(parsedData.data.dob).getFullYear(); new Date().getFullYear() - new Date(parsedData.data.dob).getFullYear();
if (age < 18) { if (age < 18) {
return { return {
message: "You must be at least 18 years old to register.", message: "You must be at least 18 years old to register.",
payload: formData, payload: formData,
db_error: "dob", db_error: "dob",
}; };
} }
const idCardExists = await checkIdOrPhone({ const idCardExists = await checkIdOrPhone({
id_card: parsedData.data.id_card, id_card: parsedData.data.id_card,
}); });
if (idCardExists.ok) { if (idCardExists.ok) {
return { return {
message: "ID card already exists.", message: "ID card already exists.",
payload: formData, payload: formData,
db_error: "id_card", db_error: "id_card",
}; };
} }
const phoneNumberExists = await checkIdOrPhone({ const phoneNumberExists = await checkIdOrPhone({
phone_number: parsedData.data.phone_number, phone_number: parsedData.data.phone_number,
}); });
const tempPhoneNumberExists = await checkTempIdOrPhone({ const tempPhoneNumberExists = await checkTempIdOrPhone({
phone_number: parsedData.data.phone_number, phone_number: parsedData.data.phone_number,
}); });
if (phoneNumberExists.ok || tempPhoneNumberExists.ok) { if (phoneNumberExists.ok || tempPhoneNumberExists.ok) {
return { return {
message: "Phone number already exists.", message: "Phone number already exists.",
payload: formData, payload: formData,
db_error: "phone_number", db_error: "phone_number",
}; };
} }
const [signupError, signupResponse] = await tryCatch( const [signupError, signupResponse] = await tryCatch(
backendRegister({ backendRegister({
payload: { payload: {
firstname: parsedData.data.name.split(" ")[0], firstname: parsedData.data.name.split(" ")[0],
lastname: parsedData.data.name.split(" ").slice(1).join(" "), lastname: parsedData.data.name.split(" ").slice(1).join(" "),
username: parsedData.data.phone_number, username: parsedData.data.phone_number,
address: parsedData.data.address, address: parsedData.data.address,
id_card: parsedData.data.id_card, id_card: parsedData.data.id_card,
dob: new Date(parsedData.data.dob).toISOString().split("T")[0], dob: new Date(parsedData.data.dob).toISOString().split("T")[0],
mobile: parsedData.data.phone_number, mobile: parsedData.data.phone_number,
island: Number.parseInt(parsedData.data.island_id), island: Number.parseInt(parsedData.data.island_id),
atoll: Number.parseInt(parsedData.data.atoll_id), atoll: Number.parseInt(parsedData.data.atoll_id),
acc_no: parsedData.data.accNo, acc_no: parsedData.data.accNo,
terms_accepted: parsedData.data.terms, terms_accepted: parsedData.data.terms,
policy_accepted: parsedData.data.policy, policy_accepted: parsedData.data.policy,
}, },
}), }),
); );
if (signupError) { if (signupError) {
return { return {
message: signupError.message, message: signupError.message,
payload: formData, payload: formData,
db_error: "phone_number", db_error: "phone_number",
}; };
} }
console.log("SIGNUP RESPONSE", signupResponse); console.log("SIGNUP RESPONSE", signupResponse);
redirect( redirect(
`/auth/verify-otp-registration?phone_number=${encodeURIComponent(signupResponse.t_username)}`, `/auth/verify-otp-registration?phone_number=${encodeURIComponent(signupResponse.t_username)}`,
); );
return { message: "User created successfully", error: "success" }; return { message: "User created successfully", error: "success" };
} }
export const sendOtp = async (phoneNumber: string, code: string) => { export const sendOtp = async (phoneNumber: string, code: string) => {
// Implement sending OTP code via SMS // Implement sending OTP code via SMS
console.log("Send OTP server fn", phoneNumber, code); console.log("Send OTP server fn", phoneNumber, code);
const respose = await fetch(`${process.env.SMS_API_BASE_URL}/api/sms`, { const respose = await fetch(`${process.env.SMS_API_BASE_URL}/api/sms`, {
method: "POST", method: "POST",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
Authorization: `Bearer ${process.env.SMS_API_KEY}`, Authorization: `Bearer ${process.env.SMS_API_KEY}`,
}, },
body: JSON.stringify({ body: JSON.stringify({
check_delivery: false, check_delivery: false,
number: phoneNumber, number: phoneNumber,
message: `Your OTP code is ${code}`, message: `Your OTP code is ${code}`,
}), }),
}); });
const data = await respose.json(); const data = await respose.json();
console.log(data); console.log(data);
return data; return data;
}; };
export async function backendMobileLogin({ mobile }: { mobile: string }) { export async function backendMobileLogin({ mobile }: { mobile: string }) {
const response = await fetch( const response = await fetch(
`${process.env.SARLINK_API_BASE_URL}/auth/mobile/`, `${process.env.SARLINK_API_BASE_URL}/auth/mobile/`,
{ {
method: "POST", method: "POST",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
}, },
body: JSON.stringify({ body: JSON.stringify({
mobile, mobile,
}), }),
}, },
); );
return handleApiResponse<{ detail: string }>(response, "backendMobileLogin"); return handleApiResponse<{ detail: string }>(response, "backendMobileLogin");
} }

View File

@@ -11,14 +11,14 @@ import { handleApiResponse } from "@/utils/tryCatch";
type VerifyUserResponse = type VerifyUserResponse =
| { | {
ok: boolean; ok: boolean;
mismatch_fields: string[] | null; mismatch_fields: string[] | null;
error: string | null; error: string | null;
detail: string | null; detail: string | null;
} }
| { | {
message: boolean; message: boolean;
}; };
export async function verifyUser(userId: string) { export async function verifyUser(userId: string) {
const session = await getServerSession(authOptions); const session = await getServerSession(authOptions);
if (!session?.apiToken) { if (!session?.apiToken) {
@@ -129,7 +129,6 @@ export type UpdateUserFormState = {
payload?: FormData; payload?: FormData;
}; };
export async function updateUser( export async function updateUser(
_prevState: UpdateUserFormState, _prevState: UpdateUserFormState,
formData: FormData, formData: FormData,
@@ -190,7 +189,6 @@ export async function updateUser(
}; };
} }
export async function updateUserAgreement( export async function updateUserAgreement(
_prevState: UpdateUserFormState, _prevState: UpdateUserFormState,
formData: FormData, formData: FormData,
@@ -258,14 +256,13 @@ export async function adminUserTopup(
const description = formData.get("description") as string; const description = formData.get("description") as string;
const session = await getServerSession(authOptions); const session = await getServerSession(authOptions);
if (!amount) { if (!amount) {
return { return {
status: false, status: false,
message: "Amount is required", message: "Amount is required",
fieldErrors: { amount: ["Amount is required"], description: [] }, fieldErrors: { amount: ["Amount is required"], description: [] },
payload: formData, payload: formData,
} };
} }
const response = await fetch( const response = await fetch(
`${process.env.SARLINK_API_BASE_URL}/api/billing/admin-topup/`, `${process.env.SARLINK_API_BASE_URL}/api/billing/admin-topup/`,

View File

@@ -3,27 +3,27 @@ import { AgreementCard } from "@/components/agreement-card";
import { tryCatch } from "@/utils/tryCatch"; import { tryCatch } from "@/utils/tryCatch";
export default async function Agreements() { export default async function Agreements() {
const [error, profile] = await tryCatch(getProfile()); const [error, profile] = await tryCatch(getProfile());
return ( return (
<div> <div>
<div className="flex justify-between items-center border rounded-md border-dashed font-bold title-bg py-4 px-2 mb-4"> <div className="flex justify-between items-center border rounded-md border-dashed font-bold title-bg py-4 px-2 mb-4">
<h3 className="text-sarLinkOrange text-2xl">Agreements</h3> <h3 className="text-sarLinkOrange text-2xl">Agreements</h3>
</div> </div>
<div className="grid grid-cols-1"> <div className="grid grid-cols-1">
{error ? ( {error ? (
<div className="text-red-500"> <div className="text-red-500">
An error occurred while fetching agreements: {error.message} An error occurred while fetching agreements: {error.message}
</div> </div>
) : ( ) : (
<div> <div>
{profile.agreement ? ( {profile.agreement ? (
<AgreementCard agreement={profile.agreement} /> <AgreementCard agreement={profile.agreement} />
) : ( ) : (
<div className="text-gray-500">No agreement found.</div> <div className="text-gray-500">No agreement found.</div>
)} )}
</div> </div>
)} )}
</div> </div>
</div> </div>
); );
} }

View File

@@ -1,76 +0,0 @@
import { Skeleton } from "@/components/ui/skeleton";
import {
Table,
TableBody,
TableCell,
TableFooter,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { cn } from "@/lib/utils";
export default function DevicesTableSkeleton() {
return (
<>
<div className="hidden sm:block">
<Table className="overflow-scroll">
<TableHeader>
<TableRow>
<TableHead>Device Name</TableHead>
<TableHead>MAC Address</TableHead>
<TableHead>#</TableHead>
</TableRow>
</TableHeader>
<TableBody className="overflow-scroll">
{Array.from({ length: 10 }).map((_, i) => (
<TableRow key={`${i + 1}`}>
<TableCell>
<Skeleton className="w-full h-10 rounded" />
</TableCell>
<TableCell>
<Skeleton className="w-full h-10 rounded" />
</TableCell>
<TableCell>
<Skeleton className="w-full h-10 rounded" />
</TableCell>
</TableRow>
))}
</TableBody>
<TableFooter>
<TableRow>
<TableCell colSpan={2}>
<Skeleton className="w-full h-4 rounded" />
</TableCell>
<TableCell className="text-muted-foreground">
<Skeleton className="w-20 h-4 rounded" />
</TableCell>
</TableRow>
</TableFooter>
</Table>
</div>
<div className="sm:hidden my-4">
{Array.from({ length: 10 }).map((_, i) => (
<DeviceCardSkeleton key={`${i + 1}`} />
))}
</div>
</>
);
}
function DeviceCardSkeleton() {
return (
<div
className={cn(
"flex text-sm justify-between items-center my-2 p-4 border rounded-md bg-gray-100",
)}
>
<div className="font-semibold flex w-full flex-col items-start gap-2 mb-2 relative">
<Skeleton className="w-32 h-6" />
<Skeleton className="w-36 h-6" />
<Skeleton className="w-32 h-4" />
<Skeleton className="w-40 h-8" />
</div>
</div>
);
}

View File

@@ -0,0 +1,22 @@
import DevicesTableSkeleton from "@/components/device-table-skeleton";
import { Skeleton } from "@/components/ui/skeleton";
export default function LoadingComponent() {
return (
<div>
<div className="flex justify-between items-center border rounded-md border-dashed font-bold title-bg py-4 px-2 mb-4">
<Skeleton className="w-48 h-8" />
<Skeleton className="w-20 h-8" />
</div>
<div
id="user-filters"
className=" pb-4 gap-4 flex sm:flex-row flex-col items-start justify-endO"
>
<DevicesTableSkeleton
headers={["Device Name", "Mac Address", "Vendor", "#"]}
length={10}
/>
</div>
</div>
);
}

View File

@@ -1,10 +1,10 @@
import { getServerSession } from "next-auth"; import { getServerSession } from "next-auth";
import { Suspense } from "react"; import { Suspense } from "react";
import { authOptions } from "@/app/auth"; import { authOptions } from "@/app/auth";
import DevicesTableSkeleton from "@/components/device-table-skeleton";
import { DevicesTable } from "@/components/devices-table"; import { DevicesTable } from "@/components/devices-table";
import DynamicFilter from "@/components/generic-filter"; import DynamicFilter from "@/components/generic-filter";
import AddDeviceDialogForm from "@/components/user/add-device-dialog"; import AddDeviceDialogForm from "@/components/user/add-device-dialog";
import DevicesTableSkeleton from "./device-table-skeleton";
export default async function Devices({ export default async function Devices({
searchParams, searchParams,
@@ -53,7 +53,15 @@ export default async function Devices({
]} ]}
/> />
</div> </div>
<Suspense key={query || page} fallback={<DevicesTableSkeleton />}> <Suspense
key={query || page}
fallback={
<DevicesTableSkeleton
headers={["Device Name", "Mac Address", "Vendor", "#"]}
length={10}
/>
}
>
<DevicesTable parentalControl={false} searchParams={searchParams} /> <DevicesTable parentalControl={false} searchParams={searchParams} />
</Suspense> </Suspense>
</div> </div>

View File

@@ -0,0 +1,22 @@
import DevicesTableSkeleton from "@/components/device-table-skeleton";
import { Skeleton } from "@/components/ui/skeleton";
export default function LoadingComponent() {
return (
<div>
<div className="flex justify-between items-center border rounded-md border-dashed font-bold title-bg py-4 px-2 mb-4">
<Skeleton className="w-48 h-8" />
<Skeleton className="w-20 h-8" />
</div>
<div
id="user-filters"
className=" pb-4 gap-4 flex sm:flex-row flex-col items-start justify-endO"
>
<DevicesTableSkeleton
headers={["Device Name", "Mac Address", "Vendor", "#"]}
length={10}
/>
</div>
</div>
);
}

View File

@@ -1,4 +1,5 @@
import { Suspense } from "react"; import { Suspense } from "react";
import DevicesTableSkeleton from "@/components/device-table-skeleton";
import { DevicesTable } from "@/components/devices-table"; import { DevicesTable } from "@/components/devices-table";
import DynamicFilter from "@/components/generic-filter"; import DynamicFilter from "@/components/generic-filter";
@@ -51,7 +52,15 @@ export default async function ParentalControl({
]} ]}
/>{" "} />{" "}
</div> </div>
<Suspense key={(await searchParams).page} fallback={"loading...."}> <Suspense
key={(await searchParams).page}
fallback={
<DevicesTableSkeleton
headers={["Device Name", "Mac Address", "Vendor", "#"]}
length={10}
/>
}
>
<DevicesTable <DevicesTable
parentalControl={true} parentalControl={true}
searchParams={searchParams} searchParams={searchParams}

View File

@@ -0,0 +1,22 @@
import DevicesTableSkeleton from "@/components/device-table-skeleton";
import { Skeleton } from "@/components/ui/skeleton";
export default function LoadingComponent() {
return (
<div>
<div className="flex justify-between items-center border rounded-md border-dashed font-bold title-bg py-4 px-2 mb-4">
<Skeleton className="w-48 h-8" />
<Skeleton className="w-20 h-8" />
</div>
<div
id="user-filters"
className=" pb-4 gap-4 flex sm:flex-row flex-col items-start justify-endO"
>
<DevicesTableSkeleton
headers={["Details", "Duration", "Status", "Amount"]}
length={10}
/>
</div>
</div>
);
}

View File

@@ -1,4 +1,5 @@
import { Suspense } from "react"; import { Suspense } from "react";
import DevicesTableSkeleton from "@/components/device-table-skeleton";
import DynamicFilter from "@/components/generic-filter"; import DynamicFilter from "@/components/generic-filter";
import { PaymentsTable } from "@/components/payments-table"; import { PaymentsTable } from "@/components/payments-table";
@@ -14,8 +15,8 @@ export default async function Payments({
return ( return (
<div> <div>
<div className="flex justify-between items-center border rounded-md border-dashed font-bold title-bg py-4 px-2 mb-4"> <div className="flex justify-between items-center border rounded-md border-dashed font-bold title-bg py-4 px-3 mb-4">
<h3 className="text-sarLinkOrange text-2xl">My Payments</h3> <h3 className="text-sarLinkOrange text-2xl">My Subscriptions</h3>
</div> </div>
<div <div
id="user-filters" id="user-filters"
@@ -72,7 +73,15 @@ export default async function Payments({
]} ]}
/>{" "} />{" "}
</div> </div>
<Suspense key={query} fallback={"loading...."}> <Suspense
key={query}
fallback={
<DevicesTableSkeleton
headers={["Details", "Duration", "Status", "Amount"]}
length={10}
/>
}
>
<PaymentsTable searchParams={searchParams} /> <PaymentsTable searchParams={searchParams} />
</Suspense> </Suspense>
</div> </div>

View File

@@ -9,72 +9,72 @@ 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 TopupPage({ export default async function TopupPage({
params, params,
}: { }: {
params: Promise<{ topupId: string }>; params: Promise<{ topupId: string }>;
}) { }) {
const topupId = (await params).topupId; const topupId = (await params).topupId;
const [error, topup] = await tryCatch(getTopup({ id: topupId })); const [error, topup] = await tryCatch(getTopup({ id: topupId }));
if (error) { if (error) {
if (error.message === "Invalid token.") redirect("/auth/signin"); if (error.message === "Invalid token.") redirect("/auth/signin");
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.paid && topup.status !== "PENDING" && ( {!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.status} {topup.status}
</Button> </Button>
)} )}
{topup.status === "PENDING" && !topup.is_expired && ( {topup.status === "PENDING" && !topup.is_expired && (
<Button> <Button>
<TextShimmer>Payment Pending</TextShimmer>{" "} <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" ? ( ) : topup.status === "PENDING" ? (
<CancelTopupButton topupId={topupId} /> <CancelTopupButton topupId={topupId} />
) : topup.status === "CANCELLED" ? ( ) : topup.status === "CANCELLED" ? (
<Button disabled>Topup Cancelled</Button> <Button disabled>Topup Cancelled</Button>
) : ( ) : (
"" ""
))} ))}
</div> </div>
</div> </div>
{!topup.paid && topup.status === "PENDING" && !topup.is_expired && ( {!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
id="user-topup-details" id="user-topup-details"
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={ disabled={
topup.paid || topup.is_expired || topup.status === "CANCELLED" topup.paid || topup.is_expired || topup.status === "CANCELLED"
} }
topup={topup || undefined} topup={topup || undefined}
/> />
</div> </div>
</div> </div>
); );
} }

View File

@@ -0,0 +1,22 @@
import DevicesTableSkeleton from "@/components/device-table-skeleton";
import { Skeleton } from "@/components/ui/skeleton";
export default function LoadingComponent() {
return (
<div>
<div className="flex justify-between items-center border rounded-md border-dashed font-bold title-bg py-4 px-2 mb-4">
<Skeleton className="w-48 h-8" />
<Skeleton className="w-20 h-8" />
</div>
<div
id="user-filters"
className=" pb-4 gap-4 flex sm:flex-row flex-col items-start justify-endO"
>
<DevicesTableSkeleton
headers={["Details", "Status", "Amount"]}
length={10}
/>
</div>
</div>
);
}

View File

@@ -1,4 +1,5 @@
import { Suspense } from "react"; import { Suspense } from "react";
import DevicesTableSkeleton from "@/components/device-table-skeleton";
import DynamicFilter from "@/components/generic-filter"; import DynamicFilter from "@/components/generic-filter";
import { TopupsTable } from "@/components/topups-table"; import { TopupsTable } from "@/components/topups-table";
@@ -78,7 +79,15 @@ export default async function Topups({
]} ]}
/> />
</div> </div>
<Suspense key={query} fallback={"loading...."}> <Suspense
key={query}
fallback={
<DevicesTableSkeleton
headers={["Details", "Status", "Amount"]}
length={10}
/>
}
>
<TopupsTable searchParams={searchParams} /> <TopupsTable searchParams={searchParams} />
</Suspense> </Suspense>
</div> </div>

View File

@@ -1,63 +1,78 @@
import { Suspense } from "react"; import { Suspense } from "react";
import DevicesTableSkeleton from "@/components/device-table-skeleton";
import DynamicFilter from "@/components/generic-filter"; import DynamicFilter from "@/components/generic-filter";
import { WalletTransactionsTable } from "@/components/wallet-transactions-table"; import { WalletTransactionsTable } from "@/components/wallet-transactions-table";
export default async function Wallet({ export default async function Wallet({
searchParams, searchParams,
}: { }: {
searchParams: Promise<{ searchParams: Promise<{
query: string; query: string;
page: number; page: number;
sortBy: string; sortBy: string;
status: string; status: string;
}>; }>;
}) { }) {
const query = (await searchParams)?.query || ""; const query = (await searchParams)?.query || "";
return ( return (
<div> <div>
<div className="flex justify-between items-center border rounded-md border-dashed font-bold title-bg py-4 px-2 mb-4"> <div className="flex justify-between items-center border rounded-md border-dashed font-bold title-bg py-4 px-2 mb-4">
<h3 className="text-sarLinkOrange text-2xl">Transaction History</h3> <h3 className="text-sarLinkOrange text-2xl">Transaction History</h3>
</div> </div>
<div <div
id="wallet-filters" id="wallet-filters"
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"
> >
<DynamicFilter <DynamicFilter
inputs={[ inputs={[
{ {
label: "Type", label: "Type",
name: "transaction_type", name: "transaction_type",
type: "radio-group", type: "radio-group",
options: [ options: [
{ {
label: "All", label: "All",
value: "", value: "",
}, },
{ {
label: "Debit", label: "Debit",
value: "debit", value: "debit",
}, },
{ {
label: "Credit", label: "Credit",
value: "credit", value: "credit",
}, },
], ],
}, },
{ {
label: "Topup Amount", label: "Topup Amount",
name: "amount", name: "amount",
type: "dual-range-slider", type: "dual-range-slider",
min: 0, min: 0,
max: 1000, max: 1000,
step: 10, step: 10,
}, },
]} ]}
/> />
</div> </div>
<Suspense key={query} fallback={"loading...."}> <Suspense
<WalletTransactionsTable searchParams={searchParams} /> key={query}
</Suspense> fallback={
</div> <DevicesTableSkeleton
); headers={[
"Description",
"Amount",
"Transaction Type",
"View Details",
"Created at",
]}
length={10}
/>
}
>
<WalletTransactionsTable searchParams={searchParams} />
</Suspense>
</div>
);
} }

View File

@@ -1,3 +1,3 @@
export default { export default {
extends: ['@commitlint/config-conventional'] extends: ["@commitlint/config-conventional"],
}; };

View File

@@ -4,13 +4,13 @@ import { redirect } from "next/navigation";
import { getServerSession } from "next-auth"; import { getServerSession } from "next-auth";
import { authOptions } from "@/app/auth"; import { authOptions } from "@/app/auth";
import { import {
Table, Table,
TableBody, TableBody,
TableCell, TableCell,
TableFooter, TableFooter,
TableHead, TableHead,
TableHeader, TableHeader,
TableRow, TableRow,
} from "@/components/ui/table"; } from "@/components/ui/table";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { getDevices } from "@/queries/devices"; import { getDevices } from "@/queries/devices";
@@ -20,155 +20,155 @@ import ClientErrorMessage from "../client-error-message";
import Pagination from "../pagination"; import Pagination from "../pagination";
export async function AdminDevicesTable({ export async function AdminDevicesTable({
searchParams, searchParams,
}: { }: {
searchParams: Promise<{ searchParams: Promise<{
[key: string]: unknown; [key: string]: unknown;
}>; }>;
}) { }) {
const resolvedParams = await searchParams; const resolvedParams = await searchParams;
const session = await getServerSession(authOptions); const session = await getServerSession(authOptions);
const isAdmin = session?.user?.is_admin; const isAdmin = session?.user?.is_admin;
const page = Number.parseInt(resolvedParams.page as string) || 1; const page = Number.parseInt(resolvedParams.page as string) || 1;
const limit = 10; const limit = 10;
const offset = (page - 1) * limit; const offset = (page - 1) * limit;
// Build params object for getDevices // Build params object for getDevices
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.limit = limit;
apiParams.offset = offset; apiParams.offset = offset;
const [error, devices] = await tryCatch(getDevices(apiParams, true)); const [error, devices] = await tryCatch(getDevices(apiParams, true));
if (error) { if (error) {
if (error.message === "UNAUTHORIZED") { if (error.message === "UNAUTHORIZED") {
redirect("/auth/signin"); redirect("/auth/signin");
} else { } else {
return <ClientErrorMessage message={error.message} />; return <ClientErrorMessage message={error.message} />;
} }
} }
const { meta, data } = devices; const { meta, data } = devices;
return ( return (
<div> <div>
{data?.length === 0 ? ( {data?.length === 0 ? (
<div className="h-[calc(100svh-400px)] text-muted-foreground flex flex-col items-center justify-center my-4"> <div className="h-[calc(100svh-400px)] text-muted-foreground flex flex-col items-center justify-center my-4">
<h3>No devices.</h3> <h3>No devices.</h3>
</div> </div>
) : ( ) : (
<> <>
<div> <div>
<Table className="overflow-scroll"> <Table className="overflow-scroll">
<TableHeader> <TableHeader>
<TableRow> <TableRow>
<TableHead>Device Name</TableHead> <TableHead>Device Name</TableHead>
<TableHead>User</TableHead> <TableHead>User</TableHead>
<TableHead>MAC Address</TableHead> <TableHead>MAC Address</TableHead>
<TableHead>Vendor</TableHead> <TableHead>Vendor</TableHead>
<TableHead>#</TableHead> <TableHead>#</TableHead>
</TableRow> </TableRow>
</TableHeader> </TableHeader>
<TableBody className="overflow-scroll"> <TableBody className="overflow-scroll">
{data?.map((device) => ( {data?.map((device) => (
<TableRow key={device.id}> <TableRow key={device.id}>
<TableCell> <TableCell>
<div className="flex flex-col items-start"> <div className="flex flex-col items-start">
<Link <Link
className={cn( className={cn(
"hover:underline font-semibold", "hover:underline font-semibold",
device.is_active ? "text-green-600" : "", device.is_active ? "text-green-600" : "",
)} )}
href={`/devices/${device.id}`} href={`/devices/${device.id}`}
> >
{device.name} {device.name}
</Link> </Link>
{device.is_active ? ( {device.is_active ? (
<div className="text-muted-foreground"> <div className="text-muted-foreground">
Active until{" "} Active until{" "}
<span className="font-semibold"> <span className="font-semibold">
{new Date( {new Date(
device.expiry_date || "", device.expiry_date || "",
).toLocaleDateString("en-US", { ).toLocaleDateString("en-US", {
month: "short", month: "short",
day: "2-digit", day: "2-digit",
year: "numeric", year: "numeric",
})} })}
</span> </span>
</div> </div>
) : ( ) : (
<p className="text-muted-foreground"> <p className="text-muted-foreground">
Device Inactive Device Inactive
</p> </p>
)} )}
{device.has_a_pending_payment && ( {device.has_a_pending_payment && (
<Link href={`/payments/${device.pending_payment_id}`}> <Link href={`/payments/${device.pending_payment_id}`}>
<span className="bg-muted rounded px-2 p-1 mt-2 flex hover:underline items-center justify-center gap-2 text-muted-foreground"> <span className="bg-muted rounded px-2 p-1 mt-2 flex hover:underline items-center justify-center gap-2 text-muted-foreground">
Payment Pending{" "} Payment Pending{" "}
<HandCoins className="animate-pulse" size={14} /> <HandCoins className="animate-pulse" size={14} />
</span> </span>
</Link> </Link>
)} )}
{device.blocked_by === "ADMIN" && device.blocked && ( {device.blocked_by === "ADMIN" && device.blocked && (
<div className="p-2 rounded border my-2 bg-white dark:bg-neutral-800 shadow"> <div className="p-2 rounded border my-2 bg-white dark:bg-neutral-800 shadow">
<span className="font-semibold">Comment</span> <span className="font-semibold">Comment</span>
<p className="text-neutral-400"> <p className="text-neutral-400">
{device?.reason_for_blocking} {device?.reason_for_blocking}
</p> </p>
</div> </div>
)} )}
</div> </div>
</TableCell> </TableCell>
<TableCell className="font-medium"> <TableCell className="font-medium">
<div className="flex flex-col items-start"> <div className="flex flex-col items-start">
{device?.user?.name} {device?.user?.name}
<span className="text-muted-foreground"> <span className="text-muted-foreground">
{device?.user?.id_card} {device?.user?.id_card}
</span> </span>
</div> </div>
</TableCell> </TableCell>
<TableCell className="font-medium">{device.mac}</TableCell> <TableCell className="font-medium">{device.mac}</TableCell>
<TableCell className="font-medium"> <TableCell className="font-medium">
{device?.vendor} {device?.vendor}
</TableCell> </TableCell>
<TableCell> <TableCell>
{!device.has_a_pending_payment && ( {!device.has_a_pending_payment && (
<BlockDeviceDialog <BlockDeviceDialog
admin={isAdmin} admin={isAdmin}
type={device.blocked ? "unblock" : "block"} type={device.blocked ? "unblock" : "block"}
device={device} device={device}
/> />
)} )}
</TableCell> </TableCell>
</TableRow> </TableRow>
))} ))}
</TableBody> </TableBody>
<TableFooter> <TableFooter>
<TableRow> <TableRow>
<TableCell colSpan={5} className="text-muted-foreground"> <TableCell colSpan={5} className="text-muted-foreground">
{meta?.total === 1 ? ( {meta?.total === 1 ? (
<p className="text-center">Total {meta?.total} device.</p> <p className="text-center">Total {meta?.total} device.</p>
) : ( ) : (
<p className="text-center"> <p className="text-center">
Total {meta?.total} devices. Total {meta?.total} devices.
</p> </p>
)} )}
</TableCell> </TableCell>
</TableRow> </TableRow>
</TableFooter> </TableFooter>
</Table> </Table>
</div> </div>
<Pagination <Pagination
totalPages={meta?.last_page} totalPages={meta?.last_page}
currentPage={meta?.current_page} currentPage={meta?.current_page}
/> />
</> </>
)} )}
</div> </div>
); );
} }

View File

@@ -104,7 +104,9 @@ export default function AddTopupDialogForm({ user_id }: { user_id?: string }) {
<Label htmlFor="description">Topup Description</Label> <Label htmlFor="description">Topup Description</Label>
<input type="hidden" name="user_id" value={user_id} /> <input type="hidden" name="user_id" value={user_id} />
<Textarea <Textarea
defaultValue={(state?.payload?.get("description") || "") as string} defaultValue={
(state?.payload?.get("description") || "") as string
}
rows={10} rows={10}
name="description" name="description"
id="topup_description" id="topup_description"

View File

@@ -2,13 +2,13 @@ import Link from "next/link";
import { redirect } from "next/navigation"; import { redirect } from "next/navigation";
import { getTopups } from "@/actions/payment"; import { getTopups } from "@/actions/payment";
import { import {
Table, Table,
TableBody, TableBody,
TableCell, TableCell,
TableFooter, TableFooter,
TableHead, TableHead,
TableHeader, TableHeader,
TableRow, TableRow,
} from "@/components/ui/table"; } from "@/components/ui/table";
import { tryCatch } from "@/utils/tryCatch"; import { tryCatch } from "@/utils/tryCatch";
import Pagination from "../pagination"; import Pagination from "../pagination";
@@ -16,122 +16,122 @@ import { Badge } from "../ui/badge";
import { Button } from "../ui/button"; import { Button } from "../ui/button";
export async function AdminTopupsTable({ export async function AdminTopupsTable({
searchParams, searchParams,
}: { }: {
searchParams: Promise<{ searchParams: Promise<{
[key: string]: unknown; [key: string]: unknown;
}>; }>;
}) { }) {
const resolvedParams = await searchParams; const resolvedParams = await searchParams;
const page = Number.parseInt(resolvedParams.page as string) || 1; const page = Number.parseInt(resolvedParams.page as string) || 1;
const limit = 10; const limit = 10;
const offset = (page - 1) * limit; 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)) {
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.limit = limit;
apiParams.offset = offset; apiParams.offset = offset;
const [error, topups] = await tryCatch(getTopups(apiParams, true)); const [error, topups] = await tryCatch(getTopups(apiParams, true));
if (error) { if (error) {
if (error.message.includes("Unauthorized")) { if (error.message.includes("Unauthorized")) {
redirect("/auth/signin"); redirect("/auth/signin");
} else { } else {
return <pre>{JSON.stringify(error, null, 2)}</pre>; return <pre>{JSON.stringify(error, null, 2)}</pre>;
} }
} }
const { data, meta } = topups; const { data, meta } = topups;
return ( return (
<div> <div>
{data?.length === 0 ? ( {data?.length === 0 ? (
<div className="h-[calc(100svh-400px)] flex flex-col items-center justify-center my-4"> <div className="h-[calc(100svh-400px)] flex flex-col items-center justify-center my-4">
<h3>No topups yet.</h3> <h3>No topups yet.</h3>
</div> </div>
) : ( ) : (
<> <>
<div> <div>
<Table className="overflow-scroll"> <Table className="overflow-scroll">
<TableHeader> <TableHeader>
<TableRow> <TableRow>
<TableHead>User</TableHead> <TableHead>User</TableHead>
<TableHead>Status</TableHead> <TableHead>Status</TableHead>
<TableHead>Amount</TableHead> <TableHead>Amount</TableHead>
<TableHead>Action</TableHead> <TableHead>Action</TableHead>
</TableRow> </TableRow>
</TableHeader> </TableHeader>
<TableBody className="overflow-scroll"> <TableBody className="overflow-scroll">
{topups?.data?.map((topup) => ( {topups?.data?.map((topup) => (
<TableRow key={topup.id}> <TableRow key={topup.id}>
<TableCell> <TableCell>
<div className="flex flex-col items-start"> <div className="flex flex-col items-start">
{topup?.user?.name} {topup?.user?.name}
<span className="text-muted-foreground"> <span className="text-muted-foreground">
{topup?.user?.id_card} {topup?.user?.id_card}
</span> </span>
</div> </div>
</TableCell> </TableCell>
<TableCell> <TableCell>
<span className="font-semibold pr-2"> <span className="font-semibold pr-2">
{topup.paid ? ( {topup.paid ? (
<Badge <Badge
className="bg-green-100 dark:bg-green-700" className="bg-green-100 dark:bg-green-700"
variant="outline" variant="outline"
> >
{topup.status} {topup.status}
</Badge> </Badge>
) : topup.is_expired ? ( ) : topup.is_expired ? (
<Badge>Expired</Badge> <Badge>Expired</Badge>
) : ( ) : (
<Badge variant="outline">{topup.status}</Badge> <Badge variant="outline">{topup.status}</Badge>
)} )}
</span> </span>
</TableCell> </TableCell>
<TableCell> <TableCell>
<span className="font-semibold pr-2"> <span className="font-semibold pr-2">
{topup.amount.toFixed(2)} {topup.amount.toFixed(2)}
</span> </span>
MVR MVR
</TableCell> </TableCell>
<TableCell> <TableCell>
<div> <div>
<div className="flex items-center gap-2 mt-2"> <div className="flex items-center gap-2 mt-2">
<Link <Link
className="font-medium hover:underline" className="font-medium hover:underline"
href={`/top-ups/${topup.id}`} href={`/top-ups/${topup.id}`}
> >
<Button size={"sm"} variant="outline"> <Button size={"sm"} variant="outline">
View Details View Details
</Button> </Button>
</Link> </Link>
</div> </div>
</div> </div>
</TableCell> </TableCell>
</TableRow> </TableRow>
))} ))}
</TableBody> </TableBody>
<TableFooter> <TableFooter>
<TableRow> <TableRow>
<TableCell colSpan={4} className="text-muted-foreground"> <TableCell colSpan={4} className="text-muted-foreground">
{meta?.total === 1 ? ( {meta?.total === 1 ? (
<p className="text-center">Total {meta?.total} topup.</p> <p className="text-center">Total {meta?.total} topup.</p>
) : ( ) : (
<p className="text-center">Total {meta?.total} topups.</p> <p className="text-center">Total {meta?.total} topups.</p>
)} )}
</TableCell> </TableCell>
</TableRow> </TableRow>
</TableFooter> </TableFooter>
</Table> </Table>
</div> </div>
<Pagination <Pagination
totalPages={meta?.last_page} totalPages={meta?.last_page}
currentPage={meta?.current_page} currentPage={meta?.current_page}
/> />
</> </>
)} )}
</div> </div>
); );
} }

View File

@@ -5,168 +5,168 @@ import Pagination from "@/components/pagination";
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { import {
Table, Table,
TableBody, TableBody,
TableCell, TableCell,
TableFooter, TableFooter,
TableHead, TableHead,
TableHeader, TableHeader,
TableRow, TableRow,
} from "@/components/ui/table"; } from "@/components/ui/table";
import { tryCatch } from "@/utils/tryCatch"; import { tryCatch } from "@/utils/tryCatch";
import ClientErrorMessage from "../client-error-message"; import ClientErrorMessage from "../client-error-message";
export async function UsersPaymentsTable({ export async function UsersPaymentsTable({
searchParams, searchParams,
}: { }: {
searchParams: Promise<{ searchParams: Promise<{
[key: string]: unknown; [key: string]: unknown;
}>; }>;
}) { }) {
const resolvedParams = await searchParams; const resolvedParams = await searchParams;
const page = Number.parseInt(resolvedParams.page as string) || 1; const page = Number.parseInt(resolvedParams.page as string) || 1;
const limit = 10; const limit = 10;
const offset = (page - 1) * limit; const offset = (page - 1) * limit;
// Build params object for getDevices // Build params object for getDevices
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.limit = limit;
apiParams.offset = offset; apiParams.offset = offset;
const [error, payments] = await tryCatch(getPayments(apiParams, true)); const [error, payments] = await tryCatch(getPayments(apiParams, true));
if (error) { if (error) {
if (error.message === "UNAUTHORIZED") { if (error.message === "UNAUTHORIZED") {
redirect("/auth/signin"); redirect("/auth/signin");
} else { } else {
return <ClientErrorMessage message={error.message} />; return <ClientErrorMessage message={error.message} />;
} }
} }
const { meta, data } = payments; const { meta, data } = payments;
// return <pre>{JSON.stringify(payments, null, 2)}</pre>; // return <pre>{JSON.stringify(payments, null, 2)}</pre>;
return ( return (
<div> <div>
{data.length === 0 ? ( {data.length === 0 ? (
<div className="h-[calc(100svh-400px)] flex flex-col items-center justify-center my-4"> <div className="h-[calc(100svh-400px)] flex flex-col items-center justify-center my-4">
<h3>No user payments yet.</h3> <h3>No user payments yet.</h3>
</div> </div>
) : ( ) : (
<> <>
<Table className="overflow-scroll"> <Table className="overflow-scroll">
<TableHeader> <TableHeader>
<TableRow> <TableRow>
<TableHead>Devices paid</TableHead> <TableHead>Devices paid</TableHead>
<TableHead>User</TableHead> <TableHead>User</TableHead>
<TableHead>Amount</TableHead> <TableHead>Amount</TableHead>
<TableHead>Duration</TableHead> <TableHead>Duration</TableHead>
<TableHead>Payment Status</TableHead> <TableHead>Payment Status</TableHead>
<TableHead>Payment Method</TableHead> <TableHead>Payment Method</TableHead>
<TableHead>MIB Reference</TableHead> <TableHead>MIB Reference</TableHead>
<TableHead>Paid At</TableHead> <TableHead>Paid At</TableHead>
<TableHead>Action</TableHead> <TableHead>Action</TableHead>
</TableRow> </TableRow>
</TableHeader> </TableHeader>
<TableBody className="overflow-scroll"> <TableBody className="overflow-scroll">
{data.map((payment) => ( {data.map((payment) => (
<TableRow <TableRow
className={`${payment.paid && "title-bg dark:bg-black"}`} className={`${payment.paid && "title-bg dark:bg-black"}`}
key={payment.id} key={payment.id}
> >
<TableCell className="font-medium"> <TableCell className="font-medium">
<ol className="list-disc list-inside text-sm"> <ol className="list-disc list-inside text-sm">
{payment.devices.map((device) => ( {payment.devices.map((device) => (
<li <li
key={device.id} key={device.id}
className="text-sm text-muted-foreground" className="text-sm text-muted-foreground"
> >
{device.name} {device.name}
</li> </li>
))} ))}
</ol> </ol>
</TableCell> </TableCell>
<TableCell className="font-medium"> <TableCell className="font-medium">
{/* {payment.user.id_card} */} {/* {payment.user.id_card} */}
<div className="flex flex-col items-start"> <div className="flex flex-col items-start">
{payment?.user?.name} {payment?.user?.name}
<span className="text-muted-foreground"> <span className="text-muted-foreground">
{payment?.user?.id_card} {payment?.user?.id_card}
</span> </span>
</div>{" "} </div>{" "}
</TableCell> </TableCell>
<TableCell>{payment.amount} MVR</TableCell> <TableCell>{payment.amount} MVR</TableCell>
<TableCell>{payment.number_of_months} Months</TableCell> <TableCell>{payment.number_of_months} Months</TableCell>
<TableCell> <TableCell>
{payment.status === "PENDING" ? ( {payment.status === "PENDING" ? (
<Badge <Badge
variant="outline" variant="outline"
className="bg-yellow-100 text-black" className="bg-yellow-100 text-black"
> >
{payment.status} {payment.status}
</Badge> </Badge>
) : payment.status === "PAID" ? ( ) : payment.status === "PAID" ? (
<Badge <Badge
variant="outline" variant="outline"
className="bg-lime-100 text-black" className="bg-lime-100 text-black"
> >
{payment.status} {payment.status}
</Badge> </Badge>
) : ( ) : (
<Badge <Badge
variant="outline" variant="outline"
className="bg-red-100 text-black" className="bg-red-100 text-black"
> >
{payment.status} {payment.status}
</Badge> </Badge>
)} )}
</TableCell> </TableCell>
<TableCell>{payment.method}</TableCell> <TableCell>{payment.method}</TableCell>
<TableCell>{payment.mib_reference}</TableCell> <TableCell>{payment.mib_reference}</TableCell>
<TableCell> <TableCell>
{new Date(payment.paid_at ?? "").toLocaleDateString( {new Date(payment.paid_at ?? "").toLocaleDateString(
"en-US", "en-US",
{ {
month: "short", month: "short",
day: "2-digit", day: "2-digit",
year: "numeric", year: "numeric",
minute: "2-digit", minute: "2-digit",
hour: "2-digit", hour: "2-digit",
}, },
)} )}
</TableCell> </TableCell>
<TableCell> <TableCell>
<Link href={`/payments/${payment.id}`}> <Link href={`/payments/${payment.id}`}>
<Button>Details</Button> <Button>Details</Button>
</Link> </Link>
</TableCell> </TableCell>
</TableRow> </TableRow>
))} ))}
</TableBody> </TableBody>
<TableFooter> <TableFooter>
<TableRow> <TableRow>
<TableCell colSpan={10} className="text-muted-foreground"> <TableCell colSpan={10} className="text-muted-foreground">
{meta?.total === 1 ? ( {meta?.total === 1 ? (
<p className="text-center">Total {meta?.total} payment.</p> <p className="text-center">Total {meta?.total} payment.</p>
) : ( ) : (
<p className="text-center">Total {meta?.total} payments.</p> <p className="text-center">Total {meta?.total} payments.</p>
)}{" "} )}{" "}
</TableCell> </TableCell>
</TableRow> </TableRow>
</TableFooter> </TableFooter>
</Table> </Table>
<Pagination <Pagination
totalPages={meta?.last_page} totalPages={meta?.last_page}
currentPage={meta?.current_page} currentPage={meta?.current_page}
/> />
</> </>
)} )}
</div> </div>
); );
} }

View File

@@ -1,30 +1,33 @@
import { EyeIcon } from "lucide-react" import { EyeIcon } from "lucide-react";
import { Button } from "@/components/ui/button" import { Button } from "@/components/ui/button";
import { import {
Card, Card,
CardDescription, CardDescription,
CardFooter, CardFooter,
CardHeader, CardHeader,
CardTitle CardTitle,
} from "@/components/ui/card" } from "@/components/ui/card";
export function AgreementCard({ agreement }: { agreement: string }) { export function AgreementCard({ agreement }: { agreement: string }) {
return ( return (
<Card className="w-full max-w-sm"> <Card className="w-full max-w-sm">
<CardHeader> <CardHeader>
<CardTitle>Sarlink User Agreement</CardTitle> <CardTitle>Sarlink User Agreement</CardTitle>
<CardDescription> <CardDescription>User agreement for Sarlink services.</CardDescription>
User agreement for Sarlink services. </CardHeader>
</CardDescription> <CardFooter className="flex-col gap-2">
</CardHeader> <a
<CardFooter className="flex-col gap-2"> target="_blank"
<a target="_blank" rel="noopener noreferrer" className="w-full hover:cursor-pointer" href={agreement}> rel="noopener noreferrer"
<Button type="button" className="w-full hover:cursor-pointer"> className="w-full hover:cursor-pointer"
<EyeIcon /> href={agreement}
View Agreement >
</Button> <Button type="button" className="w-full hover:cursor-pointer">
</a> <EyeIcon />
</CardFooter> View Agreement
</Card> </Button>
) </a>
</CardFooter>
</Card>
);
} }

View File

@@ -110,7 +110,7 @@ export default function SignUpForm() {
className={cn( className={cn(
"text-base", "text-base",
actionState?.errors?.fieldErrors.name && actionState?.errors?.fieldErrors.name &&
"border-2 border-red-500", "border-2 border-red-500",
)} )}
name="name" name="name"
type="text" type="text"
@@ -144,7 +144,7 @@ export default function SignUpForm() {
className={cn( className={cn(
"text-base", "text-base",
actionState?.errors?.fieldErrors?.id_card && actionState?.errors?.fieldErrors?.id_card &&
"border-2 border-red-500", "border-2 border-red-500",
)} )}
placeholder="ID Card" placeholder="ID Card"
/> />
@@ -244,7 +244,7 @@ export default function SignUpForm() {
className={cn( className={cn(
"text-base", "text-base",
actionState?.errors?.fieldErrors?.address && actionState?.errors?.fieldErrors?.address &&
"border-2 border-red-500", "border-2 border-red-500",
)} )}
disabled={isPending} disabled={isPending}
name="address" name="address"
@@ -272,7 +272,7 @@ export default function SignUpForm() {
className={cn( className={cn(
"text-base", "text-base",
actionState?.errors?.fieldErrors?.dob && actionState?.errors?.fieldErrors?.dob &&
"border-2 border-red-500", "border-2 border-red-500",
)} )}
name="dob" name="dob"
disabled={isPending} disabled={isPending}
@@ -305,7 +305,7 @@ export default function SignUpForm() {
className={cn( className={cn(
"text-base", "text-base",
actionState?.errors?.fieldErrors.accNo && actionState?.errors?.fieldErrors.accNo &&
"border-2 border-red-500", "border-2 border-red-500",
)} )}
name="accNo" name="accNo"
type="number" type="number"
@@ -335,8 +335,8 @@ export default function SignUpForm() {
disabled={isPending} disabled={isPending}
className={cn( className={cn(
!phoneNumberFromUrl && !phoneNumberFromUrl &&
actionState?.errors?.fieldErrors?.phone_number && actionState?.errors?.fieldErrors?.phone_number &&
"border-2 border-red-500 rounded-md", "border-2 border-red-500 rounded-md",
)} )}
defaultValue={NUMBER_WITHOUT_DASH ?? ""} defaultValue={NUMBER_WITHOUT_DASH ?? ""}
readOnly={Boolean(phoneNumberFromUrl)} readOnly={Boolean(phoneNumberFromUrl)}

View File

@@ -6,12 +6,12 @@ import { useActionState, useEffect, useState, useTransition } from "react";
import { toast } from "sonner"; import { toast } from "sonner";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { import {
Dialog, Dialog,
DialogContent, DialogContent,
DialogFooter, DialogFooter,
DialogHeader, DialogHeader,
DialogTitle, DialogTitle,
DialogTrigger, DialogTrigger,
} from "@/components/ui/dialog"; } from "@/components/ui/dialog";
import { Label } from "@/components/ui/label"; import { Label } from "@/components/ui/label";
import type { Device } from "@/lib/backend-types"; import type { Device } from "@/lib/backend-types";
@@ -21,151 +21,151 @@ import { TextShimmer } from "./ui/text-shimmer";
import { Textarea } from "./ui/textarea"; import { Textarea } from "./ui/textarea";
export type BlockDeviceFormState = { export type BlockDeviceFormState = {
message: string; message: string;
success: boolean; success: boolean;
fieldErrors?: { fieldErrors?: {
reason_for_blocking?: string[]; reason_for_blocking?: string[];
}; };
payload?: FormData; payload?: FormData;
}; };
const initialState: BlockDeviceFormState = { const initialState: BlockDeviceFormState = {
message: "", message: "",
success: false, success: false,
fieldErrors: {}, fieldErrors: {},
}; };
export default function BlockDeviceDialog({ export default function BlockDeviceDialog({
device, device,
admin, admin,
parentalControl = false, parentalControl = false,
}: { }: {
device: Device; device: Device;
type: "block" | "unblock"; type: "block" | "unblock";
admin?: boolean; admin?: boolean;
parentalControl?: boolean; parentalControl?: boolean;
}) { }) {
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const [state, formAction, isPending] = useActionState( const [state, formAction, isPending] = useActionState(
blockDeviceAction, blockDeviceAction,
initialState, initialState,
); );
const [isTransitioning, startTransition] = useTransition(); const [isTransitioning, startTransition] = useTransition();
const handleSimpleBlock = () => { const handleSimpleBlock = () => {
startTransition(() => { startTransition(() => {
const formData = new FormData(); const formData = new FormData();
formData.append("deviceId", String(device.id)); formData.append("deviceId", String(device.id));
formData.append("reason_for_blocking", ""); formData.append("reason_for_blocking", "");
formData.append("action", "simple-block"); formData.append("action", "simple-block");
formData.append("blocked_by", "PARENT"); formData.append("blocked_by", "PARENT");
formAction(formData); formAction(formData);
}); });
}; };
const handleUnblock = () => { const handleUnblock = () => {
startTransition(() => { startTransition(() => {
const formData = new FormData(); const formData = new FormData();
formData.append("deviceId", String(device.id)); formData.append("deviceId", String(device.id));
formData.append("reason_for_blocking", ""); formData.append("reason_for_blocking", "");
formData.append("action", "unblock"); formData.append("action", "unblock");
formData.append("blocked_by", "PARENT"); formData.append("blocked_by", "PARENT");
formAction(formData); formAction(formData);
}); });
}; };
// Show toast notifications based on state changes // Show toast notifications based on state changes
useEffect(() => { useEffect(() => {
if (state.message) { if (state.message) {
if (state.success) { if (state.success) {
toast.success(state.message); toast.success(state.message);
if (open) setOpen(false); if (open) setOpen(false);
} else { } else {
toast.error(state.message); toast.error(state.message);
} }
} }
}, [state, open]); }, [state, open]);
const isLoading = isPending || isTransitioning; const isLoading = isPending || isTransitioning;
// If device is blocked and user is not admin, show unblock button // If device is blocked and user is not admin, show unblock button
if (device.blocked && parentalControl) { if (device.blocked && parentalControl) {
return ( return (
<Button onClick={handleUnblock} disabled={isLoading}> <Button onClick={handleUnblock} disabled={isLoading}>
{isLoading ? <TextShimmer>Unblocking</TextShimmer> : "Unblock"} {isLoading ? <TextShimmer>Unblocking</TextShimmer> : "Unblock"}
</Button> </Button>
); );
} }
// If device is not blocked and user is not admin, show simple block button // If device is not blocked and user is not admin, show simple block button
if ((!device.blocked && parentalControl) || !admin) { if ((!device.blocked && parentalControl) || !admin) {
return ( return (
<Button <Button
onClick={handleSimpleBlock} onClick={handleSimpleBlock}
disabled={isLoading} disabled={isLoading}
variant="destructive" variant="destructive"
> >
<ShieldBan /> <ShieldBan />
{isLoading ? <TextShimmer>Blocking</TextShimmer> : "Block"} {isLoading ? <TextShimmer>Blocking</TextShimmer> : "Block"}
</Button> </Button>
); );
} }
// If user is admin, show block with reason dialog // If user is admin, show block with reason dialog
return ( return (
<div> <div>
<Dialog open={open} onOpenChange={setOpen}> <Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild> <DialogTrigger asChild>
<Button disabled={isLoading} variant="destructive"> <Button disabled={isLoading} variant="destructive">
<OctagonX /> <OctagonX />
Block Block
</Button> </Button>
</DialogTrigger> </DialogTrigger>
<DialogContent className="sm:max-w-[425px]"> <DialogContent className="sm:max-w-[425px]">
<DialogHeader> <DialogHeader>
<DialogTitle>Block 🚫</DialogTitle> <DialogTitle>Block 🚫</DialogTitle>
<DialogDescription className="text-sm text-muted-foreground"> <DialogDescription className="text-sm text-muted-foreground">
Please provide a reason for blocking this device Please provide a reason for blocking this device
</DialogDescription> </DialogDescription>
</DialogHeader> </DialogHeader>
<form action={formAction} className="space-y-4"> <form action={formAction} className="space-y-4">
<input type="hidden" name="deviceId" value={String(device.id)} /> <input type="hidden" name="deviceId" value={String(device.id)} />
<input type="hidden" name="action" value="block" /> <input type="hidden" name="action" value="block" />
<input type="hidden" name="blocked_by" value="ADMIN" /> <input type="hidden" name="blocked_by" value="ADMIN" />
<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-1">
<Label htmlFor="reason_for_blocking" className="text-right"> <Label htmlFor="reason_for_blocking" className="text-right">
Reason for blocking Reason for blocking
</Label> </Label>
<Textarea <Textarea
rows={10} rows={10}
name="reason_for_blocking" name="reason_for_blocking"
id="reason_for_blocking" id="reason_for_blocking"
defaultValue={ defaultValue={
(state?.payload?.get("reason_for_blocking") || "") as string (state?.payload?.get("reason_for_blocking") || "") as string
} }
className={cn( className={cn(
"col-span-5 mt-2", "col-span-5 mt-2",
state.fieldErrors?.reason_for_blocking && state.fieldErrors?.reason_for_blocking &&
"ring-2 ring-red-500", "ring-2 ring-red-500",
)} )}
/> />
<span className="text-sm text-red-500"> <span className="text-sm text-red-500">
{state.fieldErrors?.reason_for_blocking?.[0]} {state.fieldErrors?.reason_for_blocking?.[0]}
</span> </span>
</div> </div>
</div> </div>
<DialogFooter> <DialogFooter>
<Button variant="destructive" disabled={isLoading} type="submit"> <Button variant="destructive" disabled={isLoading} type="submit">
{isLoading ? "Blocking..." : "Block"} {isLoading ? "Blocking..." : "Block"}
</Button> </Button>
</DialogFooter> </DialogFooter>
</form> </form>
</DialogContent> </DialogContent>
</Dialog> </Dialog>
</div> </div>
); );
} }

View File

@@ -10,108 +10,108 @@ import BlockDeviceDialog from "./block-device-dialog";
import { Badge } from "./ui/badge"; import { Badge } from "./ui/badge";
export default function DeviceCard({ export default function DeviceCard({
device, device,
parentalControl, parentalControl,
isAdmin, isAdmin,
}: { }: {
device: Device; device: Device;
parentalControl?: boolean; parentalControl?: boolean;
isAdmin?: boolean; isAdmin?: boolean;
}) { }) {
const [devices, setDeviceCart] = useAtom(deviceCartAtom); const [devices, setDeviceCart] = useAtom(deviceCartAtom);
const isChecked = devices.some((d) => d.id === device.id); const isChecked = devices.some((d) => d.id === device.id);
return ( return (
// biome-ignore lint/a11y/noStaticElementInteractions: <dw about it> // biome-ignore lint/a11y/noStaticElementInteractions: <dw about it>
<div <div
onKeyUp={() => {}} onKeyUp={() => {}}
onClick={() => { onClick={() => {
if (device.blocked) return; if (device.blocked) return;
if (device.is_active === true) return; if (device.is_active === true) return;
if (device.has_a_pending_payment === true) return; if (device.has_a_pending_payment === true) return;
if (parentalControl === true) return; if (parentalControl === true) return;
setDeviceCart((prev) => setDeviceCart((prev) =>
devices.some((d) => d.id === device.id) devices.some((d) => d.id === device.id)
? prev.filter((d) => d.id !== device.id) ? prev.filter((d) => d.id !== device.id)
: [...prev, device], : [...prev, device],
); );
}} }}
className="w-full" className="w-full"
> >
<div <div
className={cn( className={cn(
"flex text-sm justify-between items-center my-2 p-4 border rounded-md", "flex text-sm justify-between items-center my-2 p-4 border rounded-md",
isChecked ? "bg-accent" : "", isChecked ? "bg-accent" : "",
device.is_active device.is_active
? "cursor-not-allowed text-green-600 hover:bg-accent-foreground/10" ? "cursor-not-allowed text-green-600 hover:bg-accent-foreground/10"
: "cursor-pointer hover:bg-muted-foreground/10", : "cursor-pointer hover:bg-muted-foreground/10",
)} )}
> >
<div className=""> <div className="">
<div className="font-semibold flex flex-col items-start gap-2 mb-2"> <div className="font-semibold flex flex-col items-start gap-2 mb-2">
<Link <Link
className={cn( className={cn(
"font-medium hover:underline ml-0.5", "font-medium hover:underline ml-0.5",
device.is_active ? "text-green-600" : "", device.is_active ? "text-green-600" : "",
)} )}
href={`/devices/${device.id}`} href={`/devices/${device.id}`}
> >
{device.name} {device.name}
</Link> </Link>
<Badge variant={"outline"}> <Badge variant={"outline"}>
<span className="font-medium">{device.mac}</span> <span className="font-medium">{device.mac}</span>
</Badge> </Badge>
<Badge variant={"outline"}> <Badge variant={"outline"}>
<span className="font-medium">{device.vendor}</span> <span className="font-medium">{device.vendor}</span>
</Badge> </Badge>
</div> </div>
{device.is_active ? ( {device.is_active ? (
<div className="text-muted-foreground ml-0.5"> <div className="text-muted-foreground ml-0.5">
Active until{" "} Active until{" "}
<span className="font-semibold"> <span className="font-semibold">
{new Date(device.expiry_date || "").toLocaleDateString( {new Date(device.expiry_date || "").toLocaleDateString(
"en-US", "en-US",
{ {
month: "short", month: "short",
day: "2-digit", day: "2-digit",
year: "numeric", year: "numeric",
}, },
)} )}
</span> </span>
</div> </div>
) : ( ) : (
<p className="text-muted-foreground ml-0.5">Device Inactive</p> <p className="text-muted-foreground ml-0.5">Device Inactive</p>
)} )}
{device.has_a_pending_payment && ( {device.has_a_pending_payment && (
<Link href={`/payments/${device.pending_payment_id}`}> <Link href={`/payments/${device.pending_payment_id}`}>
<span className="bg-muted rounded px-2 p-1 mt-2 flex hover:underline items-center justify-center gap-2 text-yellow-600"> <span className="bg-muted rounded px-2 p-1 mt-2 flex hover:underline items-center justify-center gap-2 text-yellow-600">
Payment Pending{" "} Payment Pending{" "}
<HandCoins className="animate-pulse" size={14} /> <HandCoins className="animate-pulse" size={14} />
</span> </span>
</Link> </Link>
)} )}
{device.blocked && device.blocked_by === "ADMIN" && ( {device.blocked && device.blocked_by === "ADMIN" && (
<div className="p-2 rounded border my-2 w-full"> <div className="p-2 rounded border my-2 w-full">
<span className="uppercase text-red-500">Blocked by admin </span> <span className="uppercase text-red-500">Blocked by admin </span>
<p className="text-neutral-500">{device?.reason_for_blocking}</p> <p className="text-neutral-500">{device?.reason_for_blocking}</p>
</div> </div>
)} )}
</div> </div>
<div> <div>
{!parentalControl ? ( {!parentalControl ? (
<AddDevicesToCartButton device={device} /> <AddDevicesToCartButton device={device} />
) : ( ) : (
<BlockDeviceDialog <BlockDeviceDialog
admin={isAdmin} admin={isAdmin}
type={device.blocked ? "unblock" : "block"} type={device.blocked ? "unblock" : "block"}
device={device} device={device}
/> />
)} )}
</div> </div>
</div> </div>
</div> </div>
); );
} }

View File

@@ -0,0 +1,66 @@
import { Skeleton } from "@/components/ui/skeleton";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { cn } from "@/lib/utils";
type TableSkeletonProps = {
headers: string[];
length: number;
};
export default function TableSkeleton({ headers, length }: TableSkeletonProps) {
return (
<>
<div className="hidden sm:block w-full">
<Table className="overflow-scroll w-full">
<TableHeader>
<TableRow>
{headers.map((header, index) => (
<TableHead key={`${index + 1}`}>{header}</TableHead>
))}
</TableRow>
</TableHeader>
<TableBody className="overflow-scroll">
{Array.from({ length }).map((_, i) => (
<TableRow key={`${i + 1}`}>
{headers.map((_, index) => (
<TableCell key={`${index + 1}`}>
<Skeleton className="w-full h-10 rounded" />
</TableCell>
))}
</TableRow>
))}
</TableBody>
</Table>
</div>
<div className="sm:hidden my-4 w-full">
{Array.from({ length }).map((_, i) => (
<DeviceCardSkeleton key={`${i + 1}`} />
))}
</div>
</>
);
}
function DeviceCardSkeleton() {
return (
<div
className={cn(
"flex text-sm justify-between items-center my-2 p-4 border rounded-md w-full",
)}
>
<div className="font-semibold flex w-full flex-col items-start gap-2 mb-2 relative">
<Skeleton className="w-32 h-6" />
<Skeleton className="w-36 h-6" />
<Skeleton className="w-32 h-4" />
<Skeleton className="w-40 h-8" />
</div>
</div>
);
}

View File

@@ -20,7 +20,6 @@ export default function DevicesForPayment() {
const [months, setMonths] = useAtom(numberOfMonths); const [months, setMonths] = useAtom(numberOfMonths);
const [disabled, setDisabled] = useState(false); const [disabled, setDisabled] = useState(false);
if (pathname === "/payments") { if (pathname === "/payments") {
return null; return null;
} }
@@ -48,7 +47,6 @@ export default function DevicesForPayment() {
maxAllowed={12} maxAllowed={12}
isDisabled={devices.length === 0} isDisabled={devices.length === 0}
/> />
</div> </div>
<Button <Button
onClick={async () => { onClick={async () => {

View File

@@ -2,13 +2,13 @@ import { redirect } from "next/navigation";
import { getServerSession } from "next-auth"; import { getServerSession } from "next-auth";
import { authOptions } from "@/app/auth"; import { authOptions } from "@/app/auth";
import { import {
Table, Table,
TableBody, TableBody,
TableCell, TableCell,
TableFooter, TableFooter,
TableHead, TableHead,
TableHeader, TableHeader,
TableRow, TableRow,
} from "@/components/ui/table"; } from "@/components/ui/table";
import { getDevices } from "@/queries/devices"; import { getDevices } from "@/queries/devices";
import { tryCatch } from "@/utils/tryCatch"; import { tryCatch } from "@/utils/tryCatch";
@@ -18,107 +18,107 @@ import DeviceCard from "./device-card";
import Pagination from "./pagination"; import Pagination from "./pagination";
export async function DevicesTable({ export async function DevicesTable({
searchParams, searchParams,
parentalControl, parentalControl,
additionalFilters = {}, additionalFilters = {},
}: { }: {
searchParams: Promise<{ searchParams: Promise<{
[key: string]: unknown; [key: string]: unknown;
}>; }>;
parentalControl?: boolean; parentalControl?: boolean;
additionalFilters?: Record<string, string | number | boolean>; additionalFilters?: Record<string, string | number | boolean>;
}) { }) {
const resolvedParams = await searchParams; const resolvedParams = await searchParams;
const session = await getServerSession(authOptions); const session = await getServerSession(authOptions);
const isAdmin = session?.user?.is_admin; const isAdmin = session?.user?.is_admin;
const page = Number.parseInt(resolvedParams.page as string) || 1; const page = Number.parseInt(resolvedParams.page as string) || 1;
const limit = 10; const limit = 10;
const offset = (page - 1) * limit; const offset = (page - 1) * limit;
// Build params object for getDevices // Build params object for getDevices
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);
} }
} }
for (const [key, value] of Object.entries(additionalFilters)) { for (const [key, value] of Object.entries(additionalFilters)) {
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.limit = limit;
apiParams.offset = offset; apiParams.offset = offset;
const [error, devices] = await tryCatch(getDevices(apiParams)); const [error, devices] = await tryCatch(getDevices(apiParams));
if (error) { if (error) {
if (error.message === "UNAUTHORIZED") { if (error.message === "UNAUTHORIZED") {
redirect("/auth/signin"); redirect("/auth/signin");
} else { } else {
return <ClientErrorMessage message={error.message} />; return <ClientErrorMessage message={error.message} />;
} }
} }
const { meta, data } = devices; const { meta, data } = devices;
return ( return (
<div> <div>
{data?.length === 0 ? ( {data?.length === 0 ? (
<div className="h-[calc(100svh-400px)] text-muted-foreground flex flex-col items-center justify-center my-4"> <div className="h-[calc(100svh-400px)] text-muted-foreground flex flex-col items-center justify-center my-4">
<h3>{parentalControl ? "No active devices" : "No devices."}</h3> <h3>{parentalControl ? "No active devices" : "No devices."}</h3>
</div> </div>
) : ( ) : (
<> <>
<div className="hidden sm:block"> <div className="hidden sm:block">
<Table className="overflow-scroll"> <Table className="overflow-scroll">
<TableHeader> <TableHeader>
<TableRow> <TableRow>
<TableHead>Device Name</TableHead> <TableHead>Device Name</TableHead>
<TableHead>MAC Address</TableHead> <TableHead>MAC Address</TableHead>
<TableHead>Vendor</TableHead> <TableHead>Vendor</TableHead>
<TableHead>#</TableHead> <TableHead>#</TableHead>
</TableRow> </TableRow>
</TableHeader> </TableHeader>
<TableBody className="overflow-scroll"> <TableBody className="overflow-scroll">
{data?.map((device) => ( {data?.map((device) => (
<ClickableRow <ClickableRow
admin={isAdmin} admin={isAdmin}
key={device.id} key={device.id}
device={device} device={device}
parentalControl={parentalControl} parentalControl={parentalControl}
/> />
))} ))}
</TableBody> </TableBody>
<TableFooter> <TableFooter>
<TableRow> <TableRow>
<TableCell colSpan={4} className="text-muted-foreground"> <TableCell colSpan={4} className="text-muted-foreground">
{meta?.total === 1 ? ( {meta?.total === 1 ? (
<p className="text-center">Total {meta?.total} device.</p> <p className="text-center">Total {meta?.total} device.</p>
) : ( ) : (
<p className="text-center"> <p className="text-center">
Total {meta?.total} devices. Total {meta?.total} devices.
</p> </p>
)} )}
</TableCell> </TableCell>
</TableRow> </TableRow>
</TableFooter> </TableFooter>
</Table> </Table>
</div> </div>
<div className="sm:hidden my-4"> <div className="sm:hidden my-4">
{data?.map((device) => ( {data?.map((device) => (
<DeviceCard <DeviceCard
parentalControl={parentalControl} parentalControl={parentalControl}
key={device.id} key={device.id}
device={device} device={device}
isAdmin={isAdmin} isAdmin={isAdmin}
/> />
))} ))}
</div> </div>
<Pagination <Pagination
totalPages={meta?.last_page} totalPages={meta?.last_page}
currentPage={meta?.current_page} currentPage={meta?.current_page}
/> />
</> </>
)} )}
</div> </div>
); );
} }

View File

@@ -1,63 +1,63 @@
import { Minus, Plus } from "lucide-react"; import { Minus, Plus } from "lucide-react";
import { useEffect } from "react"; import { useEffect } from "react";
import { import {
Button, Button,
Group, Group,
Input, Input,
Label, Label,
NumberField, NumberField,
} from "react-aria-components"; } from "react-aria-components";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
export default function NumberInput({ export default function NumberInput({
maxAllowed, maxAllowed,
label, label,
value = 100, value = 100,
onChange, onChange,
className, className,
isDisabled, isDisabled,
}: { }: {
maxAllowed?: number; maxAllowed?: number;
label: string; label: string;
value?: number; value?: number;
onChange: (value: number) => void; onChange: (value: number) => void;
className?: string; className?: string;
isDisabled?: boolean; isDisabled?: boolean;
}) { }) {
useEffect(() => { useEffect(() => {
if (maxAllowed) { if (maxAllowed) {
if (value > maxAllowed) { if (value > maxAllowed) {
onChange(maxAllowed); onChange(maxAllowed);
} }
} }
}, [maxAllowed, value, onChange]); }, [maxAllowed, value, onChange]);
return ( return (
<NumberField <NumberField
isDisabled={isDisabled} isDisabled={isDisabled}
className={cn(className)} className={cn(className)}
value={value} value={value}
minValue={0} minValue={0}
onChange={onChange} onChange={onChange}
> >
<div className="space-y-2"> <div className="space-y-2">
<Label className="text-sm font-medium text-foreground">{label}</Label> <Label className="text-sm font-medium text-foreground">{label}</Label>
<Group className="relative inline-flex h-9 w-full items-center overflow-hidden whitespace-nowrap rounded-lg border border-input text-sm shadow-sm shadow-black/5 transition-shadow data-[focus-within]:border-ring data-disabled:opacity-50 data-focus-within:outline-none data-focus-within:ring-[3px] data-[focus-within]:ring-ring/20"> <Group className="relative inline-flex h-9 w-full items-center overflow-hidden whitespace-nowrap rounded-lg border border-input text-sm shadow-sm shadow-black/5 transition-shadow data-[focus-within]:border-ring data-disabled:opacity-50 data-focus-within:outline-none data-focus-within:ring-[3px] data-[focus-within]:ring-ring/20">
<Button <Button
slot="decrement" slot="decrement"
className="-ms-px flex aspect-square h-[inherit] items-center justify-center rounded-s-lg border border-input bg-background text-sm text-muted-foreground/80 transition-shadow hover:bg-accent hover:text-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50" className="-ms-px flex aspect-square h-[inherit] items-center justify-center rounded-s-lg border border-input bg-background text-sm text-muted-foreground/80 transition-shadow hover:bg-accent hover:text-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50"
> >
<Minus size={16} strokeWidth={2} aria-hidden="true" /> <Minus size={16} strokeWidth={2} aria-hidden="true" />
</Button> </Button>
<Input className="w-full grow bg-background px-3 py-2 text-center text-base tabular-nums text-foreground focus:outline-none" /> <Input className="w-full grow bg-background px-3 py-2 text-center text-base tabular-nums text-foreground focus:outline-none" />
<Button <Button
slot="increment" slot="increment"
className="-me-px flex aspect-square h-[inherit] items-center justify-center rounded-e-lg border border-input bg-background text-sm text-muted-foreground/80 transition-shadow hover:bg-accent hover:text-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50" className="-me-px flex aspect-square h-[inherit] items-center justify-center rounded-e-lg border border-input bg-background text-sm text-muted-foreground/80 transition-shadow hover:bg-accent hover:text-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50"
> >
<Plus size={16} strokeWidth={2} aria-hidden="true" /> <Plus size={16} strokeWidth={2} aria-hidden="true" />
</Button> </Button>
</Group> </Group>
</div> </div>
</NumberField> </NumberField>
); );
} }

View File

@@ -6,108 +6,108 @@ import React, { useEffect, useState } from "react";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
type PaginationProps = { type PaginationProps = {
totalPages: number; totalPages: number;
currentPage: number; currentPage: number;
maxVisible?: number; maxVisible?: number;
}; };
export default function Pagination({ export default function Pagination({
totalPages, totalPages,
currentPage, currentPage,
maxVisible = 4, maxVisible = 4,
}: PaginationProps) { }: PaginationProps) {
const searchParams = useSearchParams(); const searchParams = useSearchParams();
const activePage = searchParams.get("page") ?? 1; const activePage = searchParams.get("page") ?? 1;
const router = useRouter(); const router = useRouter();
const [queryParams, setQueryParams] = useState<{ [key: string]: string }>({}); const [queryParams, setQueryParams] = useState<{ [key: string]: string }>({});
useEffect(() => { useEffect(() => {
const params = Object.fromEntries( const params = Object.fromEntries(
Array.from(searchParams.entries()).filter(([key]) => key !== "page"), Array.from(searchParams.entries()).filter(([key]) => key !== "page"),
); );
setQueryParams(params); setQueryParams(params);
}, [searchParams]); }, [searchParams]);
useEffect(() => { useEffect(() => {
if (!searchParams.has("page")) { if (!searchParams.has("page")) {
router.replace(`?page=1${IncludeQueries()}`); router.replace(`?page=1${IncludeQueries()}`);
} }
}); });
function IncludeQueries() { function IncludeQueries() {
return Object.entries(queryParams) return Object.entries(queryParams)
.map(([key, value]) => `&${key}=${value}`) .map(([key, value]) => `&${key}=${value}`)
.join(""); .join("");
} }
const generatePageNumbers = (): (number | string)[] => { const generatePageNumbers = (): (number | string)[] => {
const halfVisible = Math.floor(maxVisible / 2); const halfVisible = Math.floor(maxVisible / 2);
let startPage = Math.max(currentPage - halfVisible, 1); let startPage = Math.max(currentPage - halfVisible, 1);
const endPage = Math.min(startPage + maxVisible - 1, totalPages); const endPage = Math.min(startPage + maxVisible - 1, totalPages);
if (endPage - startPage + 1 < maxVisible) { if (endPage - startPage + 1 < maxVisible) {
startPage = Math.max(endPage - maxVisible + 1, 1); startPage = Math.max(endPage - maxVisible + 1, 1);
} }
const pageNumbers: (number | string)[] = []; const pageNumbers: (number | string)[] = [];
if (startPage > 1) { if (startPage > 1) {
pageNumbers.push(1); pageNumbers.push(1);
if (startPage > 2) pageNumbers.push("..."); if (startPage > 2) pageNumbers.push("...");
} }
for (let i = startPage; i <= endPage; i++) { for (let i = startPage; i <= endPage; i++) {
pageNumbers.push(i); pageNumbers.push(i);
} }
if (endPage < totalPages) { if (endPage < totalPages) {
if (endPage < totalPages - 1) pageNumbers.push("..."); if (endPage < totalPages - 1) pageNumbers.push("...");
pageNumbers.push(totalPages); pageNumbers.push(totalPages);
} }
return pageNumbers; return pageNumbers;
}; };
const pageNumbers = generatePageNumbers(); const pageNumbers = generatePageNumbers();
if (totalPages <= 1) { if (totalPages <= 1) {
return null; return null;
} }
return ( return (
<div className="flex items-center justify-center space-x-2 my-4"> <div className="flex items-center justify-center space-x-2 my-4">
{currentPage > 1 && ( {currentPage > 1 && (
<Link href={`?page=${Number(currentPage) - 1}${IncludeQueries()}`}> <Link href={`?page=${Number(currentPage) - 1}${IncludeQueries()}`}>
<Button variant="secondary" className="flex items-center gap-2"> <Button variant="secondary" className="flex items-center gap-2">
<ArrowLeftIcon className="h-4 w-4" /> <ArrowLeftIcon className="h-4 w-4" />
</Button> </Button>
</Link> </Link>
)} )}
{pageNumbers.map((page) => ( {pageNumbers.map((page) => (
<React.Fragment key={`${page}`}> <React.Fragment key={`${page}`}>
{typeof page === "number" ? ( {typeof page === "number" ? (
<Link href={`?page=${page}${IncludeQueries()}`}> <Link href={`?page=${page}${IncludeQueries()}`}>
<Button <Button
variant={Number(activePage) === page ? "default" : "outline"} variant={Number(activePage) === page ? "default" : "outline"}
> >
{page} {page}
</Button> </Button>
</Link> </Link>
) : ( ) : (
<span className="px-2">...</span> <span className="px-2">...</span>
)} )}
</React.Fragment> </React.Fragment>
))} ))}
{currentPage < totalPages && ( {currentPage < totalPages && (
<Link href={`?page=${Number(currentPage) + 1}${IncludeQueries()}`}> <Link href={`?page=${Number(currentPage) + 1}${IncludeQueries()}`}>
<Button variant="secondary" className="flex items-center gap-2"> <Button variant="secondary" className="flex items-center gap-2">
<ArrowRightIcon className="h-4 w-4" /> <ArrowRightIcon className="h-4 w-4" />
</Button> </Button>
</Link> </Link>
)} )}
</div> </div>
); );
} }

View File

@@ -3,13 +3,13 @@ import Link from "next/link";
import { redirect } from "next/navigation"; import { redirect } from "next/navigation";
import { getPayments } from "@/actions/payment"; import { getPayments } from "@/actions/payment";
import { import {
Table, Table,
TableBody, TableBody,
TableCell, TableCell,
TableFooter, TableFooter,
TableHead, TableHead,
TableHeader, TableHeader,
TableRow, TableRow,
} from "@/components/ui/table"; } from "@/components/ui/table";
import type { Payment } from "@/lib/backend-types"; import type { Payment } from "@/lib/backend-types";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
@@ -20,265 +20,265 @@ import { Button } from "./ui/button";
import { Separator } from "./ui/separator"; import { Separator } from "./ui/separator";
export async function PaymentsTable({ export async function PaymentsTable({
searchParams, searchParams,
}: { }: {
searchParams: Promise<{ searchParams: Promise<{
[key: string]: unknown; [key: string]: unknown;
}>; }>;
}) { }) {
const resolvedParams = await searchParams; const resolvedParams = await searchParams;
const page = Number.parseInt(resolvedParams.page as string) || 1; const page = Number.parseInt(resolvedParams.page as string) || 1;
const limit = 10; const limit = 10;
const offset = (page - 1) * limit; 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.limit = limit;
apiParams.offset = offset; apiParams.offset = offset;
const [error, payments] = await tryCatch(getPayments(apiParams)); const [error, payments] = await tryCatch(getPayments(apiParams));
if (error) { if (error) {
if (error.message.includes("Unauthorized")) { if (error.message.includes("Unauthorized")) {
redirect("/auth/signin"); redirect("/auth/signin");
} else { } else {
return <pre>{JSON.stringify(error, null, 2)}</pre>; return <pre>{JSON.stringify(error, null, 2)}</pre>;
} }
} }
const { data, meta } = payments; const { data, meta } = payments;
return ( return (
<div> <div>
{data?.length === 0 ? ( {data?.length === 0 ? (
<div className="h-[calc(100svh-400px)] text-muted-foreground flex flex-col items-center justify-center my-4"> <div className="h-[calc(100svh-400px)] text-muted-foreground flex flex-col items-center justify-center my-4">
<h3>No Payments.</h3> <h3>No Payments.</h3>
</div> </div>
) : ( ) : (
<> <>
<div className="hidden sm:block"> <div className="hidden sm:block">
<Table className="overflow-scroll"> <Table className="overflow-scroll">
<TableHeader> <TableHeader>
<TableRow> <TableRow>
<TableHead>Details</TableHead> <TableHead>Details</TableHead>
<TableHead>Duration</TableHead> <TableHead>Duration</TableHead>
<TableHead>Status</TableHead> <TableHead>Status</TableHead>
<TableHead>Amount</TableHead> <TableHead>Amount</TableHead>
</TableRow> </TableRow>
</TableHeader> </TableHeader>
<TableBody className="overflow-scroll"> <TableBody className="overflow-scroll">
{payments?.data?.map((payment) => ( {payments?.data?.map((payment) => (
<TableRow key={payment.id}> <TableRow key={payment.id}>
<TableCell> <TableCell>
<div <div
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 : payment?.is_expired
? "bg-gray-500/10 border-dashed border-gray-500 dark:border-gray-500/50" ? "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",
)} )}
> >
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Calendar size={16} opacity={0.5} /> <Calendar size={16} opacity={0.5} />
<span className="text-muted-foreground"> <span className="text-muted-foreground">
{new Date(payment.created_at).toLocaleDateString( {new Date(payment.created_at).toLocaleDateString(
"en-US", "en-US",
{ {
month: "short", month: "short",
day: "2-digit", day: "2-digit",
year: "numeric", year: "numeric",
minute: "2-digit", minute: "2-digit",
hour: "2-digit", hour: "2-digit",
timeZone: "Indian/Maldives", // Force consistent timezone timeZone: "Indian/Maldives", // Force consistent timezone
}, },
)} )}
</span> </span>
</div> </div>
<div className="flex items-center gap-2 mt-2"> <div className="flex items-center gap-2 mt-2">
<Link <Link
className="font-medium hover:underline" className="font-medium hover:underline"
href={`/payments/${payment.id}`} href={`/payments/${payment.id}`}
> >
<Button size={"sm"} variant="outline"> <Button size={"sm"} variant="outline">
View Details View Details
</Button> </Button>
</Link> </Link>
</div> </div>
<div className="bg-white dark:bg-black p-2 rounded mt-2 w-full border"> <div className="bg-white dark:bg-black p-2 rounded mt-2 w-full border">
<h3 className="text-sm font-medium">Devices</h3> <h3 className="text-sm font-medium">Devices</h3>
<ol className="list-disc list-inside text-sm"> <ol className="list-disc list-inside text-sm">
{payment.devices.map((device) => ( {payment.devices.map((device) => (
<li <li
key={device.id} key={device.id}
className="text-sm text-muted-foreground" className="text-sm text-muted-foreground"
> >
{device.name} {device.name}
</li> </li>
))} ))}
</ol> </ol>
</div> </div>
</div> </div>
</TableCell> </TableCell>
<TableCell className="font-medium"> <TableCell className="font-medium">
{payment.number_of_months} Months {payment.number_of_months} Months
</TableCell> </TableCell>
<TableCell> <TableCell>
<span className="font-semibold pr-2"> <span className="font-semibold pr-2">
{payment.paid ? ( {payment.paid ? (
<Badge <Badge
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"
> >
{payment.status} {payment.status}
</Badge> </Badge>
) : payment.is_expired ? ( ) : payment.is_expired ? (
<Badge>Expired</Badge> <Badge>Expired</Badge>
) : ( ) : (
<Badge variant="outline">{payment.status}</Badge> <Badge variant="outline">{payment.status}</Badge>
)} )}
</span> </span>
</TableCell> </TableCell>
<TableCell> <TableCell>
<span className="font-semibold pr-2"> <span className="font-semibold pr-2">
{payment.amount.toFixed(2)} {payment.amount.toFixed(2)}
</span> </span>
MVR MVR
</TableCell> </TableCell>
</TableRow> </TableRow>
))} ))}
</TableBody> </TableBody>
<TableFooter> <TableFooter>
<TableRow> <TableRow>
<TableCell colSpan={4} className="text-muted-foreground"> <TableCell colSpan={4} 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.
</p> </p>
) : ( ) : (
<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.last_page} totalPages={meta.last_page}
currentPage={meta.current_page} currentPage={meta.current_page}
/> />
</div> </div>
<div className="sm:hidden block"> <div className="sm:hidden block">
{data.map((payment) => ( {data.map((payment) => (
<MobilePaymentDetails key={payment.id} payment={payment} /> <MobilePaymentDetails key={payment.id} payment={payment} />
))} ))}
</div> </div>
</> </>
)} )}
</div> </div>
); );
} }
export function MobilePaymentDetails({ export function MobilePaymentDetails({
payment, payment,
isAdmin = false, isAdmin = false,
}: { }: {
payment: Payment; payment: Payment;
isAdmin?: boolean; isAdmin?: boolean;
}) { }) {
return ( return (
<div <div
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 : payment?.is_expired
? "bg-gray-500/10 border-dashed border-gray-500 dark:border-gray-500/50" ? "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",
)} )}
> >
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Calendar size={16} opacity={0.5} /> <Calendar size={16} opacity={0.5} />
<span className="text-muted-foreground text-sm"> <span className="text-muted-foreground text-sm">
{new Date(payment.created_at).toLocaleDateString("en-US", { {new Date(payment.created_at).toLocaleDateString("en-US", {
month: "short", month: "short",
day: "2-digit", day: "2-digit",
year: "numeric", year: "numeric",
minute: "2-digit", minute: "2-digit",
hour: "2-digit", hour: "2-digit",
timeZone: "Indian/Maldives", // Force consistent timezone timeZone: "Indian/Maldives", // Force consistent timezone
})} })}
</span> </span>
</div> </div>
<div className="flex items-center gap-2 mt-2"> <div className="flex items-center gap-2 mt-2">
<Link <Link
className="font-medium hover:underline" className="font-medium hover:underline"
href={`/payments/${payment.id}`} href={`/payments/${payment.id}`}
> >
<Button size={"sm"} variant="outline"> <Button size={"sm"} variant="outline">
View Details View Details
</Button> </Button>
</Link> </Link>
</div> </div>
<div className="bg-white dark:bg-black p-2 rounded mt-2 w-full border"> <div className="bg-white dark:bg-black p-2 rounded mt-2 w-full border">
<h3 className="text-sm font-medium">Devices</h3> <h3 className="text-sm font-medium">Devices</h3>
<ol className="list-disc list-inside text-sm"> <ol className="list-disc list-inside text-sm">
{payment.devices.map((device) => ( {payment.devices.map((device) => (
<li key={device.id} className="text-sm text-muted-foreground"> <li key={device.id} className="text-sm text-muted-foreground">
{device.name} {device.name}
</li> </li>
))} ))}
</ol> </ol>
<div className="block sm:hidden"> <div className="block sm:hidden">
<Separator className="my-2" /> <Separator className="my-2" />
<h3 className="text-sm font-medium">Duration</h3> <h3 className="text-sm font-medium">Duration</h3>
<span className="text-sm text-muted-foreground"> <span className="text-sm text-muted-foreground">
{payment.number_of_months} Months {payment.number_of_months} Months
</span> </span>
<Separator className="my-2" /> <Separator className="my-2" />
<h3 className="text-sm font-medium">Amount</h3> <h3 className="text-sm font-medium">Amount</h3>
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<span className="text-sm text-muted-foreground"> <span className="text-sm text-muted-foreground">
{payment.amount.toFixed(2)} MVR {payment.amount.toFixed(2)} MVR
</span> </span>
<span className="font-semibold pr-2"> <span className="font-semibold pr-2">
{payment.paid ? ( {payment.paid ? (
<Badge <Badge
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"
> >
{payment.status} {payment.status}
</Badge> </Badge>
) : payment.is_expired ? ( ) : payment.is_expired ? (
<Badge>Expired</Badge> <Badge>Expired</Badge>
) : ( ) : (
<Badge variant="secondary">{payment.status}</Badge> <Badge variant="secondary">{payment.status}</Badge>
)} )}
</span> </span>
{isAdmin && ( {isAdmin && (
<div className="my-2 text-primary flex flex-col items-start text-sm border rounded p-2 mt-2 w-full bg-white dark:bg-black"> <div className="my-2 text-primary flex flex-col items-start text-sm border rounded p-2 mt-2 w-full bg-white dark:bg-black">
{payment?.user?.name} {payment?.user?.name}
<span className="text-muted-foreground"> <span className="text-muted-foreground">
{payment?.user?.id_card} {payment?.user?.id_card}
</span> </span>
</div> </div>
)} )}
</div> </div>
</div> </div>
</div> </div>
</div> </div>
); );
} }

View File

@@ -1,8 +1,7 @@
"use client"; "use client";
import { Moon, Sun } from "lucide-react"; import { MonitorIcon, Moon, MoonIcon, Sun, SunIcon } from "lucide-react";
import { useTheme } from "next-themes"; import { useTheme } from "next-themes";
import * as React from "react";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { import {
@@ -25,14 +24,26 @@ export function ModeToggle() {
</Button> </Button>
</DropdownMenuTrigger> </DropdownMenuTrigger>
<DropdownMenuContent align="end"> <DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => setTheme("light")}> <DropdownMenuItem
className="flex justify-between items-center"
onClick={() => setTheme("light")}
>
Light Light
<SunIcon className="ml-2 h-4 w-4" />
</DropdownMenuItem> </DropdownMenuItem>
<DropdownMenuItem onClick={() => setTheme("dark")}> <DropdownMenuItem
className="flex justify-between items-center"
onClick={() => setTheme("dark")}
>
Dark Dark
<MoonIcon className="ml-2 h-4 w-4" />
</DropdownMenuItem> </DropdownMenuItem>
<DropdownMenuItem onClick={() => setTheme("system")}> <DropdownMenuItem
className="flex justify-between items-center"
onClick={() => setTheme("system")}
>
System System
<MonitorIcon className="ml-2 h-4 w-4" />
</DropdownMenuItem> </DropdownMenuItem>
</DropdownMenuContent> </DropdownMenuContent>
</DropdownMenu> </DropdownMenu>

View File

@@ -3,155 +3,155 @@ import { BadgeDollarSign, Loader2 } from "lucide-react";
import { useActionState, useEffect } from "react"; import { useActionState, useEffect } from "react";
import { toast } from "sonner"; import { toast } from "sonner";
import { import {
type VerifyTopupPaymentState, type VerifyTopupPaymentState,
verifyTopupPayment, verifyTopupPayment,
} from "@/actions/payment"; } from "@/actions/payment";
import { import {
Table, Table,
TableBody, TableBody,
TableCaption, TableCaption,
TableCell, TableCell,
TableFooter, TableFooter,
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 { 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({ export default function TopupToPay({
topup, topup,
disabled, disabled,
}: { }: {
topup?: Topup; topup?: Topup;
disabled?: boolean; disabled?: boolean;
}) { }) {
const [state, formAction, isPending] = useActionState( const [state, formAction, isPending] = useActionState(
verifyTopupPayment, verifyTopupPayment,
initialState, initialState,
); );
// Handle toast notifications based on state changes // Handle toast notifications based on state changes
useEffect(() => { useEffect(() => {
if (state.success && state.message) { if (state.success && state.message) {
toast.success("Topup successful!", { toast.success("Topup successful!", {
closeButton: true, closeButton: true,
description: state.transaction description: state.transaction
? `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 ( } else if (
!state.success && !state.success &&
state.message && state.message &&
state.message !== initialState.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,
}); });
} }
}, [state]); }, [state]);
return ( return (
<div className="w-full"> <div className="w-full">
<div className="m-2 flex items-end justify-end p-2 text-sm text-foreground border rounded"> <div className="m-2 flex items-end justify-end p-2 text-sm text-foreground border rounded">
<Table> <Table>
<TableCaption> <TableCaption>
{(!topup?.paid || {(!topup?.paid ||
!topup?.is_expired || !topup?.is_expired ||
topup?.status !== "CANCELLED") && ( topup?.status !== "CANCELLED") && (
<div className="max-w-sm mx-auto"> <div className="max-w-sm mx-auto">
<p>Please send the following amount to the payment address</p> <p>Please send the following amount to the payment address</p>
<AccountInfomation <AccountInfomation
accName="Baraveli Dev" accName="Baraveli Dev"
accountNo="90101400028321000" accountNo="90101400028321000"
/> />
{topup?.paid ? ( {topup?.paid ? (
<Button <Button
size={"lg"} size={"lg"}
variant={"secondary"} variant={"secondary"}
disabled disabled
className="dark:text-green-200 text-green-900 bg-green-500/20 uppercase font-semibold" className="dark:text-green-200 text-green-900 bg-green-500/20 uppercase font-semibold"
> >
Topup Payment Verified Topup Payment Verified
</Button> </Button>
) : ( ) : (
<div className="flex flex-col gap-2"> <div className="flex flex-col gap-2">
<form action={formAction}> <form action={formAction}>
<input <input
type="hidden" type="hidden"
name="topupId" name="topupId"
value={topup?.id ?? ""} value={topup?.id ?? ""}
/> />
<Button <Button
disabled={disabled || isPending} disabled={disabled || isPending}
type="submit" type="submit"
size={"lg"} size={"lg"}
className="mb-4 w-full" className="mb-4 w-full"
> >
{isPending ? "Processing payment..." : "I have paid"} {isPending ? "Processing payment..." : "I have paid"}
{isPending ? ( {isPending ? (
<Loader2 className="animate-spin" /> <Loader2 className="animate-spin" />
) : ( ) : (
<BadgeDollarSign /> <BadgeDollarSign />
)} )}
</Button> </Button>
</form> </form>
</div> </div>
)} )}
</div> </div>
)} )}
</TableCaption> </TableCaption>
<TableBody className=""> <TableBody className="">
<TableRow> <TableRow>
<TableCell>Topup created</TableCell> <TableCell>Topup created</TableCell>
<TableCell className="text-right text-muted-foreground"> <TableCell className="text-right text-muted-foreground">
{new Date(topup?.created_at ?? "").toLocaleDateString("en-US", { {new Date(topup?.created_at ?? "").toLocaleDateString("en-US", {
month: "short", month: "short",
day: "2-digit", day: "2-digit",
year: "numeric", year: "numeric",
minute: "2-digit", minute: "2-digit",
hour: "2-digit", hour: "2-digit",
second: "2-digit", second: "2-digit",
})} })}
</TableCell> </TableCell>
</TableRow> </TableRow>
<TableRow> <TableRow>
<TableCell>Payment received</TableCell> <TableCell>Payment received</TableCell>
<TableCell className="text-right text-sarLinkOrange"> <TableCell className="text-right text-sarLinkOrange">
{topup?.paid_at {topup?.paid_at
? new Date(topup.paid_at).toLocaleDateString("en-US", { ? new Date(topup.paid_at).toLocaleDateString("en-US", {
month: "short", month: "short",
day: "2-digit", day: "2-digit",
year: "numeric", year: "numeric",
minute: "2-digit", minute: "2-digit",
hour: "2-digit", hour: "2-digit",
second: "2-digit", second: "2-digit",
}) })
: "-"} : "-"}
</TableCell> </TableCell>
</TableRow> </TableRow>
<TableRow> <TableRow>
<TableCell>MIB Reference</TableCell> <TableCell>MIB Reference</TableCell>
<TableCell className="text-right"> <TableCell className="text-right">
{topup?.mib_reference ? topup.mib_reference : "-"} {topup?.mib_reference ? topup.mib_reference : "-"}
</TableCell> </TableCell>
</TableRow> </TableRow>
</TableBody> </TableBody>
<TableFooter> <TableFooter>
<TableRow className=""> <TableRow className="">
<TableCell colSpan={1}>Total Due</TableCell> <TableCell colSpan={1}>Total Due</TableCell>
<TableCell className="text-right text-3xl font-bold"> <TableCell className="text-right text-3xl font-bold">
{topup?.amount?.toFixed(2)} {topup?.amount?.toFixed(2)}
</TableCell> </TableCell>
</TableRow> </TableRow>
</TableFooter> </TableFooter>
</Table> </Table>
</div> </div>
</div> </div>
); );
} }

View File

@@ -3,13 +3,13 @@ import Link from "next/link";
import { redirect } from "next/navigation"; import { redirect } from "next/navigation";
import { getTopups } from "@/actions/payment"; import { getTopups } from "@/actions/payment";
import { import {
Table, Table,
TableBody, TableBody,
TableCell, TableCell,
TableFooter, TableFooter,
TableHead, TableHead,
TableHeader, TableHeader,
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 { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
@@ -19,199 +19,199 @@ import { Badge } from "./ui/badge";
import { Button } from "./ui/button"; import { Button } from "./ui/button";
export async function TopupsTable({ export async function TopupsTable({
searchParams, searchParams,
}: { }: {
searchParams: Promise<{ searchParams: Promise<{
[key: string]: unknown; [key: string]: unknown;
}>; }>;
}) { }) {
const resolvedParams = await searchParams; const resolvedParams = await searchParams;
const page = Number.parseInt(resolvedParams.page as string) || 1; const page = Number.parseInt(resolvedParams.page as string) || 1;
const limit = 10; const limit = 10;
const offset = (page - 1) * limit; 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)) {
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.limit = limit;
apiParams.offset = offset; apiParams.offset = offset;
const [error, topups] = await tryCatch(getTopups(apiParams)); const [error, topups] = await tryCatch(getTopups(apiParams));
if (error) { if (error) {
if (error.message.includes("Unauthorized")) { if (error.message.includes("Unauthorized")) {
redirect("/auth/signin"); redirect("/auth/signin");
} else { } else {
return <pre>{JSON.stringify(error, null, 2)}</pre>; return <pre>{JSON.stringify(error, null, 2)}</pre>;
} }
} }
const { data, meta } = topups; const { data, meta } = topups;
return ( return (
<div> <div>
{data?.length === 0 ? ( {data?.length === 0 ? (
<div className="h-[calc(100svh-400px)] flex text-muted-foreground flex-col items-center justify-center my-4"> <div className="h-[calc(100svh-400px)] flex text-muted-foreground flex-col items-center justify-center my-4">
<h3>No topups.</h3> <h3>No topups.</h3>
</div> </div>
) : ( ) : (
<> <>
<div className="hidden sm:block"> <div className="hidden sm:block">
<Table className="overflow-scroll"> <Table className="overflow-scroll">
<TableHeader> <TableHeader>
<TableRow> <TableRow>
<TableHead>Details</TableHead> <TableHead>Details</TableHead>
<TableHead>Status</TableHead> <TableHead>Status</TableHead>
<TableHead>Amount</TableHead> <TableHead>Amount</TableHead>
</TableRow> </TableRow>
</TableHeader> </TableHeader>
<TableBody className="overflow-scroll"> <TableBody className="overflow-scroll">
{topups?.data?.map((topup) => ( {topups?.data?.map((topup) => (
<TableRow key={topup.id}> <TableRow key={topup.id}>
<TableCell> <TableCell>
<div <div
className={cn( className={cn(
"flex flex-col items-start border rounded p-2", "flex flex-col items-start border rounded p-2",
topup?.paid topup?.paid
? "bg-green-500/10 border-dashed border-green-500" ? "bg-green-500/10 border-dashed border-green-500"
: topup?.is_expired : topup?.is_expired
? "bg-gray-500/10 border-dashed border-gray-500 dark:border-gray-500/50" ? "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",
)} )}
> >
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Calendar size={16} opacity={0.5} /> <Calendar size={16} opacity={0.5} />
<span className="text-muted-foreground"> <span className="text-muted-foreground">
{new Date(topup.created_at).toLocaleDateString( {new Date(topup.created_at).toLocaleDateString(
"en-US", "en-US",
{ {
month: "short", month: "short",
day: "2-digit", day: "2-digit",
year: "numeric", year: "numeric",
minute: "2-digit", minute: "2-digit",
hour: "2-digit", hour: "2-digit",
}, },
)} )}
</span> </span>
</div> </div>
<div className="flex items-center gap-2 mt-2"> <div className="flex items-center gap-2 mt-2">
<Link <Link
className="font-medium hover:underline" className="font-medium hover:underline"
href={`/top-ups/${topup.id}`} href={`/top-ups/${topup.id}`}
> >
<Button size={"sm"} variant="outline"> <Button size={"sm"} variant="outline">
View Details View Details
</Button> </Button>
</Link> </Link>
</div> </div>
</div> </div>
</TableCell> </TableCell>
<TableCell> <TableCell>
<span className="font-semibold pr-2"> <span className="font-semibold pr-2">
{topup.paid ? ( {topup.paid ? (
<Badge <Badge
className="bg-green-100 dark:bg-green-700" className="bg-green-100 dark:bg-green-700"
variant="outline" variant="outline"
> >
{topup.status} {topup.status}
</Badge> </Badge>
) : topup.is_expired ? ( ) : topup.is_expired ? (
<Badge>Expired</Badge> <Badge>Expired</Badge>
) : ( ) : (
<Badge variant="outline">{topup.status}</Badge> <Badge variant="outline">{topup.status}</Badge>
)} )}
</span> </span>
</TableCell> </TableCell>
<TableCell> <TableCell>
<span className="font-semibold pr-2"> <span className="font-semibold pr-2">
{topup.amount.toFixed(2)} {topup.amount.toFixed(2)}
</span> </span>
MVR MVR
</TableCell> </TableCell>
</TableRow> </TableRow>
))} ))}
</TableBody> </TableBody>
<TableFooter> <TableFooter>
<TableRow> <TableRow>
<TableCell colSpan={4} className="text-muted-foreground"> <TableCell colSpan={4} className="text-muted-foreground">
{meta?.total === 1 ? ( {meta?.total === 1 ? (
<p className="text-center">Total {meta?.total} topup.</p> <p className="text-center">Total {meta?.total} topup.</p>
) : ( ) : (
<p className="text-center">Total {meta?.total} topups.</p> <p className="text-center">Total {meta?.total} topups.</p>
)} )}
</TableCell> </TableCell>
</TableRow> </TableRow>
</TableFooter> </TableFooter>
</Table> </Table>
</div> </div>
<div className="sm:hidden block"> <div className="sm:hidden block">
{data.map((topup) => ( {data.map((topup) => (
<MobileTopupDetails key={topup.id} topup={topup} /> <MobileTopupDetails key={topup.id} topup={topup} />
))} ))}
</div> </div>
<Pagination <Pagination
totalPages={meta?.last_page} totalPages={meta?.last_page}
currentPage={meta?.current_page} currentPage={meta?.current_page}
/> />
</> </>
)} )}
</div> </div>
); );
} }
function MobileTopupDetails({ topup }: { topup: Topup }) { function MobileTopupDetails({ topup }: { topup: Topup }) {
return ( return (
<div <div
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",
topup?.paid topup?.paid
? "bg-green-500/10 border-dashed border-green=500" ? "bg-green-500/10 border-dashed border-green=500"
: "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",
)} )}
> >
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Calendar size={16} opacity={0.5} /> <Calendar size={16} opacity={0.5} />
<span className="text-muted-foreground text-sm"> <span className="text-muted-foreground text-sm">
{new Date(topup.created_at).toLocaleDateString("en-US", { {new Date(topup.created_at).toLocaleDateString("en-US", {
month: "short", month: "short",
day: "2-digit", day: "2-digit",
year: "numeric", year: "numeric",
})} })}
</span> </span>
</div> </div>
<div className="flex items-center gap-2 mt-2"> <div className="flex items-center gap-2 mt-2">
<Link <Link
className="font-medium hover:underline" className="font-medium hover:underline"
href={`/top-ups/${topup.id}`} href={`/top-ups/${topup.id}`}
> >
<Button size={"sm"} variant="outline"> <Button size={"sm"} variant="outline">
View Details View Details
</Button> </Button>
</Link> </Link>
</div> </div>
<div className="bg-white dark:bg-black p-2 rounded mt-2 w-full border flex justify-between items-center"> <div className="bg-white dark:bg-black p-2 rounded mt-2 w-full border flex justify-between items-center">
<div className="block sm:hidden"> <div className="block sm:hidden">
<h3 className="text-sm font-medium">Amount</h3> <h3 className="text-sm font-medium">Amount</h3>
<span className="text-sm text-muted-foreground"> <span className="text-sm text-muted-foreground">
{topup.amount.toFixed(2)} MVR {topup.amount.toFixed(2)} MVR
</span> </span>
</div> </div>
<span className="font-semibold pr-2"> <span className="font-semibold pr-2">
{topup.paid ? ( {topup.paid ? (
<Badge className="bg-green-100 dark:bg-green-700" variant="outline"> <Badge className="bg-green-100 dark:bg-green-700" variant="outline">
{topup.status} {topup.status}
</Badge> </Badge>
) : topup.is_expired ? ( ) : topup.is_expired ? (
<Badge>Expired</Badge> <Badge>Expired</Badge>
) : ( ) : (
<Badge variant="secondary">{topup.status}</Badge> <Badge variant="secondary">{topup.status}</Badge>
)} )}
</span> </span>
</div> </div>
</div> </div>
); );
} }

View File

@@ -1,226 +1,226 @@
import { import {
BadgePlus, BadgePlus,
Calculator, Calculator,
ChevronRight, ChevronRight,
Coins, Coins,
CreditCard, CreditCard,
Handshake, Handshake,
MonitorSpeaker, MonitorSpeaker,
Smartphone, Smartphone,
UsersRound, UsersRound,
Wallet2Icon, Wallet2Icon,
} from "lucide-react"; } from "lucide-react";
import Link from "next/link"; import Link from "next/link";
import { getServerSession } from "next-auth"; import { getServerSession } from "next-auth";
import { authOptions } from "@/app/auth"; import { authOptions } from "@/app/auth";
import { import {
Collapsible, Collapsible,
CollapsibleContent, CollapsibleContent,
CollapsibleTrigger, CollapsibleTrigger,
} from "@/components/ui/collapsible"; } from "@/components/ui/collapsible";
import { import {
Sidebar, Sidebar,
SidebarContent, SidebarContent,
SidebarGroup, SidebarGroup,
SidebarGroupContent, SidebarGroupContent,
SidebarGroupLabel, SidebarGroupLabel,
SidebarHeader, SidebarHeader,
SidebarMenu, SidebarMenu,
SidebarMenuButton, SidebarMenuButton,
SidebarMenuItem, SidebarMenuItem,
SidebarRail, SidebarRail,
} from "@/components/ui/sidebar"; } from "@/components/ui/sidebar";
type Permission = { type Permission = {
id: number; id: number;
name: string; name: string;
}; };
type Categories = { type Categories = {
id: string; id: string;
children: ( children: (
| { | {
title: string; title: string;
link: string; link: string;
perm_identifier: string; perm_identifier: string;
icon: React.JSX.Element; icon: React.JSX.Element;
} }
| { | {
title: string; title: string;
link: string; link: string;
icon: React.JSX.Element; icon: React.JSX.Element;
perm_identifier?: undefined; perm_identifier?: undefined;
} }
)[]; )[];
}[]; }[];
export async function AppSidebar({ export async function AppSidebar({
...props ...props
}: React.ComponentProps<typeof Sidebar>) { }: React.ComponentProps<typeof Sidebar>) {
const categories = [ const categories = [
{ {
id: "MENU", id: "MENU",
url: "#", url: "#",
children: [ children: [
{ {
title: "Devices", title: "Devices",
link: "/devices?page=1", link: "/devices?page=1",
perm_identifier: "device", perm_identifier: "device",
icon: <Smartphone size={16} />, icon: <Smartphone size={16} />,
}, },
{ {
title: "Parental Control", title: "Parental Control",
link: "/parental-control?page=1", link: "/parental-control?page=1",
icon: <CreditCard size={16} />, icon: <CreditCard size={16} />,
perm_identifier: "device", perm_identifier: "device",
}, },
{ {
title: "Subscriptions", title: "Subscriptions",
link: "/payments?page=1", link: "/payments?page=1",
icon: <CreditCard size={16} />, icon: <CreditCard size={16} />,
perm_identifier: "payment", perm_identifier: "payment",
}, },
{ {
title: "Top Ups", title: "Top Ups",
link: "/top-ups?page=1", link: "/top-ups?page=1",
icon: <BadgePlus size={16} />, icon: <BadgePlus size={16} />,
perm_identifier: "topup", perm_identifier: "topup",
}, },
{ {
title: "Transaction History", title: "Transaction History",
link: "/wallet", link: "/wallet",
icon: <Wallet2Icon size={16} />, icon: <Wallet2Icon size={16} />,
perm_identifier: "wallet transaction", perm_identifier: "wallet transaction",
}, },
{ {
title: "Agreements", title: "Agreements",
link: "/agreements", link: "/agreements",
icon: <Handshake size={16} />, icon: <Handshake size={16} />,
perm_identifier: "device", perm_identifier: "device",
}, },
], ],
}, },
{ {
id: "ADMIN CONTROL", id: "ADMIN CONTROL",
url: "#", url: "#",
children: [ children: [
{ {
title: "Users", title: "Users",
link: "/users", link: "/users",
icon: <UsersRound size={16} />, icon: <UsersRound size={16} />,
perm_identifier: "device", perm_identifier: "device",
}, },
{ {
title: "User Devices", title: "User Devices",
link: "/user-devices", link: "/user-devices",
icon: <MonitorSpeaker size={16} />, icon: <MonitorSpeaker size={16} />,
perm_identifier: "device", perm_identifier: "device",
}, },
{ {
title: "User Payments", title: "User Payments",
link: "/user-payments", link: "/user-payments",
icon: <Coins size={16} />, icon: <Coins size={16} />,
perm_identifier: "payment", perm_identifier: "payment",
}, },
{ {
title: "User Topups", title: "User Topups",
link: "/user-topups", link: "/user-topups",
icon: <Coins size={16} />, icon: <Coins size={16} />,
perm_identifier: "topup", perm_identifier: "topup",
}, },
{ {
title: "Price Calculator", title: "Price Calculator",
link: "/price-calculator", link: "/price-calculator",
icon: <Calculator size={16} />, icon: <Calculator size={16} />,
perm_identifier: "device", perm_identifier: "device",
}, },
], ],
}, },
]; ];
const session = await getServerSession(authOptions); const session = await getServerSession(authOptions);
let CATEGORIES: Categories; let CATEGORIES: Categories;
if (session?.user?.is_admin) { if (session?.user?.is_admin) {
CATEGORIES = categories; CATEGORIES = categories;
} else { } else {
// Filter out ADMIN CONTROL category for non-admin users // Filter out ADMIN CONTROL category for non-admin users
const nonAdminCategories = categories.filter( const nonAdminCategories = categories.filter(
(category) => category.id !== "ADMIN CONTROL", (category) => category.id !== "ADMIN CONTROL",
); );
const filteredCategories = nonAdminCategories.map((category) => { const filteredCategories = nonAdminCategories.map((category) => {
const filteredChildren = category.children.filter((child) => { const filteredChildren = category.children.filter((child) => {
const permIdentifier = child.perm_identifier; const permIdentifier = child.perm_identifier;
return session?.user?.user_permissions?.some( return session?.user?.user_permissions?.some(
(permission: Permission) => { (permission: Permission) => {
const permissionParts = permission.name.split(" "); const permissionParts = permission.name.split(" ");
const modelNameFromPermission = permissionParts.slice(2).join(" "); const modelNameFromPermission = permissionParts.slice(2).join(" ");
return modelNameFromPermission === permIdentifier; return modelNameFromPermission === permIdentifier;
}, },
); );
}); });
return { ...category, children: filteredChildren }; return { ...category, children: filteredChildren };
}); });
CATEGORIES = filteredCategories.filter( CATEGORIES = filteredCategories.filter(
(category) => category.children.length > 0, (category) => category.children.length > 0,
); );
} }
return ( return (
<Sidebar {...props} className="z-50"> <Sidebar {...props} className="z-50">
<SidebarHeader> <SidebarHeader>
<h4 className="p-2 rounded title-bg border text-center uppercase "> <h4 className="p-2 rounded title-bg border text-center uppercase ">
Sar Link Portal Sar Link Portal
</h4> </h4>
</SidebarHeader> </SidebarHeader>
<SidebarContent className="gap-0"> <SidebarContent className="gap-0">
{CATEGORIES.map((item) => { {CATEGORIES.map((item) => {
return ( return (
<Collapsible <Collapsible
key={item.id} key={item.id}
title={item.id} title={item.id}
defaultOpen defaultOpen
className="group/collapsible" className="group/collapsible"
> >
<SidebarGroup> <SidebarGroup>
<SidebarGroupLabel <SidebarGroupLabel
asChild asChild
className="group/label text-sm text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground" className="group/label text-sm text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground"
> >
<CollapsibleTrigger> <CollapsibleTrigger>
{item.id}{" "} {item.id}{" "}
<ChevronRight className="ml-auto transition-transform group-data-[state=open]/collapsible:rotate-90" /> <ChevronRight className="ml-auto transition-transform group-data-[state=open]/collapsible:rotate-90" />
</CollapsibleTrigger> </CollapsibleTrigger>
</SidebarGroupLabel> </SidebarGroupLabel>
<CollapsibleContent> <CollapsibleContent>
<SidebarGroupContent> <SidebarGroupContent>
<SidebarMenu> <SidebarMenu>
{item.children.map((item) => ( {item.children.map((item) => (
<SidebarMenuItem key={item.title}> <SidebarMenuItem key={item.title}>
<SidebarMenuButton className="py-6" asChild> <SidebarMenuButton className="py-6" asChild>
<Link className="text-md" href={item.link}> <Link className="text-md" href={item.link}>
{item.icon} {item.icon}
<span <span
className={`opacity-70 motion-preset-slide-left-md ml-2`} className={`opacity-70 motion-preset-slide-left-md ml-2`}
> >
{item.title} {item.title}
</span> </span>
</Link> </Link>
</SidebarMenuButton> </SidebarMenuButton>
</SidebarMenuItem> </SidebarMenuItem>
))} ))}
</SidebarMenu> </SidebarMenu>
</SidebarGroupContent> </SidebarGroupContent>
</CollapsibleContent> </CollapsibleContent>
</SidebarGroup> </SidebarGroup>
</Collapsible> </Collapsible>
); );
})} })}
</SidebarContent> </SidebarContent>
<SidebarRail /> <SidebarRail />
</Sidebar> </Sidebar>
); );
} }

View File

@@ -51,7 +51,7 @@ const sheetVariants = cva(
interface SheetContentProps interface SheetContentProps
extends React.ComponentPropsWithoutRef<typeof SheetPrimitive.Content>, extends React.ComponentPropsWithoutRef<typeof SheetPrimitive.Content>,
VariantProps<typeof sheetVariants> { } VariantProps<typeof sheetVariants> {}
const SheetContent = React.forwardRef< const SheetContent = React.forwardRef<
React.ElementRef<typeof SheetPrimitive.Content>, React.ElementRef<typeof SheetPrimitive.Content>,

View File

@@ -631,7 +631,7 @@ const SidebarMenuAction = React.forwardRef<
"peer-data-[size=lg]/menu-button:top-2.5", "peer-data-[size=lg]/menu-button:top-2.5",
"group-data-[collapsible=icon]:hidden", "group-data-[collapsible=icon]:hidden",
showOnHover && showOnHover &&
"group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 peer-data-[active=true]/menu-button:text-sidebar-accent-foreground md:opacity-0", "group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 peer-data-[active=true]/menu-button:text-sidebar-accent-foreground md:opacity-0",
className, className,
)} )}
{...props} {...props}

View File

@@ -7,134 +7,134 @@ import Pagination from "./pagination";
import { Badge } from "./ui/badge"; import { Badge } from "./ui/badge";
import { Button } from "./ui/button"; import { Button } from "./ui/button";
import { import {
Table, Table,
TableBody, TableBody,
TableCell, TableCell,
TableFooter, TableFooter,
TableHead, TableHead,
TableHeader, TableHeader,
TableRow, TableRow,
} from "./ui/table"; } from "./ui/table";
export async function UsersTable({ export async function UsersTable({
searchParams, searchParams,
}: { }: {
searchParams: Promise<{ searchParams: Promise<{
[key: string]: unknown; [key: string]: unknown;
}>; }>;
}) { }) {
const resolvedParams = await searchParams; const resolvedParams = await searchParams;
const page = Number.parseInt(resolvedParams.page as string) || 1; const page = Number.parseInt(resolvedParams.page as string) || 1;
const limit = 10; const limit = 10;
const offset = (page - 1) * limit; 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.limit = limit;
apiParams.offset = offset; apiParams.offset = offset;
const [error, users] = await tryCatch(getUsers(apiParams)); const [error, users] = await tryCatch(getUsers(apiParams));
if (error) { if (error) {
if (error.message === "UNAUTHORIZED") { if (error.message === "UNAUTHORIZED") {
redirect("/auth/signin"); redirect("/auth/signin");
} }
return <ClientErrorMessage message={error.message} />; return <ClientErrorMessage message={error.message} />;
} }
const { meta, data } = users; const { meta, data } = users;
// return null; // return null;
return ( return (
<div> <div>
{users?.data.length === 0 ? ( {users?.data.length === 0 ? (
<div className="h-[calc(100svh-400px)] flex flex-col items-center justify-center my-4"> <div className="h-[calc(100svh-400px)] flex flex-col items-center justify-center my-4">
<h3>No Users yet.</h3> <h3>No Users yet.</h3>
</div> </div>
) : ( ) : (
<> <>
<Table className="overflow-scroll"> <Table className="overflow-scroll">
<TableHeader> <TableHeader>
<TableRow> <TableRow>
<TableHead>Name</TableHead> <TableHead>Name</TableHead>
<TableHead>ID Card</TableHead> <TableHead>ID Card</TableHead>
<TableHead>Atoll</TableHead> <TableHead>Atoll</TableHead>
<TableHead>Island</TableHead> <TableHead>Island</TableHead>
<TableHead>House Name</TableHead> <TableHead>House Name</TableHead>
<TableHead>Status</TableHead> <TableHead>Status</TableHead>
<TableHead>Dob</TableHead> <TableHead>Dob</TableHead>
<TableHead>Phone Number</TableHead> <TableHead>Phone Number</TableHead>
<TableHead>Action</TableHead> <TableHead>Action</TableHead>
</TableRow> </TableRow>
</TableHeader> </TableHeader>
<TableBody className="overflow-scroll"> <TableBody className="overflow-scroll">
{data.map((user) => ( {data.map((user) => (
<TableRow <TableRow
className={`${user.verified && "title-bg dark:bg-black"}`} className={`${user.verified && "title-bg dark:bg-black"}`}
key={user.id} key={user.id}
> >
<TableCell className="font-medium"> <TableCell className="font-medium">
{user.first_name} {user.last_name} {user.first_name} {user.last_name}
</TableCell> </TableCell>
<TableCell className="font-medium">{user.id_card}</TableCell> <TableCell className="font-medium">{user.id_card}</TableCell>
<TableCell>{user.atoll?.name}</TableCell> <TableCell>{user.atoll?.name}</TableCell>
<TableCell>{user.island?.name}</TableCell> <TableCell>{user.island?.name}</TableCell>
<TableCell>{user.address}</TableCell> <TableCell>{user.address}</TableCell>
<TableCell> <TableCell>
{user.verified ? ( {user.verified ? (
<Badge <Badge
variant="outline" variant="outline"
className="bg-lime-100 text-black" className="bg-lime-100 text-black"
> >
Verified Verified
</Badge> </Badge>
) : ( ) : (
<Badge <Badge
variant="outline" variant="outline"
className="bg-yellow-100 text-black" className="bg-yellow-100 text-black"
> >
Unverified Unverified
</Badge> </Badge>
)} )}
</TableCell> </TableCell>
<TableCell> <TableCell>
{new Date(user.dob ?? "").toLocaleDateString("en-US", { {new Date(user.dob ?? "").toLocaleDateString("en-US", {
month: "short", month: "short",
day: "2-digit", day: "2-digit",
year: "numeric", year: "numeric",
})} })}
</TableCell> </TableCell>
<TableCell>{user.mobile}</TableCell> <TableCell>{user.mobile}</TableCell>
<TableCell> <TableCell>
<Link href={`/users/${user.id}/details`}> <Link href={`/users/${user.id}/details`}>
<Button>Details</Button> <Button>Details</Button>
</Link> </Link>
</TableCell> </TableCell>
</TableRow> </TableRow>
))} ))}
</TableBody> </TableBody>
<TableFooter> <TableFooter>
<TableRow> <TableRow>
<TableCell colSpan={9}> <TableCell colSpan={9}>
{meta?.total === 1 ? ( {meta?.total === 1 ? (
<p className="text-center">Total {meta?.total} user.</p> <p className="text-center">Total {meta?.total} user.</p>
) : ( ) : (
<p className="text-center">Total {meta?.total} users.</p> <p className="text-center">Total {meta?.total} users.</p>
)} )}
</TableCell> </TableCell>
</TableRow> </TableRow>
</TableFooter> </TableFooter>
</Table> </Table>
<Pagination <Pagination
totalPages={meta?.last_page} totalPages={meta?.last_page}
currentPage={meta?.current_page} currentPage={meta?.current_page}
/> />
</> </>
)} )}
</div> </div>
); );
} }

View File

@@ -2,13 +2,13 @@ import { Calendar } from "lucide-react";
import Link from "next/link"; import Link from "next/link";
import { redirect } from "next/navigation"; import { redirect } from "next/navigation";
import { import {
Table, Table,
TableBody, TableBody,
TableCell, TableCell,
TableFooter, TableFooter,
TableHead, TableHead,
TableHeader, TableHeader,
TableRow, TableRow,
} from "@/components/ui/table"; } from "@/components/ui/table";
import type { WalletTransaction } from "@/lib/backend-types"; import type { WalletTransaction } from "@/lib/backend-types";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
@@ -19,223 +19,223 @@ import { Badge } from "./ui/badge";
import { Button } from "./ui/button"; import { Button } from "./ui/button";
export async function WalletTransactionsTable({ export async function WalletTransactionsTable({
searchParams, searchParams,
}: { }: {
searchParams: Promise<{ searchParams: Promise<{
[key: string]: unknown; [key: string]: unknown;
}>; }>;
}) { }) {
const resolvedParams = await searchParams; const resolvedParams = await searchParams;
const page = Number.parseInt(resolvedParams.page as string) || 1; const page = Number.parseInt(resolvedParams.page as string) || 1;
const limit = 10; const limit = 10;
const offset = (page - 1) * limit; 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)) {
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.limit = limit;
apiParams.offset = offset; apiParams.offset = offset;
const [error, transactions] = await tryCatch( const [error, transactions] = await tryCatch(
getWaleltTransactions(apiParams), getWaleltTransactions(apiParams),
); );
if (error) { if (error) {
if (error.message.includes("Unauthorized")) { if (error.message.includes("Unauthorized")) {
redirect("/auth/signin"); redirect("/auth/signin");
} else { } else {
return <pre>{JSON.stringify(error, null, 2)}</pre>; return <pre>{JSON.stringify(error, null, 2)}</pre>;
} }
} }
const { data, meta } = transactions; const { data, meta } = transactions;
const totalDebit = data.reduce( const totalDebit = data.reduce(
(acc, trx) => acc + (trx.transaction_type === "DEBIT" ? trx.amount : 0), (acc, trx) => acc + (trx.transaction_type === "DEBIT" ? trx.amount : 0),
0, 0,
); );
const totalCredit = data.reduce( const totalCredit = data.reduce(
(acc, trx) => acc + (trx.transaction_type === "TOPUP" ? trx.amount : 0), (acc, trx) => acc + (trx.transaction_type === "TOPUP" ? trx.amount : 0),
0, 0,
); );
return ( return (
<div> <div>
{data?.length === 0 ? ( {data?.length === 0 ? (
<div className="h-[calc(100svh-400px)] flex flex-col items-center justify-center my-4"> <div className="h-[calc(100svh-400px)] flex flex-col items-center justify-center my-4">
<h3>No transactions yet.</h3> <h3>No transactions yet.</h3>
</div> </div>
) : ( ) : (
<div> <div>
<div className="flex gap-4 mb-4 w-full"> <div className="flex gap-4 mb-4 w-full">
<div className="bg-red-400 w-full sm:w-fit dark:bg-red-950 dark:text-red-400 text-red-900 p-2 px-4 rounded-md mb-2"> <div className="bg-red-400 w-full sm:w-fit dark:bg-red-950 dark:text-red-400 text-red-900 p-2 px-4 rounded-md mb-2">
<h5 className="text-lg font-semibold">Total Debit</h5> <h5 className="text-lg font-semibold">Total Debit</h5>
<p>{totalDebit.toFixed(2)} MVR</p> <p>{totalDebit.toFixed(2)} MVR</p>
</div> </div>
<div className="bg-green-400 w-full sm:w-fit dark:bg-green-950 dark:text-green-400 text-green-900 p-2 px-4 rounded-md mb-2"> <div className="bg-green-400 w-full sm:w-fit dark:bg-green-950 dark:text-green-400 text-green-900 p-2 px-4 rounded-md mb-2">
<h5 className="text-lg font-semibold">Total Credit</h5> <h5 className="text-lg font-semibold">Total Credit</h5>
<p>{totalCredit.toFixed(2)} MVR</p> <p>{totalCredit.toFixed(2)} MVR</p>
</div> </div>
</div> </div>
<div className="hidden sm:block"> <div className="hidden sm:block">
<Table className="overflow-scroll"> <Table className="overflow-scroll">
<TableHeader> <TableHeader>
<TableRow> <TableRow>
<TableHead>Description</TableHead> <TableHead>Description</TableHead>
<TableHead>Amount</TableHead> <TableHead>Amount</TableHead>
<TableHead>Transaction Type</TableHead> <TableHead>Transaction Type</TableHead>
<TableHead>View Details</TableHead> <TableHead>View Details</TableHead>
<TableHead>Created at</TableHead> <TableHead>Created at</TableHead>
</TableRow> </TableRow>
</TableHeader> </TableHeader>
<TableBody className="overflow-scroll"> <TableBody className="overflow-scroll">
{transactions?.data?.map((trx) => ( {transactions?.data?.map((trx) => (
<TableRow <TableRow
className={cn( className={cn(
"items-start border rounded p-2", "items-start border rounded p-2",
trx?.transaction_type === "TOPUP" trx?.transaction_type === "TOPUP"
? "credit-bg" ? "credit-bg"
: "debit-bg", : "debit-bg",
)} )}
key={trx.id} key={trx.id}
> >
<TableCell> <TableCell>
<span className="text-muted-foreground"> <span className="text-muted-foreground">
{trx.description} {trx.description}
</span> </span>
</TableCell> </TableCell>
<TableCell>{trx.amount.toFixed(2)} MVR</TableCell> <TableCell>{trx.amount.toFixed(2)} MVR</TableCell>
<TableCell> <TableCell>
<span className="font-semibold pr-2"> <span className="font-semibold pr-2">
{trx.transaction_type === "TOPUP" ? ( {trx.transaction_type === "TOPUP" ? (
<Badge className="bg-green-100 text-green-950 dark:bg-green-700"> <Badge className="bg-green-100 text-green-950 dark:bg-green-700">
{trx.transaction_type} {trx.transaction_type}
</Badge> </Badge>
) : ( ) : (
<Badge className="bg-red-500 text-red-950 dark:bg-red-700"> <Badge className="bg-red-500 text-red-950 dark:bg-red-700">
{trx.transaction_type} {trx.transaction_type}
</Badge> </Badge>
)} )}
</span> </span>
</TableCell> </TableCell>
<TableCell> <TableCell>
<span className=""> <span className="">
{new Date(trx.created_at).toLocaleDateString("en-US", { {new Date(trx.created_at).toLocaleDateString("en-US", {
month: "short", month: "short",
day: "2-digit", day: "2-digit",
year: "numeric", year: "numeric",
minute: "2-digit", minute: "2-digit",
hour: "2-digit", hour: "2-digit",
})} })}
</span> </span>
</TableCell> </TableCell>
<TableCell> <TableCell>
<Button> <Button>
<Link <Link
className="font-medium " className="font-medium "
href={ href={
trx.transaction_type === "TOPUP" trx.transaction_type === "TOPUP"
? `/top-ups/${trx.reference_id}` ? `/top-ups/${trx.reference_id}`
: `/payments/${trx.reference_id}` : `/payments/${trx.reference_id}`
} }
> >
View Details View Details
</Link> </Link>
</Button> </Button>
</TableCell> </TableCell>
</TableRow> </TableRow>
))} ))}
</TableBody> </TableBody>
<TableFooter> <TableFooter>
<TableRow> <TableRow>
<TableCell colSpan={5} className="text-muted-foreground"> <TableCell colSpan={5} className="text-muted-foreground">
{meta?.total === 1 ? ( {meta?.total === 1 ? (
<p className="text-center"> <p className="text-center">
Total {meta?.total} transaction. Total {meta?.total} transaction.
</p> </p>
) : ( ) : (
<p className="text-center"> <p className="text-center">
Total {meta?.total} transactions. Total {meta?.total} transactions.
</p> </p>
)} )}
</TableCell> </TableCell>
</TableRow> </TableRow>
</TableFooter> </TableFooter>
</Table> </Table>
</div> </div>
<div className="sm:hidden block"> <div className="sm:hidden block">
{data.map((trx) => ( {data.map((trx) => (
<MobileTransactionDetails key={trx.id} trx={trx} /> <MobileTransactionDetails key={trx.id} trx={trx} />
))} ))}
</div> </div>
<Pagination <Pagination
totalPages={meta?.last_page} totalPages={meta?.last_page}
currentPage={meta?.current_page} currentPage={meta?.current_page}
/> />
</div> </div>
)} )}
</div> </div>
); );
} }
function MobileTransactionDetails({ trx }: { trx: WalletTransaction }) { function MobileTransactionDetails({ trx }: { trx: WalletTransaction }) {
return ( return (
<div <div
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",
trx?.transaction_type === "TOPUP" ? "credit-bg" : "debit-bg", trx?.transaction_type === "TOPUP" ? "credit-bg" : "debit-bg",
)} )}
> >
<div className="bg-white shadow dark:bg-black p-2 rounded w-full"> <div className="bg-white shadow dark:bg-black p-2 rounded w-full">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Calendar size={16} opacity={0.5} /> <Calendar size={16} opacity={0.5} />
<span className="text-muted-foreground text-sm"> <span className="text-muted-foreground text-sm">
{new Date(trx.created_at).toLocaleDateString("en-US", { {new Date(trx.created_at).toLocaleDateString("en-US", {
month: "short", month: "short",
day: "2-digit", day: "2-digit",
year: "numeric", year: "numeric",
minute: "2-digit", minute: "2-digit",
hour: "2-digit", hour: "2-digit",
})} })}
</span> </span>
</div> </div>
<p className="text-sm text-muted-foreground py-4">{trx.description}</p> <p className="text-sm text-muted-foreground py-4">{trx.description}</p>
</div> </div>
<div className="bg-white dark:bg-black p-2 rounded mt-2 w-full border flex justify-between items-center"> <div className="bg-white dark:bg-black p-2 rounded mt-2 w-full border flex justify-between items-center">
<div className="block sm:hidden"> <div className="block sm:hidden">
<h3 className="text-sm font-medium">Amount</h3> <h3 className="text-sm font-medium">Amount</h3>
<span className="text-sm text-muted-foreground"> <span className="text-sm text-muted-foreground">
{trx.amount.toFixed(2)} MVR {trx.amount.toFixed(2)} MVR
</span> </span>
</div> </div>
<span className="font-semibold pr-2"> <span className="font-semibold pr-2">
{trx.transaction_type === "TOPUP" ? ( {trx.transaction_type === "TOPUP" ? (
<Badge className="bg-green-100 text-green-950 dark:bg-green-700"> <Badge className="bg-green-100 text-green-950 dark:bg-green-700">
{trx.transaction_type} {trx.transaction_type}
</Badge> </Badge>
) : ( ) : (
<Badge className="bg-red-500 text-red-950 dark:bg-red-700"> <Badge className="bg-red-500 text-red-950 dark:bg-red-700">
{trx.transaction_type} {trx.transaction_type}
</Badge> </Badge>
)} )}
</span> </span>
</div> </div>
<div className="flex items-center gap-2 mt-2 w-full"> <div className="flex items-center gap-2 mt-2 w-full">
<Link <Link
className="font-medium hover:underline" className="font-medium hover:underline"
href={ href={
trx.transaction_type === "TOPUP" trx.transaction_type === "TOPUP"
? `/top-ups/${trx.reference_id}` ? `/top-ups/${trx.reference_id}`
: `/payments/${trx.reference_id}` : `/payments/${trx.reference_id}`
} }
> >
<Button size={"sm"} className="w-full"> <Button size={"sm"} className="w-full">
View Details View Details
</Button> </Button>
</Link> </Link>
</div> </div>
</div> </div>
); );
} }

View File

@@ -7,100 +7,100 @@ import { toast } from "sonner";
import { createTopup } from "@/actions/payment"; import { createTopup } from "@/actions/payment";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { import {
Drawer, Drawer,
DrawerClose, DrawerClose,
DrawerContent, DrawerContent,
DrawerDescription, DrawerDescription,
DrawerFooter, DrawerFooter,
DrawerHeader, DrawerHeader,
DrawerTitle, DrawerTitle,
DrawerTrigger, DrawerTrigger,
} from "@/components/ui/drawer"; } from "@/components/ui/drawer";
import { WalletDrawerOpenAtom, walletTopUpValue } from "@/lib/atoms"; import { WalletDrawerOpenAtom, walletTopUpValue } from "@/lib/atoms";
import type { TopupType } from "@/lib/types"; import type { TopupType } from "@/lib/types";
import NumberInput from "./number-input"; import NumberInput from "./number-input";
export function Wallet({ walletBalance }: { walletBalance: number }) { export function Wallet({ walletBalance }: { walletBalance: number }) {
const pathname = usePathname(); const pathname = usePathname();
const [amount, setAmount] = useAtom(walletTopUpValue); const [amount, setAmount] = useAtom(walletTopUpValue);
const [isOpen, setIsOpen] = useAtom(WalletDrawerOpenAtom); const [isOpen, setIsOpen] = useAtom(WalletDrawerOpenAtom);
const [disabled, setDisabled] = useState(false); const [disabled, setDisabled] = useState(false);
const router = useRouter(); const router = useRouter();
if (pathname === "/payment") { if (pathname === "/payment") {
return null; return null;
} }
const data: TopupType = { const data: TopupType = {
amount: Number.parseFloat(amount.toFixed(2)), amount: Number.parseFloat(amount.toFixed(2)),
}; };
return ( return (
<Drawer open={isOpen} onOpenChange={setIsOpen}> <Drawer open={isOpen} onOpenChange={setIsOpen}>
<DrawerTrigger asChild> <DrawerTrigger asChild>
<Button onClick={() => setIsOpen(!isOpen)} variant="outline"> <Button onClick={() => setIsOpen(!isOpen)} variant="outline">
{walletBalance} MVR {walletBalance} MVR
<Wallet2 /> <Wallet2 />
</Button> </Button>
</DrawerTrigger> </DrawerTrigger>
<DrawerContent> <DrawerContent>
<div className="mx-auto w-full max-w-sm"> <div className="mx-auto w-full max-w-sm">
<DrawerHeader> <DrawerHeader>
<DrawerTitle>Wallet</DrawerTitle> <DrawerTitle>Wallet</DrawerTitle>
<DrawerDescription asChild> <DrawerDescription asChild>
<div> <div>
Your wallet balance is{" "} Your wallet balance is{" "}
<span className="font-semibold"> <span className="font-semibold">
{new Intl.NumberFormat("en-US", { {new Intl.NumberFormat("en-US", {
minimumFractionDigits: 2, minimumFractionDigits: 2,
maximumFractionDigits: 2, maximumFractionDigits: 2,
}).format(walletBalance)} }).format(walletBalance)}
</span>{" "} </span>{" "}
</div> </div>
</DrawerDescription> </DrawerDescription>
</DrawerHeader> </DrawerHeader>
<div className="px-4 flex flex-col gap-4"> <div className="px-4 flex flex-col gap-4">
<NumberInput <NumberInput
label="Set amount to top up" label="Set amount to top up"
value={amount} value={amount}
onChange={(value) => setAmount(value)} onChange={(value) => setAmount(value)}
maxAllowed={5000} maxAllowed={5000}
isDisabled={amount === 0} isDisabled={amount === 0}
/> />
</div> </div>
<DrawerFooter> <DrawerFooter>
<Button <Button
onClick={async () => { onClick={async () => {
console.log(data); console.log(data);
setDisabled(true); setDisabled(true);
const topup = await createTopup(data); const topup = await createTopup(data);
setDisabled(false); setDisabled(false);
if (topup) { if (topup) {
router.push(`/top-ups/${topup.id}`); router.push(`/top-ups/${topup.id}`);
setIsOpen(!isOpen); setIsOpen(!isOpen);
} else { } else {
toast.error("Something went wrong."); toast.error("Something went wrong.");
} }
}} }}
className="w-full" className="w-full"
disabled={amount === 0 || disabled} disabled={amount === 0 || disabled}
> >
{disabled ? ( {disabled ? (
<Loader2 className="ml-2 animate-spin" /> <Loader2 className="ml-2 animate-spin" />
) : ( ) : (
<> <>
Go to payment Go to payment
<CircleDollarSign /> <CircleDollarSign />
</> </>
)} )}
</Button> </Button>
<DrawerClose asChild> <DrawerClose asChild>
<Button variant="outline">Cancel</Button> <Button variant="outline">Cancel</Button>
</DrawerClose> </DrawerClose>
</DrawerFooter> </DrawerFooter>
</div> </div>
</DrawerContent> </DrawerContent>
</Drawer> </Drawer>
); );
} }

View File

@@ -4,36 +4,36 @@ import { AnimatePresence, motion } from "framer-motion";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
interface WelcomeBannerProps { interface WelcomeBannerProps {
firstName?: string | null; firstName?: string | null;
lastName?: string | null; lastName?: string | null;
} }
export function WelcomeBanner({ firstName, lastName }: WelcomeBannerProps) { export function WelcomeBanner({ firstName, lastName }: WelcomeBannerProps) {
const [isVisible, setIsVisible] = useState(true); const [isVisible, setIsVisible] = useState(true);
useEffect(() => { useEffect(() => {
const timer = setTimeout(() => { const timer = setTimeout(() => {
setIsVisible(false); setIsVisible(false);
}, 4000); }, 4000);
return () => clearTimeout(timer); return () => clearTimeout(timer);
}, []); }, []);
return ( return (
<AnimatePresence> <AnimatePresence>
{isVisible && ( {isVisible && (
<motion.div <motion.div
className="text-sm font-mono px-2 p-1 bg-green-500/10 text-green-900 dark:text-green-400" className="text-sm font-mono px-2 p-1 bg-green-500/10 text-green-900 dark:text-green-400"
initial={{ opacity: 0 }} initial={{ opacity: 0 }}
animate={{ opacity: 1 }} animate={{ opacity: 1 }}
exit={{ opacity: 0 }} exit={{ opacity: 0 }}
> >
Welcome,{" "} Welcome,{" "}
<p className="font-semibold motion-preset-slide-down inline-block motion-delay-200"> <p className="font-semibold motion-preset-slide-down inline-block motion-delay-200">
{firstName} {lastName} {firstName} {lastName}
</p> </p>
</motion.div> </motion.div>
)} )}
</AnimatePresence> </AnimatePresence>
); );
} }

View File

@@ -19,14 +19,14 @@ export const loadingDevicesToPayAtom = atom(false);
// Export the atoms with their store // Export the atoms with their store
export const atoms = { export const atoms = {
initialPriceAtom, initialPriceAtom,
discountPercentageAtom, discountPercentageAtom,
numberOfDevicesAtom, numberOfDevicesAtom,
numberOfDaysAtom, numberOfDaysAtom,
numberOfMonths, numberOfMonths,
formulaResultAtom, formulaResultAtom,
deviceCartAtom, deviceCartAtom,
cartDrawerOpenAtom, cartDrawerOpenAtom,
walletTopUpValue, walletTopUpValue,
loadingDevicesToPayAtom, loadingDevicesToPayAtom,
}; };

View File

@@ -6,6 +6,7 @@ const nextConfig: NextConfig = {
serverActions: { serverActions: {
bodySizeLimit: "20mb", bodySizeLimit: "20mb",
}, },
devtoolSegmentExplorer: true,
}, },
images: { images: {
remotePatterns: [ remotePatterns: [

664
package-lock.json generated
View File

@@ -30,7 +30,7 @@
"lucide-react": "^0.523.0", "lucide-react": "^0.523.0",
"moment": "^2.30.1", "moment": "^2.30.1",
"motion": "^12.15.0", "motion": "^12.15.0",
"next": "15.3.3", "next": "15.5.3",
"next-auth": "^4.24.11", "next-auth": "^4.24.11",
"next-themes": "^0.4.6", "next-themes": "^0.4.6",
"nextjs-toploader": "^3.7.15", "nextjs-toploader": "^3.7.15",
@@ -717,6 +717,16 @@
"resolved": "https://registry.npmjs.org/@date-fns/tz/-/tz-1.2.0.tgz", "resolved": "https://registry.npmjs.org/@date-fns/tz/-/tz-1.2.0.tgz",
"integrity": "sha512-LBrd7MiJZ9McsOgxqWX7AaxrDjcFVjWH/tIKJd7pnR7McaslGYOP1QmmiBXdJH/H/yLCT+rcQ7FaPBUxRGUtrg==" "integrity": "sha512-LBrd7MiJZ9McsOgxqWX7AaxrDjcFVjWH/tIKJd7pnR7McaslGYOP1QmmiBXdJH/H/yLCT+rcQ7FaPBUxRGUtrg=="
}, },
"node_modules/@emnapi/runtime": {
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.5.0.tgz",
"integrity": "sha512-97/BJ3iXHww3djw6hYIfErCZFee7qCtrneuLa20UXFCOTCfBM2cvQHjWJ2EG0s0MtdNwInarqCTz35i4wWXHsQ==",
"license": "MIT",
"optional": true,
"dependencies": {
"tslib": "^2.4.0"
}
},
"node_modules/@eslint-community/eslint-utils": { "node_modules/@eslint-community/eslint-utils": {
"version": "4.7.0", "version": "4.7.0",
"resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.7.0.tgz", "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.7.0.tgz",
@@ -851,13 +861,13 @@
} }
}, },
"node_modules/@eslint/plugin-kit": { "node_modules/@eslint/plugin-kit": {
"version": "0.3.3", "version": "0.3.5",
"resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.3.3.tgz", "resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.3.5.tgz",
"integrity": "sha512-1+WqvgNMhmlAambTvT3KPtCl/Ibr68VldY2XY40SL1CE0ZXiakFR/cbTspaF5HsnpDMvcYYoJHfl4980NBjGag==", "integrity": "sha512-Z5kJ+wU3oA7MMIqVR9tyZRtjYPr4OC004Q4Rw7pgOKUOKkJfZ3O24nz3WYfGRpMDNmcOi3TwQOmgm7B7Tpii0w==",
"dev": true, "dev": true,
"license": "Apache-2.0", "license": "Apache-2.0",
"dependencies": { "dependencies": {
"@eslint/core": "^0.15.1", "@eslint/core": "^0.15.2",
"levn": "^0.4.1" "levn": "^0.4.1"
}, },
"engines": { "engines": {
@@ -865,9 +875,9 @@
} }
}, },
"node_modules/@eslint/plugin-kit/node_modules/@eslint/core": { "node_modules/@eslint/plugin-kit/node_modules/@eslint/core": {
"version": "0.15.1", "version": "0.15.2",
"resolved": "https://registry.npmjs.org/@eslint/core/-/core-0.15.1.tgz", "resolved": "https://registry.npmjs.org/@eslint/core/-/core-0.15.2.tgz",
"integrity": "sha512-bkOp+iumZCCbt1K1CmWf0R9pM5yKpDv+ZXtvSyQpudrI9kuFLp+bM2WOPXImuD/ceQuaa8f5pj93Y7zyECIGNA==", "integrity": "sha512-78Md3/Rrxh83gCxoUc0EiciuOHsIITzLy53m3d9UyiW8y9Dj2D29FeETqyKA+BRK76tnTp6RXWb3pCay8Oyomg==",
"dev": true, "dev": true,
"license": "Apache-2.0", "license": "Apache-2.0",
"dependencies": { "dependencies": {
@@ -1050,13 +1060,100 @@
"node": ">=10.13.0" "node": ">=10.13.0"
} }
}, },
"node_modules/@img/sharp-libvips-linux-x64": { "node_modules/@img/colour": {
"version": "1.1.0", "version": "1.0.0",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.1.0.tgz", "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.0.0.tgz",
"integrity": "sha512-yRj2+reB8iMg9W5sULM3S74jVS7zqSzHG3Ol/twnAAkAhnGQnpjj6e4ayUz7V+FpKypwgs82xbRdYtchTTUB+Q==", "integrity": "sha512-A5P/LfWGFSl6nsckYtjw9da+19jB8hkJ6ACTGcDfEJ0aE+l2n2El7dsVM7UVHZQ9s2lmYMWlrS21YLy2IR1LUw==",
"license": "MIT",
"optional": true,
"engines": {
"node": ">=18"
}
},
"node_modules/@img/sharp-darwin-arm64": {
"version": "0.34.4",
"resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.34.4.tgz",
"integrity": "sha512-sitdlPzDVyvmINUdJle3TNHl+AG9QcwiAMsXmccqsCOMZNIdW2/7S26w0LyU8euiLVzFBL3dXPwVCq/ODnf2vA==",
"cpu": [
"arm64"
],
"license": "Apache-2.0",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
"@img/sharp-libvips-darwin-arm64": "1.2.3"
}
},
"node_modules/@img/sharp-darwin-x64": {
"version": "0.34.4",
"resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.34.4.tgz",
"integrity": "sha512-rZheupWIoa3+SOdF/IcUe1ah4ZDpKBGWcsPX6MT0lYniH9micvIU7HQkYTfrx5Xi8u+YqwLtxC/3vl8TQN6rMg==",
"cpu": [ "cpu": [
"x64" "x64"
], ],
"license": "Apache-2.0",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
"@img/sharp-libvips-darwin-x64": "1.2.3"
}
},
"node_modules/@img/sharp-libvips-darwin-arm64": {
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.2.3.tgz",
"integrity": "sha512-QzWAKo7kpHxbuHqUC28DZ9pIKpSi2ts2OJnoIGI26+HMgq92ZZ4vk8iJd4XsxN+tYfNJxzH6W62X5eTcsBymHw==",
"cpu": [
"arm64"
],
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
"darwin"
],
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-libvips-darwin-x64": {
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.2.3.tgz",
"integrity": "sha512-Ju+g2xn1E2AKO6YBhxjj+ACcsPQRHT0bhpglxcEf+3uyPY+/gL8veniKoo96335ZaPo03bdDXMv0t+BBFAbmRA==",
"cpu": [
"x64"
],
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
"darwin"
],
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-libvips-linux-arm": {
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.2.3.tgz",
"integrity": "sha512-x1uE93lyP6wEwGvgAIV0gP6zmaL/a0tGzJs/BIDDG0zeBhMnuUPm7ptxGhUbcGs4okDJrk4nxgrmxpib9g6HpA==",
"cpu": [
"arm"
],
"license": "LGPL-3.0-or-later",
"optional": true, "optional": true,
"os": [ "os": [
"linux" "linux"
@@ -1065,13 +1162,110 @@
"url": "https://opencollective.com/libvips" "url": "https://opencollective.com/libvips"
} }
}, },
"node_modules/@img/sharp-linux-x64": { "node_modules/@img/sharp-libvips-linux-arm64": {
"version": "0.34.1", "version": "1.2.3",
"resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.34.1.tgz", "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.2.3.tgz",
"integrity": "sha512-wExv7SH9nmoBW3Wr2gvQopX1k8q2g5V5Iag8Zk6AVENsjwd+3adjwxtp3Dcu2QhOXr8W9NusBU6XcQUohBZ5MA==", "integrity": "sha512-I4RxkXU90cpufazhGPyVujYwfIm9Nk1QDEmiIsaPwdnm013F7RIceaCc87kAH+oUB1ezqEvC6ga4m7MSlqsJvQ==",
"cpu": [
"arm64"
],
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
"linux"
],
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-libvips-linux-ppc64": {
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.2.3.tgz",
"integrity": "sha512-Y2T7IsQvJLMCBM+pmPbM3bKT/yYJvVtLJGfCs4Sp95SjvnFIjynbjzsa7dY1fRJX45FTSfDksbTp6AGWudiyCg==",
"cpu": [
"ppc64"
],
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
"linux"
],
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-libvips-linux-s390x": {
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.2.3.tgz",
"integrity": "sha512-RgWrs/gVU7f+K7P+KeHFaBAJlNkD1nIZuVXdQv6S+fNA6syCcoboNjsV2Pou7zNlVdNQoQUpQTk8SWDHUA3y/w==",
"cpu": [
"s390x"
],
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
"linux"
],
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-libvips-linux-x64": {
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.2.3.tgz",
"integrity": "sha512-3JU7LmR85K6bBiRzSUc/Ff9JBVIFVvq6bomKE0e63UXGeRw2HPVEjoJke1Yx+iU4rL7/7kUjES4dZ/81Qjhyxg==",
"cpu": [ "cpu": [
"x64" "x64"
], ],
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
"linux"
],
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-libvips-linuxmusl-arm64": {
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.2.3.tgz",
"integrity": "sha512-F9q83RZ8yaCwENw1GieztSfj5msz7GGykG/BA+MOUefvER69K/ubgFHNeSyUu64amHIYKGDs4sRCMzXVj8sEyw==",
"cpu": [
"arm64"
],
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
"linux"
],
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-libvips-linuxmusl-x64": {
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.2.3.tgz",
"integrity": "sha512-U5PUY5jbc45ANM6tSJpsgqmBF/VsL6LnxJmIf11kB7J5DctHgqm0SkuXzVWtIY90GnJxKnC/JT251TDnk1fu/g==",
"cpu": [
"x64"
],
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
"linux"
],
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-linux-arm": {
"version": "0.34.4",
"resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.34.4.tgz",
"integrity": "sha512-Xyam4mlqM0KkTHYVSuc6wXRmM7LGN0P12li03jAnZ3EJWZqj83+hi8Y9UxZUbxsgsK1qOEwg7O0Bc0LjqQVtxA==",
"cpu": [
"arm"
],
"license": "Apache-2.0",
"optional": true, "optional": true,
"os": [ "os": [
"linux" "linux"
@@ -1083,7 +1277,215 @@
"url": "https://opencollective.com/libvips" "url": "https://opencollective.com/libvips"
}, },
"optionalDependencies": { "optionalDependencies": {
"@img/sharp-libvips-linux-x64": "1.1.0" "@img/sharp-libvips-linux-arm": "1.2.3"
}
},
"node_modules/@img/sharp-linux-arm64": {
"version": "0.34.4",
"resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.34.4.tgz",
"integrity": "sha512-YXU1F/mN/Wu786tl72CyJjP/Ngl8mGHN1hST4BGl+hiW5jhCnV2uRVTNOcaYPs73NeT/H8Upm3y9582JVuZHrQ==",
"cpu": [
"arm64"
],
"license": "Apache-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
"@img/sharp-libvips-linux-arm64": "1.2.3"
}
},
"node_modules/@img/sharp-linux-ppc64": {
"version": "0.34.4",
"resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.34.4.tgz",
"integrity": "sha512-F4PDtF4Cy8L8hXA2p3TO6s4aDt93v+LKmpcYFLAVdkkD3hSxZzee0rh6/+94FpAynsuMpLX5h+LRsSG3rIciUQ==",
"cpu": [
"ppc64"
],
"license": "Apache-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
"@img/sharp-libvips-linux-ppc64": "1.2.3"
}
},
"node_modules/@img/sharp-linux-s390x": {
"version": "0.34.4",
"resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.34.4.tgz",
"integrity": "sha512-qVrZKE9Bsnzy+myf7lFKvng6bQzhNUAYcVORq2P7bDlvmF6u2sCmK2KyEQEBdYk+u3T01pVsPrkj943T1aJAsw==",
"cpu": [
"s390x"
],
"license": "Apache-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
"@img/sharp-libvips-linux-s390x": "1.2.3"
}
},
"node_modules/@img/sharp-linux-x64": {
"version": "0.34.4",
"resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.34.4.tgz",
"integrity": "sha512-ZfGtcp2xS51iG79c6Vhw9CWqQC8l2Ot8dygxoDoIQPTat/Ov3qAa8qpxSrtAEAJW+UjTXc4yxCjNfxm4h6Xm2A==",
"cpu": [
"x64"
],
"license": "Apache-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
"@img/sharp-libvips-linux-x64": "1.2.3"
}
},
"node_modules/@img/sharp-linuxmusl-arm64": {
"version": "0.34.4",
"resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.34.4.tgz",
"integrity": "sha512-8hDVvW9eu4yHWnjaOOR8kHVrew1iIX+MUgwxSuH2XyYeNRtLUe4VNioSqbNkB7ZYQJj9rUTT4PyRscyk2PXFKA==",
"cpu": [
"arm64"
],
"license": "Apache-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
"@img/sharp-libvips-linuxmusl-arm64": "1.2.3"
}
},
"node_modules/@img/sharp-linuxmusl-x64": {
"version": "0.34.4",
"resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.34.4.tgz",
"integrity": "sha512-lU0aA5L8QTlfKjpDCEFOZsTYGn3AEiO6db8W5aQDxj0nQkVrZWmN3ZP9sYKWJdtq3PWPhUNlqehWyXpYDcI9Sg==",
"cpu": [
"x64"
],
"license": "Apache-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
"@img/sharp-libvips-linuxmusl-x64": "1.2.3"
}
},
"node_modules/@img/sharp-wasm32": {
"version": "0.34.4",
"resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.34.4.tgz",
"integrity": "sha512-33QL6ZO/qpRyG7woB/HUALz28WnTMI2W1jgX3Nu2bypqLIKx/QKMILLJzJjI+SIbvXdG9fUnmrxR7vbi1sTBeA==",
"cpu": [
"wasm32"
],
"license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT",
"optional": true,
"dependencies": {
"@emnapi/runtime": "^1.5.0"
},
"engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-win32-arm64": {
"version": "0.34.4",
"resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.34.4.tgz",
"integrity": "sha512-2Q250do/5WXTwxW3zjsEuMSv5sUU4Tq9VThWKlU2EYLm4MB7ZeMwF+SFJutldYODXF6jzc6YEOC+VfX0SZQPqA==",
"cpu": [
"arm64"
],
"license": "Apache-2.0 AND LGPL-3.0-or-later",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-win32-ia32": {
"version": "0.34.4",
"resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.34.4.tgz",
"integrity": "sha512-3ZeLue5V82dT92CNL6rsal6I2weKw1cYu+rGKm8fOCCtJTR2gYeUfY3FqUnIJsMUPIH68oS5jmZ0NiJ508YpEw==",
"cpu": [
"ia32"
],
"license": "Apache-2.0 AND LGPL-3.0-or-later",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-win32-x64": {
"version": "0.34.4",
"resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.34.4.tgz",
"integrity": "sha512-xIyj4wpYs8J18sVN3mSQjwrw7fKUqRw+Z5rnHNCy5fYTxigBz81u5mOMPmFumwjcn8+ld1ppptMBCLic1nz6ig==",
"cpu": [
"x64"
],
"license": "Apache-2.0 AND LGPL-3.0-or-later",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
} }
}, },
"node_modules/@inquirer/ansi": { "node_modules/@inquirer/ansi": {
@@ -1509,9 +1911,10 @@
} }
}, },
"node_modules/@next/env": { "node_modules/@next/env": {
"version": "15.3.3", "version": "15.5.3",
"resolved": "https://registry.npmjs.org/@next/env/-/env-15.3.3.tgz", "resolved": "https://registry.npmjs.org/@next/env/-/env-15.5.3.tgz",
"integrity": "sha512-OdiMrzCl2Xi0VTjiQQUK0Xh7bJHnOuET2s+3V+Y40WJBAXrJeGA3f+I8MZJ/YQ3mVGi5XGR1L66oFlgqXhQ4Vw==" "integrity": "sha512-RSEDTRqyihYXygx/OJXwvVupfr9m04+0vH8vyy0HfZ7keRto6VX9BbEk0J2PUk0VGy6YhklJUSrgForov5F9pw==",
"license": "MIT"
}, },
"node_modules/@next/eslint-plugin-next": { "node_modules/@next/eslint-plugin-next": {
"version": "15.1.2", "version": "15.1.2",
@@ -1548,12 +1951,13 @@
} }
}, },
"node_modules/@next/swc-darwin-arm64": { "node_modules/@next/swc-darwin-arm64": {
"version": "15.3.3", "version": "15.5.3",
"resolved": "https://registry.npmjs.org/@next/swc-darwin-arm64/-/swc-darwin-arm64-15.3.3.tgz", "resolved": "https://registry.npmjs.org/@next/swc-darwin-arm64/-/swc-darwin-arm64-15.5.3.tgz",
"integrity": "sha512-WRJERLuH+O3oYB4yZNVahSVFmtxRNjNF1I1c34tYMoJb0Pve+7/RaLAJJizyYiFhjYNGHRAE1Ri2Fd23zgDqhg==", "integrity": "sha512-nzbHQo69+au9wJkGKTU9lP7PXv0d1J5ljFpvb+LnEomLtSbJkbZyEs6sbF3plQmiOB2l9OBtN2tNSvCH1nQ9Jg==",
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
"license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
"darwin" "darwin"
@@ -1563,12 +1967,13 @@
} }
}, },
"node_modules/@next/swc-darwin-x64": { "node_modules/@next/swc-darwin-x64": {
"version": "15.3.3", "version": "15.5.3",
"resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-15.3.3.tgz", "resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-15.5.3.tgz",
"integrity": "sha512-XHdzH/yBc55lu78k/XwtuFR/ZXUTcflpRXcsu0nKmF45U96jt1tsOZhVrn5YH+paw66zOANpOnFQ9i6/j+UYvw==", "integrity": "sha512-w83w4SkOOhekJOcA5HBvHyGzgV1W/XvOfpkrxIse4uPWhYTTRwtGEM4v/jiXwNSJvfRvah0H8/uTLBKRXlef8g==",
"cpu": [ "cpu": [
"x64" "x64"
], ],
"license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
"darwin" "darwin"
@@ -1578,12 +1983,13 @@
} }
}, },
"node_modules/@next/swc-linux-arm64-gnu": { "node_modules/@next/swc-linux-arm64-gnu": {
"version": "15.3.3", "version": "15.5.3",
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-15.3.3.tgz", "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-15.5.3.tgz",
"integrity": "sha512-VZ3sYL2LXB8znNGcjhocikEkag/8xiLgnvQts41tq6i+wql63SMS1Q6N8RVXHw5pEUjiof+II3HkDd7GFcgkzw==", "integrity": "sha512-+m7pfIs0/yvgVu26ieaKrifV8C8yiLe7jVp9SpcIzg7XmyyNE7toC1fy5IOQozmr6kWl/JONC51osih2RyoXRw==",
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
"license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
"linux" "linux"
@@ -1593,12 +1999,13 @@
} }
}, },
"node_modules/@next/swc-linux-arm64-musl": { "node_modules/@next/swc-linux-arm64-musl": {
"version": "15.3.3", "version": "15.5.3",
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-15.3.3.tgz", "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-15.5.3.tgz",
"integrity": "sha512-h6Y1fLU4RWAp1HPNJWDYBQ+e3G7sLckyBXhmH9ajn8l/RSMnhbuPBV/fXmy3muMcVwoJdHL+UtzRzs0nXOf9SA==", "integrity": "sha512-u3PEIzuguSenoZviZJahNLgCexGFhso5mxWCrrIMdvpZn6lkME5vc/ADZG8UUk5K1uWRy4hqSFECrON6UKQBbQ==",
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
"license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
"linux" "linux"
@@ -1608,12 +2015,13 @@
} }
}, },
"node_modules/@next/swc-linux-x64-gnu": { "node_modules/@next/swc-linux-x64-gnu": {
"version": "15.3.3", "version": "15.5.3",
"resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-15.3.3.tgz", "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-15.5.3.tgz",
"integrity": "sha512-jJ8HRiF3N8Zw6hGlytCj5BiHyG/K+fnTKVDEKvUCyiQ/0r5tgwO7OgaRiOjjRoIx2vwLR+Rz8hQoPrnmFbJdfw==", "integrity": "sha512-lDtOOScYDZxI2BENN9m0pfVPJDSuUkAD1YXSvlJF0DKwZt0WlA7T7o3wrcEr4Q+iHYGzEaVuZcsIbCps4K27sA==",
"cpu": [ "cpu": [
"x64" "x64"
], ],
"license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
"linux" "linux"
@@ -1623,12 +2031,13 @@
} }
}, },
"node_modules/@next/swc-linux-x64-musl": { "node_modules/@next/swc-linux-x64-musl": {
"version": "15.3.3", "version": "15.5.3",
"resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-15.3.3.tgz", "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-15.5.3.tgz",
"integrity": "sha512-HrUcTr4N+RgiiGn3jjeT6Oo208UT/7BuTr7K0mdKRBtTbT4v9zJqCDKO97DUqqoBK1qyzP1RwvrWTvU6EPh/Cw==", "integrity": "sha512-9vWVUnsx9PrY2NwdVRJ4dUURAQ8Su0sLRPqcCCxtX5zIQUBES12eRVHq6b70bbfaVaxIDGJN2afHui0eDm+cLg==",
"cpu": [ "cpu": [
"x64" "x64"
], ],
"license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
"linux" "linux"
@@ -1638,12 +2047,13 @@
} }
}, },
"node_modules/@next/swc-win32-arm64-msvc": { "node_modules/@next/swc-win32-arm64-msvc": {
"version": "15.3.3", "version": "15.5.3",
"resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-15.3.3.tgz", "resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-15.5.3.tgz",
"integrity": "sha512-SxorONgi6K7ZUysMtRF3mIeHC5aA3IQLmKFQzU0OuhuUYwpOBc1ypaLJLP5Bf3M9k53KUUUj4vTPwzGvl/NwlQ==", "integrity": "sha512-1CU20FZzY9LFQigRi6jM45oJMU3KziA5/sSG+dXeVaTm661snQP6xu3ykGxxwU5sLG3sh14teO/IOEPVsQMRfA==",
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
"license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
"win32" "win32"
@@ -1653,12 +2063,13 @@
} }
}, },
"node_modules/@next/swc-win32-x64-msvc": { "node_modules/@next/swc-win32-x64-msvc": {
"version": "15.3.3", "version": "15.5.3",
"resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-15.3.3.tgz", "resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-15.5.3.tgz",
"integrity": "sha512-4QZG6F8enl9/S2+yIiOiju0iCTFd93d8VC1q9LZS4p/Xuk81W2QDjCFeoogmrWWkAD59z8ZxepBQap2dKS5ruw==", "integrity": "sha512-JMoLAq3n3y5tKXPQwCK5c+6tmwkuFDa2XAxz8Wm4+IVthdBZdZGh+lmiLUHg9f9IDwIQpUjp+ysd6OkYTyZRZw==",
"cpu": [ "cpu": [
"x64" "x64"
], ],
"license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
"win32" "win32"
@@ -5014,10 +5425,6 @@
"resolved": "https://registry.npmjs.org/@standard-schema/utils/-/utils-0.3.0.tgz", "resolved": "https://registry.npmjs.org/@standard-schema/utils/-/utils-0.3.0.tgz",
"integrity": "sha512-e7Mew686owMaPJVNNLs55PUvgz371nKgwsc4vxE49zsODpJEnxgxRo2y/OKrqueavXgZNMDVj3DdHFlaSAeU8g==" "integrity": "sha512-e7Mew686owMaPJVNNLs55PUvgz371nKgwsc4vxE49zsODpJEnxgxRo2y/OKrqueavXgZNMDVj3DdHFlaSAeU8g=="
}, },
"node_modules/@swc/counter": {
"version": "0.1.3",
"license": "Apache-2.0"
},
"node_modules/@swc/helpers": { "node_modules/@swc/helpers": {
"version": "0.5.15", "version": "0.5.15",
"license": "Apache-2.0", "license": "Apache-2.0",
@@ -6051,12 +6458,13 @@
} }
}, },
"node_modules/axios": { "node_modules/axios": {
"version": "1.8.4", "version": "1.12.2",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.8.4.tgz", "resolved": "https://registry.npmjs.org/axios/-/axios-1.12.2.tgz",
"integrity": "sha512-eBSYY4Y68NNlHbHBMdeDmKNtDgXWhQsJcGqzO3iLUM0GraQFSS9cVgPX5I9b3lbdFKyYoAEGAZF1DwhTaljNAw==", "integrity": "sha512-vMJzPewAlRyOgxV2dU0Cuz2O8zzzx9VYtbJOaBgXFeLc4IV/Eg50n4LowmehOOR61S8ZMpc2K5Sa7g6A4jfkUw==",
"license": "MIT",
"dependencies": { "dependencies": {
"follow-redirects": "^1.15.6", "follow-redirects": "^1.15.6",
"form-data": "^4.0.0", "form-data": "^4.0.4",
"proxy-from-env": "^1.1.0" "proxy-from-env": "^1.1.0"
} }
}, },
@@ -6132,15 +6540,6 @@
"url": "https://github.com/sponsors/sindresorhus" "url": "https://github.com/sponsors/sindresorhus"
} }
}, },
"node_modules/busboy": {
"version": "1.6.0",
"dependencies": {
"streamsearch": "^1.1.0"
},
"engines": {
"node": ">=10.16.0"
}
},
"node_modules/c12": { "node_modules/c12": {
"version": "3.3.0", "version": "3.3.0",
"resolved": "https://registry.npmjs.org/c12/-/c12-3.3.0.tgz", "resolved": "https://registry.npmjs.org/c12/-/c12-3.3.0.tgz",
@@ -6461,19 +6860,6 @@
"react-dom": "^18 || ^19 || ^19.0.0-rc" "react-dom": "^18 || ^19 || ^19.0.0-rc"
} }
}, },
"node_modules/color": {
"version": "4.2.3",
"resolved": "https://registry.npmjs.org/color/-/color-4.2.3.tgz",
"integrity": "sha512-1rXeuUUiGGrykh+CeBdu5Ie7OJwinCgQY0bc7GCRxy5xVHy+moaqkpL/jqQq0MtQOeYcrqEz4abc5f0KtU7W4A==",
"optional": true,
"dependencies": {
"color-convert": "^2.0.1",
"color-string": "^1.9.0"
},
"engines": {
"node": ">=12.5.0"
}
},
"node_modules/color-convert": { "node_modules/color-convert": {
"version": "2.0.1", "version": "2.0.1",
"license": "MIT", "license": "MIT",
@@ -6488,16 +6874,6 @@
"version": "1.1.4", "version": "1.1.4",
"license": "MIT" "license": "MIT"
}, },
"node_modules/color-string": {
"version": "1.9.1",
"resolved": "https://registry.npmjs.org/color-string/-/color-string-1.9.1.tgz",
"integrity": "sha512-shrVawQFojnZv6xM40anx4CkoDP+fZsw/ZerEMsW/pyzsRbElpsL/DBVW7q3ExxwusdNXI3lXpuhEZkzs8p5Eg==",
"optional": true,
"dependencies": {
"color-name": "^1.0.0",
"simple-swizzle": "^0.2.2"
}
},
"node_modules/combined-stream": { "node_modules/combined-stream": {
"version": "1.0.8", "version": "1.0.8",
"resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
@@ -7417,9 +7793,9 @@
"license": "MIT" "license": "MIT"
}, },
"node_modules/detect-libc": { "node_modules/detect-libc": {
"version": "2.0.4", "version": "2.1.0",
"resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.0.4.tgz", "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.0.tgz",
"integrity": "sha512-3UDv+G9CsCKO1WKMGw9fwq/SWJYbI0c5Y7LU1AXYoDdbhE2AHQ6N6Nb34sG8Fj7T5APy8qXDCKuuIHd1BR0tVA==", "integrity": "sha512-vEtk+OcP7VBRtQZ1EJ3bdgzSfBjgnEalLTp5zjJrS+2Z1w2KZly4SBdac/WDU3hhsNAZ9E8SC96ME4Ey8MZ7cg==",
"license": "Apache-2.0", "license": "Apache-2.0",
"engines": { "engines": {
"node": ">=8" "node": ">=8"
@@ -9191,12 +9567,6 @@
"url": "https://github.com/sponsors/ljharb" "url": "https://github.com/sponsors/ljharb"
} }
}, },
"node_modules/is-arrayish": {
"version": "0.3.2",
"resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.3.2.tgz",
"integrity": "sha512-eVRqCvVlZbuw3GrM63ovNSNAeA1K16kaR/LRY/92w0zxQ5/1YzwblUX652i4Xs9RwAGjW9d9y6X88t8OaAJfWQ==",
"optional": true
},
"node_modules/is-async-function": { "node_modules/is-async-function": {
"version": "2.0.0", "version": "2.0.0",
"dev": true, "dev": true,
@@ -10511,14 +10881,13 @@
} }
}, },
"node_modules/next": { "node_modules/next": {
"version": "15.3.3", "version": "15.5.3",
"resolved": "https://registry.npmjs.org/next/-/next-15.3.3.tgz", "resolved": "https://registry.npmjs.org/next/-/next-15.5.3.tgz",
"integrity": "sha512-JqNj29hHNmCLtNvd090SyRbXJiivQ+58XjCcrC50Crb5g5u2zi7Y2YivbsEfzk6AtVI80akdOQbaMZwWB1Hthw==", "integrity": "sha512-r/liNAx16SQj4D+XH/oI1dlpv9tdKJ6cONYPwwcCC46f2NjpaRWY+EKCzULfgQYV6YKXjHBchff2IZBSlZmJNw==",
"license": "MIT",
"dependencies": { "dependencies": {
"@next/env": "15.3.3", "@next/env": "15.5.3",
"@swc/counter": "0.1.3",
"@swc/helpers": "0.5.15", "@swc/helpers": "0.5.15",
"busboy": "1.6.0",
"caniuse-lite": "^1.0.30001579", "caniuse-lite": "^1.0.30001579",
"postcss": "8.4.31", "postcss": "8.4.31",
"styled-jsx": "5.1.6" "styled-jsx": "5.1.6"
@@ -10530,19 +10899,19 @@
"node": "^18.18.0 || ^19.8.0 || >= 20.0.0" "node": "^18.18.0 || ^19.8.0 || >= 20.0.0"
}, },
"optionalDependencies": { "optionalDependencies": {
"@next/swc-darwin-arm64": "15.3.3", "@next/swc-darwin-arm64": "15.5.3",
"@next/swc-darwin-x64": "15.3.3", "@next/swc-darwin-x64": "15.5.3",
"@next/swc-linux-arm64-gnu": "15.3.3", "@next/swc-linux-arm64-gnu": "15.5.3",
"@next/swc-linux-arm64-musl": "15.3.3", "@next/swc-linux-arm64-musl": "15.5.3",
"@next/swc-linux-x64-gnu": "15.3.3", "@next/swc-linux-x64-gnu": "15.5.3",
"@next/swc-linux-x64-musl": "15.3.3", "@next/swc-linux-x64-musl": "15.5.3",
"@next/swc-win32-arm64-msvc": "15.3.3", "@next/swc-win32-arm64-msvc": "15.5.3",
"@next/swc-win32-x64-msvc": "15.3.3", "@next/swc-win32-x64-msvc": "15.5.3",
"sharp": "^0.34.1" "sharp": "^0.34.3"
}, },
"peerDependencies": { "peerDependencies": {
"@opentelemetry/api": "^1.1.0", "@opentelemetry/api": "^1.1.0",
"@playwright/test": "^1.41.2", "@playwright/test": "^1.51.1",
"babel-plugin-react-compiler": "*", "babel-plugin-react-compiler": "*",
"react": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0", "react": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0",
"react-dom": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0", "react-dom": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0",
@@ -12242,15 +12611,16 @@
} }
}, },
"node_modules/sharp": { "node_modules/sharp": {
"version": "0.34.1", "version": "0.34.4",
"resolved": "https://registry.npmjs.org/sharp/-/sharp-0.34.1.tgz", "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.34.4.tgz",
"integrity": "sha512-1j0w61+eVxu7DawFJtnfYcvSv6qPFvfTaqzTQ2BLknVhHTwGS8sc63ZBF4rzkWMBVKybo4S5OBtDdZahh2A1xg==", "integrity": "sha512-FUH39xp3SBPnxWvd5iib1X8XY7J0K0X7d93sie9CJg2PO8/7gmg89Nve6OjItK53/MlAushNNxteBYfM6DEuoA==",
"hasInstallScript": true, "hasInstallScript": true,
"license": "Apache-2.0",
"optional": true, "optional": true,
"dependencies": { "dependencies": {
"color": "^4.2.3", "@img/colour": "^1.0.0",
"detect-libc": "^2.0.3", "detect-libc": "^2.1.0",
"semver": "^7.7.1" "semver": "^7.7.2"
}, },
"engines": { "engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0" "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
@@ -12259,32 +12629,35 @@
"url": "https://opencollective.com/libvips" "url": "https://opencollective.com/libvips"
}, },
"optionalDependencies": { "optionalDependencies": {
"@img/sharp-darwin-arm64": "0.34.1", "@img/sharp-darwin-arm64": "0.34.4",
"@img/sharp-darwin-x64": "0.34.1", "@img/sharp-darwin-x64": "0.34.4",
"@img/sharp-libvips-darwin-arm64": "1.1.0", "@img/sharp-libvips-darwin-arm64": "1.2.3",
"@img/sharp-libvips-darwin-x64": "1.1.0", "@img/sharp-libvips-darwin-x64": "1.2.3",
"@img/sharp-libvips-linux-arm": "1.1.0", "@img/sharp-libvips-linux-arm": "1.2.3",
"@img/sharp-libvips-linux-arm64": "1.1.0", "@img/sharp-libvips-linux-arm64": "1.2.3",
"@img/sharp-libvips-linux-ppc64": "1.1.0", "@img/sharp-libvips-linux-ppc64": "1.2.3",
"@img/sharp-libvips-linux-s390x": "1.1.0", "@img/sharp-libvips-linux-s390x": "1.2.3",
"@img/sharp-libvips-linux-x64": "1.1.0", "@img/sharp-libvips-linux-x64": "1.2.3",
"@img/sharp-libvips-linuxmusl-arm64": "1.1.0", "@img/sharp-libvips-linuxmusl-arm64": "1.2.3",
"@img/sharp-libvips-linuxmusl-x64": "1.1.0", "@img/sharp-libvips-linuxmusl-x64": "1.2.3",
"@img/sharp-linux-arm": "0.34.1", "@img/sharp-linux-arm": "0.34.4",
"@img/sharp-linux-arm64": "0.34.1", "@img/sharp-linux-arm64": "0.34.4",
"@img/sharp-linux-s390x": "0.34.1", "@img/sharp-linux-ppc64": "0.34.4",
"@img/sharp-linux-x64": "0.34.1", "@img/sharp-linux-s390x": "0.34.4",
"@img/sharp-linuxmusl-arm64": "0.34.1", "@img/sharp-linux-x64": "0.34.4",
"@img/sharp-linuxmusl-x64": "0.34.1", "@img/sharp-linuxmusl-arm64": "0.34.4",
"@img/sharp-wasm32": "0.34.1", "@img/sharp-linuxmusl-x64": "0.34.4",
"@img/sharp-win32-ia32": "0.34.1", "@img/sharp-wasm32": "0.34.4",
"@img/sharp-win32-x64": "0.34.1" "@img/sharp-win32-arm64": "0.34.4",
"@img/sharp-win32-ia32": "0.34.4",
"@img/sharp-win32-x64": "0.34.4"
} }
}, },
"node_modules/sharp/node_modules/semver": { "node_modules/sharp/node_modules/semver": {
"version": "7.7.1", "version": "7.7.2",
"resolved": "https://registry.npmjs.org/semver/-/semver-7.7.1.tgz", "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.2.tgz",
"integrity": "sha512-hlq8tAfn0m/61p4BVRcPzIGr6LKiMwo4VM6dGi6pt4qcRkmNzTcWq6eCEjEh+qXjkMDvPlOFFSGwQjoEa6gyMA==", "integrity": "sha512-RF0Fw+rO5AMf9MAyaRXI4AV0Ulj5lMHqVxxdSgiVbixSCXoEmmX/jk0CuJw4+3SqroYO9VoUh+HcuJivvtJemA==",
"license": "ISC",
"optional": true, "optional": true,
"bin": { "bin": {
"semver": "bin/semver.js" "semver": "bin/semver.js"
@@ -12390,15 +12763,6 @@
"url": "https://github.com/sponsors/isaacs" "url": "https://github.com/sponsors/isaacs"
} }
}, },
"node_modules/simple-swizzle": {
"version": "0.2.2",
"resolved": "https://registry.npmjs.org/simple-swizzle/-/simple-swizzle-0.2.2.tgz",
"integrity": "sha512-JA//kQgZtbuY83m+xT+tXJkmJncGMTFT+C+g2h2R9uxkYIrE2yy9sgmcLhCnw57/WSD+Eh3J97FPEDFnbXnDUg==",
"optional": true,
"dependencies": {
"is-arrayish": "^0.3.1"
}
},
"node_modules/smart-buffer": { "node_modules/smart-buffer": {
"version": "4.2.0", "version": "4.2.0",
"resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz", "resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz",
@@ -12526,12 +12890,6 @@
"url": "https://github.com/sponsors/sindresorhus" "url": "https://github.com/sponsors/sindresorhus"
} }
}, },
"node_modules/streamsearch": {
"version": "1.1.0",
"engines": {
"node": ">=10.0.0"
}
},
"node_modules/string_decoder": { "node_modules/string_decoder": {
"version": "1.3.0", "version": "1.3.0",
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",

View File

@@ -1,124 +1,124 @@
{ {
"name": "sarlink-portal", "name": "sarlink-portal",
"version": "0.2.2", "version": "0.2.2",
"type": "module", "type": "module",
"private": true, "private": true,
"scripts": { "scripts": {
"dev": "next dev --turbopack", "dev": "next dev --turbopack",
"build": "next build", "build": "next build",
"start": "next start", "start": "next start",
"lint": "next lint", "lint": "next lint",
"prepare": "husky", "prepare": "husky",
"release": "release-it" "release": "release-it"
}, },
"dependencies": { "dependencies": {
"@commitlint/cli": "^19.8.1", "@commitlint/cli": "^19.8.1",
"@commitlint/config-conventional": "^19.8.1", "@commitlint/config-conventional": "^19.8.1",
"@faker-js/faker": "^9.3.0", "@faker-js/faker": "^9.3.0",
"@hookform/resolvers": "^5.1.1", "@hookform/resolvers": "^5.1.1",
"@pyncz/tailwind-mask-image": "^2.0.0", "@pyncz/tailwind-mask-image": "^2.0.0",
"@radix-ui/react-dialog": "^1.1.14", "@radix-ui/react-dialog": "^1.1.14",
"@radix-ui/react-progress": "^1.1.7", "@radix-ui/react-progress": "^1.1.7",
"@tailwindcss/postcss": "^4.1.11", "@tailwindcss/postcss": "^4.1.11",
"@tanstack/react-query": "^5.61.4", "@tanstack/react-query": "^5.61.4",
"axios": "^1.8.4", "axios": "^1.8.4",
"class-variance-authority": "^0.7.1", "class-variance-authority": "^0.7.1",
"clsx": "^2.1.1", "clsx": "^2.1.1",
"cmdk": "^1.1.1", "cmdk": "^1.1.1",
"commitlint": "^19.8.1", "commitlint": "^19.8.1",
"date-fns": "^4.1.0", "date-fns": "^4.1.0",
"embla-carousel-react": "^8.6.0", "embla-carousel-react": "^8.6.0",
"husky": "^9.1.7", "husky": "^9.1.7",
"input-otp": "^1.4.2", "input-otp": "^1.4.2",
"jotai": "2.8.0", "jotai": "2.8.0",
"lucide-react": "^0.523.0", "lucide-react": "^0.523.0",
"moment": "^2.30.1", "moment": "^2.30.1",
"motion": "^12.15.0", "motion": "^12.15.0",
"next": "15.3.3", "next": "15.5.3",
"next-auth": "^4.24.11", "next-auth": "^4.24.11",
"next-themes": "^0.4.6", "next-themes": "^0.4.6",
"nextjs-toploader": "^3.7.15", "nextjs-toploader": "^3.7.15",
"nuqs": "^2.4.3", "nuqs": "^2.4.3",
"radix-ui": "^1.4.2", "radix-ui": "^1.4.2",
"react": "19.1.0", "react": "19.1.0",
"react-aria-components": "^1.5.0", "react-aria-components": "^1.5.0",
"react-day-picker": "^9.7.0", "react-day-picker": "^9.7.0",
"react-dom": "19.1.0", "react-dom": "19.1.0",
"react-hook-form": "^7.58.1", "react-hook-form": "^7.58.1",
"react-phone-number-input": "^3.4.9", "react-phone-number-input": "^3.4.9",
"react-resizable-panels": "^3.0.3", "react-resizable-panels": "^3.0.3",
"recharts": "^3.0.0", "recharts": "^3.0.0",
"release-it": "^19.0.5", "release-it": "^19.0.5",
"sonner": "^2.0.5", "sonner": "^2.0.5",
"tailwind-merge": "^3.3.1", "tailwind-merge": "^3.3.1",
"tailwindcss-animate": "^1.0.7", "tailwindcss-animate": "^1.0.7",
"vaul": "^1.1.2", "vaul": "^1.1.2",
"zod": "^3.25.67" "zod": "^3.25.67"
}, },
"devDependencies": { "devDependencies": {
"@biomejs/biome": "2.0.6", "@biomejs/biome": "2.0.6",
"@release-it/conventional-changelog": "^10.0.1", "@release-it/conventional-changelog": "^10.0.1",
"@types/node": "^22.10.2", "@types/node": "^22.10.2",
"@types/react": "^19.1.0", "@types/react": "^19.1.0",
"@types/react-dom": "^19.1.2", "@types/react-dom": "^19.1.2",
"@typescript-eslint/eslint-plugin": "^8.35.0", "@typescript-eslint/eslint-plugin": "^8.35.0",
"@typescript-eslint/parser": "^8.35.0", "@typescript-eslint/parser": "^8.35.0",
"eslint": "^9.29.0", "eslint": "^9.29.0",
"eslint-config-next": "15.1.2", "eslint-config-next": "15.1.2",
"postcss": "^8.5.6", "postcss": "^8.5.6",
"tailwindcss": "^4.1.11", "tailwindcss": "^4.1.11",
"tailwindcss-motion": "^1.1.0", "tailwindcss-motion": "^1.1.0",
"ts-node": "^10.9.2", "ts-node": "^10.9.2",
"tw-animate-css": "^1.3.4", "tw-animate-css": "^1.3.4",
"typescript": "^5.8.3" "typescript": "^5.8.3"
}, },
"release-it": { "release-it": {
"git": { "git": {
"commitMessage": "chore: release v${version}" "commitMessage": "chore: release v${version}"
}, },
"github": { "github": {
"release": true "release": true
}, },
"npm": { "npm": {
"publish": false "publish": false
}, },
"plugins": { "plugins": {
"@release-it/conventional-changelog": { "@release-it/conventional-changelog": {
"infile": "CHANGELOG.md", "infile": "CHANGELOG.md",
"preset": { "preset": {
"name": "conventionalcommits", "name": "conventionalcommits",
"types": [ "types": [
{ {
"type": "feat", "type": "feat",
"section": "Features" "section": "Features"
}, },
{ {
"type": "fix", "type": "fix",
"section": "Bug Fixes" "section": "Bug Fixes"
}, },
{ {
"type": "chore", "type": "chore",
"section": "Chores" "section": "Chores"
}, },
{ {
"type": "docs", "type": "docs",
"section": "Documentation" "section": "Documentation"
}, },
{ {
"type": "refactor", "type": "refactor",
"section": "Refactor" "section": "Refactor"
}, },
{ {
"type": "style", "type": "style",
"section": "Style" "section": "Style"
}, },
{ {
"type": "test", "type": "test",
"section": "Tests" "section": "Tests"
} }
] ]
} }
} }
} }
} }
} }

View File

@@ -1,201 +1,201 @@
"use server"; "use server";
import { z } from "zod"; import { z } from "zod";
import type { import type {
ActionState, ActionState,
FilterTempUserResponse, FilterTempUserResponse,
FilterUserResponse, FilterUserResponse,
} from "@/actions/auth-actions"; } from "@/actions/auth-actions";
import type { TAuthUser, User } from "@/lib/types/user"; import type { TAuthUser, User } from "@/lib/types/user";
import axiosInstance from "@/utils/axiosInstance"; import axiosInstance from "@/utils/axiosInstance";
import { handleApiResponse } from "@/utils/tryCatch"; import { handleApiResponse } from "@/utils/tryCatch";
export async function login({ export async function login({
password, password,
username, username,
}: { }: {
username: string; username: string;
password: string; password: string;
}): Promise<TAuthUser> { }): Promise<TAuthUser> {
const response = await axiosInstance const response = await axiosInstance
.post("/auth/login/", { .post("/auth/login/", {
username: username, username: username,
password: password, password: password,
}) })
.then((res) => { .then((res) => {
console.log(res); console.log(res);
return res.data; // Return the data from the response return res.data; // Return the data from the response
}) })
.catch((err) => { .catch((err) => {
console.log(err.response); console.log(err.response);
throw err; // Throw the error to maintain the Promise rejection throw err; // Throw the error to maintain the Promise rejection
}); });
return response; return response;
} }
export async function logout({ token }: { token: string }) { export async function logout({ token }: { token: string }) {
const response = await fetch( const response = await fetch(
`${process.env.SARLINK_API_BASE_URL}/auth/logout/`, `${process.env.SARLINK_API_BASE_URL}/auth/logout/`,
{ {
method: "POST", method: "POST",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
Authorization: `Token ${token}`, // Include the token for authentication Authorization: `Token ${token}`, // Include the token for authentication
}, },
}, },
); );
if (response.status !== 204) { if (response.status !== 204) {
throw new Error("Failed to log out from the backend"); throw new Error("Failed to log out from the backend");
} }
console.log("logout res in backend", response); console.log("logout res in backend", response);
// Since the API endpoint returns 204 No Content on success, we don't need to parse JSON // Since the API endpoint returns 204 No Content on success, we don't need to parse JSON
return null; // Return null to indicate a successful logout with no content return null; // Return null to indicate a successful logout with no content
} }
export async function checkIdOrPhone({ export async function checkIdOrPhone({
id_card, id_card,
phone_number, phone_number,
}: { }: {
id_card?: string; id_card?: string;
phone_number?: string; phone_number?: string;
}) { }) {
const response = await fetch( const response = await fetch(
`${process.env.SARLINK_API_BASE_URL}/api/auth/users/filter/?id_card=${id_card}&mobile=${phone_number}`, `${process.env.SARLINK_API_BASE_URL}/api/auth/users/filter/?id_card=${id_card}&mobile=${phone_number}`,
{ {
method: "GET", method: "GET",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
}, },
}, },
); );
const data = (await response.json()) as FilterUserResponse; const data = (await response.json()) as FilterUserResponse;
return data; return data;
} }
export async function checkTempIdOrPhone({ export async function checkTempIdOrPhone({
id_card, id_card,
phone_number, phone_number,
}: { }: {
id_card?: string; id_card?: string;
phone_number?: string; phone_number?: string;
}) { }) {
const response = await fetch( const response = await fetch(
`${process.env.SARLINK_API_BASE_URL}/api/auth/users/temp/filter/?id_card=${id_card}&mobile=${phone_number}`, `${process.env.SARLINK_API_BASE_URL}/api/auth/users/temp/filter/?id_card=${id_card}&mobile=${phone_number}`,
{ {
method: "GET", method: "GET",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
}, },
}, },
); );
const data = (await response.json()) as FilterTempUserResponse; const data = (await response.json()) as FilterTempUserResponse;
return data; return data;
} }
type TSignupUser = Pick< type TSignupUser = Pick<
User, User,
"username" | "address" | "mobile" | "id_card" | "dob" "username" | "address" | "mobile" | "id_card" | "dob"
> & { > & {
firstname: string; firstname: string;
lastname: string; lastname: string;
atoll: number; atoll: number;
island: number; island: number;
acc_no: string; acc_no: string;
terms_accepted: boolean; terms_accepted: boolean;
policy_accepted: boolean; policy_accepted: boolean;
}; };
export async function backendRegister({ payload }: { payload: TSignupUser }) { export async function backendRegister({ payload }: { payload: TSignupUser }) {
console.log("backendRegister payload", payload); console.log("backendRegister payload", payload);
const response = await fetch( const response = await fetch(
`${process.env.SARLINK_API_BASE_URL}/api/auth/register/`, `${process.env.SARLINK_API_BASE_URL}/api/auth/register/`,
{ {
method: "POST", method: "POST",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
}, },
body: JSON.stringify(payload), body: JSON.stringify(payload),
}, },
); );
console.log("backendRegister response", response); console.log("backendRegister response", response);
return handleApiResponse<{ t_username: string }>(response, "backendRegister"); return handleApiResponse<{ t_username: string }>(response, "backendRegister");
} }
const formSchema = z.object({ const formSchema = z.object({
mobile: z.string().regex(/^[79]\d{6}$/, "Please enter a valid phone number"), mobile: z.string().regex(/^[79]\d{6}$/, "Please enter a valid phone number"),
otp: z otp: z
.string() .string()
.min(6, { .min(6, {
message: "OTP is required.", message: "OTP is required.",
}) })
.max(6, { .max(6, {
message: "OTP is required.", message: "OTP is required.",
}), }),
}); });
export async function VerifyRegistrationOTP( export async function VerifyRegistrationOTP(
_actionState: ActionState, _actionState: ActionState,
formData: FormData, formData: FormData,
) { ) {
const formValues = Object.fromEntries(formData.entries()); const formValues = Object.fromEntries(formData.entries());
const result = formSchema.safeParse(formValues); const result = formSchema.safeParse(formValues);
console.log("formValues", formValues); console.log("formValues", formValues);
if (!result.success) { if (!result.success) {
return { return {
message: result.error.errors[0].message, // Get the error message from Zod message: result.error.errors[0].message, // Get the error message from Zod
status: "error", status: "error",
}; };
} }
if (formValues.otp === "") { if (formValues.otp === "") {
return { return {
message: "OTP is required.", message: "OTP is required.",
status: "error", status: "error",
}; };
} }
const { mobile, otp } = formValues; const { mobile, otp } = formValues;
const response = await fetch( const response = await fetch(
`${process.env.SARLINK_API_BASE_URL}/api/auth/register/verify/`, `${process.env.SARLINK_API_BASE_URL}/api/auth/register/verify/`,
{ {
method: "POST", method: "POST",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
}, },
body: JSON.stringify({ body: JSON.stringify({
mobile: mobile, mobile: mobile,
otp: otp as string, otp: otp as string,
}), }),
}, },
); );
const responseJson = await response.json(); const responseJson = await response.json();
console.log("responseJson", responseJson); console.log("responseJson", responseJson);
const data = responseJson as { message: string; verified: boolean }; const data = responseJson as { message: string; verified: boolean };
if (data.verified) { if (data.verified) {
return { return {
message: message:
"Your account has been successfully verified! You may login now.", "Your account has been successfully verified! You may login now.",
status: "verify_success", status: "verify_success",
}; };
// const [mobileLoginError, mobileLoginResponse] = await tryCatch( // const [mobileLoginError, mobileLoginResponse] = await tryCatch(
// backendMobileLogin({ mobile: mobile as string }), // backendMobileLogin({ mobile: mobile as string }),
// ); // );
// if (mobileLoginError) { // if (mobileLoginError) {
// return { // return {
// message: "Login Failed. Please contact support.", // message: "Login Failed. Please contact support.",
// status: "login_error", // status: "login_error",
// }; // };
// } // }
// if (mobileLoginResponse) { // if (mobileLoginResponse) {
// redirect(`/auth/verify-otp?phone_number=${mobile}`); // redirect(`/auth/verify-otp?phone_number=${mobile}`);
// } // }
} }
return { return {
message: message:
"Your account could not be verified. Please wait for you verification to be processed.", "Your account could not be verified. Please wait for you verification to be processed.",
status: "verify_error", status: "verify_error",
}; };
} }

View File

@@ -187,7 +187,7 @@ export async function blockDeviceAction(
blocked: isBlocking, blocked: isBlocking,
reason_for_blocking: session?.user?.is_superuser reason_for_blocking: session?.user?.is_superuser
? reason_for_blocking || ? reason_for_blocking ||
(action === "simple-block" ? "Blocked by admin" : "") (action === "simple-block" ? "Blocked by admin" : "")
: isBlocking : isBlocking
? "Blocked by parent" ? "Blocked by parent"
: "-", : "-",