Skip to content

Commit

Permalink
Merge branch 'feat/coupon'
Browse files Browse the repository at this point in the history
# Conflicts:
#	go.mod
#	go.sum
  • Loading branch information
sjatsh committed Nov 23, 2023
2 parents 278d09e + 9cd97fb commit 3c11157
Show file tree
Hide file tree
Showing 54 changed files with 3,206 additions and 954 deletions.
27 changes: 27 additions & 0 deletions cache/lock.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ const (
lockTime = 180
lockTicker = 10
lockAccountId = "lock:account_id:"
lock = "lock:"
)

var ErrDistributedLockPreemption = errors.New("distributed lock preemption")
Expand All @@ -38,6 +39,32 @@ func (r *RedisCache) UnLockWithRedis(accountId string) error {
return nil
}

func (r *RedisCache) Lock(key string, expirations ...time.Duration) error {
expiration := time.Second * lockTime
if len(expirations) > 0 {
expiration = expirations[0]
}
ret := r.Red.SetNX(lock+key, 1, expiration)
if err := ret.Err(); err != nil {
return fmt.Errorf("redis set order nx-->%s", err.Error())
}
if !ret.Val() {
log.Info("Lock lock:", key)
return ErrDistributedLockPreemption
}
log.Info("Lock:", key)
return nil
}

func (r *RedisCache) UnLock(key string) error {
ret := r.Red.Del(lock + key)
if err := ret.Err(); err != nil {
return fmt.Errorf("redis del order nx-->%s", err.Error())
}
log.Info("UnLock:", key)
return nil
}

func (r *RedisCache) DoLockExpire(ctx context.Context, accountId string) {
ticker := time.NewTicker(time.Second * lockTicker)
count := 0
Expand Down
1 change: 1 addition & 0 deletions cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,7 @@ func initDasCore() (*core.DasCore, *dascache.DasCache, error) {
common.DASContractNameSubAccountCellType,
common.DASContractNameEip712LibCellType,
common.DasKeyListCellType,
common.DasContractNameDpCellType,
)

// das init
Expand Down
13 changes: 12 additions & 1 deletion config/config.example.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,18 @@ das:
tron_trx: "#eff6ff"
bsc_bnb: "#fefce8"
payment_min_price: 50
service_fee_ratio: 0.1
service_fee_ratio: 0.03
service_fee_min: 0.1
coupon:
coupon_price: 0.99
encryption_key: ""
price_min: 0.99
price_max: 500
jwt_key: ""
dp:
transfer_white_list: ""
capacity_whitelist: ""
time_online: 1700623410763
origins:
- ""
notify:
Expand Down
15 changes: 15 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,10 +86,23 @@ type CfgServer struct {
BackgroundColors map[string]string `json:"background_colors" yaml:"background_colors"`
PaymentMinPrice int64 `json:"payment_min_price" yaml:"payment_min_price"`
ServiceFeeRatio float64 `json:"service_fee_ratio" yaml:"service_fee_ratio"`
ServiceFeeMin float64 `json:"service_fee_min" yaml:"service_fee_min"`
} `json:"auto_mint" yaml:"auto_mint"`
Approval struct {
MaxDelayCount uint8 `json:"max_delay_count" yaml:"max_delay_count"`
} `json:"approval" yaml:"approval"`
Coupon struct {
CouponPrice float64 `json:"coupon_price" yaml:"coupon_price"`
EncryptionKey string `json:"encryption_key" yaml:"encryption_key"`
PriceMin float64 `json:"price_min" yaml:"price_min"`
PriceMax float64 `json:"price_max" yaml:"price_max"`
} `json:"coupon" yaml:"coupon"`
JwtKey string `json:"jwt_key" yaml:"jwt_key"`
Dp struct {
TransferWhiteList string `json:"transfer_white_list" yaml:"transfer_white_list"`
CapacityWhitelist string `json:"capacity_whitelist" yaml:"capacity_whitelist"`
TimeOnline int64 `json:"time_online" yaml:"time_online"`
} `json:"dp" yaml:"dp"`
} `json:"das" yaml:"das"`
Origins []string `json:"origins" yaml:"origins"`
Notify struct {
Expand Down Expand Up @@ -138,6 +151,8 @@ func GetUnipayAddress(tokenId tables.TokenId) string {
return Cfg.UnipayAddressMap["evm"]
case tables.TokenIdTrx, tables.TokenIdTrc20USDT:
return Cfg.UnipayAddressMap["tron"]
case tables.TokenIdCkb, tables.TokenIdCkbDas:
return Cfg.UnipayAddressMap["ckb"]
}
return ""
}
Expand Down
6 changes: 6 additions & 0 deletions consts/actions.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package consts

