Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 69 additions & 0 deletions src/app/_actions/wallet.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
"use server";

import { revalidatePath } from "next/cache";
import { createClient } from "@/lib/supabase/server";
import { topupWalletSchema, type TopupWalletInput } from "@/lib/schemas/wallet";
import type { ActionResult } from "./escrow";

// ── Helper ────────────────────────────────────────────────────────────────────
async function getAuthUserId() {
const supabase = await createClient();
const {
data: { user },
error,
} = await supabase.auth.getUser();
if (error || !user) throw new Error(error?.message ?? "Not authenticated");
return { supabase, userId: user.id };
}

// ── Top up Wallet ─────────────────────────────────────────────────────────────
// external → wallet: calls topup_wallet() SECURITY DEFINER function (test mode)
export async function topupWalletAction(
raw: TopupWalletInput,
): Promise<ActionResult<{ availableBalance: number; ledgerId: string }>> {
try {
const parsed = topupWalletSchema.safeParse(raw);
if (!parsed.success) {
return { success: false, error: parsed.error.issues[0]?.message ?? "Invalid input" };
}

const { supabase } = await getAuthUserId();
const { amount, idempotency_key } = parsed.data;

const { data, error } = await supabase.rpc("topup_wallet", {
p_amount: amount,
p_idempotency_key: idempotency_key,
});

if (error) {
const msg = error.message.toLowerCase();
if (msg.includes("invalid_amount")) {
return { success: false, error: "Amount must be between ₹100 and ₹1,00,000." };
}
if (msg.includes("not_authenticated")) {
return { success: false, error: "You need to be signed in." };
}
return { success: false, error: "Could not top up wallet. Please try again." };
}

const row = Array.isArray(data) ? data[0] : data;
if (!row) {
return { success: false, error: "Could not top up wallet. Please try again." };
}

revalidatePath("/client/wallet", "layout");
revalidatePath("/worker/wallet", "layout");

return {
success: true,
data: {
availableBalance: Number(row.available_balance),
ledgerId: row.ledger_id as string,
},
};
} catch (err) {
const msg = err instanceof Error ? err.message : "Unknown error";
// TODO: Sentry.captureException(err);
return { success: false, error: msg };
}
}
145 changes: 145 additions & 0 deletions src/components/features/topup-dialog.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
"use client";

import { formatInr } from "@/lib/format";
import { useRef, useState, useTransition, useEffect } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { Plus } from "lucide-react";

import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";

import { topupWalletAction } from "@/app/_actions/wallet";

const QUICK_AMOUNTS = [1000, 5000, 10000, 25000];

