feat(wallet): migrate to backend API

This commit is contained in:
zetaloop
2026-03-01 22:48:10 +08:00
parent ae239f3037
commit 83ea3fea97
3 changed files with 213 additions and 61 deletions
+66 -28
View File
@@ -5,9 +5,12 @@ import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Separator } from "@/components/ui/separator"
import { notifySuccess } from "@/lib/toast"
import { requestWithAuth } from "@/lib/api"
import { getWalletBalance, listWalletTransactions } from "@/lib/api/transactions"
import { toApiError } from "@/lib/errors"
import { notifyInfo, notifySuccess } from "@/lib/toast"
import type { WalletTransaction } from "@/lib/types"
import { useAuthStore } from "@/store/auth"
import { useWalletStore } from "@/store/wallet"
import {
ArrowDownLeft,
ArrowUpRight,
@@ -16,7 +19,7 @@ import {
RefreshCw,
Wallet,
} from "lucide-react"
import { useState } from "react"
import { useCallback, useEffect, useMemo, useState } from "react"
const typeLabels: Record<string, string> = {
topup: "充值",
@@ -37,39 +40,66 @@ const typeIcons: Record<string, typeof ArrowUpRight> = {
export default function WalletPage() {
const { currentRole } = useAuthStore()
const isConsumer = currentRole === "consumer"
const balance = useWalletStore((state) => state.balance)
const transactions = useWalletStore((state) => state.transactions)
const topUp = useWalletStore((state) => state.topUp)
const withdraw = useWalletStore((state) => state.withdraw)
const [balance, setBalance] = useState<number | null>(null)
const [transactions, setTransactions] = useState<WalletTransaction[]>([])
const [isLoading, setIsLoading] = useState(false)
const [loadError, setLoadError] = useState<string | null>(null)
const [selectedAmount, setSelectedAmount] = useState<number | null>(null)
const [customAmount, setCustomAmount] = useState("")
const [lastRefreshedAt, setLastRefreshedAt] = useState<string | null>(null)
const filteredTransactions = transactions.filter((tx) => {
if (isConsumer) {
return ["topup", "payment", "refund"].includes(tx.type)
}
return ["income", "withdrawal"].includes(tx.type)
})
const filteredTransactions = useMemo(() => {
return transactions.filter((tx) => {
if (isConsumer) {
return ["topup", "payment", "refund"].includes(tx.type)
}
return ["income", "withdrawal"].includes(tx.type)
})
}, [isConsumer, transactions])
const incomeBalance = transactions
.filter((tx) => ["income", "withdrawal"].includes(tx.type))
.reduce((acc, tx) => acc + tx.amount, 0)
const loadWalletData = useCallback(async (options?: { showToast?: boolean }) => {
setIsLoading(true)
setLoadError(null)
try {
const res = await requestWithAuth(async () => {
const [b, items] = await Promise.all([
getWalletBalance(),
listWalletTransactions({ offset: 0, limit: 1000 }),
])
return { balance: b, transactions: items }
})
if (!res) {
setLoadError("请先登录")
return
}
setBalance(res.balance)
setTransactions(res.transactions)
if (options?.showToast) notifySuccess("交易记录已刷新")
} catch (error) {
setLoadError(toApiError(error).msg)
} finally {
setIsLoading(false)
}
}, [])
useEffect(() => {
void loadWalletData()
}, [loadWalletData])
const handleTopUp = (rawAmount?: number) => {
const amount = rawAmount ?? Number(customAmount)
if (!Number.isFinite(amount) || amount <= 0) return
topUp(amount)
notifySuccess(`充值成功 +¥${amount}`)
notifyInfo("充值暂未开放")
setCustomAmount("")
setSelectedAmount(null)
}
const handleWithdraw = () => {
const amount = Number(customAmount || "0") || Number(incomeBalance.toFixed(2))
if (!Number.isFinite(amount) || amount <= 0) return
withdraw(amount)
notifySuccess(`提现申请已提交 ¥${amount}`)
notifyInfo("提现暂未开放")
setCustomAmount("")
}
@@ -85,8 +115,13 @@ export default function WalletPage() {
{isConsumer ? "账户余额" : "收入余额"}
</p>
<p className="text-3xl font-bold mt-1">
¥{isConsumer ? balance.toFixed(2) : incomeBalance.toFixed(2)}
{balance === null ? (
<span className="text-muted-foreground">--</span>
) : (
<>¥{balance.toFixed(2)}</>
)}
</p>
{loadError && <p className="text-xs text-destructive mt-2">{loadError}</p>}
</div>
<Wallet className="h-10 w-10 text-muted-foreground" />
</div>
@@ -172,12 +207,13 @@ export default function WalletPage() {
<Button
variant="ghost"
size="sm"
onClick={() => {
disabled={isLoading}
onClick={async () => {
await loadWalletData({ showToast: true })
setLastRefreshedAt(new Date().toLocaleTimeString("zh-CN"))
notifySuccess("交易记录已刷新")
}}
>
<RefreshCw className="mr-1 h-3.5 w-3.5" />
<RefreshCw className={`mr-1 h-3.5 w-3.5 ${isLoading ? "animate-spin" : ""}`} />
</Button>
</CardHeader>
@@ -185,7 +221,9 @@ export default function WalletPage() {
{lastRefreshedAt && (
<p className="text-xs text-muted-foreground">{lastRefreshedAt}</p>
)}
{filteredTransactions.length > 0 ? (
{isLoading ? (
<div className="text-center py-8 text-muted-foreground text-sm">...</div>
) : filteredTransactions.length > 0 ? (
filteredTransactions.map((tx) => {
const Icon = typeIcons[tx.type]
const isIncome = tx.amount > 0
@@ -193,7 +231,7 @@ export default function WalletPage() {
<div key={tx.id} className="flex items-center justify-between">
<div className="flex items-center gap-3">
<div className="h-8 w-8 rounded-full bg-muted flex items-center justify-center">
<Icon className="h-4 w-4" />
{Icon ? <Icon className="h-4 w-4" /> : <ArrowUpRight className="h-4 w-4" />}
</div>
<div>
<p className="text-sm font-medium">{tx.description}</p>