const (
ActionCurrencyUpdate = "Update-Currency"
ActionCouponCreate = "CouponCreate"
)
2 changes: 2 additions & 0 deletions dao/dao.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ func NewGormDB(dbMysql, parserMysql config.DbMysql, autoMigrate bool) (*DbDao, e
&tables.UserConfig{},
&tables.RuleWhitelist{},
&tables.TableSubAccountAutoMintWithdrawHistory{},
&tables.CouponSetInfo{},
&tables.CouponInfo{},
); err != nil {
return nil, err
}
Expand Down
231 changes: 231 additions & 0 deletions dao/t_coupon_info.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,231 @@
package dao

import (
"das_sub_account/config"
"das_sub_account/encrypt"
"das_sub_account/tables"
"errors"
"gorm.io/gorm"
)

func (d *DbDao) CouponExists(codes map[string]struct{}) ([]string, error) {
codeAry := make([]string, 0)
for v := range codes {
codeAry = append(codeAry, v)
}

find := make([]*tables.CouponInfo, 0)
if err := d.db.Where("code in (?)", codeAry).Find(&find).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return []string{}, nil
}
return nil, err
}

res := make([]string, 0)
for _, v := range find {
res = append(res, v.Code)
}
return res, nil
}

func (d *DbDao) CreateCoupon(set *tables.CouponSetInfo, codes []tables.CouponInfo) error {
return d.db.Transaction(func(tx *gorm.DB) error {
if err := tx.Create(set).Error; err != nil {
return err
}
for idx := range codes {
if err := tx.Create(&codes[idx]).Error; err != nil {
return err
}
}
return nil
})
}

func (d *DbDao) GetCouponSetInfo(cid string) (res tables.CouponSetInfo, err error) {
if err = d.db.Where("cid = ?", cid).First(&res).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
err = nil
return
}
}
return
}

func (d *DbDao) GetCouponSetInfoByOrderId(orderId string) (res tables.CouponSetInfo, err error) {
if err = d.db.Where("order_id = ?", orderId).First(&res).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
err = nil
return
}
}
return
}

func (d *DbDao) GetCouponSetInfoByCode(code string) (res tables.CouponSetInfo, err error) {
code, err = encrypt.AesEncrypt(code, config.Cfg.Das.Coupon.EncryptionKey)
if err != nil {
return
}
var couponInfo tables.CouponInfo
err = d.db.Where("code = ?", code).First(&couponInfo).Error
if err != nil {
return
}
if err = d.db.Where("cid = ?", couponInfo.Cid).First(&res).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
err = nil
return
}
}
return
}

func (d *DbDao) FindCouponByCid(cid string) ([]*tables.CouponInfo, error) {
res := make([]*tables.CouponInfo, 0)
if err := d.db.Where("cid = ?", cid).Find(&res).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return res, nil
}
return nil, err
}
return res, nil
}

func (d *DbDao) UpdateCouponSetInfo(setInfo *tables.CouponSetInfo) error {
return d.db.Save(setInfo).Error
}

func (d *DbDao) GetUnPaidCouponSetByAccId(accId string) (res tables.CouponSetInfo, err error) {
if err = d.db.Where("account_id = ? and status = ?", accId, tables.CouponSetInfoStatusCreated).First(&res).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
err = nil
return
}
}
return
}

