-
Notifications
You must be signed in to change notification settings - Fork 0
feat(wallet): test-mode top-up RPC + Add Money UI #16
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 }; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 () => { | ||
| 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> | ||
| </> | ||
| ); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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>; |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Suggestion:
startTransitionis being passed an async callback, but transition pending state is not reliably tied to the awaited RPC lifecycle. As a result,isPendingcan 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 asyncstartTransition. [api mismatch]Severity Level: Major⚠️
Steps of Reproduction ✅
Fix in Cursor | Fix in VSCode Claude
(Use Cmd/Ctrl + Click for best experience)
Prompt for AI Agent 🤖