From 07b4fdb5598eaae32d87e10eef0e25753ca826a6 Mon Sep 17 00:00:00 2001 From: long2ice Date: Fri, 16 Jan 2026 10:33:41 +0800 Subject: [PATCH] refactor: update Order model to use pointer for ConfirmedAt and simplify variable declarations --- .gitignore | 1 + app/model/order.go | 75 +++++++++++++++++----------------------- app/notifier/telegram.go | 22 ++++++------ app/task/notify.go | 3 +- 4 files changed, 44 insertions(+), 57 deletions(-) diff --git a/.gitignore b/.gitignore index 6a031ec..29c9d5f 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,4 @@ conf.toml # Added by goreleaser init: dist/ static/web +*.log \ No newline at end of file diff --git a/app/model/order.go b/app/model/order.go index 2b85eb2..e7d304f 100644 --- a/app/model/order.go +++ b/app/model/order.go @@ -55,27 +55,27 @@ var calcMutex sync.Mutex type Order struct { Id - OrderId string `gorm:"column:order_id;type:varchar(128);not null;index;comment:商户ID" json:"order_id"` - TradeId string `gorm:"column:trade_id;type:varchar(128);not null;uniqueIndex;comment:本地ID" json:"trade_id"` - TradeType TradeType `gorm:"column:trade_type;type:varchar(20);not null;index;comment:交易类型" json:"trade_type"` - Fiat Fiat `gorm:"column:fiat;type:varchar(16);not null;index;default:CNY;comment:法定货币" json:"fiat"` - Crypto Crypto `gorm:"column:crypto;type:varchar(16);not null;index;default:USDT;comment:加密货币" json:"crypto"` - Rate string `gorm:"column:rate;type:varchar(10);not null;comment:交易汇率" json:"rate"` - Amount string `gorm:"column:amount;type:varchar(32);not null;default:0.00;comment:交易数额" json:"amount"` - Money string `gorm:"column:money;type:varchar(32);not null;default:0.00;comment:交易金额" json:"money"` - Address string `gorm:"column:address;type:varchar(128);index;not null;comment:收款地址" json:"address"` - FromAddress string `gorm:"column:from_address;type:varchar(128);not null;default:'';comment:支付地址" json:"from_address"` - Status int `gorm:"column:status;type:tinyint(1);not null;default:1;index;comment:交易状态" json:"status"` - Name string `gorm:"column:name;type:varchar(64);not null;default:'';comment:商品名称" json:"name"` - ApiType string `gorm:"column:api_type;type:varchar(20);not null;default:'epusdt';comment:API类型" json:"api_type"` - ReturnUrl string `gorm:"column:return_url;type:varchar(255);not null;default:'';comment:同步地址" json:"return_url"` - NotifyUrl string `gorm:"column:notify_url;type:varchar(255);not null;default:'';comment:异步地址" json:"notify_url"` - NotifyNum int `gorm:"column:notify_num;type:int(11);not null;default:0;comment:回调次数" json:"notify_num"` - NotifyState int `gorm:"column:notify_state;type:tinyint(1);not null;default:0;comment:回调状态 1:成功 0:失败" json:"notify_state"` - RefHash string `gorm:"column:ref_hash;type:varchar(128);default:'';index;comment:交易哈希" json:"ref_hash"` - RefBlockNum int64 `gorm:"column:ref_block_num;type:bigint(20);not null;default:0;comment:区块索引" json:"ref_block_num"` - ExpiredAt time.Time `gorm:"column:expired_at;type:timestamp;not null;comment:失效时间" json:"expired_at"` - ConfirmedAt time.Time `gorm:"column:confirmed_at;type:timestamp;null;comment:交易确认时间" json:"confirmed_at"` + OrderId string `gorm:"column:order_id;type:varchar(128);not null;index;comment:商户ID" json:"order_id"` + TradeId string `gorm:"column:trade_id;type:varchar(128);not null;uniqueIndex;comment:本地ID" json:"trade_id"` + TradeType TradeType `gorm:"column:trade_type;type:varchar(20);not null;index;comment:交易类型" json:"trade_type"` + Fiat Fiat `gorm:"column:fiat;type:varchar(16);not null;index;default:CNY;comment:法定货币" json:"fiat"` + Crypto Crypto `gorm:"column:crypto;type:varchar(16);not null;index;default:USDT;comment:加密货币" json:"crypto"` + Rate string `gorm:"column:rate;type:varchar(10);not null;comment:交易汇率" json:"rate"` + Amount string `gorm:"column:amount;type:varchar(32);not null;default:0.00;comment:交易数额" json:"amount"` + Money string `gorm:"column:money;type:varchar(32);not null;default:0.00;comment:交易金额" json:"money"` + Address string `gorm:"column:address;type:varchar(128);index;not null;comment:收款地址" json:"address"` + FromAddress string `gorm:"column:from_address;type:varchar(128);not null;default:'';comment:支付地址" json:"from_address"` + Status int `gorm:"column:status;type:tinyint(1);not null;default:1;index;comment:交易状态" json:"status"` + Name string `gorm:"column:name;type:varchar(64);not null;default:'';comment:商品名称" json:"name"` + ApiType string `gorm:"column:api_type;type:varchar(20);not null;default:'epusdt';comment:API类型" json:"api_type"` + ReturnUrl string `gorm:"column:return_url;type:varchar(255);not null;default:'';comment:同步地址" json:"return_url"` + NotifyUrl string `gorm:"column:notify_url;type:varchar(255);not null;default:'';comment:异步地址" json:"notify_url"` + NotifyNum int `gorm:"column:notify_num;type:int(11);not null;default:0;comment:回调次数" json:"notify_num"` + NotifyState int `gorm:"column:notify_state;type:tinyint(1);not null;default:0;comment:回调状态 1:成功 0:失败" json:"notify_state"` + RefHash string `gorm:"column:ref_hash;type:varchar(128);default:'';index;comment:交易哈希" json:"ref_hash"` + RefBlockNum int64 `gorm:"column:ref_block_num;type:bigint(20);not null;default:0;comment:区块索引" json:"ref_block_num"` + ExpiredAt time.Time `gorm:"column:expired_at;type:timestamp;not null;comment:失效时间" json:"expired_at"` + ConfirmedAt *time.Time `gorm:"column:confirmed_at;type:timestamp;null;comment:交易确认时间" json:"confirmed_at"` AutoTimeAt } @@ -105,7 +105,7 @@ func (o *Order) SetFailed() { func (o *Order) MarkConfirming(blockNum int64, from, hash string, at time.Time) { o.FromAddress = from - o.ConfirmedAt = at + o.ConfirmedAt = &at o.RefHash = hash o.RefBlockNum = blockNum o.Status = OrderStatusConfirming @@ -121,17 +121,14 @@ func (o *Order) SetNotifyState(state int) error { } func (o *Order) GetStatusLabel() string { - var label = "🟢收款成功" + label := "🟢收款成功" if o.Status == OrderStatusExpired { - label = "🔴交易过期" } if o.Status == OrderStatusWaiting { - label = "🟡等待支付" } if o.Status == OrderStatusCanceled { - label = "⚪️订单取消" } @@ -139,17 +136,14 @@ func (o *Order) GetStatusLabel() string { } func (o *Order) GetStatusEmoji() string { - var label = "🟢" + label := "🟢" if o.Status == OrderStatusExpired { - label = "🔴" } if o.Status == OrderStatusWaiting { - label = "🟡" } if o.Status == OrderStatusCanceled { - label = "⚪️" } @@ -157,24 +151,22 @@ func (o *Order) GetStatusEmoji() string { } func (o *Order) GetTxUrl() string { - return GetTxUrl(o.TradeType, o.RefHash) } func (o *Order) TableName() string { - return "bep_order" } func GetTradeOrder(tradeId string) (Order, bool) { var order Order - var res = Db.Where("trade_id = ?", tradeId).Take(&order) + res := Db.Where("trade_id = ?", tradeId).Take(&order) return order, res.Error == nil } func GetOrderByStatus(Status int) []Order { - var orders = make([]Order, 0) + orders := make([]Order, 0) Db.Where("status = ?", Status).Find(&orders) @@ -183,7 +175,7 @@ func GetOrderByStatus(Status int) []Order { func GetNotifyFailedTradeOrders() ([]Order, error) { var orders []Order - var res = Db.Where("status = ?", OrderStatusSuccess). + res := Db.Where("status = ?", OrderStatusSuccess). Where("notify_num <= ?", GetC(NotifyMaxRetry)). Where("notify_state = ?", OrderNotifyStateFail).Find(&orders) @@ -196,20 +188,19 @@ func CalcTradeAmount(address []string, rate, money decimal.Decimal, t TradeType) defer calcMutex.Unlock() var orders []Order - var lock = make(map[string]bool) - var status = []int{OrderStatusConfirming, OrderStatusWaiting} + lock := make(map[string]bool) + status := []int{OrderStatusConfirming, OrderStatusWaiting} Db.Where("status in (?) and trade_type = ?", status, t).Find(&orders) for _, order := range orders { lock[order.Address+order.Amount] = true } - var atom, precision = GetAtomicity(t) + atom, precision := GetAtomicity(t) if rate.LessThanOrEqual(decimal.Zero) || precision <= 0 { - return "", "", errors.New(fmt.Sprintf("[%v - %v]原子颗粒度计算异常,联系管理员处理!", atom, precision)) } - var amount = money.DivRound(rate, precision) + amount := money.DivRound(rate, precision) if amount.LessThan(atom) { // 低于最小原子精度,从最小原子精度开始计算 amount = atom } @@ -218,7 +209,6 @@ func CalcTradeAmount(address []string, rate, money decimal.Decimal, t TradeType) for _, addr := range address { k := addr + amount.String() if _, ok := lock[k]; ok { - continue } @@ -233,7 +223,6 @@ func CalcTradeAmount(address []string, rate, money decimal.Decimal, t TradeType) // CalcTradeExpiredAt 计算订单过期时间 最小180,最大3600,默认1200 func CalcTradeExpiredAt(sec int64) time.Time { if sec >= 180 && sec <= 3600 { - return time.Now().Add(time.Duration(sec) * time.Second) } @@ -246,7 +235,7 @@ func GetAtomicity(t TradeType) (decimal.Decimal, int32) { confKey = "atom_usdt" } - var atom, _ = decimal.NewFromString(GetK(confKey)) + atom, _ := decimal.NewFromString(GetK(confKey)) return atom, cast.ToInt32(math.Abs(float64(atom.Exponent()))) } diff --git a/app/notifier/telegram.go b/app/notifier/telegram.go index 1799195..edd93dd 100644 --- a/app/notifier/telegram.go +++ b/app/notifier/telegram.go @@ -26,7 +26,7 @@ type Telegram struct { } func (t *Telegram) Initialize(params string) error { - var info = gjson.Parse(params) + info := gjson.Parse(params) t.token = info.Get("bot_token").String() t.chatID = info.Get("chat_id").Int() @@ -44,7 +44,6 @@ func (t *Telegram) Initialize(params string) error { func (t *Telegram) Success(o model.Order) { if o.Status != model.OrderStatusSuccess { - return } @@ -58,7 +57,7 @@ func (t *Telegram) Success(o model.Order) { token := string(tokenType) - var text = ` + text := ` \#收款成功 \#订单交易 \#` + token + ` \-\-\- ` + "```" + ` @@ -106,7 +105,7 @@ func (t *Telegram) NotifyFail(o model.Order, reason string) { token := string(tokenT) - var text = fmt.Sprintf(` + text := fmt.Sprintf(` \#回调失败 \#订单交易 \#`+token+` \-\-\- `+"```"+` @@ -124,7 +123,7 @@ func (t *Telegram) NotifyFail(o model.Order, reason string) { o.Money, o.Rate, strings.ToUpper(tradeType), o.ConfirmedAt.Format(time.DateTime), - utils.CalcNextNotifyTime(o.ConfirmedAt, o.NotifyNum+1).Format(time.DateTime), + utils.CalcNextNotifyTime(*o.ConfirmedAt, o.NotifyNum+1).Format(time.DateTime), reason, ) @@ -142,12 +141,12 @@ func (t *Telegram) NotifyFail(o model.Order, reason string) { } func (t *Telegram) NonOrderTransfer(trans model.TronTransfer, wa model.Wallet) { - var title = "收入" + title := "收入" if trans.RecvAddress != wa.Address { title = "支出" } - var text = fmt.Sprintf( + text := fmt.Sprintf( "\\#账户%s \\#非订单交易\n\\-\\-\\-\n```\n💲交易数额:%v \n💍交易类别:"+strings.ToUpper(string(trans.TradeType))+"\n⏱️交易时间:%v\n✅接收地址:%v\n🅾️发送地址:%v```\n", title, trans.Amount.String(), @@ -170,12 +169,12 @@ func (t *Telegram) NonOrderTransfer(trans model.TronTransfer, wa model.Wallet) { } func (t *Telegram) TronResourceChange(res model.TronResource) { - var title = "代理" + title := "代理" if res.Type == core.Transaction_Contract_UnDelegateResourceContract { title = "回收" } - var text = fmt.Sprintf( + text := fmt.Sprintf( "\\#资源动态 \\#能量"+title+"\n\\-\\-\\-\n```\n🔋质押数量:"+cast.ToString(res.Balance/1000000)+"\n⏱️交易时间:%v\n✅操作地址:%v\n🅾️资源来源:%v```\n", res.Timestamp.Format(time.DateTime), utils.MaskAddress(res.RecvAddress), @@ -196,7 +195,7 @@ func (t *Telegram) TronResourceChange(res model.TronResource) { } func (t *Telegram) Welcome() { - var text = ` + text := ` 👋 欢迎使用 BEpusdt,` + conf.Desc + `,如果您看到此消息,说明系统已启动成功! 📌当前版本:` + app.Version + ` @@ -232,12 +231,11 @@ func (t *Telegram) sendMessage(p *bot.SendMessageParams) { p.ChatID = t.chatID p.MessageThreadID = t.topicID - var ctx, cancel = context.WithTimeout(context.Background(), time.Second*10) + ctx, cancel := context.WithTimeout(context.Background(), time.Second*10) defer cancel() _, err := t.api.SendMessage(ctx, p) if err != nil { - log.Warn("Bot Send Message Error:", err.Error()) } } diff --git a/app/task/notify.go b/app/task/notify.go index f29332c..d48042e 100644 --- a/app/task/notify.go +++ b/app/task/notify.go @@ -25,9 +25,8 @@ func notifyRetry(context.Context) { } for _, order := range tradeOrders { - var next = utils.CalcNextNotifyTime(order.ConfirmedAt, order.NotifyNum) + next := utils.CalcNextNotifyTime(*order.ConfirmedAt, order.NotifyNum) if time.Now().Unix() >= next.Unix() { - go notify.Handle(order) } }