193 lines
5.3 KiB
Go
193 lines
5.3 KiB
Go
package balance
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"errors"
|
|
"fmt"
|
|
"math"
|
|
"strings"
|
|
|
|
"github.com/gogf/gf/v2/database/gdb"
|
|
"github.com/gogf/gf/v2/errors/gerror"
|
|
"github.com/gogf/gf/v2/frame/g"
|
|
"github.com/gogf/gf/v2/os/gtime"
|
|
"github.com/gogf/gf/v2/util/gconv"
|
|
)
|
|
|
|
const (
|
|
rechargeStatusPending = iota
|
|
rechargeStatusPaid
|
|
rechargeStatusExpired
|
|
|
|
rechargeChannelAlipay = 1
|
|
)
|
|
|
|
type TradeQueryResult struct {
|
|
OutTradeNo string
|
|
TradeNo string
|
|
TradeStatus string
|
|
TotalAmount string
|
|
BuyerLogonID string
|
|
}
|
|
|
|
type TradeQueryer interface {
|
|
Query(context.Context, string) (*TradeQueryResult, error)
|
|
}
|
|
|
|
type Service struct {
|
|
queryer TradeQueryer
|
|
}
|
|
|
|
func New() *Service {
|
|
return NewWithQuery(newAlipayTradeQueryer())
|
|
}
|
|
|
|
func NewWithQuery(queryer TradeQueryer) *Service {
|
|
return &Service{queryer: queryer}
|
|
}
|
|
|
|
func (s *Service) CheckRechargeTimeout(ctx context.Context, outTradeNo string) error {
|
|
outTradeNo = strings.TrimSpace(outTradeNo)
|
|
if outTradeNo == "" {
|
|
return nil
|
|
}
|
|
|
|
detail := rechargeDetail{}
|
|
if err := g.DB().Model("t_balance_detail").Ctx(ctx).
|
|
Where("order_sn", outTradeNo).
|
|
Where("transaction_channel", rechargeChannelAlipay).
|
|
Scan(&detail); err != nil {
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return nil
|
|
}
|
|
return gerror.Wrap(err, "query recharge detail failed")
|
|
}
|
|
if detail.ID == 0 || detail.TransactionStatus != rechargeStatusPending {
|
|
return nil
|
|
}
|
|
if s.queryer == nil {
|
|
return gerror.New("alipay trade queryer is not configured")
|
|
}
|
|
|
|
result, err := s.queryer.Query(ctx, outTradeNo)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if result != nil && (result.TradeStatus == "TRADE_SUCCESS" || result.TradeStatus == "TRADE_FINISHED") {
|
|
return s.creditRecharge(ctx, detail, result)
|
|
}
|
|
|
|
_, err = g.DB().Model("t_balance_detail").Ctx(ctx).
|
|
Where("id", detail.ID).
|
|
Where("transaction_status", rechargeStatusPending).
|
|
Data(g.Map{
|
|
"transaction_status": rechargeStatusExpired,
|
|
"remark": "Alipay recharge timed out without payment",
|
|
"updated_at": gtime.Now(),
|
|
}).
|
|
Update()
|
|
return gerror.Wrap(err, "expire recharge detail failed")
|
|
}
|
|
|
|
func (s *Service) creditRecharge(ctx context.Context, initial rechargeDetail, result *TradeQueryResult) error {
|
|
amount := gconv.Float64(strings.TrimSpace(result.TotalAmount))
|
|
if amount <= 0 {
|
|
return gerror.New("paid recharge has invalid amount")
|
|
}
|
|
|
|
return g.DB().Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
|
|
detail := rechargeDetail{}
|
|
detailModel := lockForUpdate(tx.Ctx(ctx).Model("t_balance_detail"))
|
|
if err := detailModel.
|
|
Where("id", initial.ID).
|
|
Scan(&detail); err != nil {
|
|
return gerror.Wrap(err, "lock recharge detail failed")
|
|
}
|
|
if detail.ID == 0 || detail.TransactionStatus == rechargeStatusPaid {
|
|
return nil
|
|
}
|
|
if detail.TransactionStatus != rechargeStatusPending {
|
|
return gerror.New("recharge order is closed")
|
|
}
|
|
if math.Abs(detail.Amount-amount) > 0.001 {
|
|
return gerror.New("paid amount does not match recharge detail")
|
|
}
|
|
|
|
account := agentBalance{}
|
|
accountModel := lockForUpdate(tx.Ctx(ctx).Model("t_agent_balance"))
|
|
if err := accountModel.
|
|
Where("dept_id", detail.DeptID).
|
|
Where("tenant_id", detail.TenantID).
|
|
Scan(&account); err != nil {
|
|
return gerror.Wrap(err, "lock agent balance failed")
|
|
}
|
|
now := gtime.Now()
|
|
if account.ID == 0 {
|
|
id, err := tx.Ctx(ctx).Model("t_agent_balance").Data(g.Map{
|
|
"dept_id": detail.DeptID,
|
|
"balance": 0,
|
|
"withdraw_amount": 0,
|
|
"withdraw_amount_status": 1,
|
|
"invoice_amount": 0,
|
|
"can_invoice_amount": 0,
|
|
"credit_limit": 0,
|
|
"used_credit": 0,
|
|
"pending_repayment": 0,
|
|
"status": 0,
|
|
"tenant_id": detail.TenantID,
|
|
"created_dept": detail.CreatedDept,
|
|
"created_by": detail.CreatedBy,
|
|
"created_at": now,
|
|
}).InsertAndGetId()
|
|
if err != nil {
|
|
return gerror.Wrap(err, "initialize agent balance failed")
|
|
}
|
|
account = agentBalance{ID: id}
|
|
}
|
|
|
|
before := account.Balance
|
|
after := before + detail.Amount
|
|
if _, err := tx.Ctx(ctx).Model("t_agent_balance").Where("id", account.ID).Data(g.Map{
|
|
"balance": after,
|
|
"updated_by": detail.CreatedBy,
|
|
"updated_at": now,
|
|
}).Update(); err != nil {
|
|
return gerror.Wrap(err, "update agent balance failed")
|
|
}
|
|
_, err := tx.Ctx(ctx).Model("t_balance_detail").Where("id", detail.ID).Data(g.Map{
|
|
"transaction_status": rechargeStatusPaid,
|
|
"transaction_time": now,
|
|
"before_balance": before,
|
|
"balance_after": after,
|
|
"channel_serial_no": result.TradeNo,
|
|
"remark": fmt.Sprintf("Alipay recharge, buyer: %s", result.BuyerLogonID),
|
|
"updated_by": detail.CreatedBy,
|
|
"updated_at": now,
|
|
}).Update()
|
|
return gerror.Wrap(err, "mark recharge paid failed")
|
|
})
|
|
}
|
|
|
|
type rechargeDetail struct {
|
|
ID int64 `orm:"id"`
|
|
DeptID int64 `orm:"dept_id"`
|
|
TransactionStatus int `orm:"transaction_status"`
|
|
Amount float64 `orm:"amount"`
|
|
TenantID string `orm:"tenant_id"`
|
|
CreatedDept int64 `orm:"created_dept"`
|
|
CreatedBy int64 `orm:"created_by"`
|
|
}
|
|
|
|
type agentBalance struct {
|
|
ID int64 `orm:"id"`
|
|
Balance float64 `orm:"balance"`
|
|
}
|
|
|
|
func lockForUpdate(model *gdb.Model) *gdb.Model {
|
|
if g.DB().GetConfig().Type == "sqlite" {
|
|
return model
|
|
}
|
|
return model.LockUpdate()
|
|
}
|