Merge pull request #8 from i701/feat/wallet-topups
All checks were successful
Build and Push Docker Images / Build and Push Docker Images (push) Successful in 6m36s

feature/wallet topups
This commit is contained in:
Abdulla Aidhaan
2025-07-05 15:36:39 +05:00
committed by GitHub
3 changed files with 109 additions and 59 deletions

View File

@ -225,24 +225,71 @@ export async function verifyPayment({ id, method }: UpdatePayment) {
return handleApiResponse<Payment>(response, "updatePayment"); return handleApiResponse<Payment>(response, "updatePayment");
} }
type UpdateTopupPayment = {
id: string;
};
export async function verifyTopupPayment({ id }: UpdateTopupPayment) { 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); const session = await getServerSession(authOptions);
const response = await fetch(
`${process.env.SARLINK_API_BASE_URL}/api/billing/topup/${id}/verify/`, // Get the topup ID from the form data or use a hidden input
{ const topupId = formData.get('topupId') as string;
method: "PUT",
headers: { if (!topupId) {
"Content-Type": "application/json", return {
Authorization: `Token ${session?.apiToken}`, 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}`,
},
}, },
}, );
);
revalidatePath("/top-ups/[topupId]", "page"); const result = await handleApiResponse<TopupResponse>(response, "verifyTopupPayment");
return 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() { export async function getProfile() {

View File

@ -5,9 +5,9 @@ import {
ClipboardCheck, ClipboardCheck,
Loader2, Loader2,
} 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 { verifyTopupPayment } from "@/actions/payment"; import { type VerifyTopupPaymentState, verifyTopupPayment } from "@/actions/payment";
import { import {
Table, Table,
TableBody, TableBody,
@ -19,9 +19,32 @@ import {
import type { Topup } from "@/lib/backend-types"; import type { Topup } from "@/lib/backend-types";
import { Button } from "./ui/button"; import { Button } from "./ui/button";
const initialState: VerifyTopupPaymentState = {
message: "",
success: false,
fieldErrors: {},
};
export default function TopupToPay({ topup, disabled }: { topup?: Topup, disabled?: boolean }) { export default function TopupToPay({ topup, disabled }: { topup?: Topup, disabled?: boolean }) {
const [verifyingTransferPayment, setVerifyingTransferPayment] = const [state, formAction, isPending] = useActionState(verifyTopupPayment, initialState);
useState(false);
// 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 ( return (
<div className="w-full"> <div className="w-full">
@ -45,45 +68,25 @@ export default function TopupToPay({ topup, disabled }: { topup?: Topup, disable
</Button> </Button>
) : ( ) : (
<div className="flex flex-col gap-2"> <div className="flex flex-col gap-2">
<Button <form action={formAction}>
disabled={disabled || verifyingTransferPayment} <input type="hidden" name="topupId" value={topup?.id ?? ""} />
onClick={async () => { <Button
setVerifyingTransferPayment(true); disabled={disabled || isPending}
try { type="submit"
const response = await verifyTopupPayment({ size={"lg"}
id: topup?.id ?? "", className="mb-4"
}); >
toast.success("Topup successful!", { {isPending
closeButton: true, ? "Processing payment..."
description: : "I have paid"}
`Your topup payment has been verified successfully using ${response.transaction?.sourceBank} bank transfer on ${response.transaction?.trxDate}.` || response.message, {isPending ? (
}); <Loader2 className="animate-spin" />
} catch (error: unknown) { ) : (
if (error instanceof Error) { <BadgeDollarSign />
toast.error("Topup Payment Verification Failed", { )}
closeButton: true, </Button>
description: </form>
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>
)} )}
</div> </div>

View File

@ -18,7 +18,7 @@ const Progress = React.forwardRef<
{...props} {...props}
> >
<ProgressPrimitive.Indicator <ProgressPrimitive.Indicator
className={cn("h-full w-full flex-1 transition-all", className, value ?? 0 < 20 ? "bg-red-500" : "bg-sarLinkOrange")} 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)}%)` }} style={{ transform: `translateX(-${100 - (value || 0)}%)` }}
/> />
</ProgressPrimitive.Root> </ProgressPrimitive.Root>