7 Commits

Author SHA1 Message Date
1a11f1a06c refactor: implement device payment verification with useActionState hook 🔨 2025-07-06 23:06:51 +05:00
837cc35ad3 refactor: reorder imports and improve variable naming in CancelPaymentButton component 🔨 2025-07-06 22:39:16 +05:00
e984705849 refactor: update cancelPayment function to use PATCH method and new endpoint 🔨 2025-07-06 22:38:55 +05:00
4797ee8dde feat: add expiry label to ExpiryCountDown component 2025-07-06 22:38:39 +05:00
df2b3da22e feat: enhance payment and topup interfaces with status and expiration details 2025-07-06 22:38:01 +05:00
9e25da717b feat: add expiry label to ExpiryCountDown component in TopupPage 2025-07-06 22:37:23 +05:00
Abdulla Aidhaan
62678b6a84 Merge pull request #12 from i701/feat/wallet-topups
All checks were successful
Build and Push Docker Images / Build and Push Docker Images (push) Successful in 4m59s
refactor: enhance topup status display and improve conditional rendering in TopupsTable component 🔨
2025-07-06 20:16:27 +05:00
9 changed files with 214 additions and 122 deletions

View File

@@ -179,24 +179,16 @@ export async function cancelTopup({ id }: { id: string }) {
export async function cancelPayment({ id }: { id: string }) { export async function cancelPayment({ id }: { id: string }) {
const session = await getServerSession(authOptions); const session = await getServerSession(authOptions);
const response = await fetch( const response = await fetch(
`${process.env.SARLINK_API_BASE_URL}/api/billing/payment/${id}/delete/`, `${process.env.SARLINK_API_BASE_URL}/api/billing/payment/${id}/cancel/`,
{ {
method: "DELETE", method: "PATCH",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
Authorization: `Token ${session?.apiToken}`, Authorization: `Token ${session?.apiToken}`,
}, },
}, },
); );
if (!response.ok) { return handleApiResponse<Payment>(response, "cancelPayment");
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." };
} }
type UpdatePayment = { type UpdatePayment = {
@@ -226,6 +218,84 @@ export async function verifyPayment({ id, method }: UpdatePayment) {
return handleApiResponse<Payment>(response, "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 = { export type VerifyTopupPaymentState = {
transaction?: { transaction?: {

View File

@@ -1,11 +1,12 @@
import { redirect } from "next/navigation";
import { getPayment, getProfile } from "@/actions/payment"; import { getPayment, getProfile } from "@/actions/payment";
import CancelPaymentButton from "@/components/billing/cancel-payment-button"; import CancelPaymentButton from "@/components/billing/cancel-payment-button";
import ExpiryCountDown from "@/components/billing/expiry-time-countdown";
import ClientErrorMessage from "@/components/client-error-message"; import ClientErrorMessage from "@/components/client-error-message";
import DevicesToPay from "@/components/devices-to-pay"; import DevicesToPay from "@/components/devices-to-pay";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { tryCatch } from "@/utils/tryCatch"; import { tryCatch } from "@/utils/tryCatch";
import { redirect } from "next/navigation";
export default async function PaymentPage({ export default async function PaymentPage({
params, params,
}: { }: {
@@ -40,13 +41,24 @@ export default async function PaymentPage({
{payment?.paid ? "Paid" : "Pending"} {payment?.paid ? "Paid" : "Pending"}
</Button> </Button>
{!payment.paid && ( {!payment.paid && (
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} /> <CancelPaymentButton paymentId={paymentId} />
)
)} )}
</div> </div>
</div> </div>
{!payment.paid && (
<ExpiryCountDown expiryLabel="Payment" expiresAt={payment.expires_at} />
)}
<div <div
id="user-filters" id="user-device-payments"
className="pb-4 gap-4 flex sm:flex-row flex-col items-start justify-start" className="pb-4 gap-4 flex sm:flex-row flex-col items-start justify-start"
> >
<DevicesToPay <DevicesToPay

View File

@@ -56,7 +56,7 @@ export default async function TopupPage({
</div> </div>
</div> </div>
{!topup.paid && ( {!topup.paid && (
<ExpiryCountDown expiresAt={topup.expires_at} /> <ExpiryCountDown expiryLabel="Top up" expiresAt={topup.expires_at} />
)} )}
<div <div
id="user-topup-details" id="user-topup-details"

View File

@@ -1,11 +1,11 @@
"use client"; "use client";
import { cancelPayment } from "@/actions/payment";
import { tryCatch } from "@/utils/tryCatch";
import { Loader2, Trash2 } from "lucide-react"; import { Loader2, Trash2 } from "lucide-react";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import React from "react"; import React from "react";
import { toast } from "sonner"; import { toast } from "sonner";
import { cancelPayment } from "@/actions/payment";
import { tryCatch } from "@/utils/tryCatch";
import { Button } from "../ui/button"; import { Button } from "../ui/button";
export default function CancelPaymentButton({ export default function CancelPaymentButton({
@@ -17,12 +17,16 @@ export default function CancelPaymentButton({
<Button <Button
onClick={async () => { onClick={async () => {
setLoading(true); setLoading(true);
const [error, x] = await tryCatch(cancelPayment({ id: paymentId })); const [error, payment] = await tryCatch(cancelPayment({ id: paymentId }));
console.log(x); console.log(payment);
if (error) { if (error) {
toast.error(error.message); toast.error(error.message);
setLoading(false); setLoading(false);
} else { } else {
toast.success("Payment cancelled successfully!", {
description: `Your payment of ${payment?.amount} MVR has been cancelled.`,
closeButton: true,
});
router.replace("/devices"); router.replace("/devices");
} }
}} }}

View File

@@ -15,7 +15,7 @@ const HumanizeTimeLeft = (seconds: number) => {
return `${minutes}m ${remainingSeconds}s` return `${minutes}m ${remainingSeconds}s`
} }
export default function ExpiryCountDown({ expiresAt }: { expiresAt: string }) { export default function ExpiryCountDown({ expiresAt, expiryLabel }: { expiresAt: string, expiryLabel: string }) {
const [timeLeft, setTimeLeft] = useState(calculateTimeLeft(expiresAt)) const [timeLeft, setTimeLeft] = useState(calculateTimeLeft(expiresAt))
const [mounted, setMounted] = useState(false) const [mounted, setMounted] = useState(false)
const router = useRouter() const router = useRouter()
@@ -47,7 +47,7 @@ export default function ExpiryCountDown({ expiresAt }: { expiresAt: string }) {
{timeLeft ? ( {timeLeft ? (
<span>Time left: {HumanizeTimeLeft(timeLeft)}</span> <span>Time left: {HumanizeTimeLeft(timeLeft)}</span>
) : ( ) : (
<span>Top up has expired. Please make another topup to add balance to your wallet.</span> <span>{expiryLabel} has expired.</span>
)} )}
{timeLeft > 0 && ( {timeLeft > 0 && (
<Progress className='absolute bottom-0 left-0 right-0' color='#f49b5b' value={timeLeft / 600 * 100} /> <Progress className='absolute bottom-0 left-0 right-0' color='#f49b5b' value={timeLeft / 600 * 100} />

View File

@@ -6,9 +6,9 @@ import {
Loader2, Loader2,
Wallet, Wallet,
} from "lucide-react"; } from "lucide-react";
import { useState } from "react"; import { useActionState, useEffect, useState } from "react";
import { toast } from "sonner"; import { toast } from "sonner";
import { verifyPayment } from "@/actions/payment"; import { type VerifyDevicePaymentState, verifyDevicePayment } from "@/actions/payment";
import { import {
Table, Table,
TableBody, TableBody,
@@ -21,13 +21,32 @@ import type { Payment } from "@/lib/backend-types";
import type { User } from "@/lib/types/user"; import type { User } from "@/lib/types/user";
import { Button } from "./ui/button"; import { Button } from "./ui/button";
const initialState: VerifyDevicePaymentState = {
message: "",
success: false,
fieldErrors: {},
};
export default function DevicesToPay({ export default function DevicesToPay({
payment, payment,
user, user,
}: { payment?: Payment; user?: User }) { }: { payment?: Payment; user?: User }) {
const [verifyingWalletPayment, setVerifyingWalletPayment] = useState(false); const [state, formAction, isPending] = useActionState(verifyDevicePayment, initialState);
const [verifyingTransferPayment, setVerifyingTransferPayment] = useState(false);
// 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; const devices = payment?.devices;
if (devices?.length === 0) { if (devices?.length === 0) {
@@ -81,53 +100,37 @@ export default function DevicesToPay({
) : ( ) : (
<div className="flex flex-col gap-2"> <div className="flex flex-col gap-2">
{isWalletPayVisible && ( {isWalletPayVisible && (
<form action={formAction}>
<input type="hidden" name="paymentId" value={payment?.id ?? ""} />
<input type="hidden" name="method" value="WALLET" />
<Button <Button
disabled={verifyingWalletPayment || verifyingTransferPayment} disabled={isPending}
onClick={async () => { type="submit"
setVerifyingWalletPayment(true);
await verifyPayment({
method: "WALLET",
id: payment?.id ?? "",
});
setVerifyingWalletPayment(false);
}}
variant={"secondary"} variant={"secondary"}
size={"lg"} size={"lg"}
> >
{verifyingWalletPayment ? "Processing payment..." : "Pay with wallet"} {isPending ? "Processing payment..." : "Pay with wallet"}
<Wallet /> <Wallet />
</Button> </Button>
</form>
)} )}
<form action={formAction}>
<input type="hidden" name="paymentId" value={payment?.id ?? ""} />
<input type="hidden" name="method" value="TRANSFER" />
<Button <Button
disabled={verifyingTransferPayment || verifyingWalletPayment} disabled={isPending}
onClick={async () => { type="submit"
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"} size={"lg"}
className="mb-4" className="mb-4"
> >
{verifyingTransferPayment ? "Processing payment..." : "I have paid"} {isPending ? "Processing payment..." : "I have paid"}
{verifyingTransferPayment ? ( {isPending ? (
<Loader2 className="animate-spin" /> <Loader2 className="animate-spin" />
) : ( ) : (
<BadgeDollarSign /> <BadgeDollarSign />
)} )}
</Button> </Button>
</form>
</div> </div>
)} )}
</div> </div>

View File

@@ -59,7 +59,7 @@ export async function PaymentsTable({
<TableRow> <TableRow>
<TableHead>Details</TableHead> <TableHead>Details</TableHead>
<TableHead>Duration</TableHead> <TableHead>Duration</TableHead>
<TableHead>Status</TableHead>
<TableHead>Amount</TableHead> <TableHead>Amount</TableHead>
</TableRow> </TableRow>
</TableHeader> </TableHeader>
@@ -84,6 +84,8 @@ export async function PaymentsTable({
month: "short", month: "short",
day: "2-digit", day: "2-digit",
year: "numeric", year: "numeric",
minute: "2-digit",
hour: "2-digit",
}, },
)} )}
</span> </span>
@@ -98,16 +100,6 @@ export async function PaymentsTable({
View Details View Details
</Button> </Button>
</Link> </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>
<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>
@@ -124,9 +116,30 @@ export async function PaymentsTable({
</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>
<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> <TableCell>
<span className="font-semibold pr-2"> <span className="font-semibold pr-2">
{payment.amount.toFixed(2)} {payment.amount.toFixed(2)}
@@ -185,6 +198,8 @@ function MobilePaymentDetails({ payment }: { payment: Payment }) {
month: "short", month: "short",
day: "2-digit", day: "2-digit",
year: "numeric", year: "numeric",
minute: "2-digit",
hour: "2-digit",
})} })}
</span> </span>
</div> </div>
@@ -198,16 +213,6 @@ function MobilePaymentDetails({ payment }: { payment: Payment }) {
View Details View Details
</Button> </Button>
</Link> </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>
<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>
@@ -226,9 +231,29 @@ function MobilePaymentDetails({ payment }: { payment: Payment }) {
</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">
<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">
{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> </div>
</div> </div>

View File

@@ -103,19 +103,6 @@ export async function TopupsTable({
View Details View Details
</Button> </Button>
</Link> </Link>
{!topup.is_expired &&
topup.status !== "CANCELLED" && (
<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>
</div> </div>
</TableCell> </TableCell>
@@ -203,18 +190,6 @@ function MobileTopupDetails({ topup }: { topup: Topup }) {
View Details View Details
</Button> </Button>
</Link> </Link>
{!topup.is_expired && topup.status !== "CANCELLED" && (
<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>
<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">

View File

@@ -81,9 +81,12 @@ export interface Payment {
paid: boolean; paid: boolean;
paid_at: string | null; paid_at: string | null;
method: string; method: string;
expires_at: string | null; expires_at: string;
is_expired: boolean;
created_at: string; created_at: string;
updated_at: string; updated_at: string;
status: "CANCELLED" | "PENDING" | "PAID";
mib_reference: string | null;
user: number; user: number;
} }