refactor(order): rewrite store around state machine transitions

This commit is contained in:
zetaloop
2026-02-23 11:04:00 +08:00
parent f8c4c87c61
commit 385dac2d49
4 changed files with 411 additions and 104 deletions
+33
View File
@@ -9,6 +9,7 @@ interface WalletState {
topUp: (amount: number) => void
withdraw: (amount: number) => void
deductBalance: (orderId: string, amount: number) => boolean
refundPayment: (orderId: string, amount: number) => boolean
addIncome: (orderId: string, amount: number) => void
addTransaction: (transaction: WalletTransaction) => void
}
@@ -76,6 +77,38 @@ export const useWalletStore = create<WalletState>((set, get) => ({
}))
return true
},
refundPayment: (orderId, amount) => {
if (!Number.isFinite(amount) || amount <= 0) return false
const state = get()
const paid = state.transactions.some(
(transaction) => transaction.type === "payment" && transaction.description.includes(orderId),
)
const refunded = state.transactions.some(
(transaction) => transaction.type === "refund" && transaction.description.includes(orderId),
)
if (!paid || refunded) {
return false
}
const now = new Date().toISOString()
set((prev) => ({
balance: prev.balance + amount,
transactions: [
{
id: generateId("tx"),
type: "refund",
amount,
description: `订单 ${orderId} 退款`,
createdAt: now,
},
...prev.transactions,
],
}))
return true
},
addIncome: (orderId, amount) => {
if (!Number.isFinite(amount) || amount <= 0) return