Browse Source

add 绿色积分

tags/v3.6.4
DengBiao 2 years ago
parent
commit
d22a22800b
13 changed files with 1569 additions and 0 deletions
  1. +157
    -0
      db/db_block_green_chain.go
  2. +157
    -0
      db/db_block_green_chain_custom_user_airdrop.go
  3. +157
    -0
      db/db_block_green_chain_flow.go
  4. +157
    -0
      db/db_block_green_chain_reward_records.go
  5. +157
    -0
      db/db_block_green_chain_settlement_records.go
  6. +32
    -0
      db/model/block_green_chain.go
  7. +17
    -0
      db/model/block_green_chain_custom_user_airdrop.go
  8. +23
    -0
      db/model/block_green_chain_flow.go
  9. +21
    -0
      db/model/block_green_chain_reward_records.go
  10. +19
    -0
      db/model/block_green_chain_settlement_records.go
  11. +35
    -0
      enum/block_green_chain.go
  12. +12
    -0
      md/block_star_chain.go
  13. +625
    -0
      rule/block_green_chain_settlement.go

+ 157
- 0
db/db_block_green_chain.go View File

@@ -0,0 +1,157 @@
package db

import (
"code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/db/model"
zhios_order_relate_utils "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/utils"
zhios_order_relate_logx "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/utils/logx"
"errors"
"fmt"
"reflect"
"xorm.io/xorm"
)

// BatchSelectBlockGreenChains 批量查询数据 TODO::和下面的方法重复了,建议采用下面的 `BlockGreenChainFindByParams` 方法
func BatchSelectBlockGreenChains(Db *xorm.Engine, params map[string]interface{}) (*[]model.BlockGreenChain, error) {
var BlockGreenChainData []model.BlockGreenChain
if err := Db.In(zhios_order_relate_utils.AnyToString(params["key"]), params["value"]).
Find(&BlockGreenChainData); err != nil {
return nil, zhios_order_relate_logx.Warn(err)
}
return &BlockGreenChainData, nil
}

// BlockGreenChainInsert 插入单条数据
func BlockGreenChainInsert(Db *xorm.Engine, BlockGreenChain *model.BlockGreenChain) (int, error) {
_, err := Db.InsertOne(BlockGreenChain)
if err != nil {
return 0, err
}
return BlockGreenChain.Id, nil
}

// BatchAddBlockGreenChains 批量新增数据
func BatchAddBlockGreenChains(Db *xorm.Engine, BlockGreenChainData []*model.BlockGreenChain) (int64, error) {
affected, err := Db.Insert(BlockGreenChainData)
if err != nil {
return 0, err
}
return affected, nil
}

func GetBlockGreenChainCount(Db *xorm.Engine) int {
var BlockGreenChain model.BlockGreenChain
session := Db.Where("")
count, err := session.Count(&BlockGreenChain)
if err != nil {
return 0
}
return int(count)
}

// BlockGreenChainDelete 删除记录
func BlockGreenChainDelete(Db *xorm.Engine, id interface{}) (int64, error) {
if reflect.TypeOf(id).Kind() == reflect.Slice {
return Db.In("id", id).Delete(model.BlockGreenChain{})
} else {
return Db.Where("id = ?", id).Delete(model.BlockGreenChain{})
}
}

// BlockGreenChainUpdate 更新记录
func BlockGreenChainUpdate(session *xorm.Session, id interface{}, BlockGreenChain *model.BlockGreenChain, forceColums ...string) (int64, error) {
var (
affected int64
err error
)
if forceColums != nil {
affected, err = session.Where("id=?", id).Cols(forceColums...).Update(BlockGreenChain)
} else {
affected, err = session.Where("id=?", id).Update(BlockGreenChain)
}
if err != nil {
return 0, err
}
return affected, nil
}

// BlockGreenChainGetOneByParams 通过传入的参数查询数据(单条)
func BlockGreenChainGetOneByParams(session *xorm.Session, params map[string]interface{}) (*model.BlockGreenChain, error) {
var m model.BlockGreenChain
var query = fmt.Sprintf("%s =?", params["key"])
has, err := session.Where(query, params["value"]).Get(&m)
if err != nil {
return nil, zhios_order_relate_logx.Error(err)
}
if has == false {
return nil, errors.New("未查询到相应的 block_star_chain 记录")
}
return &m, nil
}

// BlockGreenChainFindByParams 通过传入的参数查询数据(多条)
func BlockGreenChainFindByParams(Db *xorm.Engine, params map[string]interface{}) (*[]model.BlockGreenChain, error) {
var m []model.BlockGreenChain
if params["value"] == nil {
return nil, errors.New("参数有误")
}
if params["key"] == nil {
//查询全部数据
err := Db.Find(&m)
if err != nil {
return nil, zhios_order_relate_logx.Error(err)
}
return &m, nil
} else {
if reflect.TypeOf(params["value"]).Kind() == reflect.Slice {
//指定In查询
if err := Db.In(zhios_order_relate_utils.AnyToString(params["key"]), params["value"]).Find(&m); err != nil {
return nil, zhios_order_relate_logx.Warn(err)
}
return &m, nil
} else {
var query = fmt.Sprintf("%s =?", params["key"])
err := Db.Where(query, params["value"]).Find(&m)
if err != nil {
return nil, zhios_order_relate_logx.Error(err)
}
return &m, nil
}

}
}

func BlockGreenChainFindByParamsByPage(Db *xorm.Engine, params map[string]interface{}, page, pageSize int) (*[]model.BlockGreenChain, error) {
var m []model.BlockGreenChain
if params["value"] == nil {
return nil, errors.New("参数有误")
}
if page == 0 && pageSize == 0 {
page = 1
pageSize = 10
}

if params["key"] == nil {
//查询全部数据
err := Db.Limit(pageSize, (page-1)*pageSize).Find(&m)
if err != nil {
return nil, zhios_order_relate_logx.Error(err)
}
return &m, nil
} else {
if reflect.TypeOf(params["value"]).Kind() == reflect.Slice {
//指定In查询
if err := Db.In(zhios_order_relate_utils.AnyToString(params["key"]), params["value"]).Limit(pageSize, (page-1)*pageSize).Find(&m); err != nil {
return nil, zhios_order_relate_logx.Warn(err)
}
return &m, nil
} else {
var query = fmt.Sprintf("%s =?", params["key"])
err := Db.Where(query, params["value"]).Limit(pageSize, (page-1)*pageSize).Find(&m)
if err != nil {
return nil, zhios_order_relate_logx.Error(err)
}
return &m, nil
}

}
}

+ 157
- 0
db/db_block_green_chain_custom_user_airdrop.go View File

@@ -0,0 +1,157 @@
package db

import (
"code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/db/model"
zhios_order_relate_utils "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/utils"
zhios_order_relate_logx "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/utils/logx"
"errors"
"fmt"
"reflect"
"xorm.io/xorm"
)

// BatchSelectBlockGreenChainCustomUserAirdrops 批量查询数据 TODO::和下面的方法重复了,建议采用下面的 `BlockGreenChainCustomUserAirdropFindByParams` 方法
func BatchSelectBlockGreenChainCustomUserAirdrops(Db *xorm.Engine, params map[string]interface{}) (*[]model.BlockGreenChainCustomUserAirdrop, error) {
var BlockGreenChainCustomUserAirdropData []model.BlockGreenChainCustomUserAirdrop
if err := Db.In(zhios_order_relate_utils.AnyToString(params["key"]), params["value"]).
Find(&BlockGreenChainCustomUserAirdropData); err != nil {
return nil, zhios_order_relate_logx.Warn(err)
}
return &BlockGreenChainCustomUserAirdropData, nil
}

// BlockGreenChainCustomUserAirdropInsert 插入单条数据
func BlockGreenChainCustomUserAirdropInsert(Db *xorm.Engine, BlockGreenChainCustomUserAirdrop *model.BlockGreenChainCustomUserAirdrop) (int64, error) {
_, err := Db.InsertOne(BlockGreenChainCustomUserAirdrop)
if err != nil {
return 0, err
}
return BlockGreenChainCustomUserAirdrop.Id, nil
}

// BatchAddBlockGreenChainCustomUserAirdrops 批量新增数据
func BatchAddBlockGreenChainCustomUserAirdrops(Db *xorm.Engine, BlockGreenChainCustomUserAirdropData []*model.BlockGreenChainCustomUserAirdrop) (int64, error) {
affected, err := Db.Insert(BlockGreenChainCustomUserAirdropData)
if err != nil {
return 0, err
}
return affected, nil
}

func GetBlockGreenChainCustomUserAirdropCount(Db *xorm.Engine) int {
var BlockGreenChainCustomUserAirdrop model.BlockGreenChainCustomUserAirdrop
session := Db.Where("")
count, err := session.Count(&BlockGreenChainCustomUserAirdrop)
if err != nil {
return 0
}
return int(count)
}

// BlockGreenChainCustomUserAirdropDelete 删除记录
func BlockGreenChainCustomUserAirdropDelete(Db *xorm.Engine, id interface{}) (int64, error) {
if reflect.TypeOf(id).Kind() == reflect.Slice {
return Db.In("id", id).Delete(model.BlockGreenChainCustomUserAirdrop{})
} else {
return Db.Where("id = ?", id).Delete(model.BlockGreenChainCustomUserAirdrop{})
}
}

