-
Notifications
You must be signed in to change notification settings - Fork 1
/
wallet.go
261 lines (245 loc) · 7.56 KB
/
wallet.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
package customer
import (
"github.com/admpub/decimal"
"github.com/webx-top/db"
"github.com/webx-top/echo"
"github.com/webx-top/echo/code"
"github.com/webx-top/echo/param"
"github.com/admpub/nging/v5/application/library/common"
"github.com/admpub/nging/v5/application/model/base"
"github.com/admpub/webx/application/dbschema"
"github.com/admpub/webx/application/library/xdatabase"
"github.com/admpub/webx/application/middleware/sessdata"
)
func NewWallet(ctx echo.Context) *Wallet {
m := &Wallet{
Wallet: dbschema.NewOfficialCustomerWallet(ctx),
Flow: dbschema.NewOfficialCustomerWalletFlow(ctx),
base: base.New(ctx),
}
return m
}
type Wallet struct {
Wallet *dbschema.OfficialCustomerWallet
Flow *dbschema.OfficialCustomerWalletFlow
base *base.Base
}
func (f *Wallet) Add() (pk interface{}, err error) {
return f.Wallet.Insert()
}
func (f *Wallet) Edit(mw func(db.Result) db.Result, args ...interface{}) error {
return f.Wallet.Update(mw, args...)
}
func (f *Wallet) GetBalance(assetType string, customerID uint64) (float64, error) {
return f.GetAssetBalance(assetType, customerID)
}
// AddRepeatableFlow 添加允许重复的流水记录
// unique_key: customer_id, asset_type, amount_type, source_type, source_table, source_id, number
func (f *Wallet) AddRepeatableFlow(flows ...*dbschema.OfficialCustomerWalletFlow) (err error) {
flow := f.Flow
if len(flows) > 0 {
flow = flows[0]
}
cond := db.And(
db.Cond{`customer_id`: flow.CustomerId},
db.Cond{`asset_type`: flow.AssetType},
db.Cond{`amount_type`: flow.AmountType},
db.Cond{`source_type`: flow.SourceType},
db.Cond{`source_table`: flow.SourceTable},
db.Cond{`source_id`: flow.SourceId},
)
m := dbschema.NewOfficialCustomerWalletFlow(f.base.Context)
maxN, err := m.Param(nil, cond.And()).Stat(`MAX`, `number`)
if err != nil {
return err
}
flow.Number = uint64(maxN) + 1
return f.AddFlow(flow)
}
// AddFlow 添加不允许重复的流水记录
func (f *Wallet) AddFlow(flows ...*dbschema.OfficialCustomerWalletFlow) (err error) {
flow := f.Flow
if len(flows) > 0 {
flow = flows[0]
}
err = f.base.Context.Begin()
if err != nil {
return
}
cond := db.And(
db.Cond{`customer_id`: flow.CustomerId},
db.Cond{`asset_type`: flow.AssetType},
)
var exists bool
exists, err = f.Wallet.Exists(nil, cond)
if err != nil {
f.base.Context.Rollback()
return err
}
if !exists {
f.Wallet.Freeze = 0
f.Wallet.Balance = 0
if flow.AmountType == `balance` { // 余额操作
if flow.Amount < 0 { // 扣款操作
f.base.Context.Rollback()
return common.ErrBalanceNoEnough.SetZone(`balance`)
}
// 加款操作
f.Wallet.Balance = flow.Amount
flow.WalletAmount = f.Wallet.Balance
if !AssetTypeIsIgnoreAccumulated(flow.AssetType) {
f.Wallet.Accumulated = flow.Amount
}
} else { // 冻结金额操作
if flow.Amount < 0 { // 扣除冻结
f.base.Context.Rollback()
return f.base.NewError(code.BalanceNoEnough, `冻结额不能小于0`).SetZone(`freeze`)
}
// 增加冻结
f.Wallet.Freeze = flow.Amount
flow.WalletAmount = f.Wallet.Freeze
}
f.Wallet.CustomerId = flow.CustomerId
f.Wallet.AssetType = flow.AssetType
_, err = f.Wallet.Insert()
} else {
err = xdatabase.GetAndLock(f.Wallet, cond)
if err != nil {
f.base.Context.Rollback()
return err
}
incrAmount := param.AsString(flow.Amount)
kvset := echo.H{
flow.AmountType: db.Raw(flow.AmountType + `+` + incrAmount),
}
var amount float64
if flow.AmountType == `balance` {
amount = f.Wallet.Balance
if flow.Amount > 0 && !AssetTypeIsIgnoreAccumulated(flow.AssetType) { // 加款操作时增加累计加款金额
kvset.Set(`accumulated`, db.Raw(`accumulated+`+incrAmount))
}
} else {
amount = f.Wallet.Freeze
}
//flow.WalletAmount = amount+flow.Amount
oldAmountDecimal := decimal.NewFromFloat(amount)
newAmountDecimal := decimal.NewFromFloat(flow.Amount)
newAmountDecimal = oldAmountDecimal.Add(newAmountDecimal).Truncate(2)
flow.WalletAmount, _ = newAmountDecimal.Float64()
if flow.WalletAmount < 0 { //处理flow.Amount为负数(即扣除余额)的情况。扣款操作时检查余额是否足够
f.base.Context.Rollback()
if sessdata.User(f.base.Context) != nil {
return f.base.NewError(code.BalanceNoEnough, `扣除余额(%v)失败!客户(ID:%d)的余额不足`, flow.Amount, flow.CustomerId).SetZone(`balance`)
}
return common.ErrBalanceNoEnough
}
err = f.Wallet.UpdateFields(nil, kvset, cond)
}
if err != nil {
f.base.Context.Rollback()
return
}
/*
flow := &dbschema.OfficialCustomerWalletFlow{
CustomerId: 0,
SourceCustomer: 0,
AssetType: `money`,
AmountType: AmountTypeBalance, //金额类型(balance-余额;freeze-冻结额)
Amount: 0,
SourceType: ``,
SourceTable: ``,
SourceId: 0,
TradeNo: ``,
Status: FlowStatusPending, //状态(pending-待确认;confirmed-已确认;canceled-已取消)
Description: ``,
}
*/
_, err = flow.Insert()
f.base.Context.End(err == nil)
return
}
func (f *Wallet) ListPage(cond *db.Compounds, orderby ...interface{}) ([]*WalletExt, error) {
list := []*WalletExt{}
_, err := common.NewLister(f.Wallet, &list, func(r db.Result) db.Result {
return r.OrderBy(orderby...).Relation(`Customer`, CusomterSafeFieldsSelector)
}, cond.And()).Paging(f.base.Context)
if err != nil {
return list, err
}
for k, v := range list {
v.AssetTypeName = AssetTypes.Get(v.AssetType)
list[k] = v
}
return list, err
}
func (f *Wallet) FlowListPage(cond *db.Compounds, orderby ...interface{}) ([]*WalletFlowExt, error) {
list := []*WalletFlowExt{}
_, err := common.NewLister(f.Flow, &list, func(r db.Result) db.Result {
return r.OrderBy(orderby...).Relation(`Customer`, CusomterSafeFieldsSelector).Relation(`SourceCustomer`, CusomterSafeFieldsSelector)
}, cond.And()).Paging(f.base.Context)
if err != nil {
return list, err
}
for k, v := range list {
v.AssetTypeName = AssetTypes.Get(v.AssetType)
list[k] = v
}
return list, err
}
var (
emptyAsset = dbschema.NewOfficialCustomerWallet(nil)
emptyCredit = &dbschema.OfficialCustomerWallet{Balance: 10}
)
func (f *Wallet) GetAssetBalance(assetType string, customerID uint64) (float64, error) {
recv := dbschema.NewOfficialCustomerWallet(f.base.Context)
err := recv.Get(func(r db.Result) db.Result {
return r.Select(`balance`)
}, db.And(
db.Cond{`customer_id`: customerID},
db.Cond{`asset_type`: assetType},
))
if err != nil {
if err == db.ErrNoMoreRows {
err = nil
}
}
return recv.Balance, err
}
func (f *Wallet) GetAsset(assetType string, customerID uint64) (*dbschema.OfficialCustomerWallet, error) {
recv := dbschema.NewOfficialCustomerWallet(f.base.Context)
err := recv.Get(nil, db.And(
db.Cond{`customer_id`: customerID},
db.Cond{`asset_type`: assetType},
))
if err != nil {
if err == db.ErrNoMoreRows {
err = nil
}
}
return recv, err
}
// ListCustomerAllAssets 列出客户所有资产
func (f *Wallet) ListCustomerAllAssets(customerID uint64) (map[string]*dbschema.OfficialCustomerWallet, error) {
var assetTypes []string
assets := map[string]*dbschema.OfficialCustomerWallet{}
assetTypeList := AssetTypeList()
for _, assetType := range assetTypeList {
if assetType.K == `credit` {
assets[assetType.K] = emptyCredit
} else {
assets[assetType.K] = emptyAsset
}
assetTypes = append(assetTypes, assetType.K)
}
_, err := f.Wallet.ListByOffset(nil, nil, 0, -1, db.And(
db.Cond{`customer_id`: customerID},
db.Cond{`asset_type`: db.In(assetTypes)},
))
if err != nil {
return nil, err
}
for _, asset := range f.Wallet.Objects() {
assets[asset.AssetType] = asset
}
return assets, err
}