feat(wallet): migrate to backend API
This commit is contained in:
@@ -5,9 +5,12 @@ import { Button } from "@/components/ui/button"
|
|||||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
|
||||||
import { Input } from "@/components/ui/input"
|
import { Input } from "@/components/ui/input"
|
||||||
import { Separator } from "@/components/ui/separator"
|
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 { useAuthStore } from "@/store/auth"
|
||||||
import { useWalletStore } from "@/store/wallet"
|
|
||||||
import {
|
import {
|
||||||
ArrowDownLeft,
|
ArrowDownLeft,
|
||||||
ArrowUpRight,
|
ArrowUpRight,
|
||||||
@@ -16,7 +19,7 @@ import {
|
|||||||
RefreshCw,
|
RefreshCw,
|
||||||
Wallet,
|
Wallet,
|
||||||
} from "lucide-react"
|
} from "lucide-react"
|
||||||
import { useState } from "react"
|
import { useCallback, useEffect, useMemo, useState } from "react"
|
||||||
|
|
||||||
const typeLabels: Record<string, string> = {
|
const typeLabels: Record<string, string> = {
|
||||||
topup: "充值",
|
topup: "充值",
|
||||||
@@ -37,39 +40,66 @@ const typeIcons: Record<string, typeof ArrowUpRight> = {
|
|||||||
export default function WalletPage() {
|
export default function WalletPage() {
|
||||||
const { currentRole } = useAuthStore()
|
const { currentRole } = useAuthStore()
|
||||||
const isConsumer = currentRole === "consumer"
|
const isConsumer = currentRole === "consumer"
|
||||||
const balance = useWalletStore((state) => state.balance)
|
|
||||||
const transactions = useWalletStore((state) => state.transactions)
|
const [balance, setBalance] = useState<number | null>(null)
|
||||||
const topUp = useWalletStore((state) => state.topUp)
|
const [transactions, setTransactions] = useState<WalletTransaction[]>([])
|
||||||
const withdraw = useWalletStore((state) => state.withdraw)
|
const [isLoading, setIsLoading] = useState(false)
|
||||||
|
const [loadError, setLoadError] = useState<string | null>(null)
|
||||||
|
|
||||||
const [selectedAmount, setSelectedAmount] = useState<number | null>(null)
|
const [selectedAmount, setSelectedAmount] = useState<number | null>(null)
|
||||||
const [customAmount, setCustomAmount] = useState("")
|
const [customAmount, setCustomAmount] = useState("")
|
||||||
const [lastRefreshedAt, setLastRefreshedAt] = useState<string | null>(null)
|
const [lastRefreshedAt, setLastRefreshedAt] = useState<string | null>(null)
|
||||||
|
|
||||||
const filteredTransactions = transactions.filter((tx) => {
|
const filteredTransactions = useMemo(() => {
|
||||||
|
return transactions.filter((tx) => {
|
||||||
if (isConsumer) {
|
if (isConsumer) {
|
||||||
return ["topup", "payment", "refund"].includes(tx.type)
|
return ["topup", "payment", "refund"].includes(tx.type)
|
||||||
}
|
}
|
||||||
return ["income", "withdrawal"].includes(tx.type)
|
return ["income", "withdrawal"].includes(tx.type)
|
||||||
})
|
})
|
||||||
|
}, [isConsumer, transactions])
|
||||||
|
|
||||||
const incomeBalance = transactions
|
const loadWalletData = useCallback(async (options?: { showToast?: boolean }) => {
|
||||||
.filter((tx) => ["income", "withdrawal"].includes(tx.type))
|
setIsLoading(true)
|
||||||
.reduce((acc, tx) => acc + tx.amount, 0)
|
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 handleTopUp = (rawAmount?: number) => {
|
||||||
const amount = rawAmount ?? Number(customAmount)
|
const amount = rawAmount ?? Number(customAmount)
|
||||||
if (!Number.isFinite(amount) || amount <= 0) return
|
if (!Number.isFinite(amount) || amount <= 0) return
|
||||||
topUp(amount)
|
notifyInfo("充值暂未开放")
|
||||||
notifySuccess(`充值成功 +¥${amount}`)
|
|
||||||
setCustomAmount("")
|
setCustomAmount("")
|
||||||
setSelectedAmount(null)
|
setSelectedAmount(null)
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleWithdraw = () => {
|
const handleWithdraw = () => {
|
||||||
const amount = Number(customAmount || "0") || Number(incomeBalance.toFixed(2))
|
notifyInfo("提现暂未开放")
|
||||||
if (!Number.isFinite(amount) || amount <= 0) return
|
|
||||||
withdraw(amount)
|
|
||||||
notifySuccess(`提现申请已提交 ¥${amount}`)
|
|
||||||
setCustomAmount("")
|
setCustomAmount("")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -85,8 +115,13 @@ export default function WalletPage() {
|
|||||||
{isConsumer ? "账户余额" : "收入余额"}
|
{isConsumer ? "账户余额" : "收入余额"}
|
||||||
</p>
|
</p>
|
||||||
<p className="text-3xl font-bold mt-1">
|
<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>
|
</p>
|
||||||
|
{loadError && <p className="text-xs text-destructive mt-2">{loadError}</p>}
|
||||||
</div>
|
</div>
|
||||||
<Wallet className="h-10 w-10 text-muted-foreground" />
|
<Wallet className="h-10 w-10 text-muted-foreground" />
|
||||||
</div>
|
</div>
|
||||||
@@ -172,12 +207,13 @@ export default function WalletPage() {
|
|||||||
<Button
|
<Button
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
size="sm"
|
size="sm"
|
||||||
onClick={() => {
|
disabled={isLoading}
|
||||||
|
onClick={async () => {
|
||||||
|
await loadWalletData({ showToast: true })
|
||||||
setLastRefreshedAt(new Date().toLocaleTimeString("zh-CN"))
|
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>
|
</Button>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
@@ -185,7 +221,9 @@ export default function WalletPage() {
|
|||||||
{lastRefreshedAt && (
|
{lastRefreshedAt && (
|
||||||
<p className="text-xs text-muted-foreground">最近刷新:{lastRefreshedAt}</p>
|
<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) => {
|
filteredTransactions.map((tx) => {
|
||||||
const Icon = typeIcons[tx.type]
|
const Icon = typeIcons[tx.type]
|
||||||
const isIncome = tx.amount > 0
|
const isIncome = tx.amount > 0
|
||||||
@@ -193,7 +231,7 @@ export default function WalletPage() {
|
|||||||
<div key={tx.id} className="flex items-center justify-between">
|
<div key={tx.id} className="flex items-center justify-between">
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
<div className="h-8 w-8 rounded-full bg-muted flex items-center justify-center">
|
<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>
|
||||||
<div>
|
<div>
|
||||||
<p className="text-sm font-medium">{tx.description}</p>
|
<p className="text-sm font-medium">{tx.description}</p>
|
||||||
|
|||||||
@@ -10,13 +10,17 @@ import {
|
|||||||
TableHeader,
|
TableHeader,
|
||||||
TableRow,
|
TableRow,
|
||||||
} from "@/components/ui/table"
|
} 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 { isActiveOrder, isCompletedOrder } from "@/lib/domain/order-filters"
|
||||||
import { resolveOwnerShop } from "@/lib/domain/resolve-current-shop"
|
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 { useAuthStore } from "@/store/auth"
|
||||||
import { useOrderStore } from "@/store/orders"
|
import { useOrderStore } from "@/store/orders"
|
||||||
import { useShopStore } from "@/store/shops"
|
import { useShopStore } from "@/store/shops"
|
||||||
import { ArrowDownLeft, ArrowUpRight, CreditCard, DollarSign } from "lucide-react"
|
import { ArrowDownLeft, ArrowUpRight, CreditCard, DollarSign } from "lucide-react"
|
||||||
|
import { useEffect, useState } from "react"
|
||||||
|
|
||||||
export default function ShopIncomePage() {
|
export default function ShopIncomePage() {
|
||||||
const userId = useAuthStore((state) => state.user?.id)
|
const userId = useAuthStore((state) => state.user?.id)
|
||||||
@@ -24,6 +28,41 @@ export default function ShopIncomePage() {
|
|||||||
const orders = useOrderStore((state) => state.orders)
|
const orders = useOrderStore((state) => state.orders)
|
||||||
const shop = resolveOwnerShop(userId, shops)
|
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) {
|
if (!shop) {
|
||||||
return <div className="text-sm text-muted-foreground">当前账号没有可管理的店铺</div>
|
return <div className="text-sm text-muted-foreground">当前账号没有可管理的店铺</div>
|
||||||
}
|
}
|
||||||
@@ -45,7 +84,7 @@ export default function ShopIncomePage() {
|
|||||||
.reduce((acc, order) => acc + order.totalPrice, 0)
|
.reduce((acc, order) => acc + order.totalPrice, 0)
|
||||||
|
|
||||||
const shopOrderIds = new Set(shopOrders.map((order) => order.id))
|
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 === "withdrawal") return true
|
||||||
if (transaction.type !== "income") return false
|
if (transaction.type !== "income") return false
|
||||||
const match = transaction.description.match(/ord[-\d]+/)
|
const match = transaction.description.match(/ord[-\d]+/)
|
||||||
@@ -102,7 +141,20 @@ export default function ShopIncomePage() {
|
|||||||
</TableRow>
|
</TableRow>
|
||||||
</TableHeader>
|
</TableHeader>
|
||||||
<TableBody>
|
<TableBody>
|
||||||
{relatedTransactions.map((transaction) => (
|
{isLoading ? (
|
||||||
|
<TableRow>
|
||||||
|
<TableCell colSpan={4} className="text-center py-8 text-muted-foreground text-sm">
|
||||||
|
加载中...
|
||||||
|
</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}>
|
<TableRow key={transaction.id}>
|
||||||
<TableCell>
|
<TableCell>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
@@ -125,13 +177,22 @@ export default function ShopIncomePage() {
|
|||||||
</div>
|
</div>
|
||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell>{transaction.description}</TableCell>
|
<TableCell>{transaction.description}</TableCell>
|
||||||
<TableCell className={transaction.amount > 0 ? "text-green-600" : "text-red-600"}>
|
<TableCell
|
||||||
|
className={transaction.amount > 0 ? "text-green-600" : "text-red-600"}
|
||||||
|
>
|
||||||
{transaction.amount > 0 ? "+" : ""}
|
{transaction.amount > 0 ? "+" : ""}
|
||||||
{transaction.amount}
|
{transaction.amount}
|
||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell>{new Date(transaction.createdAt).toLocaleString()}</TableCell>
|
<TableCell>{new Date(transaction.createdAt).toLocaleString()}</TableCell>
|
||||||
</TableRow>
|
</TableRow>
|
||||||
))}
|
))
|
||||||
|
) : (
|
||||||
|
<TableRow>
|
||||||
|
<TableCell colSpan={4} className="text-center py-8 text-muted-foreground text-sm">
|
||||||
|
暂无交易记录
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
)}
|
||||||
</TableBody>
|
</TableBody>
|
||||||
</Table>
|
</Table>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
|
|||||||
+56
-3
@@ -1,5 +1,58 @@
|
|||||||
import { useWalletStore } from "@/store/wallet"
|
import type { WalletTransaction } from "@/lib/types"
|
||||||
|
|
||||||
export function listTransactions() {
|
import { httpJson } from "./http"
|
||||||
return useWalletStore.getState().transactions
|
|
||||||
|
type Paginated<T> = {
|
||||||
|
items: T[]
|
||||||
|
meta: {
|
||||||
|
total: number
|
||||||
|
offset: number
|
||||||
|
limit: number
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ListWalletTransactionsOptions = {
|
||||||
|
offset?: number
|
||||||
|
limit?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
function withOffsetLimit(path: string, options?: ListWalletTransactionsOptions): string {
|
||||||
|
const offset = options?.offset ?? 0
|
||||||
|
const limit = options?.limit ?? 1000
|
||||||
|
const searchParams = new URLSearchParams({
|
||||||
|
offset: String(offset),
|
||||||
|
limit: String(limit),
|
||||||
|
})
|
||||||
|
return `${path}?${searchParams.toString()}`
|
||||||
|
}
|
||||||
|
|
||||||
|
function unwrapWalletBalance(value: unknown): number | undefined {
|
||||||
|
if (typeof value === "number") return value
|
||||||
|
if (typeof value !== "object" || value === null) return undefined
|
||||||
|
|
||||||
|
const v = value as { balance?: unknown; amount?: unknown }
|
||||||
|
if (typeof v.balance === "number") return v.balance
|
||||||
|
if (typeof v.amount === "number") return v.amount
|
||||||
|
return undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getWalletBalance(): Promise<number> {
|
||||||
|
const res = await httpJson<unknown>("/api/v1/wallet/balance", { cache: "no-store" })
|
||||||
|
const balance = unwrapWalletBalance(res)
|
||||||
|
if (balance === undefined) {
|
||||||
|
throw new Error("Invalid wallet balance response")
|
||||||
|
}
|
||||||
|
return balance
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function listWalletTransactions(
|
||||||
|
options?: ListWalletTransactionsOptions,
|
||||||
|
): Promise<WalletTransaction[]> {
|
||||||
|
const res = await httpJson<Paginated<WalletTransaction>>(
|
||||||
|
withOffsetLimit("/api/v1/wallet/transactions", options),
|
||||||
|
{
|
||||||
|
cache: "no-store",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
return res.items
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user