// BlockGreenChainCustomUserAirdropUpdate 更新记录
func BlockGreenChainCustomUserAirdropUpdate(session *xorm.Session, id interface{}, BlockGreenChainCustomUserAirdrop *model.BlockGreenChainCustomUserAirdrop, forceColums ...string) (int64, error) {
var (
affected int64
err error
)
if forceColums != nil {
affected, err = session.Where("id=?", id).Cols(forceColums...).Update(BlockGreenChainCustomUserAirdrop)
} else {
affected, err = session.Where("id=?", id).Update(BlockGreenChainCustomUserAirdrop)
}
if err != nil {
return 0, err
}
return affected, nil
}

// BlockGreenChainCustomUserAirdropGetOneByParams 通过传入的参数查询数据(单条)
func BlockGreenChainCustomUserAirdropGetOneByParams(session *xorm.Session, params map[string]interface{}) (*model.BlockGreenChainCustomUserAirdrop, error) {
var m model.BlockGreenChainCustomUserAirdrop
var query = fmt.Sprintf("%s =?", params["key"])
has, err := session.Where(query, params["value"]).Get(&m)
if err != nil {
return nil, zhios_order_relate_logx.Error(err)
}
if has == false {
return nil, errors.New("未查询到相应的 block_star_chain 记录")
}
return &m, nil
}

// BlockGreenChainCustomUserAirdropFindByParams 通过传入的参数查询数据(多条)
func BlockGreenChainCustomUserAirdropFindByParams(Db *xorm.Engine, params map[string]interface{}) (*[]model.BlockGreenChainCustomUserAirdrop, error) {
var m []model.BlockGreenChainCustomUserAirdrop
if params["value"] == nil {
return nil, errors.New("参数有误")
}
if params["key"] == nil {
//查询全部数据
err := Db.Find(&m)
if err != nil {
return nil, zhios_order_relate_logx.Error(err)
}
return &m, nil
} else {
if reflect.TypeOf(params["value"]).Kind() == reflect.Slice {
//指定In查询
if err := Db.In(zhios_order_relate_utils.AnyToString(params["key"]), params["value"]).Find(&m); err != nil {
return nil, zhios_order_relate_logx.Warn(err)
}
return &m, nil
} else {
var query = fmt.Sprintf("%s =?", params["key"])
err := Db.Where(query, params["value"]).Find(&m)
if err != nil {
return nil, zhios_order_relate_logx.Error(err)
}
return &m, nil
}

}
}

func BlockGreenChainCustomUserAirdropFindByParamsByPage(Db *xorm.Engine, params map[string]interface{}, page, pageSize int) (*[]model.BlockGreenChainCustomUserAirdrop, error) {
var m []model.BlockGreenChainCustomUserAirdrop
if params["value"] == nil {
return nil, errors.New("参数有误")
}
if page == 0 && pageSize == 0 {
page = 1
pageSize = 10
}

if params["key"] == nil {
//查询全部数据
err := Db.Limit(pageSize, (page-1)*pageSize).Find(&m)
if err != nil {
return nil, zhios_order_relate_logx.Error(err)
}
return &m, nil
} else {
if reflect.TypeOf(params["value"]).Kind() == reflect.Slice {
//指定In查询
if err := Db.In(zhios_order_relate_utils.AnyToString(params["key"]), params["value"]).Limit(pageSize, (page-1)*pageSize).Find(&m); err != nil {
return nil, zhios_order_relate_logx.Warn(err)
}
return &m, nil
} else {
var query = fmt.Sprintf("%s =?", params["key"])
err := Db.Where(query, params["value"]).Limit(pageSize, (page-1)*pageSize).Find(&m)
if err != nil {
return nil, zhios_order_relate_logx.Error(err)
}
return &m, nil
}

}
}

+ 157
- 0
db/db_block_green_chain_flow.go View File

@@ -0,0 +1,157 @@
package db

import (
"code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/db/model"
zhios_order_relate_utils "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/utils"
zhios_order_relate_logx "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/utils/logx"
"errors"
"fmt"
"reflect"
"xorm.io/xorm"
)

// BatchSelectBlockGreenChainFlows 批量查询数据 TODO::和下面的方法重复了,建议采用下面的 `BlockGreenChainFlowFindByParams` 方法
func BatchSelectBlockGreenChainFlows(Db *xorm.Engine, params map[string]interface{}) (*[]model.BlockGreenChainFlow, error) {
var BlockGreenChainFlowData []model.BlockGreenChainFlow
if err := Db.In(zhios_order_relate_utils.AnyToString(params["key"]), params["value"]).
Find(&BlockGreenChainFlowData); err != nil {
return nil, zhios_order_relate_logx.Warn(err)
}
return &BlockGreenChainFlowData, nil
}

// BlockGreenChainFlowInsert 插入单条数据
func BlockGreenChainFlowInsert(session *xorm.Session, BlockGreenChainFlow *model.BlockGreenChainFlow) (int64, error) {
_, err := session.InsertOne(BlockGreenChainFlow)
if err != nil {
return 0, err
}
return BlockGreenChainFlow.Id, nil
}

// BatchAddBlockGreenChainFlows 批量新增数据
func BatchAddBlockGreenChainFlows(Db *xorm.Engine, BlockGreenChainFlowData []*model.BlockGreenChainFlow) (int64, error) {
affected, err := Db.Insert(BlockGreenChainFlowData)
if err != nil {
return 0, err
}
return affected, nil
}

func GetBlockGreenChainFlowCount(Db *xorm.Engine) int {
var BlockGreenChainFlow model.BlockGreenChainFlow
session := Db.Where("")
count, err := session.Count(&BlockGreenChainFlow)
if err != nil {
return 0
}
return int(count)
}

// BlockGreenChainFlowDelete 删除记录
func BlockGreenChainFlowDelete(Db *xorm.Engine, id interface{}) (int64, error) {
if reflect.TypeOf(id).Kind() == reflect.Slice {
return Db.In("id", id).Delete(model.BlockGreenChainFlow{})
} else {
return Db.Where("id = ?", id).Delete(model.BlockGreenChainFlow{})
}
}

// BlockGreenChainFlowUpdate 更新记录
func BlockGreenChainFlowUpdate(session *xorm.Session, id interface{}, BlockGreenChainFlow *model.BlockGreenChainFlow, forceColums ...string) (int64, error) {
var (
affected int64
err error
)
if forceColums != nil {
affected, err = session.Where("id=?", id).Cols(forceColums...).Update(BlockGreenChainFlow)
} else {
affected, err = session.Where("id=?", id).Update(BlockGreenChainFlow)
}
if err != nil {
return 0, err
}
return affected, nil
}

// BlockGreenChainFlowGetOneByParams 通过传入的参数查询数据(单条)
func BlockGreenChainFlowGetOneByParams(session *xorm.Session, params map[string]interface{}) (*model.BlockGreenChainFlow, error) {
var m model.BlockGreenChainFlow
var query = fmt.Sprintf("%s =?", params["key"])
has, err := session.Where(query, params["value"]).Get(&m)
if err != nil {
return nil, zhios_order_relate_logx.Error(err)
}
if has == false {
return nil, errors.New("未查询到相应的 block_star_chain 记录")
}
return &m, nil
}

// BlockGreenChainFlowFindByParams 通过传入的参数查询数据(多条)
func BlockGreenChainFlowFindByParams(Db *xorm.Engine, params map[string]interface{}) (*[]model.BlockGreenChainFlow, error) {
var m []model.BlockGreenChainFlow
if params["value"] == nil {
return nil, errors.New("参数有误")
}
if params["key"] == nil {
//查询全部数据
err := Db.Find(&m)
if err != nil {
return nil, zhios_order_relate_logx.Error(err)
}
return &m, nil
} else {
if reflect.TypeOf(params["value"]).Kind() == reflect.Slice {
//指定In查询
if err := Db.In(zhios_order_relate_utils.AnyToString(params["key"]), params["value"]).Find(&m); err != nil {
return nil, zhios_order_relate_logx.Warn(err)
}
return &m, nil
} else {
var query = fmt.Sprintf("%s =?", params["key"])
err := Db.Where(query, params["value"]).Find(&m)
if err != nil {
return nil, zhios_order_relate_logx.Error(err)
}
return &m, nil
}

}
}

func BlockGreenChainFlowFindByParamsByPage(Db *xorm.Engine, params map[string]interface{}, page, pageSize int) (*[]model.BlockGreenChainFlow, error) {
var m []model.BlockGreenChainFlow
if params["value"] == nil {
return nil, errors.New("参数有误")
}
if page == 0 && pageSize == 0 {
page = 1
pageSize = 10
}

if params["key"] == nil {
//查询全部数据
err := Db.Limit(pageSize, (page-1)*pageSize).Find(&m)
if err != nil {
return nil, zhios_order_relate_logx.Error(err)
}
return &m, nil
} else {
if reflect.TypeOf(params["value"]).Kind() == reflect.Slice {
//指定In查询
if err := Db.In(zhios_order_relate_utils.AnyToString(params["key"]), params["value"]).Limit(pageSize, (page-1)*pageSize).Find(&m); err != nil {
return nil, zhios_order_relate_logx.Warn(err)
}
return &m, nil
} else {
var query = fmt.Sprintf("%s =?", params["key"])
err := Db.Where(query, params["value"]).Limit(pageSize, (page-1)*pageSize).Find(&m)
if err != nil {
return nil, zhios_order_relate_logx.Error(err)
}
return &m, nil
}

}
}

+ 157
- 0
db/db_block_green_chain_reward_records.go View File

@@ -0,0 +1,157 @@
package db

import (
"code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/db/model"
zhios_order_relate_utils "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/utils"
zhios_order_relate_logx "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/utils/logx"
"errors"
"fmt"
"reflect"
"xorm.io/xorm"
)