export function TopUpDialog() {
const queryClient = useQueryClient();
const [open, setOpen] = useState(false);
const [amountStr, setAmountStr] = useState("");
const [isPending, startTransition] = useTransition();
const inFlightRef = useRef(false);
const mountedRef = useRef(true);

useEffect(() => {
mountedRef.current = true;
return () => {
mountedRef.current = false;
};
}, []);

function handleTopUp() {
const amount = Number(amountStr);
if (!Number.isFinite(amount) || amount < 100) {
toast.error("Enter at least ₹100.");
return;
}
if (amount > 100000) {
toast.error("Maximum top-up is ₹1,00,000.");
return;
}
if (inFlightRef.current) return;
inFlightRef.current = true;

startTransition(async () => {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: startTransition is being passed an async callback, but transition pending state is not reliably tied to the awaited RPC lifecycle. As a result, isPending can flip false before the request finishes, so the dialog/buttons may become interactive mid-request and allow close/cancel while the top-up is still in flight. Use an explicit pending state for the async mutation lifecycle (or a mutation hook) instead of relying on async startTransition. [api mismatch]

Severity Level: Major ⚠️
- ⚠️ Dialog can be closed while top-up still processing.
- ⚠️ Pending label and disabled states not aligned with RPC.
- ⚠️ Users may see success toast after dialog already closed.
Steps of Reproduction ✅
1. Render `WalletView` from `src/components/features/wallet-view.tsx:116-136`, which
includes `<TopUpDialog />` at `wallet-view.tsx:166-167`.

2. In the rendered UI, click the "Add Money" button defined at `topup-dialog.tsx:83-86` to
open the dialog controlled by `open` / `setOpen` at `topup-dialog.tsx:27,81-87`.

3. Enter a valid amount (e.g., 1000) in the input at `topup-dialog.tsx:96-109` and click
the primary "Add Money" button at `topup-dialog.tsx:137-139`, which calls `handleTopUp()`
at `topup-dialog.tsx:40-79`.

4. Observe that `handleTopUp()` sets `inFlightRef.current = true` at
`topup-dialog.tsx:50-51` and wraps the async RPC call `topupWalletAction(...)` at
`topup-dialog.tsx:55-58` in `startTransition(async () => { ... })` at
`topup-dialog.tsx:53`. Because the only state updates (`setAmountStr("")` and
`setOpen(false)`) occur after the `await` inside this async callback
(`topup-dialog.tsx:72-73`), React's `useTransition` `isPending` flag at
`topup-dialog.tsx:29` is not reliably true during the RPC. In practice, the
`disabled={isPending}` props on the input, quick-amount buttons, Cancel, and primary
button at `topup-dialog.tsx:108-109,119-120,132,137` remain false while the request is in
flight, and the `onOpenChange={(o) => !isPending && setOpen(o)}` handler at
`topup-dialog.tsx:87` allows the dialog to be closed mid-request. This breaks the intended
"dialog can't be closed mid-request" behavior even though `inFlightRef` still guards
against double submission.

Fix in Cursor | Fix in VSCode Claude

(Use Cmd/Ctrl + Click for best experience)

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** src/components/features/topup-dialog.tsx
**Line:** 53:53
**Comment:**
	*Api Mismatch: `startTransition` is being passed an async callback, but transition pending state is not reliably tied to the awaited RPC lifecycle. As a result, `isPending` can flip false before the request finishes, so the dialog/buttons may become interactive mid-request and allow close/cancel while the top-up is still in flight. Use an explicit pending state for the async mutation lifecycle (or a mutation hook) instead of relying on async `startTransition`.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎

try {
const result = await topupWalletAction({
amount,
idempotency_key: crypto.randomUUID(),
});

if (!result.success) {
if (mountedRef.current) toast.error(result.error);
return;
}

// Cache invalidation — safe to run regardless of mount state.
// Adjust query keys below if yours differ.
queryClient.invalidateQueries({ queryKey: ["wallet"] });

if (mountedRef.current) {
const newBalance = result.data?.availableBalance ?? 0;
toast.success(`Added ${formatInr(amount)}. New balance: ${formatInr(newBalance)}`);
setAmountStr("");
setOpen(false);
}
} finally {
inFlightRef.current = false;
}
});
}

return (
<>
<Button size="sm" variant="default" className="gap-1.5" onClick={() => setOpen(true)}>
<Plus className="h-4 w-4" />
Add Money
</Button>
<Dialog open={open} onOpenChange={(o) => !isPending && setOpen(o)}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>Add money to wallet</DialogTitle>
<DialogDescription>Test-mode top-up. ₹100 – ₹1,00,000.</DialogDescription>
</DialogHeader>

<div className="space-y-4 py-2">
<div className="space-y-2">
<Label htmlFor="topup-amount">Amount (₹)</Label>
<Input
id="topup-amount"
type="number"
inputMode="numeric"
min={100}
max={100000}
step={100}
placeholder="1000"
value={amountStr}
onChange={(e) => setAmountStr(e.target.value)}
onWheel={(e) => (e.target as HTMLInputElement).blur()}
disabled={isPending}
/>
</div>

<div className="flex flex-wrap gap-2">
{QUICK_AMOUNTS.map((amt) => (
<Button
key={amt}
type="button"
size="sm"
variant="outline"
disabled={isPending}
onClick={() => setAmountStr(String(amt))}
>
{formatInr(amt)}
</Button>
))}
</div>
</div>

<DialogFooter>
<Button
type="button"
variant="outline"
disabled={isPending}
onClick={() => setOpen(false)}
>
Cancel
</Button>
<Button type="button" disabled={isPending} onClick={handleTopUp}>
{isPending ? "Adding..." : "Add Money"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</>
);
}
35 changes: 22 additions & 13 deletions src/components/features/wallet-view.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { useUser } from "@/hooks/use-user";
import { StatusBadge } from "@/components/ui/status-badge";
import { Skeleton } from "@/components/ui/skeleton";
import { Separator } from "@/components/ui/separator";
import { TopUpDialog } from "@/components/features/topup-dialog";
import { formatInr, relativeTime } from "@/lib/format";

// ── Types ─────────────────────────────────────────────────────────────────────
Expand Down Expand Up @@ -45,11 +46,13 @@ async function fetchWalletData(role: "client" | "worker", userId: string) {
.single(),
supabase
.from("escrow_ledger")
.select(`
.select(
`
id,amount,type,created_at,from_wallet,to_wallet,
jobs!escrow_ledger_job_id_fkey(title),
milestones!escrow_ledger_milestone_id_fkey(title)
`)
`,
)
.or(`from_wallet.eq.${userId},to_wallet.eq.${userId}`)
.order("created_at", { ascending: false })
.limit(50),
Expand Down Expand Up @@ -155,21 +158,21 @@ export function WalletView({ role }: { role: "client" | "worker" }) {
Locked
</p>
</div>
<p className="text-2xl font-bold text-blue-700">
{formatInr(wallet.locked_balance)}
</p>
<p className="text-2xl font-bold text-blue-700">{formatInr(wallet.locked_balance)}</p>
<p className="text-xs text-muted-foreground">In active escrows</p>
</div>
</section>

<div className="flex justify-end">
<TopUpDialog />
</div>
Comment thread
shaiksohelll marked this conversation as resolved.

{/* ── Locked breakdown (client only) ── */}
{role === "client" && lockedByJob.length > 0 && (
<>
<Separator />
<section>
<h2 className="mb-3 text-base font-semibold text-foreground">
Locked Breakdown
</h2>
<h2 className="mb-3 text-base font-semibold text-foreground">Locked Breakdown</h2>
<ul className="space-y-2">
{lockedByJob.map((job) => (
<li
Expand All @@ -196,9 +199,7 @@ export function WalletView({ role }: { role: "client" | "worker" }) {

{/* ── Transaction history ── */}
<section>
<h2 className="mb-3 text-base font-semibold text-foreground">
Recent Transactions
</h2>
<h2 className="mb-3 text-base font-semibold text-foreground">Recent Transactions</h2>
{ledger.length === 0 ? (
<div className="rounded-xl border bg-muted/40 py-10 text-center text-sm text-muted-foreground">
No transactions yet.
Expand Down Expand Up @@ -232,7 +233,11 @@ export function WalletView({ role }: { role: "client" | "worker" }) {
</div>
<div>
<p className="text-sm font-medium">
{entry.milestone_title ?? entry.job_title}
{entry.type === "topup"
? "Wallet top-up"
: entry.type === "withdraw"
? "Wallet withdrawal"
: (entry.milestone_title ?? entry.job_title)}
</p>
<div className="flex items-center gap-1.5 text-xs text-muted-foreground">
<StatusBadge
Expand All @@ -243,7 +248,11 @@ export function WalletView({ role }: { role: "client" | "worker" }) {
? "released"
: entry.type === "refund"
? "refunded"
: "pending"
: entry.type === "topup"
? "funded"
: entry.type === "withdraw"
? "refunded"
: "pending"
}
/>
<span>{relativeTime(entry.created_at)}</span>
Expand Down
11 changes: 11 additions & 0 deletions src/lib/schemas/wallet.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { z } from "zod";

export const topupWalletSchema = z.object({
amount: z
.number({ invalid_type_error: "Amount must be a number." })
.min(100, "Minimum top-up is ₹100.")
.max(100000, "Maximum top-up is ₹1,00,000."),
idempotency_key: z.string().uuid(),
});

export type TopupWalletInput = z.infer<typeof topupWalletSchema>;
Loading
Loading