func (d *DbDao) FindCouponSetInfoList(accId string, page, pageSize int) ([]*tables.CouponSetInfo, int64, error) {
var total int64
res := make([]*tables.CouponSetInfo, 0)

db := d.db.Model(&tables.CouponSetInfo{}).Where("account_id = ?", accId)
if err := db.Count(&total).Error; err != nil {
if !errors.Is(err, gorm.ErrRecordNotFound) {
return nil, 0, err
}
return res, 0, nil
}

if err := db.Order("expired_at desc").Order("created_at desc").Offset((page - 1) * pageSize).Limit(pageSize).Find(&res).Error; err != nil {
if !errors.Is(err, gorm.ErrRecordNotFound) {
return nil, 0, err
}
}
return res, total, nil
}

func (d *DbDao) FindCouponCodeList(cid string, page, pageSize int) (res []*tables.CouponInfo, total int64, used int64, err error) {
db := d.db.Model(&tables.CouponInfo{}).Where("cid = ?", cid)
if err = db.Count(&total).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
err = nil
}
return
}
if err = d.db.Model(&tables.CouponInfo{}).Where("cid=? and status=?", cid, tables.CouponStatusUsed).Count(&used).Error; err != nil {
if !errors.Is(err, gorm.ErrRecordNotFound) {
return
}
err = nil
}
if err = db.Order("status asc").Order("created_at desc").Offset((page - 1) * pageSize).Limit(pageSize).Find(&res).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
err = nil
}
return
}
for idx, v := range res {
res[idx].Code, err = encrypt.AesDecrypt(v.Code, config.Cfg.Das.Coupon.EncryptionKey)
if err != nil {
return
}
}
return
}

func (d *DbDao) FindCouponCode(cid string) (res []*tables.CouponInfo, err error) {
if err = d.db.Where("cid = ?", cid).Order("status asc").Order("created_at desc").Find(&res).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
err = nil
}
}
for idx, v := range res {
res[idx].Code, err = encrypt.AesDecrypt(v.Code, config.Cfg.Das.Coupon.EncryptionKey)
if err != nil {
return
}
}
return res, nil
}

func (d *DbDao) GetCouponByCode(code string) (res tables.CouponInfo, err error) {
code, err = encrypt.AesEncrypt(code, config.Cfg.Das.Coupon.EncryptionKey)
if err != nil {
return
}
err = d.db.Where("code = ?", code).First(&res).Error
if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
err = nil
return
}
return
}

func (d *DbDao) GetSetInfoByCoupon(coupon string) (res tables.CouponSetInfo, err error) {
code, err := encrypt.AesEncrypt(coupon, config.Cfg.Das.Coupon.EncryptionKey)
if err != nil {
return
}

couponInfo := &tables.CouponInfo{}
if err = d.db.Where("code = ?", code).First(couponInfo).Error; err != nil {
return
}
err = d.db.Where("cid = ?", couponInfo.Cid).First(&res).Error
return
}

func (d *DbDao) UpdateCouponInfo(cid string, ids []int64, status int) error {
return d.db.Where("cid=? and status!=? and id in(?)", cid, tables.CouponStatusUsed, ids).Updates(map[string]interface{}{"status": status}).Error
}

func (d *DbDao) GetCouponNum(status ...tables.CouponStatus) (num int64, err error) {
if len(status) > 0 {
err = d.db.Model(&tables.CouponInfo{}).Where("status=?", status[0]).Count(&num).Error
} else {
err = d.db.Model(&tables.CouponInfo{}).Count(&num).Error
}
if errors.Is(err, gorm.ErrRecordNotFound) {
err = nil
}
return
}

func (d *DbDao) GetCouponAccount() (num int64, err error) {
err = d.db.Model(&tables.CouponSetInfo{}).Distinct("account_id").Where("status=?", tables.CouponSetInfoStatusSuccess).Count(&num).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
err = nil
}
return
}

func (d *DbDao) GetUsedCoupon(cid string) (num int64, err error) {
err = d.db.Model(&tables.CouponInfo{}).Where("cid=? and status=?", cid, tables.CouponStatusUsed).Count(&num).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
err = nil
}
return
}
Loading

0 comments on commit 3c11157

Please sign in to comment.