// BatchSelectBlockGreenChainRewardRecords 批量查询数据 TODO::和下面的方法重复了,建议采用下面的 `BlockGreenChainRewardRecordsFindByParams` 方法
func BatchSelectBlockGreenChainRewardRecords(Db *xorm.Engine, params map[string]interface{}) (*[]model.BlockGreenChainRewardRecords, error) {
var BlockGreenChainRewardRecordsData []model.BlockGreenChainRewardRecords
if err := Db.In(zhios_order_relate_utils.AnyToString(params["key"]), params["value"]).
Find(&BlockGreenChainRewardRecordsData); err != nil {
return nil, zhios_order_relate_logx.Warn(err)
}
return &BlockGreenChainRewardRecordsData, nil
}

// BlockGreenChainRewardRecordsInsert 插入单条数据
func BlockGreenChainRewardRecordsInsert(Db *xorm.Engine, BlockGreenChainRewardRecords *model.BlockGreenChainRewardRecords) (int64, error) {
_, err := Db.InsertOne(BlockGreenChainRewardRecords)
if err != nil {
return 0, err
}
return BlockGreenChainRewardRecords.Id, nil
}

// BatchAddBlockGreenChainRewardRecordss 批量新增数据
func BatchAddBlockGreenChainRewardRecordss(Db *xorm.Engine, BlockGreenChainRewardRecordsData []*model.BlockGreenChainRewardRecords) (int64, error) {
affected, err := Db.Insert(BlockGreenChainRewardRecordsData)
if err != nil {
return 0, err
}
return affected, nil
}

func GetBlockGreenChainRewardRecordsCount(Db *xorm.Engine) int {
var BlockGreenChainRewardRecords model.BlockGreenChainRewardRecords
session := Db.Where("")
count, err := session.Count(&BlockGreenChainRewardRecords)
if err != nil {
return 0
}
return int(count)
}

// BlockGreenChainRewardRecordsDelete 删除记录
func BlockGreenChainRewardRecordsDelete(Db *xorm.Engine, id interface{}) (int64, error) {
if reflect.TypeOf(id).Kind() == reflect.Slice {
return Db.In("id", id).Delete(model.BlockGreenChainRewardRecords{})
} else {
return Db.Where("id = ?", id).Delete(model.BlockGreenChainRewardRecords{})
}
}

// BlockGreenChainRewardRecordsUpdate 更新记录
func BlockGreenChainRewardRecordsUpdate(session *xorm.Session, id interface{}, BlockGreenChainRewardRecords *model.BlockGreenChainRewardRecords, forceColums ...string) (int64, error) {
var (
affected int64
err error
)
if forceColums != nil {
affected, err = session.Where("id=?", id).Cols(forceColums...).Update(BlockGreenChainRewardRecords)
} else {
affected, err = session.Where("id=?", id).Update(BlockGreenChainRewardRecords)
}
if err != nil {
return 0, err
}
return affected, nil
}

// BlockGreenChainRewardRecordsGetOneByParams 通过传入的参数查询数据(单条)
func BlockGreenChainRewardRecordsGetOneByParams(session *xorm.Session, params map[string]interface{}) (*model.BlockGreenChainRewardRecords, error) {
var m model.BlockGreenChainRewardRecords
var query = fmt.Sprintf("%s =?", params["key"])
has, err := session.Where(query, params["value"]).Get(&m)
if err != nil {
return nil, zhios_order_relate_logx.Error(err)
}
if has == false {
return nil, errors.New("未查询到相应的 block_star_chain 记录")
}
return &m, nil
}

// BlockGreenChainRewardRecordsFindByParams 通过传入的参数查询数据(多条)
func BlockGreenChainRewardRecordsFindByParams(Db *xorm.Engine, params map[string]interface{}) (*[]model.BlockGreenChainRewardRecords, error) {
var m []model.BlockGreenChainRewardRecords
if params["value"] == nil {
return nil, errors.New("参数有误")
}
if params["key"] == nil {
//查询全部数据
err := Db.Find(&m)
if err != nil {
return nil, zhios_order_relate_logx.Error(err)
}
return &m, nil
} else {
if reflect.TypeOf(params["value"]).Kind() == reflect.Slice {
//指定In查询
if err := Db.In(zhios_order_relate_utils.AnyToString(params["key"]), params["value"]).Find(&m); err != nil {
return nil, zhios_order_relate_logx.Warn(err)
}
return &m, nil
} else {
var query = fmt.Sprintf("%s =?", params["key"])
err := Db.Where(query, params["value"]).Find(&m)
if err != nil {
return nil, zhios_order_relate_logx.Error(err)
}
return &m, nil
}

}
}

func BlockGreenChainRewardRecordsFindByParamsByPage(Db *xorm.Engine, params map[string]interface{}, page, pageSize int) (*[]model.BlockGreenChainRewardRecords, error) {
var m []model.BlockGreenChainRewardRecords
if params["value"] == nil {
return nil, errors.New("参数有误")
}
if page == 0 && pageSize == 0 {
page = 1
pageSize = 10
}

if params["key"] == nil {
//查询全部数据
err := Db.Limit(pageSize, (page-1)*pageSize).Find(&m)
if err != nil {
return nil, zhios_order_relate_logx.Error(err)
}
return &m, nil
} else {
if reflect.TypeOf(params["value"]).Kind() == reflect.Slice {
//指定In查询
if err := Db.In(zhios_order_relate_utils.AnyToString(params["key"]), params["value"]).Limit(pageSize, (page-1)*pageSize).Find(&m); err != nil {
return nil, zhios_order_relate_logx.Warn(err)
}
return &m, nil
} else {
var query = fmt.Sprintf("%s =?", params["key"])
err := Db.Where(query, params["value"]).Limit(pageSize, (page-1)*pageSize).Find(&m)
if err != nil {
return nil, zhios_order_relate_logx.Error(err)
}
return &m, nil
}

}
}

+ 157
- 0
db/db_block_green_chain_settlement_records.go View File

@@ -0,0 +1,157 @@
package db

import (
"code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/db/model"
zhios_order_relate_utils "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/utils"
zhios_order_relate_logx "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/utils/logx"
"errors"
"fmt"
"reflect"
"xorm.io/xorm"
)

// BatchSelectBlockGreenChainSettlementRecords 批量查询数据 TODO::和下面的方法重复了,建议采用下面的 `BlockGreenChainSettlementRecordsFindByParams` 方法
func BatchSelectBlockGreenChainSettlementRecords(Db *xorm.Engine, params map[string]interface{}) (*[]model.BlockGreenChainSettlementRecords, error) {
var BlockGreenChainSettlementRecordsData []model.BlockGreenChainSettlementRecords
if err := Db.In(zhios_order_relate_utils.AnyToString(params["key"]), params["value"]).
Find(&BlockGreenChainSettlementRecordsData); err != nil {
return nil, zhios_order_relate_logx.Warn(err)
}
return &BlockGreenChainSettlementRecordsData, nil
}

// BlockGreenChainSettlementRecordsInsert 插入单条数据
func BlockGreenChainSettlementRecordsInsert(session *xorm.Session, BlockGreenChainSettlementRecords *model.BlockGreenChainSettlementRecords) (int64, error) {
_, err := session.InsertOne(BlockGreenChainSettlementRecords)
if err != nil {
return 0, err
}
return BlockGreenChainSettlementRecords.Id, nil
}

// BatchAddBlockGreenChainSettlementRecords 批量新增数据
func BatchAddBlockGreenChainSettlementRecords(Db *xorm.Engine, BlockGreenChainSettlementRecordsData []*model.BlockGreenChainSettlementRecords) (int64, error) {
affected, err := Db.Insert(BlockGreenChainSettlementRecordsData)
if err != nil {
return 0, err
}
return affected, nil
}

func GetBlockGreenChainSettlementRecordsCount(Db *xorm.Engine) int {
var BlockGreenChainSettlementRecords model.BlockGreenChainSettlementRecords
session := Db.Where("")
count, err := session.Count(&BlockGreenChainSettlementRecords)
if err != nil {
return 0
}
return int(count)
}

// BlockGreenChainSettlementRecordsDelete 删除记录
func BlockGreenChainSettlementRecordsDelete(Db *xorm.Engine, id interface{}) (int64, error) {
if reflect.TypeOf(id).Kind() == reflect.Slice {
return Db.In("id", id).Delete(model.BlockGreenChainSettlementRecords{})
} else {
return Db.Where("id = ?", id).Delete(model.BlockGreenChainSettlementRecords{})
}
}

// BlockGreenChainSettlementRecordsUpdate 更新记录
func BlockGreenChainSettlementRecordsUpdate(session *xorm.Session, id interface{}, BlockGreenChainSettlementRecords *model.BlockGreenChainSettlementRecords, forceColums ...string) (int64, error) {
var (
affected int64
err error
)
if forceColums != nil {
affected, err = session.Where("id=?", id).Cols(forceColums...).Update(BlockGreenChainSettlementRecords)
} else {
affected, err = session.Where("id=?", id).Update(BlockGreenChainSettlementRecords)
}
if err != nil {
return 0, err
}
return affected, nil
}

// BlockGreenChainSettlementRecordsGetOneByParams 通过传入的参数查询数据(单条)
func BlockGreenChainSettlementRecordsGetOneByParams(session *xorm.Session, params map[string]interface{}) (*model.BlockGreenChainSettlementRecords, error) {
var m model.BlockGreenChainSettlementRecords
var query = fmt.Sprintf("%s =?", params["key"])
has, err := session.Where(query, params["value"]).Get(&m)
if err != nil {
return nil, zhios_order_relate_logx.Error(err)
}
if has == false {
return nil, errors.New("未查询到相应的 block_star_chain 记录")
}
return &m, nil
}

