refactor(order): rewrite store around state machine transitions
This commit is contained in:
@@ -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
|
||||
|
||||
|
||||
Reference in New Issue
Block a user