mirror of
https://github.com/i701/sarlink-portal.git
synced 2025-07-06 18:19:33 +00:00
Merge pull request #7 from i701/feat/wallet-topups
Some checks failed
Build and Push Docker Images / Build and Push Docker Images (push) Has been cancelled
Some checks failed
Build and Push Docker Images / Build and Push Docker Images (push) Has been cancelled
feature/wallet topups
This commit is contained in:
@ -1,25 +1,31 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { getServerSession } from "next-auth";
|
||||
import { authOptions } from "@/app/auth";
|
||||
import type {
|
||||
ApiError,
|
||||
ApiResponse,
|
||||
NewPayment,
|
||||
Payment,
|
||||
Topup
|
||||
} from "@/lib/backend-types";
|
||||
import type { TopupResponse } from "@/lib/types";
|
||||
import type { User } from "@/lib/types/user";
|
||||
import { checkSession } from "@/utils/session";
|
||||
import { handleApiResponse, tryCatch } from "@/utils/tryCatch";
|
||||
import { getServerSession } from "next-auth";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { redirect } from "next/navigation";
|
||||
import { handleApiResponse } from "@/utils/tryCatch";
|
||||
|
||||
type GenericGetResponseProps = {
|
||||
offset?: number;
|
||||
limit?: number;
|
||||
page?: number;
|
||||
[key: string]: string | number | undefined;
|
||||
};
|
||||
|
||||
export async function createPayment(data: NewPayment) {
|
||||
const session = await getServerSession(authOptions);
|
||||
console.log("data", data);
|
||||
const response = await fetch(
|
||||
`${
|
||||
process.env.SARLINK_API_BASE_URL // });
|
||||
`${process.env.SARLINK_API_BASE_URL // });
|
||||
}/api/billing/payment/`,
|
||||
{
|
||||
method: "POST",
|
||||
@ -43,6 +49,22 @@ export async function createPayment(data: NewPayment) {
|
||||
return payment;
|
||||
}
|
||||
|
||||
export async function createTopup(data: { amount: number }) {
|
||||
const session = await getServerSession(authOptions);
|
||||
const response = await fetch(
|
||||
`${process.env.SARLINK_API_BASE_URL}/api/billing/topup/`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Token ${session?.apiToken}`,
|
||||
},
|
||||
body: JSON.stringify(data),
|
||||
},
|
||||
);
|
||||
return handleApiResponse<Topup>(response, "createTopup");
|
||||
}
|
||||
|
||||
export async function getPayment({ id }: { id: string }) {
|
||||
const session = await getServerSession(authOptions);
|
||||
const response = await fetch(
|
||||
@ -92,6 +114,67 @@ export async function getPayments() {
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function getTopups(params: GenericGetResponseProps) {
|
||||
|
||||
// Build query string from all defined params
|
||||
const query = Object.entries(params)
|
||||
.filter(([_, value]) => value !== undefined && value !== "")
|
||||
.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`)
|
||||
.join("&");
|
||||
|
||||
const session = await getServerSession(authOptions);
|
||||
const response = await fetch(
|
||||
`${process.env.SARLINK_API_BASE_URL}/api/billing/topup/?${query}`,
|
||||
{
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Token ${session?.apiToken}`,
|
||||
},
|
||||
},
|
||||
);
|
||||
return handleApiResponse<ApiResponse<Topup>>(response, "getTopups");
|
||||
}
|
||||
|
||||
export async function getTopup({ id }: { id: string }) {
|
||||
const session = await getServerSession(authOptions);
|
||||
const response = await fetch(
|
||||
`${process.env.SARLINK_API_BASE_URL}/api/billing/topup/${id}`,
|
||||
{
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Token ${session?.apiToken}`,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
return handleApiResponse<Topup>(response, "getTopup");
|
||||
}
|
||||
|
||||
export async function cancelTopup({ id }: { id: string }) {
|
||||
const session = await getServerSession(authOptions);
|
||||
const response = await fetch(
|
||||
`${process.env.SARLINK_API_BASE_URL}/api/billing/topup/${id}/delete/`,
|
||||
{
|
||||
method: "DELETE",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Token ${session?.apiToken}`,
|
||||
},
|
||||
},
|
||||
);
|
||||
if (!response.ok) {
|
||||
const errorData = (await response.json()) as ApiError;
|
||||
const errorMessage =
|
||||
errorData.message || errorData.detail || "An error occurred.";
|
||||
const error = new Error(errorMessage);
|
||||
(error as ApiError & { details?: ApiError }).details = errorData; // Attach the errorData to the error object
|
||||
throw error;
|
||||
}
|
||||
return { message: "Topup successfully canceled." };
|
||||
}
|
||||
|
||||
export async function cancelPayment({ id }: { id: string }) {
|
||||
const session = await getServerSession(authOptions);
|
||||
const response = await fetch(
|
||||
@ -142,6 +225,25 @@ export async function verifyPayment({ id, method }: UpdatePayment) {
|
||||
return handleApiResponse<Payment>(response, "updatePayment");
|
||||
}
|
||||
|
||||
type UpdateTopupPayment = {
|
||||
id: string;
|
||||
};
|
||||
|
||||
export async function verifyTopupPayment({ id }: UpdateTopupPayment) {
|
||||
const session = await getServerSession(authOptions);
|
||||
const response = await fetch(
|
||||
`${process.env.SARLINK_API_BASE_URL}/api/billing/topup/${id}/verify/`,
|
||||
{
|
||||
method: "PUT",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Token ${session?.apiToken}`,
|
||||
},
|
||||
},
|
||||
);
|
||||
revalidatePath("/top-ups/[topupId]", "page");
|
||||
return handleApiResponse<TopupResponse>(response, "verifyTopupPayment");
|
||||
}
|
||||
|
||||
export async function getProfile() {
|
||||
const session = await getServerSession(authOptions);
|
||||
|
72
app/(dashboard)/top-ups/[topupId]/page.tsx
Normal file
72
app/(dashboard)/top-ups/[topupId]/page.tsx
Normal file
@ -0,0 +1,72 @@
|
||||
import { redirect } from "next/navigation";
|
||||
import { getTopup } from "@/actions/payment";
|
||||
import CancelTopupButton from "@/components/billing/cancel-topup-button";
|
||||
import ExpiryCountDown from "@/components/billing/expiry-time-countdown";
|
||||
import ClientErrorMessage from "@/components/client-error-message";
|
||||
import TopupToPay from "@/components/topup-to-pay";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { TextShimmer } from "@/components/ui/text-shimmer";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { tryCatch } from "@/utils/tryCatch";
|
||||
export default async function TopupPage({
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{ topupId: string }>;
|
||||
}) {
|
||||
const topupId = (await params).topupId;
|
||||
const [error, topup] = await tryCatch(getTopup({ id: topupId }));
|
||||
if (error) {
|
||||
if (error.message === "Invalid token.") redirect("/auth/signin");
|
||||
return <ClientErrorMessage message={error.message} />;
|
||||
}
|
||||
|
||||
|
||||
return (
|
||||
<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">
|
||||
<h3 className="text-sarLinkOrange text-2xl">Topup</h3>
|
||||
<div className="flex flex-col gap-4 items-end w-full">
|
||||
{!topup.is_expired && (
|
||||
|
||||
<Button
|
||||
disabled
|
||||
className={cn(
|
||||
"rounded-md opacity-100! uppercase font-semibold",
|
||||
// topup?.paid
|
||||
// ? "text-green-900 bg-green-500/20"
|
||||
// : "text-inherit bg-yellow-400",
|
||||
)}
|
||||
>
|
||||
{topup?.paid ? <span>Paid</span> : <TextShimmer>Payment Pending</TextShimmer>}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{!topup.paid && (
|
||||
topup.is_expired ? (
|
||||
<Button
|
||||
disabled
|
||||
className="rounded-md opacity-100! uppercase font-semibold text-red-500 bg-red-500/20"
|
||||
>
|
||||
Topup Expired
|
||||
</Button>
|
||||
) : (
|
||||
<CancelTopupButton topupId={topupId} />
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{!topup.paid && (
|
||||
<ExpiryCountDown expiresAt={topup.expires_at} />
|
||||
)}
|
||||
<div
|
||||
id="user-topup-details"
|
||||
className="pb-4 gap-4 flex sm:flex-row flex-col items-start justify-start"
|
||||
>
|
||||
<TopupToPay
|
||||
disabled={topup.paid || topup.is_expired}
|
||||
topup={topup || undefined}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
63
app/(dashboard)/top-ups/page.tsx
Normal file
63
app/(dashboard)/top-ups/page.tsx
Normal file
@ -0,0 +1,63 @@
|
||||
import { Suspense } from "react";
|
||||
import DynamicFilter from "@/components/generic-filter";
|
||||
import { TopupsTable } from "@/components/topups-table";
|
||||
|
||||
export default async function Topups({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<{
|
||||
query: string;
|
||||
page: number;
|
||||
sortBy: string;
|
||||
status: string;
|
||||
}>;
|
||||
}) {
|
||||
const query = (await searchParams)?.query || "";
|
||||
|
||||
return (
|
||||
<div>
|
||||
<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">My Topups</h3>
|
||||
</div>
|
||||
<div
|
||||
id="topup-filters"
|
||||
className=" pb-4 gap-4 flex sm:flex-row flex-col items-start justify-start"
|
||||
>
|
||||
<DynamicFilter
|
||||
inputs={[
|
||||
{
|
||||
label: "Paid",
|
||||
name: "paid",
|
||||
type: "radio-group",
|
||||
options: [
|
||||
{
|
||||
label: "All",
|
||||
value: "",
|
||||
},
|
||||
{
|
||||
label: "Paid",
|
||||
value: "true",
|
||||
},
|
||||
{
|
||||
label: "Pending",
|
||||
value: "false",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
label: "Topup Amount",
|
||||
name: "amount",
|
||||
type: "dual-range-slider",
|
||||
min: 0,
|
||||
max: 1000,
|
||||
step: 10,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
<Suspense key={query} fallback={"loading...."}>
|
||||
<TopupsTable searchParams={searchParams} />
|
||||
</Suspense>
|
||||
</div>
|
||||
);
|
||||
}
|
37
components/billing/cancel-topup-button.tsx
Normal file
37
components/billing/cancel-topup-button.tsx
Normal file
@ -0,0 +1,37 @@
|
||||
"use client";
|
||||
|
||||
import { Loader2, Trash2 } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import React from "react";
|
||||
import { toast } from "sonner";
|
||||
import { cancelTopup } from "@/actions/payment";
|
||||
import { tryCatch } from "@/utils/tryCatch";
|
||||
import { Button } from "../ui/button";
|
||||
|
||||
export default function CancelTopupButton({
|
||||
topupId,
|
||||
}: { topupId: string }) {
|
||||
const router = useRouter();
|
||||
const [loading, setLoading] = React.useState(false);
|
||||
return (
|
||||
<Button
|
||||
onClick={async () => {
|
||||
setLoading(true);
|
||||
const [error, x] = await tryCatch(cancelTopup({ id: topupId }));
|
||||
console.log(x);
|
||||
if (error) {
|
||||
toast.error(error.message);
|
||||
setLoading(false);
|
||||
} else {
|
||||
toast.success("Topup cancelled successfully!")
|
||||
router.replace("/top-ups");
|
||||
}
|
||||
}}
|
||||
disabled={loading}
|
||||
variant={"destructive"}
|
||||
>
|
||||
Cancel Topup
|
||||
{loading ? <Loader2 className="animate-spin" /> : <Trash2 />}
|
||||
</Button>
|
||||
);
|
||||
}
|
57
components/billing/expiry-time-countdown.tsx
Normal file
57
components/billing/expiry-time-countdown.tsx
Normal file
@ -0,0 +1,57 @@
|
||||
'use client'
|
||||
import { usePathname, useRouter } from 'next/navigation'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { Progress } from '@/components/ui/progress'
|
||||
|
||||
const calculateTimeLeft = (expiresAt: string) => {
|
||||
const now = Date.now()
|
||||
const expirationTime = new Date(expiresAt).getTime()
|
||||
return Math.max(0, Math.floor((expirationTime - now) / 1000))
|
||||
}
|
||||
|
||||
const HumanizeTimeLeft = (seconds: number) => {
|
||||
const minutes = Math.floor(seconds / 60)
|
||||
const remainingSeconds = seconds % 60
|
||||
return `${minutes}m ${remainingSeconds}s`
|
||||
}
|
||||
|
||||
export default function ExpiryCountDown({ expiresAt }: { expiresAt: string }) {
|
||||
const [timeLeft, setTimeLeft] = useState(calculateTimeLeft(expiresAt))
|
||||
const [mounted, setMounted] = useState(false)
|
||||
const router = useRouter()
|
||||
const pathname = usePathname()
|
||||
useEffect(() => {
|
||||
setMounted(true)
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
const timer = setInterval(() => {
|
||||
setTimeLeft(calculateTimeLeft(expiresAt))
|
||||
}, 1000)
|
||||
|
||||
return () => clearInterval(timer)
|
||||
}, [expiresAt])
|
||||
|
||||
useEffect(() => {
|
||||
if (timeLeft <= 0) {
|
||||
router.replace(pathname)
|
||||
}
|
||||
}, [timeLeft, router, pathname])
|
||||
|
||||
if (!mounted) {
|
||||
return null
|
||||
}
|
||||
return (
|
||||
<div className='overflow-clip relative mx-2 p-4 rounded-md border border-dashed flex items-center justify-between text-muted-foreground'>
|
||||
<div className='absolute inset-0 title-bg mask-b-from-0' />
|
||||
{timeLeft ? (
|
||||
<span>Time left: {HumanizeTimeLeft(timeLeft)}</span>
|
||||
) : (
|
||||
<span>Top up has expired. Please make another topup to add balance to your wallet.</span>
|
||||
)}
|
||||
{timeLeft > 0 && (
|
||||
<Progress className='absolute bottom-0 left-0 right-0' color='#f49b5b' value={timeLeft / 600 * 100} />
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
177
components/topup-to-pay.tsx
Normal file
177
components/topup-to-pay.tsx
Normal file
@ -0,0 +1,177 @@
|
||||
"use client";
|
||||
import {
|
||||
BadgeDollarSign,
|
||||
Clipboard,
|
||||
ClipboardCheck,
|
||||
Loader2,
|
||||
} from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { verifyTopupPayment } from "@/actions/payment";
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCaption,
|
||||
TableCell,
|
||||
TableFooter,
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
import type { Topup } from "@/lib/backend-types";
|
||||
import { Button } from "./ui/button";
|
||||
|
||||
export default function TopupToPay({ topup, disabled }: { topup?: Topup, disabled?: boolean }) {
|
||||
const [verifyingTransferPayment, setVerifyingTransferPayment] =
|
||||
useState(false);
|
||||
|
||||
return (
|
||||
<div className="w-full">
|
||||
<div className="m-2 flex items-end justify-end p-2 text-sm text-foreground border rounded">
|
||||
<Table>
|
||||
<TableCaption>
|
||||
<div className="max-w-sm mx-auto">
|
||||
<p>Please send the following amount to the payment address</p>
|
||||
<AccountInfomation
|
||||
accName="Baraveli Dev"
|
||||
accountNo="90101400028321000"
|
||||
/>
|
||||
{topup?.paid ? (
|
||||
<Button
|
||||
size={"lg"}
|
||||
variant={"secondary"}
|
||||
disabled
|
||||
className="dark:text-green-200 text-green-900 bg-green-500/20 uppercase font-semibold"
|
||||
>
|
||||
Topup Payment Verified
|
||||
</Button>
|
||||
) : (
|
||||
<div className="flex flex-col gap-2">
|
||||
<Button
|
||||
disabled={disabled || verifyingTransferPayment}
|
||||
onClick={async () => {
|
||||
setVerifyingTransferPayment(true);
|
||||
try {
|
||||
const response = await verifyTopupPayment({
|
||||
id: topup?.id ?? "",
|
||||
});
|
||||
toast.success("Topup successful!", {
|
||||
closeButton: true,
|
||||
description:
|
||||
`Your topup payment has been verified successfully using ${response.transaction?.sourceBank} bank transfer on ${response.transaction?.trxDate}.` || response.message,
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof Error) {
|
||||
toast.error("Topup Payment Verification Failed", {
|
||||
closeButton: true,
|
||||
description:
|
||||
error.message || "Please check your payment details and try again.",
|
||||
});
|
||||
} else {
|
||||
toast.error("Topup verification failed.");
|
||||
}
|
||||
} finally {
|
||||
setVerifyingTransferPayment(false);
|
||||
}
|
||||
}}
|
||||
size={"lg"}
|
||||
className="mb-4"
|
||||
>
|
||||
{verifyingTransferPayment
|
||||
? "Processing payment..."
|
||||
: "I have paid"}
|
||||
{verifyingTransferPayment ? (
|
||||
<Loader2 className="animate-spin" />
|
||||
) : (
|
||||
<BadgeDollarSign />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</TableCaption>
|
||||
<TableBody className="">
|
||||
<TableRow>
|
||||
<TableCell>Topup created at</TableCell>
|
||||
<TableCell className="text-right text-muted-foreground">
|
||||
{new Date(topup?.created_at ?? "").toLocaleDateString("en-US", {
|
||||
month: "short",
|
||||
day: "2-digit",
|
||||
year: "numeric",
|
||||
minute: "2-digit",
|
||||
hour: "2-digit",
|
||||
second: "2-digit",
|
||||
})}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell>Topup expires at</TableCell>
|
||||
<TableCell className="text-right text-sarLinkOrange">
|
||||
{new Date(topup?.expires_at ?? "").toLocaleDateString("en-US", {
|
||||
month: "short",
|
||||
day: "2-digit",
|
||||
year: "numeric",
|
||||
minute: "2-digit",
|
||||
hour: "2-digit",
|
||||
second: "2-digit",
|
||||
})}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell>MIB Reference</TableCell>
|
||||
<TableCell className="text-right">
|
||||
{topup?.mib_reference ? topup.mib_reference : "N/A"}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
<TableFooter>
|
||||
<TableRow className="">
|
||||
<TableCell colSpan={1}>Total Due</TableCell>
|
||||
<TableCell className="text-right text-3xl font-bold">
|
||||
{topup?.amount?.toFixed(2)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableFooter>
|
||||
</Table>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function AccountInfomation({
|
||||
accountNo,
|
||||
accName,
|
||||
}: {
|
||||
accountNo: string;
|
||||
accName: string;
|
||||
}) {
|
||||
const [accNo, setAccNo] = useState(false);
|
||||
return (
|
||||
<div className="justify-start items-start border my-4 flex flex-col gap-2 p-2 rounded-md">
|
||||
<h6 className="title-bg uppercase p-2 border rounded w-full font-semibold">
|
||||
Account Information
|
||||
</h6>
|
||||
<div className="border justify-start flex flex-col items-start bg-white/10 w-full p-2 rounded">
|
||||
<div className="text-sm font-semibold">Account Name</div>
|
||||
<span>{accName}</span>
|
||||
</div>
|
||||
<div className="border flex justify-between items-start gap-2 bg-white/10 w-full p-2 rounded">
|
||||
<div className="flex flex-col items-start justify-start">
|
||||
<p className="text-sm font-semibold">Account No</p>
|
||||
<span>{accountNo}</span>
|
||||
</div>
|
||||
<Button
|
||||
onClick={() => {
|
||||
setTimeout(() => {
|
||||
setAccNo(true);
|
||||
navigator.clipboard.writeText(accountNo);
|
||||
}, 2000);
|
||||
toast.success("Account number copied!");
|
||||
setAccNo((prev) => !prev);
|
||||
}}
|
||||
variant={"link"}
|
||||
>
|
||||
{accNo ? <Clipboard /> : <ClipboardCheck color="green" />}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
235
components/topups-table.tsx
Normal file
235
components/topups-table.tsx
Normal file
@ -0,0 +1,235 @@
|
||||
import { Calendar } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { redirect } from "next/navigation";
|
||||
import { getTopups } from "@/actions/payment";
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCaption,
|
||||
TableCell,
|
||||
TableFooter,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
import type { Topup } from "@/lib/backend-types";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { tryCatch } from "@/utils/tryCatch";
|
||||
import Pagination from "./pagination";
|
||||
import { Badge } from "./ui/badge";
|
||||
import { Button } from "./ui/button";
|
||||
|
||||
export async function TopupsTable({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<{
|
||||
[key: string]: unknown;
|
||||
}>;
|
||||
}) {
|
||||
const resolvedParams = await searchParams;
|
||||
|
||||
// Build params object
|
||||
const apiParams: Record<string, string | number | undefined> = {};
|
||||
for (const [key, value] of Object.entries(resolvedParams)) {
|
||||
if (value !== undefined && value !== "") {
|
||||
apiParams[key] = typeof value === "number" ? value : String(value);
|
||||
}
|
||||
}
|
||||
|
||||
const [error, topups] = await tryCatch(getTopups(apiParams));
|
||||
|
||||
if (error) {
|
||||
if (error.message.includes("Unauthorized")) {
|
||||
redirect("/auth/signin");
|
||||
} else {
|
||||
return <pre>{JSON.stringify(error, null, 2)}</pre>;
|
||||
}
|
||||
}
|
||||
const { data, meta } = topups;
|
||||
return (
|
||||
<div>
|
||||
{data?.length === 0 ? (
|
||||
<div className="h-[calc(100svh-400px)] flex flex-col items-center justify-center my-4">
|
||||
<h3>No topups yet.</h3>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="hidden sm:block">
|
||||
<Table className="overflow-scroll">
|
||||
<TableCaption>Table of all topups.</TableCaption>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Details</TableHead>
|
||||
<TableHead>Expires at</TableHead>
|
||||
<TableHead>Expired</TableHead>
|
||||
<TableHead>Amount</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody className="overflow-scroll">
|
||||
{topups?.data?.map((topup) => (
|
||||
<TableRow key={topup.id}>
|
||||
<TableCell>
|
||||
<div
|
||||
className={cn(
|
||||
"flex flex-col items-start border rounded p-2",
|
||||
topup?.paid
|
||||
? "bg-green-500/10 border-dashed border-green-500"
|
||||
: topup?.is_expired
|
||||
? "bg-gray-500/10 border-dashed border-gray-500 dark:border-gray-500/50"
|
||||
: "bg-yellow-500/10 border-dashed border-yellow-500 dark:border-yellow-500/50",
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<Calendar size={16} opacity={0.5} />
|
||||
<span className="text-muted-foreground">
|
||||
{new Date(topup.created_at).toLocaleDateString(
|
||||
"en-US",
|
||||
{
|
||||
month: "short",
|
||||
day: "2-digit",
|
||||
year: "numeric",
|
||||
minute: "2-digit",
|
||||
hour: "2-digit",
|
||||
},
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2 mt-2">
|
||||
<Link
|
||||
className="font-medium hover:underline"
|
||||
href={`/top-ups/${topup.id}`}
|
||||
>
|
||||
<Button size={"sm"} variant="outline">
|
||||
View Details
|
||||
</Button>
|
||||
</Link>
|
||||
{!topup.is_expired && (
|
||||
|
||||
<Badge
|
||||
className={cn(
|
||||
topup?.paid
|
||||
? "text-green-500 bg-green-500/20"
|
||||
: "text-yellow-500 bg-yellow-500/20",
|
||||
)}
|
||||
variant={topup.paid ? "outline" : "secondary"}
|
||||
>
|
||||
{topup.paid ? "Paid" : "Unpaid"}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<span>
|
||||
{new Date(topup.expires_at).toLocaleDateString("en-US", {
|
||||
month: "short",
|
||||
day: "2-digit",
|
||||
year: "numeric",
|
||||
minute: "2-digit",
|
||||
hour: "2-digit",
|
||||
})}
|
||||
</span>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<span className="font-semibold pr-2">
|
||||
{topup.is_expired ? <Badge>Yes</Badge> : <Badge variant="secondary">No</Badge>}
|
||||
</span>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<span className="font-semibold pr-2">
|
||||
{topup.amount.toFixed(2)}
|
||||
</span>
|
||||
MVR
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
<TableFooter>
|
||||
<TableRow>
|
||||
<TableCell colSpan={4} className="text-muted-foreground">
|
||||
{meta?.total === 1 ? (
|
||||
<p className="text-center">
|
||||
Total {meta?.total} topup.
|
||||
</p>
|
||||
) : (
|
||||
<p className="text-center">
|
||||
Total {meta?.total} topups.
|
||||
</p>
|
||||
)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableFooter>
|
||||
</Table>
|
||||
<Pagination
|
||||
totalPages={meta.total / meta.per_page}
|
||||
currentPage={meta.current_page}
|
||||
/>
|
||||
</div>
|
||||
<div className="sm:hidden block">
|
||||
{data.map((topup) => (
|
||||
<MobileTopupDetails key={topup.id} topup={topup} />
|
||||
))}
|
||||
</div>
|
||||
<Pagination
|
||||
totalPages={meta?.last_page}
|
||||
currentPage={meta?.current_page}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function MobileTopupDetails({ topup }: { topup: Topup }) {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"flex flex-col items-start border rounded p-2 my-2",
|
||||
topup?.paid
|
||||
? "bg-green-500/10 border-dashed border-green=500"
|
||||
: "bg-yellow-500/10 border-dashed border-yellow-500 dark:border-yellow-500/50",
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<Calendar size={16} opacity={0.5} />
|
||||
<span className="text-muted-foreground text-sm">
|
||||
{new Date(topup.created_at).toLocaleDateString("en-US", {
|
||||
month: "short",
|
||||
day: "2-digit",
|
||||
year: "numeric",
|
||||
})}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2 mt-2">
|
||||
<Link
|
||||
className="font-medium hover:underline"
|
||||
href={`/top-ups/${topup.id}`}
|
||||
>
|
||||
<Button size={"sm"} variant="outline">
|
||||
View Details
|
||||
</Button>
|
||||
</Link>
|
||||
<Badge
|
||||
className={cn(
|
||||
topup?.paid
|
||||
? "text-green-500 bg-green-500/20"
|
||||
: "text-yellow-500 bg-yellow-500/20",
|
||||
)}
|
||||
variant={topup.paid ? "outline" : "secondary"}
|
||||
>
|
||||
{topup.paid ? "Paid" : "Unpaid"}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="bg-white dark:bg-black p-2 rounded mt-2 w-full border">
|
||||
<div className="block sm:hidden">
|
||||
<h3 className="text-sm font-medium">Amount</h3>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{topup.amount.toFixed(2)} MVR
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
@ -1,4 +1,5 @@
|
||||
import {
|
||||
BadgePlus,
|
||||
Calculator,
|
||||
ChevronRight,
|
||||
Coins,
|
||||
@ -73,6 +74,12 @@ export async function AppSidebar({
|
||||
icon: <CreditCard size={16} />,
|
||||
perm_identifier: "payment",
|
||||
},
|
||||
{
|
||||
title: "Top Ups",
|
||||
link: "/top-ups?page=1",
|
||||
icon: <BadgePlus size={16} />,
|
||||
perm_identifier: "topup",
|
||||
},
|
||||
{
|
||||
title: "Parental Control",
|
||||
link: "/parental-control",
|
||||
|
@ -1,7 +1,7 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Progress as ProgressPrimitive } from "radix-ui"
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
@ -12,13 +12,13 @@ const Progress = React.forwardRef<
|
||||
<ProgressPrimitive.Root
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"relative h-2 w-full overflow-hidden rounded-full bg-primary/20",
|
||||
"relative h-1 w-full overflow-hidden rounded-full bg-primary/20",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ProgressPrimitive.Indicator
|
||||
className="h-full w-full flex-1 bg-primary transition-all"
|
||||
className={cn("h-full w-full flex-1 transition-all", className, value ?? 0 < 20 ? "bg-red-500" : "bg-sarLinkOrange")}
|
||||
style={{ transform: `translateX(-${100 - (value || 0)}%)` }}
|
||||
/>
|
||||
</ProgressPrimitive.Root>
|
||||
|
@ -1,4 +1,11 @@
|
||||
"use client";
|
||||
import { useAtom } from "jotai";
|
||||
import { CircleDollarSign, Loader2, Wallet2 } from "lucide-react";
|
||||
import millify from "millify";
|
||||
import { usePathname, useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { createTopup } from "@/actions/payment";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Drawer,
|
||||
@ -12,12 +19,6 @@ import {
|
||||
} from "@/components/ui/drawer";
|
||||
import { WalletDrawerOpenAtom, walletTopUpValue } from "@/lib/atoms";
|
||||
import type { TopupType } from "@/lib/types";
|
||||
import { useAtom } from "jotai";
|
||||
import { CircleDollarSign, Loader2, Wallet2 } from "lucide-react";
|
||||
import millify from "millify";
|
||||
import { useSession } from "next-auth/react";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import NumberInput from "./number-input";
|
||||
|
||||
export function Wallet({
|
||||
@ -25,21 +26,18 @@ export function Wallet({
|
||||
}: {
|
||||
walletBalance: number;
|
||||
}) {
|
||||
const session = useSession();
|
||||
const pathname = usePathname();
|
||||
const [amount, setAmount] = useAtom(walletTopUpValue);
|
||||
const [isOpen, setIsOpen] = useAtom(WalletDrawerOpenAtom);
|
||||
const [disabled, setDisabled] = useState(false);
|
||||
// const router = useRouter();
|
||||
const router = useRouter();
|
||||
|
||||
if (pathname === "/payment") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const data: TopupType = {
|
||||
userId: session?.data?.user?.id ?? "",
|
||||
amount: Number.parseFloat(amount.toFixed(2)),
|
||||
paid: false,
|
||||
};
|
||||
|
||||
return (
|
||||
@ -85,23 +83,20 @@ export function Wallet({
|
||||
onClick={async () => {
|
||||
console.log(data);
|
||||
setDisabled(true);
|
||||
// const payment = await createPayment(data)
|
||||
const topup = await createTopup(data)
|
||||
setDisabled(false);
|
||||
// setMonths(1)
|
||||
// if (payment) {
|
||||
// router.push(`/payments/${payment.id}`);
|
||||
// setIsOpen(!isOpen);
|
||||
// } else {
|
||||
// toast.error("Something went wrong.")
|
||||
// }
|
||||
if (topup) {
|
||||
router.push(`/top-ups/${topup.id}`);
|
||||
setIsOpen(!isOpen);
|
||||
} else {
|
||||
toast.error("Something went wrong.")
|
||||
}
|
||||
}}
|
||||
className="w-full"
|
||||
disabled={amount === 0 || disabled}
|
||||
>
|
||||
{disabled ? (
|
||||
<>
|
||||
<Loader2 className="ml-2 animate-spin" />
|
||||
</>
|
||||
<Loader2 className="ml-2 animate-spin" />
|
||||
) : (
|
||||
<>
|
||||
Go to payment
|
||||
|
@ -57,6 +57,20 @@ export interface ApiError {
|
||||
detail?: string;
|
||||
}
|
||||
|
||||
export interface Topup {
|
||||
id: string;
|
||||
amount: number;
|
||||
user: Pick<User, "id" | "id_card" | "mobile"> & {
|
||||
name: string;
|
||||
};
|
||||
paid: boolean;
|
||||
mib_reference: string | null;
|
||||
expires_at: string;
|
||||
is_expired: boolean;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface Payment {
|
||||
id: string;
|
||||
devices: Device[];
|
||||
|
14
lib/types.ts
14
lib/types.ts
@ -1,9 +1,19 @@
|
||||
export type TopupType = {
|
||||
amount: number;
|
||||
userId: string;
|
||||
paid: boolean;
|
||||
};
|
||||
|
||||
export type Transaction = {
|
||||
ref: string;
|
||||
sourceBank: string;
|
||||
trxDate: string;
|
||||
}
|
||||
|
||||
export type TopupResponse = {
|
||||
status: boolean;
|
||||
message: string;
|
||||
transaction?: Transaction
|
||||
}
|
||||
|
||||
interface IpAddress {
|
||||
ip: string;
|
||||
mask: number;
|
||||
|
1
package-lock.json
generated
1
package-lock.json
generated
@ -12,6 +12,7 @@
|
||||
"@hookform/resolvers": "^5.1.1",
|
||||
"@pyncz/tailwind-mask-image": "^2.0.0",
|
||||
"@radix-ui/react-dialog": "^1.1.14",
|
||||
"@radix-ui/react-progress": "^1.1.7",
|
||||
"@tailwindcss/postcss": "^4.1.11",
|
||||
"@tanstack/react-query": "^5.61.4",
|
||||
"axios": "^1.8.4",
|
||||
|
@ -13,6 +13,7 @@
|
||||
"@hookform/resolvers": "^5.1.1",
|
||||
"@pyncz/tailwind-mask-image": "^2.0.0",
|
||||
"@radix-ui/react-dialog": "^1.1.14",
|
||||
"@radix-ui/react-progress": "^1.1.7",
|
||||
"@tailwindcss/postcss": "^4.1.11",
|
||||
"@tanstack/react-query": "^5.61.4",
|
||||
"axios": "^1.8.4",
|
||||
|
Reference in New Issue
Block a user