// BlockGreenChainSettlementRecordsFindByParams 通过传入的参数查询数据(多条)
func BlockGreenChainSettlementRecordsFindByParams(Db *xorm.Engine, params map[string]interface{}) (*[]model.BlockGreenChainSettlementRecords, error) {
var m []model.BlockGreenChainSettlementRecords
if params["value"] == nil {
return nil, errors.New("参数有误")
}
if params["key"] == nil {
//查询全部数据
err := Db.Find(&m)
if err != nil {
return nil, zhios_order_relate_logx.Error(err)
}
return &m, nil
} else {
if reflect.TypeOf(params["value"]).Kind() == reflect.Slice {
//指定In查询
if err := Db.In(zhios_order_relate_utils.AnyToString(params["key"]), params["value"]).Find(&m); err != nil {
return nil, zhios_order_relate_logx.Warn(err)
}
return &m, nil
} else {
var query = fmt.Sprintf("%s =?", params["key"])
err := Db.Where(query, params["value"]).Find(&m)
if err != nil {
return nil, zhios_order_relate_logx.Error(err)
}
return &m, nil
}

}
}

func BlockGreenChainSettlementRecordsFindByParamsByPage(Db *xorm.Engine, params map[string]interface{}, page, pageSize int) (*[]model.BlockGreenChainSettlementRecords, error) {
var m []model.BlockGreenChainSettlementRecords
if params["value"] == nil {
return nil, errors.New("参数有误")
}
if page == 0 && pageSize == 0 {
page = 1
pageSize = 10
}

if params["key"] == nil {
//查询全部数据
err := Db.Limit(pageSize, (page-1)*pageSize).Find(&m)
if err != nil {
return nil, zhios_order_relate_logx.Error(err)
}
return &m, nil
} else {
if reflect.TypeOf(params["value"]).Kind() == reflect.Slice {
//指定In查询
if err := Db.In(zhios_order_relate_utils.AnyToString(params["key"]), params["value"]).Limit(pageSize, (page-1)*pageSize).Find(&m); err != nil {
return nil, zhios_order_relate_logx.Warn(err)
}
return &m, nil
} else {
var query = fmt.Sprintf("%s =?", params["key"])
err := Db.Where(query, params["value"]).Limit(pageSize, (page-1)*pageSize).Find(&m)
if err != nil {
return nil, zhios_order_relate_logx.Error(err)
}
return &m, nil
}

}
}

+ 32
- 0
db/model/block_green_chain.go View File

@@ -0,0 +1,32 @@
package model

import (
"time"
)

type BlockGreenChain struct {
Id int `json:"id" xorm:"not null pk autoincr comment('主键id') INT(11)"`
IsUse int `json:"is_use" xorm:"not null default 0 comment('是否开启(否:0;是:1)') TINYINT(1)"`
Coin1 int `json:"coin_1" xorm:"not null default 0 comment('coinId_1(类似于区块币)') INT(11)"`
Coin2 int `json:"coin_2" xorm:"not null default 0 comment('coinId_2(类似于静态贡献值)') INT(11)"`
InitialEverydayPublishCoin string `json:"initial_everyday_publish_coin" xorm:"not null default 0.0000000000 comment('初始每日区块币发行数量') DECIMAL(28,10)"`
NowEverydayPublishCoin string `json:"now_everyday_publish_coin" xorm:"not null default 0.0000000000 comment('当前每日区块币发行数量') DECIMAL(28,10)"`
TodayPublishCoin string `json:"today_publish_coin" xorm:"not null default 0.0000000000 comment('今日区块币发行数量(若为0,则按当前每日区块币发行数量)') DECIMAL(28,10)"`
EveryThirtyDaysReduceRate string `json:"every_thirty_days_reduce_rate" xorm:"not null default 5.00 comment('每三十日递减发行百分比') DECIMAL(5,2)"`
TotalNowCoin string `json:"total_now_coin" xorm:"not null default 0.0000000000 comment('当前区块币总量') DECIMAL(28,10)"`
TotalPublishCoin string `json:"total_publish_coin" xorm:"not null default 0.0000000000 comment('累计区块币发行总量') DECIMAL(28,10)"`
TotalDestroyCoin string `json:"total_destroy_coin" xorm:"not null default 0.0000000000 comment('累计区块币销毁总量') DECIMAL(28,10)"`
TotalRemainderCoin string `json:"total_remainder_coin" xorm:"not null default 0.0000000000 comment('累计区块币剩余总量') DECIMAL(28,10)"`
InitialCoinTotal string `json:"initial_coin_total" xorm:"not null default 0.0000000000 comment('初始区块币总量') DECIMAL(28,10)"`
PlatformGuidePriceForCoin string `json:"platform_guide_price_for_coin" xorm:"not null default 0.0000000000 comment('平台区块币指导价') DECIMAL(22,10)"`
PlatformBusinessDiscountRate string `json:"platform_business_discount_rate" xorm:"not null default 10.00 comment('平台商家让利百分比') DECIMAL(5,2)"`
ChemicalsForDailyRate string `json:"chemicals_for_daily_rate" xorm:"not null default 100.00 comment('日化率') DECIMAL(5,2)"`
PublishCoinConsumeRate string `json:"publish_coin_consume_rate" xorm:"not null default 45.00 comment('区块币发行消费占比') DECIMAL(5,2)"`
PublishCoinAirdropRate string `json:"publish_coin_airdrop_rate" xorm:"not null default 45.00 comment('区块币发行空投占比') DECIMAL(5,2)"`
RewardSettings string `json:"reward_settings" xorm:"comment('奖励设置') TEXT"`
StartAt string `json:"start_at" xorm:"not null default '0000-00' comment('起始时间(0000-00)') CHAR(50)"`
SettlementDate string `json:"settlement_date" xorm:"not null default '0000-00' comment('结算日期(0000-00)') CHAR(50)"`
CreateAt time.Time `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('创建时间') TIMESTAMP"`
UpdateAt time.Time `json:"update_at" xorm:"default 'CURRENT_TIMESTAMP' comment('更新时间') TIMESTAMP"`
IntegralRewardMultiple int `json:"integral_reward_multiple" xorm:"default 0 comment('自购积分奖励倍数') INT(11)"`
}

+ 17
- 0
db/model/block_green_chain_custom_user_airdrop.go View File

@@ -0,0 +1,17 @@
package model

import (
"time"
)

type BlockGreenChainCustomUserAirdrop struct {
Id int64 `json:"id" xorm:"pk autoincr BIGINT(20)"`
Uid int `json:"uid" xorm:"not null default 0 comment('用户id') INT(11)"`
AirdropTotalNums string `json:"airdrop_total_nums" xorm:"not null default 0.0000 comment('空投总数量') DECIMAL(10,4)"`
AirdropAlreadyNums string `json:"airdrop_already_nums" xorm:"not null default 0.0000 comment('已空投数量') DECIMAL(10,4)"`
AirdropFrequency int `json:"airdrop_frequency" xorm:"not null default 0 comment('空投频率(天/次)') INT(11)"`
AirdropNums string `json:"airdrop_nums" xorm:"not null default 0.0000 comment('空投数量(个/次)') DECIMAL(10,4)"`
AirdropDate string `json:"airdrop_date" xorm:"not null default '0000-00' comment('空投日期') CHAR(50)"`
CreateAt time.Time `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('创建时间') DATETIME"`
UpdateAt time.Time `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"`
}

+ 23
- 0
db/model/block_green_chain_flow.go View File

@@ -0,0 +1,23 @@
package model

import (
"time"
)

type BlockGreenChainFlow struct {
Id int64 `json:"id" xorm:"pk autoincr BIGINT(20)"`
CoinId int `json:"coin_id" xorm:"not null comment('虚拟币id') INT(11)"`
Direction int `json:"direction" xorm:"not null default 1 comment('方向:1收入 2支出') TINYINT(255)"`
Kind int `json:"kind" xorm:"not null default 1 comment('种类(1:消费返利 2:平台空投 3:消费返利未分配完销毁 4平台空投未分配完销毁 5:打赏销毁 6:管理员销毁)') TINYINT(1)"`
Title string `json:"title" xorm:"not null default '' comment('标题') VARCHAR(255)"`
Amount string `json:"amount" xorm:"not null comment('变更数量') DECIMAL(28,10)"`
BeforeTotalNowCoin string `json:"before_total_now_coin" xorm:"not null default 0.0000000000 comment('变更前-区块币总量') DECIMAL(28,10)"`
AfterTotalNowCoin string `json:"after_total_now_coin" xorm:"not null default 0.0000000000 comment('变更后-区块币总量') DECIMAL(28,10)"`
BeforeTotalRemainderCoin string `json:"before_total_remainder_coin" xorm:"not null default 0.0000000000 comment('变更前-累计区块币剩余总量') DECIMAL(28,10)"`
AfterTotalRemainderCoin string `json:"after_total_remainder_coin" xorm:"not null default 0.0000000000 comment('变更后-累计区块币剩余总量') DECIMAL(28,10)"`
BeforeTotalPublishCoin string `json:"before_total_publish_coin" xorm:"not null default 0.0000000000 comment('变更前-累计区块币发行总量') DECIMAL(28,10)"`
AfterTotalPublishCoin string `json:"after_total_publish_coin" xorm:"not null default 0.0000000000 comment('变更后-累计区块币发行总量') DECIMAL(28,10)"`
BeforeTotalDestroyCoin string `json:"before_total_destroy_coin" xorm:"not null default 0.0000000000 comment('变更前-累计区块币销毁总量') DECIMAL(28,10)"`
AfterTotalDestroyCoin string `json:"after_total_destroy_coin" xorm:"not null default 0.0000000000 comment('变更后-累计区块币销毁总量') DECIMAL(28,10)"`
CreateTime time.Time `json:"create_time" xorm:"default 'CURRENT_TIMESTAMP' comment('创建时间') DATETIME"`
}

