mirror of
https://github.com/i701/sarlink-portal.git
synced 2025-11-05 13:17:00 +00:00
Compare commits
39 Commits
feat/block
...
feat/devic
| Author | SHA1 | Date | |
|---|---|---|---|
| 1a11f1a06c | |||
| 837cc35ad3 | |||
| e984705849 | |||
| 4797ee8dde | |||
| df2b3da22e | |||
| 9e25da717b | |||
|
|
62678b6a84 | ||
| 8c94c92281 | |||
|
|
b3805feefe | ||
| b9d8e56c3c | |||
| d4993530f7 | |||
| 3e3b5f15db | |||
| 13f0e720f4 | |||
| 9fe3c3b774 | |||
| 135edf80a8 | |||
| c0a71dd811 | |||
| 2597ac7d79 | |||
| 154226b48d | |||
| 683d85798a | |||
| da7d101ea6 | |||
| fa0d088f7f | |||
|
5bc8366003
|
|||
|
b22a26a2e8
|
|||
|
f9ed95ae18
|
|||
| 5de4bb9100 | |||
|
|
d5968a5c6b | ||
| 378fb4074c | |||
|
|
15c2713a1b | ||
| ef7121f247 | |||
|
|
a41be97cdf | ||
| 0c7f34fa85 | |||
| 013befa433 | |||
| f4c34d3b7b | |||
|
|
f6e60c0188 | ||
| f3328f7a7b | |||
| ee461bbbf8 | |||
| 89a35a9674 | |||
| cd1dba06f0 | |||
|
|
ed19f440d8 |
@@ -35,6 +35,11 @@ jobs:
|
||||
- name: Deploy production
|
||||
if: github.event_name != 'pull_request'
|
||||
run: |
|
||||
ssh root@10.0.1.5 -t "cd /mnt && docker compose --progress plain pull portal-ui"
|
||||
ssh root@10.0.1.5 -t "cd /mnt && docker compose --progress plain down portal-ui"
|
||||
ssh root@10.0.1.5 -t "cd /mnt && docker compose --progress plain up -d portal-ui"
|
||||
ssh root@10.0.1.5 -t "cd /mnt && \
|
||||
docker compose --progress plain pull portal-ui && \
|
||||
docker compose --progress plain down portal-ui && \
|
||||
docker compose --progress plain up -d portal-ui"
|
||||
|
||||
- name: Clean up dangling images
|
||||
if: github.event_name != 'pull_request'
|
||||
run: ssh root@10.0.1.5 -t "docker image prune -f"
|
||||
|
||||
@@ -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(
|
||||
@@ -68,10 +90,19 @@ export async function getPayment({ id }: { id: string }) {
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function getPayments() {
|
||||
type GetPaymentProps = {
|
||||
[key: string]: string | number | undefined; // Allow additional properties for flexibility
|
||||
};
|
||||
|
||||
export async function getPayments(params: GetPaymentProps) {
|
||||
// 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/payment/`,
|
||||
`${process.env.SARLINK_API_BASE_URL}/api/billing/payment/?${query}`,
|
||||
{
|
||||
method: "GET",
|
||||
headers: {
|
||||
@@ -92,27 +123,72 @@ export async function getPayments() {
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function cancelPayment({ id }: { id: string }) {
|
||||
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/payment/${id}/delete/`,
|
||||
`${process.env.SARLINK_API_BASE_URL}/api/billing/topup/?${query}`,
|
||||
{
|
||||
method: "DELETE",
|
||||
method: "GET",
|
||||
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: "Payment successfully canceled." };
|
||||
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}/cancel/`,
|
||||
{
|
||||
method: "PATCH",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Token ${session?.apiToken}`,
|
||||
},
|
||||
},
|
||||
);
|
||||
return handleApiResponse<Topup>(response, "cancelTopup");
|
||||
}
|
||||
|
||||
export async function cancelPayment({ id }: { id: string }) {
|
||||
const session = await getServerSession(authOptions);
|
||||
const response = await fetch(
|
||||
`${process.env.SARLINK_API_BASE_URL}/api/billing/payment/${id}/cancel/`,
|
||||
{
|
||||
method: "PATCH",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Token ${session?.apiToken}`,
|
||||
},
|
||||
},
|
||||
);
|
||||
return handleApiResponse<Payment>(response, "cancelPayment");
|
||||
}
|
||||
|
||||
type UpdatePayment = {
|
||||
@@ -142,6 +218,150 @@ export async function verifyPayment({ id, method }: UpdatePayment) {
|
||||
return handleApiResponse<Payment>(response, "updatePayment");
|
||||
}
|
||||
|
||||
export type VerifyDevicePaymentState = {
|
||||
payment?: Payment;
|
||||
message: string;
|
||||
success: boolean;
|
||||
fieldErrors: Record<string, string>;
|
||||
payload?: FormData;
|
||||
}
|
||||
|
||||
export async function verifyDevicePayment(
|
||||
_prevState: VerifyDevicePaymentState,
|
||||
formData: FormData
|
||||
): Promise<VerifyDevicePaymentState> {
|
||||
const session = await getServerSession(authOptions);
|
||||
|
||||
// Get the payment ID and method from the form data
|
||||
const paymentId = formData.get('paymentId') as string;
|
||||
const method = formData.get('method') as "TRANSFER" | "WALLET";
|
||||
|
||||
if (!paymentId) {
|
||||
return {
|
||||
message: "Payment ID is required",
|
||||
success: false,
|
||||
fieldErrors: { paymentId: "Payment ID is required" },
|
||||
};
|
||||
}
|
||||
|
||||
if (!method) {
|
||||
return {
|
||||
message: "Payment method is required",
|
||||
success: false,
|
||||
fieldErrors: { method: "Payment method is required" },
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(
|
||||
`${process.env.SARLINK_API_BASE_URL}/api/billing/payment/${paymentId}/verify/`,
|
||||
{
|
||||
method: "PUT",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Token ${session?.apiToken}`,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
method,
|
||||
}),
|
||||
},
|
||||
);
|
||||
|
||||
const result = await handleApiResponse<Payment>(response, "verifyDevicePayment");
|
||||
|
||||
revalidatePath("/payments/[paymentId]", "page");
|
||||
|
||||
return {
|
||||
message: method === "WALLET"
|
||||
? "Payment completed successfully using wallet!"
|
||||
: "Payment verification successful!",
|
||||
success: true,
|
||||
fieldErrors: {},
|
||||
payment: result,
|
||||
};
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof Error) {
|
||||
return {
|
||||
message: error.message || "Payment verification failed. Please try again.",
|
||||
success: false,
|
||||
fieldErrors: {},
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
message: "Payment verification failed.",
|
||||
success: false,
|
||||
fieldErrors: {},
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
export type VerifyTopupPaymentState = {
|
||||
transaction?: {
|
||||
sourceBank: string;
|
||||
trxDate: string;
|
||||
};
|
||||
message: string;
|
||||
success: boolean;
|
||||
fieldErrors: Record<string, string>;
|
||||
payload?: FormData;
|
||||
}
|
||||
export async function verifyTopupPayment(
|
||||
_prevState: VerifyTopupPaymentState,
|
||||
formData: FormData
|
||||
): Promise<VerifyTopupPaymentState> {
|
||||
const session = await getServerSession(authOptions);
|
||||
|
||||
// Get the topup ID from the form data or use a hidden input
|
||||
const topupId = formData.get('topupId') as string;
|
||||
|
||||
if (!topupId) {
|
||||
return {
|
||||
message: "Topup ID is required",
|
||||
success: false,
|
||||
fieldErrors: { topupId: "Topup ID is required" },
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(
|
||||
`${process.env.SARLINK_API_BASE_URL}/api/billing/topup/${topupId}/verify/`,
|
||||
{
|
||||
method: "PUT",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Token ${session?.apiToken}`,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const result = await handleApiResponse<TopupResponse>(response, "verifyTopupPayment");
|
||||
|
||||
revalidatePath("/top-ups/[topupId]", "page");
|
||||
|
||||
return {
|
||||
message: result.message || "Topup payment verified successfully",
|
||||
success: true,
|
||||
fieldErrors: {},
|
||||
transaction: result.transaction,
|
||||
};
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof Error) {
|
||||
return {
|
||||
message: error.message || "Please check your payment details and try again.",
|
||||
success: false,
|
||||
fieldErrors: {},
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
message: "Topup verification failed.",
|
||||
success: false,
|
||||
fieldErrors: {},
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function getProfile() {
|
||||
const session = await getServerSession(authOptions);
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import { redirect } from "next/navigation";
|
||||
import { getPayment, getProfile } from "@/actions/payment";
|
||||
import CancelPaymentButton from "@/components/billing/cancel-payment-button";
|
||||
import ExpiryCountDown from "@/components/billing/expiry-time-countdown";
|
||||
import ClientErrorMessage from "@/components/client-error-message";
|
||||
import DevicesToPay from "@/components/devices-to-pay";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { tryCatch } from "@/utils/tryCatch";
|
||||
import { redirect } from "next/navigation";
|
||||
export default async function PaymentPage({
|
||||
params,
|
||||
}: {
|
||||
@@ -40,13 +41,24 @@ export default async function PaymentPage({
|
||||
{payment?.paid ? "Paid" : "Pending"}
|
||||
</Button>
|
||||
{!payment.paid && (
|
||||
<CancelPaymentButton paymentId={paymentId} />
|
||||
payment.is_expired ? (
|
||||
<Button
|
||||
disabled
|
||||
className="rounded-md opacity-100! uppercase font-semibold text-red-500 bg-red-500/20"
|
||||
>
|
||||
Payment Expired
|
||||
</Button>
|
||||
) : (
|
||||
<CancelPaymentButton paymentId={paymentId} />
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!payment.paid && (
|
||||
<ExpiryCountDown expiryLabel="Payment" expiresAt={payment.expires_at} />
|
||||
)}
|
||||
<div
|
||||
id="user-filters"
|
||||
id="user-device-payments"
|
||||
className="pb-4 gap-4 flex sm:flex-row flex-col items-start justify-start"
|
||||
>
|
||||
<DevicesToPay
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Suspense } from "react";
|
||||
import DynamicFilter from "@/components/generic-filter";
|
||||
import { PaymentsTable } from "@/components/payments-table";
|
||||
import Search from "@/components/search";
|
||||
|
||||
export default async function Payments({
|
||||
searchParams,
|
||||
@@ -8,8 +8,6 @@ export default async function Payments({
|
||||
searchParams: Promise<{
|
||||
query: string;
|
||||
page: number;
|
||||
sortBy: string;
|
||||
status: string;
|
||||
}>;
|
||||
}) {
|
||||
const query = (await searchParams)?.query || "";
|
||||
@@ -23,7 +21,56 @@ export default async function Payments({
|
||||
id="user-filters"
|
||||
className=" pb-4 gap-4 flex sm:flex-row flex-col items-start justify-start"
|
||||
>
|
||||
<Search />
|
||||
<DynamicFilter
|
||||
inputs={[
|
||||
{
|
||||
label: "Payment",
|
||||
name: "paid",
|
||||
type: "radio-group",
|
||||
options: [
|
||||
{
|
||||
label: "All",
|
||||
value: "",
|
||||
},
|
||||
{
|
||||
label: "Paid",
|
||||
value: "true",
|
||||
},
|
||||
{
|
||||
label: "Unpaid",
|
||||
value: "false",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
label: "Payment Method",
|
||||
name: "method",
|
||||
type: "radio-group",
|
||||
options: [
|
||||
{
|
||||
label: "All",
|
||||
value: "",
|
||||
},
|
||||
{
|
||||
label: "Transfer",
|
||||
value: "TRANSFER",
|
||||
},
|
||||
{
|
||||
label: "Wallet",
|
||||
value: "WALLET",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
label: "Number of months",
|
||||
name: "number_of_months",
|
||||
type: "dual-range-slider",
|
||||
min: 1,
|
||||
max: 12,
|
||||
step: 1,
|
||||
},
|
||||
]}
|
||||
/>{" "}
|
||||
</div>
|
||||
<Suspense key={query} fallback={"loading...."}>
|
||||
<PaymentsTable searchParams={searchParams} />
|
||||
|
||||
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 expiryLabel="Top up" 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>
|
||||
);
|
||||
}
|
||||
86
app/(dashboard)/top-ups/page.tsx
Normal file
86
app/(dashboard)/top-ups/page.tsx
Normal file
@@ -0,0 +1,86 @@
|
||||
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: "Status",
|
||||
name: "status",
|
||||
type: "radio-group",
|
||||
options: [
|
||||
{
|
||||
label: "All",
|
||||
value: "",
|
||||
},
|
||||
{
|
||||
label: "Pending",
|
||||
value: "PENDING",
|
||||
},
|
||||
{
|
||||
label: "Cancelled",
|
||||
value: "CANCELLED",
|
||||
},
|
||||
{
|
||||
label: "Paid",
|
||||
value: "PAID",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
label: "Topup Expiry",
|
||||
name: "is_expired",
|
||||
type: "radio-group",
|
||||
options: [
|
||||
{
|
||||
label: "All",
|
||||
value: "",
|
||||
},
|
||||
{
|
||||
label: "Expired",
|
||||
value: "true",
|
||||
},
|
||||
{
|
||||
label: "Not Expired",
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -1,11 +1,11 @@
|
||||
"use client";
|
||||
|
||||
import { cancelPayment } from "@/actions/payment";
|
||||
import { tryCatch } from "@/utils/tryCatch";
|
||||
import { Loader2, Trash2 } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import React from "react";
|
||||
import { toast } from "sonner";
|
||||
import { cancelPayment } from "@/actions/payment";
|
||||
import { tryCatch } from "@/utils/tryCatch";
|
||||
import { Button } from "../ui/button";
|
||||
|
||||
export default function CancelPaymentButton({
|
||||
@@ -17,12 +17,16 @@ export default function CancelPaymentButton({
|
||||
<Button
|
||||
onClick={async () => {
|
||||
setLoading(true);
|
||||
const [error, x] = await tryCatch(cancelPayment({ id: paymentId }));
|
||||
console.log(x);
|
||||
const [error, payment] = await tryCatch(cancelPayment({ id: paymentId }));
|
||||
console.log(payment);
|
||||
if (error) {
|
||||
toast.error(error.message);
|
||||
setLoading(false);
|
||||
} else {
|
||||
toast.success("Payment cancelled successfully!", {
|
||||
description: `Your payment of ${payment?.amount} MVR has been cancelled.`,
|
||||
closeButton: true,
|
||||
});
|
||||
router.replace("/devices");
|
||||
}
|
||||
}}
|
||||
|
||||
39
components/billing/cancel-topup-button.tsx
Normal file
39
components/billing/cancel-topup-button.tsx
Normal file
@@ -0,0 +1,39 @@
|
||||
"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, topup] = await tryCatch(cancelTopup({ id: topupId }));
|
||||
if (error) {
|
||||
toast.error(error.message);
|
||||
setLoading(false);
|
||||
} else {
|
||||
toast.success("Topup cancelled successfully!", {
|
||||
description: `Your topup of ${topup?.amount} MVR has been cancelled.`,
|
||||
closeButton: true,
|
||||
})
|
||||
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, expiryLabel }: { expiresAt: string, expiryLabel: 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>{expiryLabel} has expired.</span>
|
||||
)}
|
||||
{timeLeft > 0 && (
|
||||
<Progress className='absolute bottom-0 left-0 right-0' color='#f49b5b' value={timeLeft / 600 * 100} />
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -22,7 +22,6 @@ export async function DevicesTable({
|
||||
searchParams,
|
||||
parentalControl,
|
||||
additionalFilters = {},
|
||||
|
||||
}: {
|
||||
searchParams: Promise<{
|
||||
[key: string]: unknown;
|
||||
|
||||
@@ -6,9 +6,9 @@ import {
|
||||
Loader2,
|
||||
Wallet,
|
||||
} from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { useActionState, useEffect, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { verifyPayment } from "@/actions/payment";
|
||||
import { type VerifyDevicePaymentState, verifyDevicePayment } from "@/actions/payment";
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
@@ -21,13 +21,32 @@ import type { Payment } from "@/lib/backend-types";
|
||||
import type { User } from "@/lib/types/user";
|
||||
import { Button } from "./ui/button";
|
||||
|
||||
const initialState: VerifyDevicePaymentState = {
|
||||
message: "",
|
||||
success: false,
|
||||
fieldErrors: {},
|
||||
};
|
||||
|
||||
export default function DevicesToPay({
|
||||
payment,
|
||||
user,
|
||||
}: { payment?: Payment; user?: User }) {
|
||||
const [verifyingWalletPayment, setVerifyingWalletPayment] = useState(false);
|
||||
const [verifyingTransferPayment, setVerifyingTransferPayment] = useState(false);
|
||||
const [state, formAction, isPending] = useActionState(verifyDevicePayment, initialState);
|
||||
|
||||
// Handle toast notifications based on state changes
|
||||
useEffect(() => {
|
||||
if (state.success && state.message) {
|
||||
toast.success("Payment successful!", {
|
||||
closeButton: true,
|
||||
description: state.message,
|
||||
});
|
||||
} else if (!state.success && state.message && state.message !== initialState.message) {
|
||||
toast.error("Payment Verification Failed", {
|
||||
closeButton: true,
|
||||
description: state.message,
|
||||
});
|
||||
}
|
||||
}, [state]);
|
||||
|
||||
const devices = payment?.devices;
|
||||
if (devices?.length === 0) {
|
||||
@@ -81,53 +100,37 @@ export default function DevicesToPay({
|
||||
) : (
|
||||
<div className="flex flex-col gap-2">
|
||||
{isWalletPayVisible && (
|
||||
<Button
|
||||
disabled={verifyingWalletPayment || verifyingTransferPayment}
|
||||
onClick={async () => {
|
||||
setVerifyingWalletPayment(true);
|
||||
await verifyPayment({
|
||||
method: "WALLET",
|
||||
id: payment?.id ?? "",
|
||||
});
|
||||
setVerifyingWalletPayment(false);
|
||||
}}
|
||||
variant={"secondary"}
|
||||
size={"lg"}
|
||||
>
|
||||
{verifyingWalletPayment ? "Processing payment..." : "Pay with wallet"}
|
||||
<Wallet />
|
||||
</Button>
|
||||
<form action={formAction}>
|
||||
<input type="hidden" name="paymentId" value={payment?.id ?? ""} />
|
||||
<input type="hidden" name="method" value="WALLET" />
|
||||
<Button
|
||||
disabled={isPending}
|
||||
type="submit"
|
||||
variant={"secondary"}
|
||||
size={"lg"}
|
||||
>
|
||||
{isPending ? "Processing payment..." : "Pay with wallet"}
|
||||
<Wallet />
|
||||
</Button>
|
||||
</form>
|
||||
)}
|
||||
<Button
|
||||
disabled={verifyingTransferPayment || verifyingWalletPayment}
|
||||
onClick={async () => {
|
||||
setVerifyingTransferPayment(true);
|
||||
try {
|
||||
await verifyPayment({
|
||||
id: payment?.id ?? "",
|
||||
method: "TRANSFER"
|
||||
});
|
||||
toast.success("Payment verification successful!");
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof Error) {
|
||||
toast.error(error.message);
|
||||
} else {
|
||||
toast.error("Payment verification failed.");
|
||||
}
|
||||
} finally {
|
||||
setVerifyingTransferPayment(false);
|
||||
}
|
||||
}}
|
||||
size={"lg"}
|
||||
className="mb-4"
|
||||
>
|
||||
{verifyingTransferPayment ? "Processing payment..." : "I have paid"}
|
||||
{verifyingTransferPayment ? (
|
||||
<Loader2 className="animate-spin" />
|
||||
) : (
|
||||
<BadgeDollarSign />
|
||||
)}
|
||||
</Button>
|
||||
<form action={formAction}>
|
||||
<input type="hidden" name="paymentId" value={payment?.id ?? ""} />
|
||||
<input type="hidden" name="method" value="TRANSFER" />
|
||||
<Button
|
||||
disabled={isPending}
|
||||
type="submit"
|
||||
size={"lg"}
|
||||
className="mb-4"
|
||||
>
|
||||
{isPending ? "Processing payment..." : "I have paid"}
|
||||
{isPending ? (
|
||||
<Loader2 className="animate-spin" />
|
||||
) : (
|
||||
<BadgeDollarSign />
|
||||
)}
|
||||
</Button>
|
||||
</form>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -315,25 +315,14 @@ export default function DynamicFilter<
|
||||
}> = [];
|
||||
|
||||
for (const input of inputs) {
|
||||
const urlValue = searchParams.get(input.name);
|
||||
if (urlValue) {
|
||||
if (input.type === "checkbox-group") {
|
||||
const deserialize = input.deserialize || defaultDeserialize;
|
||||
const deserialized = deserialize(urlValue);
|
||||
if (deserialized.length > 0) {
|
||||
filters.push({
|
||||
key: input.name,
|
||||
value: deserialized,
|
||||
label: input.label,
|
||||
config: input,
|
||||
});
|
||||
}
|
||||
} else if (input.type === "dual-range-slider") {
|
||||
const minValue = searchParams.get(`${input.name}_min`);
|
||||
const maxValue = searchParams.get(`${input.name}_max`);
|
||||
if (minValue && maxValue) {
|
||||
const parsedMin = Number(minValue);
|
||||
const parsedMax = Number(maxValue);
|
||||
if (input.type === "dual-range-slider") {
|
||||
const minValue = searchParams.get(`${input.name}_min`);
|
||||
const maxValue = searchParams.get(`${input.name}_max`);
|
||||
if (minValue && maxValue) {
|
||||
const parsedMin = Number(minValue);
|
||||
const parsedMax = Number(maxValue);
|
||||
// Only show as applied filter if values are different from defaults
|
||||
if (parsedMin !== input.min || parsedMax !== input.max) {
|
||||
filters.push({
|
||||
key: input.name,
|
||||
value: [parsedMin, parsedMax],
|
||||
@@ -341,13 +330,29 @@ export default function DynamicFilter<
|
||||
config: input,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
filters.push({
|
||||
key: input.name,
|
||||
value: urlValue,
|
||||
label: input.label,
|
||||
config: input,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
const urlValue = searchParams.get(input.name);
|
||||
if (urlValue) {
|
||||
if (input.type === "checkbox-group") {
|
||||
const deserialize = input.deserialize || defaultDeserialize;
|
||||
const deserialized = deserialize(urlValue);
|
||||
if (deserialized.length > 0) {
|
||||
filters.push({
|
||||
key: input.name,
|
||||
value: deserialized,
|
||||
label: input.label,
|
||||
config: input,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
filters.push({
|
||||
key: input.name,
|
||||
value: urlValue,
|
||||
label: input.label,
|
||||
config: input,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -383,6 +388,25 @@ export default function DynamicFilter<
|
||||
</p>
|
||||
);
|
||||
}
|
||||
if (config.type === "radio-group") {
|
||||
const stringValue = value as string;
|
||||
// For true/false values, display the label instead of the value
|
||||
if (stringValue === "true" || stringValue === "false") {
|
||||
const option = config.options.find((opt) => opt.value === stringValue);
|
||||
const displayValue = option?.label || stringValue;
|
||||
return (
|
||||
<p>
|
||||
{config.label}: <span className="text-muted-foreground">{displayValue}</span>
|
||||
</p>
|
||||
);
|
||||
}
|
||||
// For other values, display as normal
|
||||
return (
|
||||
<p>
|
||||
{config.label}: <span className="text-muted-foreground">{stringValue}</span>
|
||||
</p>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<p>
|
||||
{config.label}: <span className="text-muted-foreground">{value}</span>
|
||||
@@ -577,4 +601,4 @@ export default function DynamicFilter<
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -24,13 +24,17 @@ export async function PaymentsTable({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<{
|
||||
query: string;
|
||||
page: number;
|
||||
sortBy: string;
|
||||
[key: string]: unknown;
|
||||
}>;
|
||||
}) {
|
||||
const query = (await searchParams)?.query || "";
|
||||
const [error, payments] = await tryCatch(getPayments());
|
||||
const resolvedParams = await searchParams;
|
||||
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, payments] = await tryCatch(getPayments(apiParams));
|
||||
|
||||
if (error) {
|
||||
if (error.message.includes("Unauthorized")) {
|
||||
@@ -55,7 +59,7 @@ export async function PaymentsTable({
|
||||
<TableRow>
|
||||
<TableHead>Details</TableHead>
|
||||
<TableHead>Duration</TableHead>
|
||||
|
||||
<TableHead>Status</TableHead>
|
||||
<TableHead>Amount</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
@@ -80,6 +84,8 @@ export async function PaymentsTable({
|
||||
month: "short",
|
||||
day: "2-digit",
|
||||
year: "numeric",
|
||||
minute: "2-digit",
|
||||
hour: "2-digit",
|
||||
},
|
||||
)}
|
||||
</span>
|
||||
@@ -94,16 +100,6 @@ export async function PaymentsTable({
|
||||
View Details
|
||||
</Button>
|
||||
</Link>
|
||||
<Badge
|
||||
className={cn(
|
||||
payment?.paid
|
||||
? "text-green-500 bg-green-500/20"
|
||||
: "text-yellow-500 bg-yellow-500/20",
|
||||
)}
|
||||
variant={payment.paid ? "outline" : "secondary"}
|
||||
>
|
||||
{payment.paid ? "Paid" : "Unpaid"}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="bg-white dark:bg-black p-2 rounded mt-2 w-full border">
|
||||
<h3 className="text-sm font-medium">Devices</h3>
|
||||
@@ -120,9 +116,30 @@ export async function PaymentsTable({
|
||||
</div>
|
||||
</div>
|
||||
</TableCell>
|
||||
|
||||
<TableCell className="font-medium">
|
||||
{payment.number_of_months} Months
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<span className="font-semibold pr-2">
|
||||
{payment.paid ? (
|
||||
<Badge
|
||||
className={cn(
|
||||
payment.status === "PENDING"
|
||||
? "bg-yellow-100 text-yellow-700 dark:bg-yellow-700 dark:text-yellow-100"
|
||||
: "bg-green-100 dark:bg-green-700"
|
||||
)}
|
||||
variant="outline"
|
||||
>
|
||||
{payment.status}
|
||||
</Badge>
|
||||
) : payment.is_expired ? (
|
||||
<Badge>Expired</Badge>
|
||||
) : (
|
||||
<Badge variant="outline">{payment.status}</Badge>
|
||||
)}
|
||||
</span>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<span className="font-semibold pr-2">
|
||||
{payment.amount.toFixed(2)}
|
||||
@@ -134,18 +151,17 @@ export async function PaymentsTable({
|
||||
</TableBody>
|
||||
<TableFooter>
|
||||
<TableRow>
|
||||
<TableCell colSpan={2}>
|
||||
{query.length > 0 && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Showing {payments?.data?.length} payments for "
|
||||
{query}
|
||||
"
|
||||
|
||||
<TableCell colSpan={3} className="text-muted-foreground">
|
||||
{meta?.total === 1 ? (
|
||||
<p className="text-center">
|
||||
Total {meta?.total} payment.
|
||||
</p>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell className="text-muted-foreground">
|
||||
{meta.total} payments
|
||||
</TableCell>
|
||||
) : (
|
||||
<p className="text-center">
|
||||
Total {meta?.total} payments.
|
||||
</p>
|
||||
)} </TableCell>
|
||||
</TableRow>
|
||||
</TableFooter>
|
||||
</Table>
|
||||
@@ -182,6 +198,8 @@ function MobilePaymentDetails({ payment }: { payment: Payment }) {
|
||||
month: "short",
|
||||
day: "2-digit",
|
||||
year: "numeric",
|
||||
minute: "2-digit",
|
||||
hour: "2-digit",
|
||||
})}
|
||||
</span>
|
||||
</div>
|
||||
@@ -195,16 +213,6 @@ function MobilePaymentDetails({ payment }: { payment: Payment }) {
|
||||
View Details
|
||||
</Button>
|
||||
</Link>
|
||||
<Badge
|
||||
className={cn(
|
||||
payment?.paid
|
||||
? "text-green-500 bg-green-500/20"
|
||||
: "text-yellow-500 bg-yellow-500/20",
|
||||
)}
|
||||
variant={payment.paid ? "outline" : "secondary"}
|
||||
>
|
||||
{payment.paid ? "Paid" : "Unpaid"}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="bg-white dark:bg-black p-2 rounded mt-2 w-full border">
|
||||
<h3 className="text-sm font-medium">Devices</h3>
|
||||
@@ -223,9 +231,29 @@ function MobilePaymentDetails({ payment }: { payment: Payment }) {
|
||||
</span>
|
||||
<Separator className="my-2" />
|
||||
<h3 className="text-sm font-medium">Amount</h3>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{payment.amount.toFixed(2)} MVR
|
||||
</span>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{payment.amount.toFixed(2)} MVR
|
||||
</span>
|
||||
<span className="font-semibold pr-2">
|
||||
{payment.paid ? (
|
||||
<Badge
|
||||
className={cn(
|
||||
payment.status === "PENDING"
|
||||
? "bg-yellow-100 text-yellow-700 dark:bg-yellow-700 dark:text-yellow-100"
|
||||
: "bg-green-100 dark:bg-green-700"
|
||||
)}
|
||||
variant="outline"
|
||||
>
|
||||
{payment.status}
|
||||
</Badge>
|
||||
) : payment.is_expired ? (
|
||||
<Badge>Expired</Badge>
|
||||
) : (
|
||||
<Badge variant="secondary">{payment.status}</Badge>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
182
components/topup-to-pay.tsx
Normal file
182
components/topup-to-pay.tsx
Normal file
@@ -0,0 +1,182 @@
|
||||
"use client";
|
||||
import {
|
||||
BadgeDollarSign,
|
||||
Clipboard,
|
||||
ClipboardCheck,
|
||||
Loader2,
|
||||
} from "lucide-react";
|
||||
import { useActionState, useEffect, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { type VerifyTopupPaymentState, 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";
|
||||
|
||||
|
||||
|
||||
const initialState: VerifyTopupPaymentState = {
|
||||
message: "",
|
||||
success: false,
|
||||
fieldErrors: {},
|
||||
};
|
||||
export default function TopupToPay({ topup, disabled }: { topup?: Topup, disabled?: boolean }) {
|
||||
const [state, formAction, isPending] = useActionState(verifyTopupPayment, initialState);
|
||||
|
||||
// Handle toast notifications based on state changes
|
||||
useEffect(() => {
|
||||
if (state.success && state.message) {
|
||||
toast.success("Topup successful!", {
|
||||
closeButton: true,
|
||||
description: state.transaction
|
||||
? `Your topup payment has been verified successfully using ${state.transaction.sourceBank} bank transfer on ${state.transaction.trxDate}.`
|
||||
: state.message,
|
||||
});
|
||||
} else if (!state.success && state.message && state.message !== initialState.message) {
|
||||
toast.error("Topup Payment Verification Failed", {
|
||||
closeButton: true,
|
||||
description: state.message,
|
||||
});
|
||||
}
|
||||
}, [state]);
|
||||
|
||||
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">
|
||||
<form action={formAction}>
|
||||
<input type="hidden" name="topupId" value={topup?.id ?? ""} />
|
||||
<Button
|
||||
disabled={disabled || isPending}
|
||||
type="submit"
|
||||
size={"lg"}
|
||||
className="mb-4"
|
||||
>
|
||||
{isPending
|
||||
? "Processing payment..."
|
||||
: "I have paid"}
|
||||
{isPending ? (
|
||||
<Loader2 className="animate-spin" />
|
||||
) : (
|
||||
<BadgeDollarSign />
|
||||
)}
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</TableCaption>
|
||||
<TableBody className="">
|
||||
<TableRow>
|
||||
<TableCell>Topup created</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>Payment received</TableCell>
|
||||
<TableCell className="text-right text-sarLinkOrange">
|
||||
{topup?.paid_at
|
||||
? new Date(topup.paid_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 : "-"}
|
||||
</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>
|
||||
);
|
||||
}
|
||||
216
components/topups-table.tsx
Normal file
216
components/topups-table.tsx
Normal file
@@ -0,0 +1,216 @@
|
||||
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>Status</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>
|
||||
</div>
|
||||
</div>
|
||||
</TableCell>
|
||||
|
||||
<TableCell>
|
||||
<span className="font-semibold pr-2">
|
||||
{topup.paid ? (
|
||||
<Badge
|
||||
className="bg-green-100 dark:bg-green-700"
|
||||
variant="outline"
|
||||
>
|
||||
{topup.status}
|
||||
</Badge>
|
||||
) : topup.is_expired ? (
|
||||
<Badge>Expired</Badge>
|
||||
) : (
|
||||
<Badge variant="outline">{topup.status}</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>
|
||||
</div>
|
||||
<div className="sm:hidden block">
|
||||
{data.map((topup) => (
|
||||
<MobileTopupDetails key={topup.id} topup={topup} />
|
||||
))}
|
||||
</div>
|
||||
<Pagination
|
||||
totalPages={meta.total / meta.per_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>
|
||||
</div>
|
||||
|
||||
<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">
|
||||
<h3 className="text-sm font-medium">Amount</h3>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{topup.amount.toFixed(2)} MVR
|
||||
</span>
|
||||
</div>
|
||||
<span className="font-semibold pr-2">
|
||||
{topup.paid ? (
|
||||
<Badge className="bg-green-100 dark:bg-green-700" variant="outline">
|
||||
{topup.status}
|
||||
</Badge>
|
||||
) : topup.is_expired ? (
|
||||
<Badge>Expired</Badge>
|
||||
) : (
|
||||
<Badge variant="secondary">{topup.status}</Badge>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import {
|
||||
BadgePlus,
|
||||
Calculator,
|
||||
ChevronRight,
|
||||
Coins,
|
||||
@@ -73,9 +74,15 @@ 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",
|
||||
link: "/parental-control?page=1",
|
||||
icon: <CreditCard size={16} />,
|
||||
perm_identifier: "device",
|
||||
},
|
||||
|
||||
@@ -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,22 @@ export interface ApiError {
|
||||
detail?: string;
|
||||
}
|
||||
|
||||
export interface Topup {
|
||||
id: string;
|
||||
amount: number;
|
||||
user: Pick<User, "id" | "id_card" | "mobile"> & {
|
||||
name: string;
|
||||
};
|
||||
paid: boolean;
|
||||
status: "CANCELLED" | "PENDING" | "VERIFIED";
|
||||
paid_at: string | null;
|
||||
mib_reference: string | null;
|
||||
expires_at: string;
|
||||
is_expired: boolean;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface Payment {
|
||||
id: string;
|
||||
devices: Device[];
|
||||
@@ -65,9 +81,12 @@ export interface Payment {
|
||||
paid: boolean;
|
||||
paid_at: string | null;
|
||||
method: string;
|
||||
expires_at: string | null;
|
||||
expires_at: string;
|
||||
is_expired: boolean;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
status: "CANCELLED" | "PENDING" | "PAID";
|
||||
mib_reference: string | null;
|
||||
user: number;
|
||||
}
|
||||
|
||||
|
||||
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;
|
||||
|
||||
@@ -21,6 +21,19 @@ const nextConfig: NextConfig = {
|
||||
],
|
||||
},
|
||||
output: "standalone",
|
||||
async headers() {
|
||||
return [
|
||||
{
|
||||
source: '/:path*{/}?',
|
||||
headers: [
|
||||
{
|
||||
key: 'X-Accel-Buffering',
|
||||
value: 'no',
|
||||
},
|
||||
],
|
||||
},
|
||||
]
|
||||
},
|
||||
};
|
||||
|
||||
export default nextConfig;
|
||||
|
||||
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