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>
+91 -30
View File
@@ -10,13 +10,17 @@ import {
TableHeader,
TableRow,
} from "@/components/ui/table"
import { listTransactions } from "@/lib/api"
import { requestWithAuth } from "@/lib/api"
import { listWalletTransactions } from "@/lib/api/transactions"
import { isActiveOrder, isCompletedOrder } from "@/lib/domain/order-filters"
import { resolveOwnerShop } from "@/lib/domain/resolve-current-shop"
import { toApiError } from "@/lib/errors"
import type { WalletTransaction } from "@/lib/types"
import { useAuthStore } from "@/store/auth"
import { useOrderStore } from "@/store/orders"
import { useShopStore } from "@/store/shops"
import { ArrowDownLeft, ArrowUpRight, CreditCard, DollarSign } from "lucide-react"
import { useEffect, useState } from "react"
export default function ShopIncomePage() {
const userId = useAuthStore((state) => state.user?.id)
@@ -24,6 +28,41 @@ export default function ShopIncomePage() {
const orders = useOrderStore((state) => state.orders)
const shop = resolveOwnerShop(userId, shops)
const [transactions, setTransactions] = useState<WalletTransaction[]>([])
const [isLoading, setIsLoading] = useState(false)
const [loadError, setLoadError] = useState<string | null>(null)
useEffect(() => {
if (!shop) return
let cancelled = false
async function load() {
setIsLoading(true)
setLoadError(null)
try {
const res = await requestWithAuth(() => listWalletTransactions({ offset: 0, limit: 1000 }))
if (cancelled) return
if (!res) {
setLoadError("请先登录")
setTransactions([])
return
}
setTransactions(res)
} catch (error) {
if (cancelled) return
setLoadError(toApiError(error).msg)
} finally {
if (!cancelled) setIsLoading(false)
}
}
void load()
return () => {
cancelled = true
}
}, [shop])
if (!shop) {
return <div className="text-sm text-muted-foreground"></div>
}
@@ -45,7 +84,7 @@ export default function ShopIncomePage() {
.reduce((acc, order) => acc + order.totalPrice, 0)
const shopOrderIds = new Set(shopOrders.map((order) => order.id))
const relatedTransactions = listTransactions().filter((transaction) => {
const relatedTransactions = transactions.filter((transaction) => {
if (transaction.type === "withdrawal") return true
if (transaction.type !== "income") return false
const match = transaction.description.match(/ord[-\d]+/)
@@ -102,36 +141,58 @@ export default function ShopIncomePage() {
</TableRow>
</TableHeader>
<TableBody>
{relatedTransactions.map((transaction) => (
<TableRow key={transaction.id}>
<TableCell>
<div className="flex items-center gap-2">
{transaction.amount > 0 ? (
<ArrowDownLeft className="h-4 w-4 text-green-500" />
) : (
<ArrowUpRight className="h-4 w-4 text-red-500" />
)}
<Badge variant={transaction.amount > 0 ? "default" : "secondary"}>
{transaction.type === "topup"
? "充值"
: transaction.type === "payment"
? "支付"
: transaction.type === "income"
? "收入"
: transaction.type === "withdrawal"
? "提现"
: "退款"}
</Badge>
</div>
{isLoading ? (
<TableRow>
<TableCell colSpan={4} className="text-center py-8 text-muted-foreground text-sm">
...
</TableCell>
<TableCell>{transaction.description}</TableCell>
<TableCell className={transaction.amount > 0 ? "text-green-600" : "text-red-600"}>
{transaction.amount > 0 ? "+" : ""}
{transaction.amount}
</TableCell>
<TableCell>{new Date(transaction.createdAt).toLocaleString()}</TableCell>
</TableRow>
))}
) : loadError ? (
<TableRow>
<TableCell colSpan={4} className="text-center py-8 text-destructive text-sm">
{loadError}
</TableCell>
</TableRow>
) : relatedTransactions.length > 0 ? (
relatedTransactions.map((transaction) => (
<TableRow key={transaction.id}>
<TableCell>
<div className="flex items-center gap-2">
{transaction.amount > 0 ? (
<ArrowDownLeft className="h-4 w-4 text-green-500" />
) : (
<ArrowUpRight className="h-4 w-4 text-red-500" />
)}
<Badge variant={transaction.amount > 0 ? "default" : "secondary"}>
{transaction.type === "topup"
? "充值"
: transaction.type === "payment"
? "支付"
: transaction.type === "income"
? "收入"
: transaction.type === "withdrawal"
? "提现"
: "退款"}
</Badge>
</div>
</TableCell>
<TableCell>{transaction.description}</TableCell>
<TableCell
className={transaction.amount > 0 ? "text-green-600" : "text-red-600"}
>
{transaction.amount > 0 ? "+" : ""}
{transaction.amount}
</TableCell>
<TableCell>{new Date(transaction.createdAt).toLocaleString()}</TableCell>
</TableRow>
))
) : (
<TableRow>
<TableCell colSpan={4} className="text-center py-8 text-muted-foreground text-sm">
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</CardContent>