+ 21
- 0
db/model/block_green_chain_reward_records.go View File

@@ -0,0 +1,21 @@
package model

import (
"time"
)

type BlockGreenChainRewardRecords struct {
Id int64 `json:"id" xorm:"pk autoincr BIGINT(20)"`
CoinIdForReward int `json:"coin_id_for_reward" xorm:"not null default 0 comment('打赏-虚拟币id') INT(11)"`
CoinIdForDestroyAndDistribute int `json:"coin_id_for_destroy_and_distribute" xorm:"not null default 0 comment('销毁&派发-虚拟币id') INT(11)"`
Amount string `json:"amount" xorm:"not null default 0.0000000000 comment('消费金额') DECIMAL(28,10)"`
RewardUid int `json:"reward_uid" xorm:"not null default 0 comment('打赏uid') INT(11)"`
BeRewardUid int `json:"be_reward_uid" xorm:"not null default 0 comment('被打赏uid') INT(11)"`
RewardAccountPhone int64 `json:"reward_account_phone" xorm:"not null default 0 comment('被打赏账号') BIGINT(20)"`
RewardValue string `json:"reward_value" xorm:"not null default 0.0000000000 comment('打赏值') DECIMAL(28,10)"`
DeductionCoin string `json:"deduction_coin" xorm:"not null default 0.0000000000 comment('扣除虚拟币值') DECIMAL(28,10)"`
DestroyCoin string `json:"destroy_coin" xorm:"not null default 0.0000000000 comment('销毁虚拟币') DECIMAL(28,10)"`
CreateAt time.Time `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('创建时间') DATETIME"`
UpdateAt time.Time `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"`
OrdId string `json:"ord_id" xorm:"default '' VARCHAR(50)"`
}

+ 19
- 0
db/model/block_green_chain_settlement_records.go View File

@@ -0,0 +1,19 @@
package model

import (
"time"
)

type BlockGreenChainSettlementRecords struct {
Id int64 `json:"id" xorm:"pk autoincr BIGINT(20)"`
CoinId int `json:"coin_id" xorm:"not null comment('虚拟币id') INT(11)"`
TodayPublishCoin string `json:"today_publish_coin" xorm:"not null default 0.0000000000 comment('今日区块币发行总数量') DECIMAL(28,10)"`
TodayDestroyCoinForSystem string `json:"today_destroy_coin_for_system" xorm:"not null default 0.0000000000 comment('今日销毁区块币数量-系统') DECIMAL(28,10)"`
TodayPublishCoinForConsume string `json:"today_publish_coin_for_consume" xorm:"not null default 0.0000000000 comment('今日区块币发行数量-消费奖励区') DECIMAL(28,10)"`
TodayDestroyCoinForConsume string `json:"today_destroy_coin_for_consume" xorm:"not null default 0.0000000000 comment('今日销毁区块币数量-消费奖励区') DECIMAL(28,10)"`
TodayPublishCoinForAirdrop string `json:"today_publish_coin_for_airdrop" xorm:"not null default 0.0000000000 comment('今日区块币发行数量-空投区') DECIMAL(28,10)"`
TodayDestroyCoinForAirdrop string `json:"today_destroy_coin_for_airdrop" xorm:"not null default 0.0000000000 comment('今日销毁区块币数量-空投区') DECIMAL(28,10)"`
Date string `json:"date" xorm:"not null default '' comment('日期(0000-00)') VARCHAR(50)"`
CreateAt time.Time `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('创建时间') DATETIME"`
UpdateAt time.Time `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"`
}

+ 35
- 0
enum/block_green_chain.go View File

@@ -0,0 +1,35 @@
package enum

// 退款状态
type BlockGreenChainFlowKind int

const (
ConsumeIssue BlockGreenChainFlowKind = iota
AirdropIssue
ConsumeUnallocatedAndDestroy
AirdropUnallocatedAndDestroy
TransactionDestroy
AdminDestroy
SystemDestroyForGreen
)

func (kind BlockGreenChainFlowKind) String() string {
switch kind {
case ConsumeIssue:
return "消费区发放"
case AirdropIssue:
return "空投区发放"
case ConsumeUnallocatedAndDestroy:
return "消费区未分配完销毁"
case AirdropUnallocatedAndDestroy:
return "空投区未分配完销毁"
case TransactionDestroy:
return "交易销毁"
case AdminDestroy:
return "管理员销毁"
case SystemDestroyForGreen:
return "系统销毁"
default:
return "未知状态"
}
}

+ 12
- 0
md/block_star_chain.go View File

@@ -35,6 +35,12 @@ const (
GroupLotteryAndDirectPushRewardTitleForUserVirtualCoinFlow = "自营拼团抽奖奖励(直推)"
GroupLotteryAndGroupRewardTitleForUserVirtualCoinFlow = "自营拼团抽奖奖励(团队)"
GroupSpellRewardTitleForUserVirtualCoinFlow = "自营拼团拼中奖励"

BlockGreenChainConsumeAreaDistributionTitleForUserVirtualCoinFlow = "绿色积分-消费区发放"
BlockGreenChainAirdropAreaDistributionTitleForUserVirtualCoinFlow = "绿色积分-空投区发放"
BlockGreenChainConsumeAreaIssueAndDestroyTitleForUserVirtualCoinFlow = "绿色积分-消费区发放(销毁贡献值)"
BlockGreenChainTransactionAndDestroyTitleForUserVirtualCoinFlow = "绿色积分-交易(销毁贡献值)"
BlockGreenChainAdminDestroyTitleForUserVirtualCoinFlow = "绿色积分-管理员销毁"
)

const (
@@ -62,6 +68,12 @@ const (
OperationCenterAndDestroyStaticContributionTransferTypeForUserVirtualCoinFlow = 120 // 区块星链-运营中心发放(销毁静态贡献值)
OtherAndDestroyStaticContributionTransferTypeForUserVirtualCoinFlow = 121 // 区块星链-其他发放(销毁静态贡献值)
GroupSpellRewardTransferTypeForUserVirtualCoinFlow = 122

BlockGreenChainConsumeAreaDistributionTransferTypeForUserVirtualCoinFlow = 130 // 绿色积分-消费区发放
BlockGreenChainAirdropAreaDistributionTransferTypeForUserVirtualCoinFlow = 131 // 绿色积分-空投区发放
BlockGreenChainConsumeAreaIssueAndDestroyTransferTypeForUserVirtualCoinFlow = 132 // 绿色积分-消费区发放(销毁贡献值)
BlockGreenChainTransactionAndDestroyTransferTypeForUserVirtualCoinFlow = 133 // 绿色积分-交易(销毁贡献值)
BlockGreenChainAdminDestroyTransferTypeForUserVirtualCoinFlow = 134 // 绿色积分-管理员销毁
)

const DealUserCoinRequestIdPrefix = "%s:block_star_chain_deal_user_coin:%d:uid:%d"


+ 625
- 0
rule/block_green_chain_settlement.go View File

@@ -0,0 +1,625 @@
package rule

import (
"code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/db"
"code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/db/model"
"code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/enum"
"code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/md"
"code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/svc"
zhios_order_relate_utils "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/utils"
"code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/utils/cache"
zhios_order_relate_logx "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/utils/logx"
"errors"
"fmt"
"github.com/shopspring/decimal"
"strconv"
"time"
"xorm.io/xorm"
)

func InitForGreen(redisAddr string) (err error) {
if redisAddr != "" {
cache.NewRedis(redisAddr)
}
_, err = cache.SelectDb(md.RedisDataBase)
return
}

const PessimismLockKeyForGreen = "daily_settlement_block_green_chain_pessimism_lock_key"
const PessimismLockValueForGreen = "running"

// DailySettlementBlockGreenChain 每日结算“绿色积分”
func DailySettlementBlockGreenChain(engine *xorm.Engine, mid string, isTask bool) (err error) {
session := engine.NewSession()
defer func() {
session.Close()
if err := recover(); err != nil {
_ = zhios_order_relate_logx.Error(err)
}
}()
session.Begin()
now := time.Now()
today := now.Format("2006-01-02")

fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>", now.Hour())
if isTask && (now.Hour() > 8) {
//TODO::只在凌晨一点 ~ 凌晨 8 点运行
return errors.New("非运行时间")
}

//1、查找 `block_green_chain` 基础设置
blockGreenChain, err := db.BlockGreenChainGetOneByParams(session, map[string]interface{}{
"key": "is_use",
"value": 1,
})
if err != nil {
_ = session.Rollback()
return err
}
if blockGreenChain.SettlementDate == today {
_ = session.Rollback()
return errors.New("今日“绿色积分”已结算")
}

isHasBlockGreenChainSettlementRecords, err := db.BlockGreenChainSettlementRecordsGetOneByParams(session, map[string]interface{}{
"key": "date",
"value": today,
})
if isHasBlockGreenChainSettlementRecords != nil {
_ = session.Rollback()
return errors.New("今日绿色积分已结算!!!")
}

//TODO::增加“悲观锁”防止串行
getString, _ := cache.GetString(PessimismLockKeyForGreen)
//if err != nil {
// return err
//}
if getString == PessimismLockValueForGreen {
fmt.Println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", "上一次结算未执行完")
return errors.New("上一次结算未执行完")
}
cache.SetEx(PessimismLockKeyForGreen, PessimismLockValueForGreen, 3600*8) //8小时

//TODO::关闭系统
zhios_order_relate_utils.CurlPost("http://zhios-app:5000/api/v1/check_app_over_time", map[string]string{
"mid": mid,
"is_close": "1",
}, map[string]string{})

todayPublishCoin := zhios_order_relate_utils.StrToFloat64(blockGreenChain.TodayPublishCoin) //今日区块币发行数量(若为0,则按当前每日区块币发行数量)
nowEverydayPublishCoin := zhios_order_relate_utils.StrToFloat64(blockGreenChain.NowEverydayPublishCoin) //当前每日区块币发行数量

//1、判断今日是否有系统销毁
var destroyCoinForSystem string
if todayPublishCoin != 0 && todayPublishCoin != nowEverydayPublishCoin {
destroyCoinForSystemValue, _ := decimal.NewFromFloat(nowEverydayPublishCoin).Sub(decimal.NewFromFloat(todayPublishCoin)).Float64()
if destroyCoinForSystemValue < 0 {
_ = session.Rollback()
return errors.New("当前\"今日区块币发行数量\"大于\"当前每日区块币发行数量\"")
}
err := DealDestroyCoinForGreen(session, int(enum.SystemDestroyForGreen), destroyCoinForSystemValue, enum.SystemDestroyForGreen.String(), blockGreenChain)
if err != nil {
_ = session.Rollback()
return err
}
destroyCoinForSystem = zhios_order_relate_utils.Float64ToStrPrec10(destroyCoinForSystemValue)
nowEverydayPublishCoin = todayPublishCoin
}
//2、计算出"消费返利"、"平台空投" 区各需发放多少枚区块币
var publishCoin = nowEverydayPublishCoin //实际空投虚拟数量

publishCoinConsumeRate, _ := decimal.NewFromString(blockGreenChain.PublishCoinConsumeRate) //区块币发行消费占比
publishCoinConsumeRate = publishCoinConsumeRate.Div(decimal.NewFromFloat(100))
consumeAreaCoinNums := zhios_order_relate_utils.StrToFloat64(decimal.NewFromFloat(publishCoin).Mul(publishCoinConsumeRate).String()) //消费区区块币发行数量

publishCoinAirdropRate, _ := decimal.NewFromString(blockGreenChain.PublishCoinAirdropRate) //区块币发行空投占比
publishCoinAirdropRate = publishCoinAirdropRate.Div(decimal.NewFromFloat(100))
airdropAreaCoinNums := zhios_order_relate_utils.StrToFloat64(decimal.NewFromFloat(publishCoin).Mul(publishCoinAirdropRate).String()) //空投区区块币发行数量

//3、进行"消费返利"、"平台空投" 区区块币发放
err = dealIssueCoinForGreen(session, int(enum.ConsumeIssue), consumeAreaCoinNums, enum.ConsumeIssue.String(), blockGreenChain)
if err != nil {
_ = session.Rollback()
return err
}

err = dealIssueCoinForGreen(session, int(enum.AirdropIssue), airdropAreaCoinNums, enum.AirdropIssue.String(), blockGreenChain)
if err != nil {
_ = session.Rollback()
return err
}

userIds, err := db.UserLevelDescByWeightLow(session)
if err != nil {
_ = session.Rollback()
return err
}

//4、进行消费返利-区块币统计分配
err, destroyCoinForConsume := statisticsAndDistributeCoinForConsume(session, userIds, mid, consumeAreaCoinNums, blockGreenChain)
if err != nil {
_ = session.Rollback()
return err
}

//5、进行空投区-区块币统计分配
err, destroyCoinForAirdrop := statisticsAndDistributeCoinForAirdrop(session, mid, airdropAreaCoinNums, blockGreenChain)
if err != nil {
_ = session.Rollback()
return err
}

//6、插入 block_star_chain_settlement_records 记录
var blockGreenChainSettlementRecords = model.BlockGreenChainSettlementRecords{
CoinId: blockGreenChain.Coin1,
TodayPublishCoin: zhios_order_relate_utils.Float64ToStr(publishCoin),
TodayDestroyCoinForSystem: destroyCoinForSystem,
TodayPublishCoinForConsume: zhios_order_relate_utils.Float64ToStr(consumeAreaCoinNums),
TodayDestroyCoinForConsume: zhios_order_relate_utils.Float64ToStr(destroyCoinForConsume),
TodayPublishCoinForAirdrop: zhios_order_relate_utils.Float64ToStr(airdropAreaCoinNums),
TodayDestroyCoinForAirdrop: zhios_order_relate_utils.Float64ToStr(destroyCoinForAirdrop),
Date: now.Format("2006-01-02"),
CreateAt: now,
UpdateAt: now,
}
_, err = db.BlockGreenChainSettlementRecordsInsert(session, &blockGreenChainSettlementRecords)
if err != nil {
_ = session.Rollback()
return err
}

//7、计算当前每日区块币应发行数量
err = calcNowEverydayPublishCoinForGreen(session, blockGreenChain)
if err != nil {
_ = session.Rollback()
return err
}

//8、更新 block_green_chain 中的 settlement_date 字段
blockGreenChain.SettlementDate = today
//updateAffected, err := db.BlockGreenChainUpdate(session, blockGreenChain.Id, blockGreenChain, "settlement_date")
updateAffected, err := db.BlockGreenChainUpdate(session, blockGreenChain.Id, blockGreenChain)
if err != nil {
_ = session.Rollback()
return err
}
if updateAffected == 0 {
_ = session.Rollback()
return errors.New("更新 block_green_chain 的 settlement_date 记录失败")
}

//9、将昨日的“平台区块币指导价”插入到 block_coin_platform_guide_price_for_coin_records
var blockCoinPlatformGuidePriceForCoinRecords = model.BlockCoinPlatformGuidePriceForCoinRecords{
CoinId: blockGreenChain.Coin1,
PlatformGuidePriceForCoin: blockGreenChain.PlatformGuidePriceForCoin,
Date: now.AddDate(0, 0, -1).Format("2006-01-02"),
CreateAt: now,
UpdateAt: now,
}
_, err = db.BlockCoinPlatformGuidePriceForCoinRecordsInsert(session, &blockCoinPlatformGuidePriceForCoinRecords)
if err != nil {
_ = session.Rollback()
return err
}

err = session.Commit()
if err != nil {
_ = session.Rollback()
return errors.New("事务提交失败")
}

zhios_order_relate_utils.CurlPost("http://zhios-app:5000/api/v1/check_app_over_time", map[string]string{
"mid": mid,
"is_close": "0",
}, map[string]string{})

//cache.Del(PessimismLockKeyForGreen)

fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>绿色积分结束<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<")
return nil
}

/*
统计分配区块币-消费区
TODO:: 公式【 个人贡献值/全网贡献值x2100枚=每天获取的绿色积分 】
*/
func statisticsAndDistributeCoinForConsume(session *xorm.Session, userIds []int, mid string, publishCoin float64, chain *model.BlockGreenChain) (err error, unassignedTotalCoinValue float64) {
publishCoinValue := decimal.NewFromFloat(publishCoin) //消费区发行区块币数量
platformGuidePriceForCoinValue := decimal.NewFromFloat(zhios_order_relate_utils.StrToFloat64(chain.PlatformGuidePriceForCoin)) //今日平台区块币指导价
var unassignedTotalCoin = decimal.NewFromFloat(0) //分配的区块币
var userVirtualAmount model.UserVirtualAmount
var userVirtualAmounts []model.UserVirtualAmount
//1、统计出消费区的总贡献值
sumStatic, err := session.Table("user_virtual_amount").Where("coin_id =?", chain.Coin2).Sum(&userVirtualAmount, "amount")
if err != nil {
return err, unassignedTotalCoinValue
}
sumStaticValue := decimal.NewFromFloat(sumStatic)

//2、查询出所有拥有贡献值的用户
err = session.Table("user_virtual_amount").NotIn("uid", userIds).Where("coin_id =?", chain.Coin2).And("amount > 0").Find(&userVirtualAmounts)
if err != nil {
return err, unassignedTotalCoinValue
}

for _, item := range userVirtualAmounts {
amount := decimal.NewFromFloat(zhios_order_relate_utils.StrToFloat64(item.Amount)) //用户贡献值余额
getCoin := amount.Div(sumStaticValue).Mul(publishCoinValue) //得到的区块币
needDestroyContribution := getCoin.Mul(platformGuidePriceForCoinValue) //需销毁贡献值

coinAmount, err := svc.GetUserCoinAmount(session, mid, chain.Coin2, item.Uid) //获取此时用户的"贡献值"
if err != nil {
return err, unassignedTotalCoinValue
}
coinAmountValue, _ := decimal.NewFromString(coinAmount)

//3.1判断静态贡献值是否足够
if needDestroyContribution.GreaterThan(coinAmountValue) {
//TODO::公式【得到的区块币 = ((需销毁贡献值 - 用户贡献值余额) / 今日平台区块币指导价)】
tempCoin := (needDestroyContribution.Sub(coinAmountValue)).Div(platformGuidePriceForCoinValue)
getCoin = getCoin.Sub(tempCoin)
needDestroyContribution = coinAmountValue
}
unassignedTotalCoin = unassignedTotalCoin.Add(getCoin)

//3.2给相应用户加上分配到的虚拟币
err = DealUserCoinForGreen(session, md.DealUserCoinReq{
Kind: "add",
Mid: mid,
Title: md.BlockGreenChainConsumeAreaDistributionTitleForUserVirtualCoinFlow,
TransferType: md.BlockGreenChainConsumeAreaDistributionTransferTypeForUserVirtualCoinFlow,
OrdId: "",
CoinId: chain.Coin1,
Uid: item.Uid,
Amount: zhios_order_relate_utils.StrToFloat64(getCoin.String()),
})
if err != nil {
return err, unassignedTotalCoinValue
}

//3.3给相应用户扣除 "消费区发放(销毁贡献值)"
err = DealUserCoinForGreen(session, md.DealUserCoinReq{
Kind: "sub",
Mid: mid,
Title: md.BlockGreenChainConsumeAreaIssueAndDestroyTitleForUserVirtualCoinFlow,
TransferType: md.BlockGreenChainConsumeAreaIssueAndDestroyTransferTypeForUserVirtualCoinFlow,
OrdId: "",
CoinId: chain.Coin2,
Uid: item.Uid,
Amount: zhios_order_relate_utils.StrToFloat64(needDestroyContribution.String()),
})
if err != nil {
return err, unassignedTotalCoinValue
}
}

//4、处理未分配完的区块币-消费区
if publishCoinValue.GreaterThan(unassignedTotalCoin) {
unassignedTotalCoinValue, _ = publishCoinValue.Sub(unassignedTotalCoin).Float64()
err := DealDestroyCoinForGreen(session, int(enum.ConsumeUnallocatedAndDestroy), unassignedTotalCoinValue, enum.ConsumeUnallocatedAndDestroy.String(), chain)
if err != nil {
return err, unassignedTotalCoinValue
}
}
return nil, unassignedTotalCoinValue
}

/*
统计分配区块币-空投区
*/
func statisticsAndDistributeCoinForAirdrop(session *xorm.Session, mid string, publishCoin float64, chain *model.BlockGreenChain) (err error, unassignedTotalCoinValue float64) {
publishCoinValue := decimal.NewFromFloat(publishCoin) //空投区-发行区块币数量
var totalCoin = decimal.NewFromFloat(0)

//1、查询出所有需要空投的用户
var userList []*model.BlockGreenChainCustomUserAirdrop
totalUser, err := session.Table("user").Where("1 =1 ").FindAndCount(&userList)
if err != nil {
return err, unassignedTotalCoinValue
}
if totalUser > 0 {
now := time.Now()
for _, item := range userList {
var singleValue = decimal.NewFromFloat(0)

if item.AirdropDate != "0000-00" {
startAt, err := time.ParseInLocation("2006-01-02", chain.StartAt, time.Local) //起始时间
if err != nil {
return err, unassignedTotalCoinValue
}
diffDays := zhios_order_relate_utils.GetDiffDays(now, startAt) //相差天数
remainder := diffDays % item.AirdropFrequency
if remainder == 0 {
//需要空投
singleValue, _ = decimal.NewFromString(item.AirdropNums)
}
} else {
singleValue, _ = decimal.NewFromString(item.AirdropNums)
}

if singleValue.GreaterThan(decimal.NewFromFloat(0)) {
totalCoin = totalCoin.Add(singleValue)
err = DealUserCoinForGreen(session, md.DealUserCoinReq{
Kind: "add",
Mid: mid,
Title: md.BlockGreenChainAirdropAreaDistributionTitleForUserVirtualCoinFlow,
TransferType: md.BlockGreenChainAirdropAreaDistributionTransferTypeForUserVirtualCoinFlow,
OrdId: "",
CoinId: chain.Coin1,
Uid: item.Uid,
Amount: zhios_order_relate_utils.StrToFloat64(singleValue.String()),
})
if err != nil {
return err, unassignedTotalCoinValue
}
}
}
}

//处理未分配完的区块币-空投区
unassignedTotalCoinValue, _ = publishCoinValue.Sub(totalCoin).Float64()
if unassignedTotalCoinValue > 0 {
err := DealDestroyCoinForGreen(session, int(enum.AirdropUnallocatedAndDestroy), unassignedTotalCoinValue, enum.AirdropUnallocatedAndDestroy.String(), chain)
if err != nil {
return err, unassignedTotalCoinValue
}
}
return nil, unassignedTotalCoinValue
}

//计算当前每日区块币应发行数量
func calcNowEverydayPublishCoinForGreen(session *xorm.Session, chain *model.BlockGreenChain) error {
now := time.Now()
startAt, err := time.ParseInLocation("2006-01-02", chain.StartAt, time.Local) //起始时间
if err != nil {
return err
}
diffDays := zhios_order_relate_utils.GetDiffDays(now, startAt) //相差天数
remainder := diffDays % 30
if remainder == 0 {
everyThirtyDaysReduceRate := zhios_order_relate_utils.StrToFloat64(chain.EveryThirtyDaysReduceRate) / 100 //每三十日递减发行百分比
nowEverydayPublishCoin := zhios_order_relate_utils.StrToFloat64(chain.NowEverydayPublishCoin) //当前每日区块币发行数量
chain.NowEverydayPublishCoin = zhios_order_relate_utils.Float64ToStrPrec10(nowEverydayPublishCoin * (1 - everyThirtyDaysReduceRate))
//updateAffected, err := db.BlockGreenChainUpdate(session, chain.Id, chain, "now_everyday_publish_coin")
//if err != nil {
// return err
//}
//if updateAffected == 0 {
// err = errors.New("更新 block_green_chain 的 now_everyday_publish_coin 记录失败")
// return err
//}
}
return nil
}

//处理虚拟币 - 发放
func dealIssueCoinForGreen(session *xorm.Session, kind int, amount float64, title string, chain *model.BlockGreenChain) error {
amountValue := decimal.NewFromFloat(amount)
now := time.Now()
var blockGreenChainFlow model.BlockGreenChainFlow
blockGreenChainFlow.CoinId = chain.Coin1
blockGreenChainFlow.Direction = md.FlowDirectionIncome
blockGreenChainFlow.Kind = kind
blockGreenChainFlow.Title = title
blockGreenChainFlow.CreateTime = now
blockGreenChainFlow.Amount = amountValue.RoundFloor(4).String()
switch kind {
case int(enum.ConsumeIssue):
blockGreenChainFlow.BeforeTotalNowCoin = chain.TotalNowCoin
beforeTotalNowCoin, _ := decimal.NewFromString(chain.TotalNowCoin)
blockGreenChainFlow.AfterTotalNowCoin = beforeTotalNowCoin.Add(amountValue).RoundFloor(4).String()

blockGreenChainFlow.BeforeTotalRemainderCoin = chain.TotalRemainderCoin
beforeTotalRemainderCoin, _ := decimal.NewFromString(chain.TotalRemainderCoin)
blockGreenChainFlow.AfterTotalRemainderCoin = beforeTotalRemainderCoin.Sub(amountValue).RoundFloor(4).String()

blockGreenChainFlow.BeforeTotalPublishCoin = chain.TotalPublishCoin
beforeTotalPublishCoin, _ := decimal.NewFromString(chain.TotalPublishCoin)
blockGreenChainFlow.AfterTotalPublishCoin = beforeTotalPublishCoin.Add(amountValue).RoundFloor(4).String()
blockGreenChainFlow.BeforeTotalDestroyCoin = chain.TotalDestroyCoin
blockGreenChainFlow.AfterTotalDestroyCoin = chain.TotalDestroyCoin
break
case int(enum.AirdropIssue):
blockGreenChainFlow.BeforeTotalNowCoin = chain.TotalNowCoin
beforeTotalNowCoin, _ := decimal.NewFromString(chain.TotalNowCoin)
blockGreenChainFlow.AfterTotalNowCoin = beforeTotalNowCoin.Add(amountValue).RoundFloor(4).String()

blockGreenChainFlow.BeforeTotalRemainderCoin = chain.TotalRemainderCoin
beforeTotalRemainderCoin, _ := decimal.NewFromString(chain.TotalRemainderCoin)
blockGreenChainFlow.AfterTotalRemainderCoin = beforeTotalRemainderCoin.Sub(amountValue).RoundFloor(4).String()

blockGreenChainFlow.BeforeTotalPublishCoin = chain.TotalPublishCoin
beforeTotalPublishCoin, _ := decimal.NewFromString(chain.TotalPublishCoin)
blockGreenChainFlow.AfterTotalPublishCoin = beforeTotalPublishCoin.Add(amountValue).RoundFloor(4).String()
blockGreenChainFlow.BeforeTotalDestroyCoin = chain.TotalDestroyCoin
blockGreenChainFlow.AfterTotalDestroyCoin = chain.TotalDestroyCoin
break
}
chain.TotalNowCoin = blockGreenChainFlow.AfterTotalNowCoin
chain.TotalRemainderCoin = blockGreenChainFlow.AfterTotalRemainderCoin
chain.TotalPublishCoin = blockGreenChainFlow.AfterTotalPublishCoin
chain.TotalDestroyCoin = blockGreenChainFlow.AfterTotalDestroyCoin

//更新 `block_green_chain` 表
updateAffected, err := db.BlockGreenChainUpdate(session, chain.Id, chain)
if err != nil {
return err
}
if updateAffected == 0 {
err = errors.New("更新 block_green_chain 记录失败")
return err
}

//插入 `block_star_chain_flow` 记录
_, err = db.BlockGreenChainFlowInsert(session, &blockGreenChainFlow)
if err != nil {
return err
}
return nil
}

//DealDestroyCoinForGreen 处理虚拟币 - 销毁
func DealDestroyCoinForGreen(session *xorm.Session, kind int, amount float64, title string, chain *model.BlockGreenChain) error {
amountValue := decimal.NewFromFloat(amount)
now := time.Now()
var blockGreenChainFlow model.BlockGreenChainFlow
blockGreenChainFlow.CoinId = chain.Coin1
blockGreenChainFlow.Direction = md.FlowDirectionExpenditure
blockGreenChainFlow.Kind = kind
blockGreenChainFlow.Title = title
blockGreenChainFlow.Amount = amountValue.RoundFloor(4).String()
blockGreenChainFlow.CreateTime = now
switch kind {
case int(enum.ConsumeUnallocatedAndDestroy):
blockGreenChainFlow.BeforeTotalNowCoin = chain.TotalNowCoin
blockGreenChainFlow.AfterTotalNowCoin = chain.TotalNowCoin
blockGreenChainFlow.BeforeTotalRemainderCoin = chain.TotalRemainderCoin
blockGreenChainFlow.AfterTotalRemainderCoin = chain.TotalRemainderCoin
blockGreenChainFlow.BeforeTotalPublishCoin = chain.TotalPublishCoin
blockGreenChainFlow.AfterTotalPublishCoin = chain.TotalPublishCoin
blockGreenChainFlow.BeforeTotalDestroyCoin = chain.TotalDestroyCoin
beforeTotalDestroyCoin, _ := decimal.NewFromString(chain.TotalDestroyCoin)
blockGreenChainFlow.AfterTotalDestroyCoin = beforeTotalDestroyCoin.Add(amountValue).RoundFloor(4).String()
break
case int(enum.AirdropUnallocatedAndDestroy):
blockGreenChainFlow.BeforeTotalNowCoin = chain.TotalNowCoin
beforeTotalNowCoin, _ := decimal.NewFromString(chain.TotalNowCoin)
blockGreenChainFlow.AfterTotalNowCoin = beforeTotalNowCoin.Sub(amountValue).RoundFloor(4).String()
blockGreenChainFlow.BeforeTotalRemainderCoin = chain.TotalRemainderCoin
blockGreenChainFlow.AfterTotalRemainderCoin = chain.TotalRemainderCoin
blockGreenChainFlow.BeforeTotalPublishCoin = chain.TotalPublishCoin
blockGreenChainFlow.AfterTotalPublishCoin = chain.TotalPublishCoin
blockGreenChainFlow.BeforeTotalDestroyCoin = chain.TotalDestroyCoin
beforeTotalDestroyCoin, _ := decimal.NewFromString(chain.TotalDestroyCoin)
blockGreenChainFlow.AfterTotalDestroyCoin = beforeTotalDestroyCoin.Add(amountValue).RoundFloor(4).String()
break
case int(enum.TransactionDestroy):
blockGreenChainFlow.BeforeTotalNowCoin = chain.TotalNowCoin
beforeTotalNowCoin, _ := decimal.NewFromString(chain.TotalNowCoin)
blockGreenChainFlow.AfterTotalNowCoin = beforeTotalNowCoin.Sub(amountValue).RoundFloor(4).String()
blockGreenChainFlow.BeforeTotalRemainderCoin = chain.TotalRemainderCoin
blockGreenChainFlow.AfterTotalRemainderCoin = chain.TotalRemainderCoin
blockGreenChainFlow.BeforeTotalPublishCoin = chain.TotalPublishCoin
blockGreenChainFlow.AfterTotalPublishCoin = chain.TotalPublishCoin
blockGreenChainFlow.BeforeTotalDestroyCoin = chain.TotalDestroyCoin
beforeTotalDestroyCoin, _ := decimal.NewFromString(chain.TotalDestroyCoin)
blockGreenChainFlow.AfterTotalDestroyCoin = beforeTotalDestroyCoin.Add(amountValue).RoundFloor(4).String()
break
case int(enum.AdminDestroy):
blockGreenChainFlow.BeforeTotalNowCoin = chain.TotalNowCoin
beforeTotalNowCoin, _ := decimal.NewFromString(chain.TotalNowCoin)
blockGreenChainFlow.AfterTotalNowCoin = beforeTotalNowCoin.Sub(amountValue).RoundFloor(4).String()
blockGreenChainFlow.BeforeTotalRemainderCoin = chain.TotalRemainderCoin
blockGreenChainFlow.AfterTotalRemainderCoin = chain.TotalRemainderCoin
blockGreenChainFlow.BeforeTotalPublishCoin = chain.TotalPublishCoin
blockGreenChainFlow.AfterTotalPublishCoin = chain.TotalPublishCoin
blockGreenChainFlow.BeforeTotalDestroyCoin = chain.TotalDestroyCoin
beforeTotalDestroyCoin, _ := decimal.NewFromString(chain.TotalDestroyCoin)
blockGreenChainFlow.AfterTotalDestroyCoin = beforeTotalDestroyCoin.Add(amountValue).RoundFloor(4).String()
break
case int(enum.SystemDestroyForGreen):
blockGreenChainFlow.BeforeTotalNowCoin = chain.TotalNowCoin
beforeTotalNowCoin, _ := decimal.NewFromString(chain.TotalNowCoin)
blockGreenChainFlow.AfterTotalNowCoin = beforeTotalNowCoin.Sub(amountValue).RoundFloor(4).String()
blockGreenChainFlow.BeforeTotalRemainderCoin = chain.TotalRemainderCoin
blockGreenChainFlow.AfterTotalRemainderCoin = chain.TotalRemainderCoin
blockGreenChainFlow.BeforeTotalPublishCoin = chain.TotalPublishCoin
blockGreenChainFlow.AfterTotalPublishCoin = chain.TotalPublishCoin
blockGreenChainFlow.BeforeTotalDestroyCoin = chain.TotalDestroyCoin
beforeTotalDestroyCoin, _ := decimal.NewFromString(chain.TotalDestroyCoin)
blockGreenChainFlow.AfterTotalDestroyCoin = beforeTotalDestroyCoin.Add(amountValue).RoundFloor(4).String()
break
}

chain.TotalNowCoin = blockGreenChainFlow.AfterTotalNowCoin
chain.TotalDestroyCoin = blockGreenChainFlow.AfterTotalDestroyCoin
//更新 `block_green_chain` 表
_, err := db.BlockGreenChainUpdate(session, chain.Id, chain)
if err != nil {
return err
}

//插入 `block_star_chain_flow` 记录
_, err = db.BlockGreenChainFlowInsert(session, &blockGreenChainFlow)
if err != nil {
return err
}
return nil
}

// DealUserCoinForGreen 处理给用户虚拟币积分
func DealUserCoinForGreen(session *xorm.Session, req md.DealUserCoinReq) (err error) {
if req.Amount < 0 {
req.Amount = 0
}
//1、分布式锁阻拦
requestIdPrefix := fmt.Sprintf(md.DealUserCoinRequestIdPrefix, req.Mid, req.CoinId, req.Uid)
cb, err := svc.HandleDistributedLock(req.Mid, strconv.Itoa(req.Uid), requestIdPrefix)
if err != nil {
return err
}
if cb != nil {
defer cb() // 释放锁
}

//2、计算&&组装数据
now := time.Now()
coinAmount, err := svc.GetUserCoinAmount(session, req.Mid, req.CoinId, req.Uid)
if err != nil {
return err
}
coinAmountValue := decimal.NewFromFloat(zhios_order_relate_utils.StrToFloat64(coinAmount))
amountValue := decimal.NewFromFloat(req.Amount).RoundFloor(4)

var userVirtualCoinFlow model.UserVirtualCoinFlow
userVirtualCoinFlow.CoinId = req.CoinId
userVirtualCoinFlow.Title = req.Title
userVirtualCoinFlow.TransferType = req.TransferType
userVirtualCoinFlow.Uid = req.Uid
userVirtualCoinFlow.ToUid = req.ToUid
userVirtualCoinFlow.OrdId = req.OrdId
userVirtualCoinFlow.BeforeAmout = coinAmount
userVirtualCoinFlow.Amout = amountValue.String()
userVirtualCoinFlow.CreateTime = now

if req.Kind == "add" {
userVirtualCoinFlow.Direction = 1
userVirtualCoinFlow.AfterAmout = coinAmountValue.Add(amountValue).RoundFloor(4).String()
} else if req.Kind == "sub" {
userVirtualCoinFlow.Direction = 2
userVirtualCoinFlow.AfterAmout = coinAmountValue.Sub(amountValue).RoundFloor(4).String()
} else {
err = errors.New("错误的kind类型")
return err
}
if zhios_order_relate_utils.StrToFloat64(userVirtualCoinFlow.AfterAmout) < 0 {
var coin model.VirtualCoin
_, err = session.Where("id = ?", req.CoinId).Get(&coin)
if err != nil {
return err
}
zhios_order_relate_utils.FilePutContents("virtual_coin_not", zhios_order_relate_utils.SerializeStr(map[string]interface{}{
"uid": userVirtualCoinFlow.Uid,
"amount": userVirtualCoinFlow.Amout,
"before_amount": userVirtualCoinFlow.BeforeAmout,
"after_amount": userVirtualCoinFlow.AfterAmout,
"coin_id": userVirtualCoinFlow.CoinId,
}))
return errors.New("用户" + zhios_order_relate_utils.IntToStr(userVirtualCoinFlow.Uid) + "的" + coin.Name + "不足")
//userVirtualCoinFlow.AfterAmout = "0"
}
//3、插入 `user_virtual_coin_flow` 记录
_, err = db.UserVirtualCoinFlowInsert(session, &userVirtualCoinFlow)
if err != nil {
return err
}

//4、修改 `user_virtual_amount`的amount值 && 及缓存
err = svc.SetCacheUserVirtualAmount(session, req.Mid, userVirtualCoinFlow.AfterAmout, req.CoinId, req.Uid, true)
if err != nil {
return err
}

return nil
}

Loading…
Cancel
Save