Browse Source

Merge remote-tracking branch 'origin/master'

master
DengBiao 9 months ago
parent
commit
df027c8f1a
83 changed files with 7311 additions and 191 deletions
  1. +25
    -1
      db/db.go
  2. +157
    -0
      db/db_green_coin_double_chain.go
  3. +157
    -0
      db/db_green_coin_double_chain_exchange_records.go
  4. +153
    -0
      db/db_one_circles_available_green_energy_points_flow.go
  5. +167
    -0
      db/db_one_circles_green_energy_basic_setting.go
  6. +175
    -0
      db/db_one_circles_green_energy_price.go
  7. +167
    -0
      db/db_one_circles_green_energy_sign_in.go
  8. +107
    -0
      db/db_one_circles_public_platoon_basic_setting.go
  9. +46
    -0
      db/db_one_circles_public_platoon_free_punish_with_user.go
  10. +46
    -0
      db/db_one_circles_public_platoon_records_punish_with_user.go
  11. +195
    -0
      db/db_one_circles_public_platoon_user_relation.go
  12. +187
    -0
      db/db_one_circles_star_level_dividends_records.go
  13. +167
    -0
      db/db_one_circles_user_activity.go
  14. +15
    -0
      db/db_one_circles_user_public_platoon_system_punish_records.go
  15. +187
    -0
      db/db_one_circles_user_watch_records.go
  16. +7
    -0
      db/db_second_newcomers_free.go
  17. +40
    -0
      db/db_subsidy_with_month.go
  18. +153
    -0
      db/db_user_public_platoon_double_network_relation.go
  19. +117
    -0
      db/db_user_public_platoon_double_network_setting.go
  20. +121
    -0
      db/db_user_public_platoon_double_network_user_coin_record.go
  21. +9
    -0
      db/db_user_public_platoon_relation.go
  22. +38
    -0
      db/dbs_user.go
  23. +1
    -0
      db/model/fin_user_flow.go
  24. +12
    -0
      db/model/green_coin_double_chain.go
  25. +19
    -0
      db/model/green_coin_double_chain_exchange_records.go
  26. +17
    -0
      db/model/more_newcomers_free_price_type.go
  27. +39
    -0
      db/model/one_circles_available_green_energy_points_flow.go
  28. +38
    -0
      db/model/one_circles_green_energy_basic_setting.go
  29. +8
    -0
      db/model/one_circles_green_energy_price.go
  30. +9
    -0
      db/model/one_circles_green_energy_sign_in.go
  31. +21
    -0
      db/model/one_circles_public_platoon_basic_setting.go
  32. +6
    -0
      db/model/one_circles_public_platoon_free_punish_with_user.go
  33. +7
    -0
      db/model/one_circles_public_platoon_records_punish_with_user.go
  34. +52
    -0
      db/model/one_circles_public_platoon_user_relation.go
  35. +9
    -0
      db/model/one_circles_star_level_dividends_records.go
  36. +7
    -0
      db/model/one_circles_user_activity.go
  37. +18
    -0
      db/model/one_circles_user_public_platoon_system_punish_records.go
  38. +14
    -0
      db/model/one_circles_user_watch_records.go
  39. +17
    -14
      db/model/subsidy_base.go
  40. +1
    -0
      db/model/subsidy_with_user.go
  41. +8
    -4
      db/model/subsidy_with_user_flow.go
  42. +9
    -0
      db/model/subsidy_with_user_month.go
  43. +20
    -0
      db/model/user_public_platoon_double_network_relation.go
  44. +19
    -0
      db/model/user_public_platoon_double_network_setting.go
  45. +12
    -0
      db/model/user_public_platoon_double_network_user_coin_record.go
  46. +6
    -0
      enum/fin_user_flow.go
  47. +1
    -0
      go.mod
  48. +4
    -0
      go.sum
  49. +1
    -1
      lib/comm_plan/all.go
  50. +12
    -11
      lib/comm_plan/init.go
  51. +40
    -1
      md/block_star_chain.go
  52. +12
    -5
      md/fin_user_flow.go
  53. +13
    -0
      md/mq.go
  54. +6
    -0
      md/one_circles_public_platoon_user_relation_commission.go
  55. +25
    -0
      md/public_platoon_double_network_relate_commission.go
  56. +7
    -6
      md/public_platoon_relate_commission.go
  57. +1
    -0
      md/regional_agent.go
  58. +0
    -77
      rule/block_star_chain_settlement.go
  59. +174
    -54
      rule/consume_integral_settlement.go
  60. +478
    -0
      rule/green_coin_double_chain_settlement.go
  61. +94
    -0
      rule/one_circles/coin_settlement.go
  62. +41
    -0
      rule/one_circles/enum/one_circles_available_green_energy_points_flow.go
  63. +51
    -0
      rule/one_circles/md/one_circles_green_energy.go
  64. +21
    -0
      rule/one_circles/md/one_circles_public_platoon.go
  65. +207
    -0
      rule/one_circles/one_circles_activity_coin_auto_exchange_green_energy.go
  66. +94
    -0
      rule/one_circles/one_circles_auto_adjust_prices.go
  67. +111
    -0
      rule/one_circles/one_circles_auto_release_green_energy.go
  68. +155
    -0
      rule/one_circles/one_circles_available_green_energy_settlement.go
  69. +436
    -0
      rule/one_circles/one_circles_deal_available_green_energy_points.go
  70. +14
    -0
      rule/one_circles/one_circles_init.go
  71. +242
    -0
      rule/one_circles/one_circles_public_platoon_give_activty_coin.go
  72. +909
    -0
      rule/one_circles/one_circles_public_platoon_user_relation_commission.go
  73. +268
    -0
      rule/one_circles/one_circles_sign_in_green_energy_settlement.go
  74. +205
    -0
      rule/one_circles/one_circles_star_level_dividends.go
  75. +367
    -0
      rule/public_platoon_double_network_relate_commission.go
  76. +13
    -0
      rule/public_platoon_relate_commission.go
  77. +91
    -0
      rule/user_amount.go
  78. +55
    -7
      svc/get_plan_cfg.go
  79. +131
    -3
      svc/public_platoon_relate_commission.go
  80. +3
    -4
      svc/reward_commission.go
  81. +133
    -3
      svc/small_public_platoon_relate_commission.go
  82. +88
    -0
      svc/svc_deal_user_amount.go
  83. +3
    -0
      utils/convert.go

+ 25
- 1
db/db.go View File

@@ -1,6 +1,10 @@
package db

import "xorm.io/xorm"
import (
zhios_order_relate_logx "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/utils/logx"
"database/sql"
"xorm.io/xorm"
)

func QueryNativeString(Db *xorm.Engine, sql string, args ...interface{}) ([]map[string]string, error) {
results, err := Db.SQL(sql, args...).QueryString()
@@ -16,3 +20,23 @@ func InsertCommWithSession(session *xorm.Session, model interface{}) (int64, err
row, err := session.InsertOne(model)
return row, err
}

// ExecuteOriginalSqlBySession 执行原生sql
func ExecuteOriginalSqlBySession(session *xorm.Session, sql string) (sql.Result, error) {
result, err := session.Exec(sql)
if err != nil {
_ = zhios_order_relate_logx.Warn(err)
return nil, err
}
return result, nil
}

// ExecuteOriginalSql 执行原生sql
func ExecuteOriginalSql(Db *xorm.Engine, sql string) (sql.Result, error) {
result, err := Db.Exec(sql)
if err != nil {
_ = zhios_order_relate_logx.Warn(err)
return nil, err
}
return result, nil
}

+ 157
- 0
db/db_green_coin_double_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"
)

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

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

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

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

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

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

// GreenCoinDoubleChainGetOneByParams 通过传入的参数查询数据(单条)
func GreenCoinDoubleChainGetOneByParams(session *xorm.Engine, params map[string]interface{}) (*model.GreenCoinDoubleChain, error) {
var m model.GreenCoinDoubleChain
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
}

// GreenCoinDoubleChainFindByParams 通过传入的参数查询数据(多条)
func GreenCoinDoubleChainFindByParams(Db *xorm.Engine, params map[string]interface{}) (*[]model.GreenCoinDoubleChain, error) {
var m []model.GreenCoinDoubleChain
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 GreenCoinDoubleChainFindByParamsByPage(Db *xorm.Engine, params map[string]interface{}, page, pageSize int) (*[]model.GreenCoinDoubleChain, error) {
var m []model.GreenCoinDoubleChain
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_green_coin_double_chain_exchange_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"
)

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

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

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

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

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

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

// GreenCoinDoubleChainExchangeRecordsGetOneByParams 通过传入的参数查询数据(单条)
func GreenCoinDoubleChainExchangeRecordsGetOneByParams(session *xorm.Session, params map[string]interface{}) (*model.GreenCoinDoubleChainExchangeRecords, error) {
var m model.GreenCoinDoubleChainExchangeRecords
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
}

// GreenCoinDoubleChainExchangeRecordsFindByParams 通过传入的参数查询数据(多条)
func GreenCoinDoubleChainExchangeRecordsFindByParams(Db *xorm.Engine, params map[string]interface{}) (*[]model.GreenCoinDoubleChainExchangeRecords, error) {
var m []model.GreenCoinDoubleChainExchangeRecords
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 GreenCoinDoubleChainExchangeRecordsFindByParamsByPage(Db *xorm.Engine, params map[string]interface{}, page, pageSize int) (*[]model.GreenCoinDoubleChainExchangeRecords, error) {
var m []model.GreenCoinDoubleChainExchangeRecords
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
}

}
}

+ 153
- 0
db/db_one_circles_available_green_energy_points_flow.go View File

@@ -0,0 +1,153 @@
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"
)

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

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

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

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

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

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

// OneCirclesAvailableGreenEnergyPointsFlowGetOneByParams 通过传入的参数查询数据(单条)
func OneCirclesAvailableGreenEnergyPointsFlowGetOneByParams(Db *xorm.Engine, params map[string]interface{}) (*model.OneCirclesAvailableGreenEnergyPointsFlow, error) {
var m model.OneCirclesAvailableGreenEnergyPointsFlow
var query = fmt.Sprintf("%s =?", params["key"])
if has, err := Db.Where(query, params["value"]).Get(&m); err != nil || has == false {
return nil, zhios_order_relate_logx.Error(err)
}
return &m, nil
}

// OneCirclesAvailableGreenEnergyPointsFlowFindByParams 通过传入的参数查询数据(多条)
func OneCirclesAvailableGreenEnergyPointsFlowFindByParams(Db *xorm.Engine, params map[string]interface{}) (*[]model.OneCirclesAvailableGreenEnergyPointsFlow, error) {
var m []model.OneCirclesAvailableGreenEnergyPointsFlow
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 OneCirclesAvailableGreenEnergyPointsFlowFindByParamsByPage(Db *xorm.Engine, params map[string]interface{}, page, pageSize int) (*[]model.OneCirclesAvailableGreenEnergyPointsFlow, error) {
var m []model.OneCirclesAvailableGreenEnergyPointsFlow
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
}

}
}

+ 167
- 0
db/db_one_circles_green_energy_basic_setting.go View File

@@ -0,0 +1,167 @@
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"
)

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

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

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

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

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

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

// OneCirclesGreenEnergyBasicSettingGetOneByParamsBySession 通过传入的参数查询数据(单条)
func OneCirclesGreenEnergyBasicSettingGetOneByParamsBySession(session *xorm.Session, params map[string]interface{}) (*model.OneCirclesGreenEnergyBasicSetting, error) {
var m model.OneCirclesGreenEnergyBasicSetting
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
}

// OneCirclesGreenEnergyBasicSettingGetOneByParams 通过传入的参数查询数据(单条)
func OneCirclesGreenEnergyBasicSettingGetOneByParams(Db *xorm.Engine, params map[string]interface{}) (*model.OneCirclesGreenEnergyBasicSetting, error) {
var m model.OneCirclesGreenEnergyBasicSetting
var query = fmt.Sprintf("%s =?", params["key"])
if has, err := Db.Where(query, params["value"]).Get(&m); err != nil || has == false {
return nil, zhios_order_relate_logx.Error(err)
}
return &m, nil
}

// OneCirclesGreenEnergyBasicSettingFindByParams 通过传入的参数查询数据(多条)
func OneCirclesGreenEnergyBasicSettingFindByParams(Db *xorm.Engine, params map[string]interface{}) (*[]model.OneCirclesGreenEnergyBasicSetting, error) {
var m []model.OneCirclesGreenEnergyBasicSetting
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 OneCirclesGreenEnergyBasicSettingFindByParamsByPage(Db *xorm.Engine, params map[string]interface{}, page, pageSize int) (*[]model.OneCirclesGreenEnergyBasicSetting, error) {
var m []model.OneCirclesGreenEnergyBasicSetting
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
}

}
}

+ 175
- 0
db/db_one_circles_green_energy_price.go View File

@@ -0,0 +1,175 @@
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"
)

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

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

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

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

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

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

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

// OneCirclesGreenEnergyPriceGetOneByParamsBySession 通过传入的参数查询数据(单条)
func OneCirclesGreenEnergyPriceGetOneByParamsBySession(session *xorm.Session, date, hour string) (*model.OneCirclesGreenEnergyPrice, error) {
var m model.OneCirclesGreenEnergyPrice
has, err := session.Where("date =? and hour =?", date, hour).Get(&m)
if err != nil {
return nil, zhios_order_relate_logx.Error(err)
}
if has == false {
return nil, nil
}
return &m, nil
}

// OneCirclesGreenEnergyPriceGetOneByParams 通过传入的参数查询数据(单条)
func OneCirclesGreenEnergyPriceGetOneByParams(Db *xorm.Engine, params map[string]interface{}) (*model.OneCirclesGreenEnergyPrice, error) {
var m model.OneCirclesGreenEnergyPrice
var query = fmt.Sprintf("%s =?", params["key"])
if has, err := Db.Where(query, params["value"]).Get(&m); err != nil || has == false {
return nil, zhios_order_relate_logx.Error(err)
}
return &m, nil
}

// OneCirclesGreenEnergyPriceFindByParams 通过传入的参数查询数据(多条)
func OneCirclesGreenEnergyPriceFindByParams(Db *xorm.Engine, params map[string]interface{}) (*[]model.OneCirclesGreenEnergyPrice, error) {
var m []model.OneCirclesGreenEnergyPrice
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 OneCirclesGreenEnergyPriceFindByParamsByPage(Db *xorm.Engine, params map[string]interface{}, page, pageSize int) (*[]model.OneCirclesGreenEnergyPrice, error) {
var m []model.OneCirclesGreenEnergyPrice
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
}

}
}

+ 167
- 0
db/db_one_circles_green_energy_sign_in.go View File

@@ -0,0 +1,167 @@
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"
)

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

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

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

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

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

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

// OneCirclesGreenEnergySignInGetOneByParamsBySession 通过传入的参数查询数据(单条)
func OneCirclesGreenEnergySignInGetOneByParamsBySession(session *xorm.Session, params map[string]interface{}) (*model.OneCirclesGreenEnergySignIn, error) {
var m model.OneCirclesGreenEnergySignIn
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
}

// OneCirclesGreenEnergySignInGetOneByParams 通过传入的参数查询数据(单条)
func OneCirclesGreenEnergySignInGetOneByParams(Db *xorm.Engine, params map[string]interface{}) (*model.OneCirclesGreenEnergySignIn, error) {
var m model.OneCirclesGreenEnergySignIn
var query = fmt.Sprintf("%s =?", params["key"])
if has, err := Db.Where(query, params["value"]).Get(&m); err != nil || has == false {
return nil, zhios_order_relate_logx.Error(err)
}
return &m, nil
}

// OneCirclesGreenEnergySignInFindByParams 通过传入的参数查询数据(多条)
func OneCirclesGreenEnergySignInFindByParams(Db *xorm.Engine, params map[string]interface{}) (*[]model.OneCirclesGreenEnergySignIn, error) {
var m []model.OneCirclesGreenEnergySignIn
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 OneCirclesGreenEnergySignInFindByParamsByPage(Db *xorm.Engine, params map[string]interface{}, page, pageSize int) (*[]model.OneCirclesGreenEnergySignIn, error) {
var m []model.OneCirclesGreenEnergySignIn
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
}

}
}

+ 107
- 0
db/db_one_circles_public_platoon_basic_setting.go View File

@@ -0,0 +1,107 @@
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"
)

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

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

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

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

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

// OneCirclesPublicPlatoonBasicSettingGetOneByParams 通过传入的参数查询数据(单条)
func OneCirclesPublicPlatoonBasicSettingGetOneByParams(Db *xorm.Engine, params map[string]interface{}) (*model.OneCirclesPublicPlatoonBasicSetting, error) {
var m model.OneCirclesPublicPlatoonBasicSetting
var query = fmt.Sprintf("%s =?", params["key"])
if has, err := Db.Where(query, params["value"]).Get(&m); err != nil || has == false {
return nil, zhios_order_relate_logx.Error(err)
}
return &m, nil
}

// OneCirclesPublicPlatoonBasicSettingFindByParams 通过传入的参数查询数据(多条)
func OneCirclesPublicPlatoonBasicSettingFindByParams(Db *xorm.Engine, params map[string]interface{}) (*[]model.OneCirclesPublicPlatoonBasicSetting, error) {
var m []model.OneCirclesPublicPlatoonBasicSetting
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
}

}
}

+ 46
- 0
db/db_one_circles_public_platoon_free_punish_with_user.go View File

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

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

func FindAllOneCirclesPublicPlatoonFreePunishWithUser(Db *xorm.Engine) (resp map[int]*model.OneCirclesPublicPlatoonFreePunishWithUser, err error) {
var m []model.OneCirclesPublicPlatoonFreePunishWithUser
err = Db.Where("1=1").Find(&m)
if err != nil {
return nil, zhios_order_relate_logx.Error(err)
}
resp = map[int]*model.OneCirclesPublicPlatoonFreePunishWithUser{}
for _, v := range m {
resp[v.Uid] = &v
}
return
}

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

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

+ 46
- 0
db/db_one_circles_public_platoon_records_punish_with_user.go View File

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

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

func FindAllOneCirclesPublicPlatoonRecordsPunishWithUser(Db *xorm.Engine) (resp map[int]*model.OneCirclesPublicPlatoonRecordsPunishWithUser, err error) {
var m []model.OneCirclesPublicPlatoonRecordsPunishWithUser
err = Db.Where("1=1").Find(&m)
if err != nil {
return nil, zhios_order_relate_logx.Error(err)
}
resp = map[int]*model.OneCirclesPublicPlatoonRecordsPunishWithUser{}
for _, v := range m {
resp[v.Uid] = &v
}
return
}

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

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

+ 195
- 0
db/db_one_circles_public_platoon_user_relation.go View File

@@ -0,0 +1,195 @@
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"
)

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

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

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

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

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

// OneCirclesPublicPlatoonUserRelationGetOneByParams 通过传入的参数查询数据(单条)
func OneCirclesPublicPlatoonUserRelationGetOneByParams(Db *xorm.Engine, params map[string]interface{}) (*model.OneCirclesPublicPlatoonUserRelation, error) {
var m model.OneCirclesPublicPlatoonUserRelation
var query = fmt.Sprintf("%s =?", params["key"])
if has, err := Db.Where(query, params["value"]).Get(&m); err != nil || has == false {
return nil, zhios_order_relate_logx.Error(err)
}
return &m, nil
}

func OneCirclesPublicPlatoonUserRelationFindByEmptyPosition(Db *xorm.Engine) (*model.OneCirclesPublicPlatoonUserRelation, error) {
var m model.OneCirclesPublicPlatoonUserRelation
if has, err := Db.Where("uid = -1").Or("uid = -2").Get(&m); err != nil || has == false {
return nil, zhios_order_relate_logx.Error(err)
}
return &m, nil
}

func OneCirclesPublicPlatoonUserRelationGetOneByPid(Db *xorm.Engine, recommendUid string, params map[string]interface{}) (*model.OneCirclesPublicPlatoonUserRelation, error) {
var m model.OneCirclesPublicPlatoonUserRelation
var query = fmt.Sprintf("%s <=?", params["key"])
if has, err := Db.Where("recommend_uid = ?", recommendUid).And(query, params["value"]).OrderBy("id ASC").Get(&m); err != nil || has == false {
return nil, zhios_order_relate_logx.Error(err)
}
return &m, nil
}

func OneCirclesPublicPlatoonUserRelationFindByPid(Db *xorm.Engine, fatherUid int, fatherName, positionName string) ([]model.OneCirclesPublicPlatoonUserRelation, error) {
var m []model.OneCirclesPublicPlatoonUserRelation
//var query1 = fmt.Sprintf("%s >= ?", pidName)
var query2 = fmt.Sprintf("%s = ?", fatherName)
var order = fmt.Sprintf("%s Desc", positionName)
if err := Db.Where(query2, fatherUid).OrderBy(order).
Find(&m); err != nil {
return nil, zhios_order_relate_logx.Warn(err)
}
return m, nil
}

func OneCirclesPublicPlatoonUserRelationFindCountByPosition(Db *xorm.Engine, fatherUid int, fatherName, positionName string, startPosition, endPosition int64) ([]model.OneCirclesPublicPlatoonUserRelation, int64, error) {
var m []model.OneCirclesPublicPlatoonUserRelation
var count int64
var query1 = fmt.Sprintf("%s >= ?", positionName)
var query2 = fmt.Sprintf("%s <= ?", positionName)
var query3 = fmt.Sprintf("%s = ?", fatherName)
if count, err := Db.Where(query3, fatherUid).And(query1, startPosition).And(query2, endPosition).OrderBy("has_son_num ASC").
FindAndCount(&m); err != nil {
return nil, count, zhios_order_relate_logx.Warn(err)
}
return m, count, nil
}

// OneCirclesPublicPlatoonUserRelationFindByParams 通过传入的参数查询数据(多条)
func OneCirclesPublicPlatoonUserRelationFindByParams(Db *xorm.Engine, params map[string]interface{}) (*[]model.OneCirclesPublicPlatoonUserRelation, error) {
var m []model.OneCirclesPublicPlatoonUserRelation
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 OneCirclesPublicPlatoonUserRelationFindRecommends(Db *xorm.Engine) ([]model.OneCirclesPublicPlatoonUserRelation, error) {
var m []model.OneCirclesPublicPlatoonUserRelation
var query = fmt.Sprintf("recommend_uid > 0")
err := Db.Where(query).Find(&m)
if err != nil {
return nil, zhios_order_relate_logx.Error(err)
}
return m, nil
}

func OneCirclesPublicPlatoonUserRelationFindByParamsByPage(Db *xorm.Engine, params map[string]interface{}, page, pageSize int) (*[]model.OneCirclesPublicPlatoonUserRelation, error) {
var m []model.OneCirclesPublicPlatoonUserRelation
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
}

}
}

+ 187
- 0
db/db_one_circles_star_level_dividends_records.go View File

@@ -0,0 +1,187 @@
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"
)

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

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

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

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

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

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

func OneCirclesStarLevelDividendsRecordsUpdateBySession(session *xorm.Session, id interface{}, OneCirclesStarLevelDividendsRecords *model.OneCirclesStarLevelDividendsRecords, forceColums ...string) (int64, error) {
var (
affected int64
err error
)
if forceColums != nil {
affected, err = session.Where("id=?", id).Cols(forceColums...).Update(OneCirclesStarLevelDividendsRecords)
} else {
affected, err = session.Where("id=?", id).Update(OneCirclesStarLevelDividendsRecords)
}
if err != nil {
return 0, err
}
return affected, nil
}

// OneCirclesStarLevelDividendsRecordsGetOneByParamsBySession 通过传入的参数查询数据(单条)
func OneCirclesStarLevelDividendsRecordsGetOneByParamsBySession(session *xorm.Session, params map[string]interface{}) (*model.OneCirclesStarLevelDividendsRecords, error) {
var m model.OneCirclesStarLevelDividendsRecords
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, nil
}
return &m, nil
}

// OneCirclesStarLevelDividendsRecordsGetOneByParams 通过传入的参数查询数据(单条)
func OneCirclesStarLevelDividendsRecordsGetOneByParams(Db *xorm.Engine, params map[string]interface{}) (*model.OneCirclesStarLevelDividendsRecords, error) {
var m model.OneCirclesStarLevelDividendsRecords
var query = fmt.Sprintf("%s =?", params["key"])
has, err := Db.Where(query, params["value"]).Get(&m)
if err != nil {
return nil, zhios_order_relate_logx.Error(err)
}
if !has {
return nil, nil
}
return &m, nil
}

// OneCirclesStarLevelDividendsRecordsFindByParams 通过传入的参数查询数据(多条)
func OneCirclesStarLevelDividendsRecordsFindByParams(Db *xorm.Engine, params map[string]interface{}) (*[]model.OneCirclesStarLevelDividendsRecords, error) {
var m []model.OneCirclesStarLevelDividendsRecords
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 OneCirclesStarLevelDividendsRecordsFindByParamsByPage(Db *xorm.Engine, params map[string]interface{}, page, pageSize int) (*[]model.OneCirclesStarLevelDividendsRecords, error) {
var m []model.OneCirclesStarLevelDividendsRecords
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
}

}
}

+ 167
- 0
db/db_one_circles_user_activity.go View File

@@ -0,0 +1,167 @@
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"
)

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

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

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

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

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

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

// OneCirclesUserActivityGetOneByParamsBySession 通过传入的参数查询数据(单条)
func OneCirclesUserActivityGetOneByParamsBySession(session *xorm.Session, params map[string]interface{}) (*model.OneCirclesUserActivity, error) {
var m model.OneCirclesUserActivity
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
}

// OneCirclesUserActivityGetOneByParams 通过传入的参数查询数据(单条)
func OneCirclesUserActivityGetOneByParams(Db *xorm.Engine, params map[string]interface{}) (*model.OneCirclesUserActivity, error) {
var m model.OneCirclesUserActivity
var query = fmt.Sprintf("%s =?", params["key"])
if has, err := Db.Where(query, params["value"]).Get(&m); err != nil || has == false {
return nil, zhios_order_relate_logx.Error(err)
}
return &m, nil
}

// OneCirclesUserActivityFindByParams 通过传入的参数查询数据(多条)
func OneCirclesUserActivityFindByParams(Db *xorm.Engine, params map[string]interface{}) (*[]model.OneCirclesUserActivity, error) {
var m []model.OneCirclesUserActivity
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 OneCirclesUserActivityFindByParamsByPage(Db *xorm.Engine, params map[string]interface{}, page, pageSize int) (*[]model.OneCirclesUserActivity, error) {
var m []model.OneCirclesUserActivity
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
}

}
}

+ 15
- 0
db/db_one_circles_user_public_platoon_system_punish_records.go View File

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

import (
"code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/db/model"
"xorm.io/xorm"
)

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

+ 187
- 0
db/db_one_circles_user_watch_records.go View File

@@ -0,0 +1,187 @@
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"
)

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

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

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

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

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

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

func OneCirclesUserWatchRecordsUpdateBySession(session *xorm.Session, id interface{}, OneCirclesUserWatchRecords *model.OneCirclesUserWatchRecords, forceColums ...string) (int64, error) {
var (
affected int64
err error
)
if forceColums != nil {
affected, err = session.Where("id=?", id).Cols(forceColums...).Update(OneCirclesUserWatchRecords)
} else {
affected, err = session.Where("id=?", id).Update(OneCirclesUserWatchRecords)
}
if err != nil {
return 0, err
}
return affected, nil
}

// OneCirclesUserWatchRecordsGetOneByParamsBySession 通过传入的参数查询数据(单条)
func OneCirclesUserWatchRecordsGetOneByParamsBySession(session *xorm.Session, params map[string]interface{}) (*model.OneCirclesUserWatchRecords, error) {
var m model.OneCirclesUserWatchRecords
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
}

// OneCirclesUserWatchRecordsGetOneByParams 通过传入的参数查询数据(单条)
func OneCirclesUserWatchRecordsGetOneByParams(Db *xorm.Engine, params map[string]interface{}) (*model.OneCirclesUserWatchRecords, error) {
var m model.OneCirclesUserWatchRecords
var query = fmt.Sprintf("%s =?", params["key"])
has, err := Db.Where(query, params["value"]).Get(&m)
if err != nil {
return nil, zhios_order_relate_logx.Error(err)
}
if !has {
return nil, nil
}
return &m, nil
}

// OneCirclesUserWatchRecordsFindByParams 通过传入的参数查询数据(多条)
func OneCirclesUserWatchRecordsFindByParams(Db *xorm.Engine, params map[string]interface{}) (*[]model.OneCirclesUserWatchRecords, error) {
var m []model.OneCirclesUserWatchRecords
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 OneCirclesUserWatchRecordsFindByParamsByPage(Db *xorm.Engine, params map[string]interface{}, page, pageSize int) (*[]model.OneCirclesUserWatchRecords, error) {
var m []model.OneCirclesUserWatchRecords
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
}

}
}

+ 7
- 0
db/db_second_newcomers_free.go View File

@@ -12,3 +12,10 @@ func SecondGetAllPriceTypeList(Db *xorm.Engine) ([]model.SecondNewcomersFreePric
}
return priceType, nil
}
func MoreGetAllPriceTypeList(Db *xorm.Engine) ([]model.MoreNewcomersFreePriceType, error) {
var priceType []model.MoreNewcomersFreePriceType
if err := Db.Find(&priceType); err != nil {
return nil, err
}
return priceType, nil
}

+ 40
- 0
db/db_subsidy_with_month.go View File

@@ -0,0 +1,40 @@
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"
"github.com/shopspring/decimal"
"xorm.io/xorm"
)

// SubsidyWithUserFlowInsert 插入单条数据
func SubsidyWithMonthInsert(session *xorm.Session, SubsidyWithUserFlow *model.SubsidyWithUserMonth) (int, error) {
var data model.SubsidyWithUserMonth
session.Where("date=? and uid=?", SubsidyWithUserFlow.Date, SubsidyWithUserFlow.Uid).Get(&data)
if data.Id == 0 {
data = model.SubsidyWithUserMonth{
Uid: SubsidyWithUserFlow.Uid,
Date: SubsidyWithUserFlow.Date,
}
_, err := session.InsertOne(&data)
if err != nil {
return 0, err
}

}
if zhios_order_relate_utils.StrToFloat64(SubsidyWithUserFlow.ConsumeAmount) > 0 {
userAmountValue := decimal.NewFromFloat(zhios_order_relate_utils.StrToFloat64(data.ConsumeAmount))
amountValue := decimal.NewFromFloat(zhios_order_relate_utils.StrToFloat64(SubsidyWithUserFlow.ConsumeAmount))
data.ConsumeAmount = userAmountValue.Add(amountValue).RoundFloor(8).String()
}
if zhios_order_relate_utils.StrToFloat64(SubsidyWithUserFlow.ExperienceAmount) > 0 {
userAmountValue := decimal.NewFromFloat(zhios_order_relate_utils.StrToFloat64(data.ExperienceAmount))
amountValue := decimal.NewFromFloat(zhios_order_relate_utils.StrToFloat64(SubsidyWithUserFlow.ExperienceAmount))
data.ExperienceAmount = userAmountValue.Add(amountValue).RoundFloor(8).String()
}
_, err := session.Where("id=?", data.Id).Cols("consume_amount,experience_amount").Update(&data)
if err != nil {
return 0, err
}
return SubsidyWithUserFlow.Id, nil
}

+ 153
- 0
db/db_user_public_platoon_double_network_relation.go View File

@@ -0,0 +1,153 @@
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"
)

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

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

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

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

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

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

// UserPublicPlatoonDoubleNetworkRelationGetOneByParams 通过传入的参数查询数据(单条)
func UserPublicPlatoonDoubleNetworkRelationGetOneByParams(Db *xorm.Engine, params map[string]interface{}) (*model.UserPublicPlatoonDoubleNetworkRelation, error) {
var m model.UserPublicPlatoonDoubleNetworkRelation
var query = fmt.Sprintf("%s =?", params["key"])
if has, err := Db.Where(query, params["value"]).Get(&m); err != nil || has == false {
return nil, zhios_order_relate_logx.Error(err)
}
return &m, nil
}

// UserPublicPlatoonDoubleNetworkRelationFindByParams 通过传入的参数查询数据(多条)
func UserPublicPlatoonDoubleNetworkRelationFindByParams(Db *xorm.Engine, params map[string]interface{}) (*[]model.UserPublicPlatoonDoubleNetworkRelation, error) {
var m []model.UserPublicPlatoonDoubleNetworkRelation
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 UserPublicPlatoonDoubleNetworkRelationFindByParamsByPage(Db *xorm.Engine, params map[string]interface{}, page, pageSize int) (*[]model.UserPublicPlatoonDoubleNetworkRelation, error) {
var m []model.UserPublicPlatoonDoubleNetworkRelation
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
}

}
}

+ 117
- 0
db/db_user_public_platoon_double_network_setting.go View File

@@ -0,0 +1,117 @@
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"
)

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

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

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

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

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

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

// UserPublicPlatoonDoubleNetworkSettingGetOneByParams 通过传入的参数查询数据(单条)
func UserPublicPlatoonDoubleNetworkSettingGetOneByParams(Db *xorm.Engine, params map[string]interface{}) (*model.UserPublicPlatoonDoubleNetworkSetting, error) {
var m model.UserPublicPlatoonDoubleNetworkSetting
var query = fmt.Sprintf("%s =?", params["key"])
if has, err := Db.Where(query, params["value"]).Get(&m); err != nil || has == false {
return nil, zhios_order_relate_logx.Error(err)
}
return &m, nil
}

// UserPublicPlatoonDoubleNetworkSettingFindByParams 通过传入的参数查询数据(多条)
func UserPublicPlatoonDoubleNetworkSettingFindByParams(Db *xorm.Engine, params map[string]interface{}) (*[]model.UserPublicPlatoonDoubleNetworkSetting, error) {
var m []model.UserPublicPlatoonDoubleNetworkSetting
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
}

}
}

+ 121
- 0
db/db_user_public_platoon_double_network_user_coin_record.go View File

@@ -0,0 +1,121 @@
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"
)

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

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

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

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

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

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

// UserPublicPlatoonDoubleNetworkUserCoinRecordGetOneByParams 通过传入的参数查询数据(单条)
func UserPublicPlatoonDoubleNetworkUserCoinRecordGetOneByParams(Db *xorm.Engine, params map[string]interface{}) (*model.UserPublicPlatoonDoubleNetworkUserCoinRecord, error) {
var m model.UserPublicPlatoonDoubleNetworkUserCoinRecord
var query = fmt.Sprintf("%s =?", params["key"])
has, err := Db.Where(query, params["value"]).Get(&m)
if err != nil {
return nil, zhios_order_relate_logx.Error(err)
}
if has == false {
return nil, nil
}
return &m, nil
}

// UserPublicPlatoonDoubleNetworkUserCoinRecordFindByParams 通过传入的参数查询数据(多条)
func UserPublicPlatoonDoubleNetworkUserCoinRecordFindByParams(Db *xorm.Engine, params map[string]interface{}) (*[]model.UserPublicPlatoonDoubleNetworkUserCoinRecord, error) {
var m []model.UserPublicPlatoonDoubleNetworkUserCoinRecord
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
}

}
}

+ 9
- 0
db/db_user_public_platoon_relation.go View File

@@ -29,6 +29,15 @@ func UserPublicPlatoonRelationInsert(Db *xorm.Engine, UserPublicPlatoonRelation
return UserPublicPlatoonRelation.Id, nil
}

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

// BatchAddUserPublicPlatoonRelations 批量新增数据
func BatchAddUserPublicPlatoonRelations(Db *xorm.Engine, UserPublicPlatoonRelationData []*model.UserPublicPlatoonRelation) (int64, error) {
affected, err := Db.Insert(UserPublicPlatoonRelationData)


+ 38
- 0
db/dbs_user.go View File

@@ -17,6 +17,15 @@ func DbsUserFindByIds(eg *xorm.Engine, uid []int) (*[]model.User, error) {
return &users, nil
}

func DbsUserFindByUid(eg *xorm.Engine, uid int) (*model.User, error) {
var data model.User
get, err := eg.Where("uid =?", uid).Get(&data)
if get == false || err != nil {
return nil, zhios_order_relate_logx.Error(err)
}
return &data, nil
}

func DbsUserRelate(eg *xorm.Engine, uid, level int) (*[]model.UserRelate, error) {
var userRelate []model.UserRelate
sess := eg.Where("uid = ?", uid)
@@ -31,3 +40,32 @@ func DbsUserRelate(eg *xorm.Engine, uid, level int) (*[]model.UserRelate, error)
}
return &userRelate, nil
}

func GetUserParentUserRelate(eg *xorm.Engine, uid int) (*model.UserRelate, error) {
var data model.UserRelate
get, err := eg.Where("level=1 and uid =?", uid).Get(&data)
if get == false || err != nil {
return nil, zhios_order_relate_logx.Error(err)
}
return &data, nil
}

func DbsUserRelateByParentUid(eg *xorm.Engine, uid, level int) (*[]model.UserRelate, error) {
var userRelate []model.UserRelate
sess := eg.Where("parent_uid = ?", uid)
if level > 0 {
sess.And("level<=?", level)
}
if err := sess.Asc("level").Find(&userRelate); err != nil {
return nil, zhios_order_relate_logx.Error(err)
}
if len(userRelate) == 0 {
return nil, nil
}
return &userRelate, nil
}

func SumUserRelateByParentUid(eg *xorm.Engine, parentUid string) (total int64, userRelate []*model.UserRelate, err error) {
total, err = eg.Where("parent_uid = ?", parentUid).And("level = 1").FindAndCount(&userRelate)
return
}

+ 1
- 0
db/model/fin_user_flow.go View File

@@ -26,4 +26,5 @@ type FinUserFlow struct {
AliOrdId string `json:"ali_ord_id" xorm:"default '' comment('支付宝订单号') VARCHAR(128)"`
CreateAt time.Time `json:"create_at" xorm:"created not null default CURRENT_TIMESTAMP comment('创建时间') TIMESTAMP"`
UpdateAt time.Time `json:"update_at" xorm:"updated not null default CURRENT_TIMESTAMP comment('更新时间') TIMESTAMP"`
Date string `json:"date" xorm:"comment('2023-12-01') VARCHAR(255)"`
}

+ 12
- 0
db/model/green_coin_double_chain.go View File

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

type GreenCoinDoubleChain 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:"coin_1 not null default 0 comment('coinId_1(作用于绿色积分)') INT(11)"`
Coin2 int `json:"coin_2" xorm:"coin_2 not null default 0 comment('coinId_2(作用于贡献积分)') INT(11)"`
ExchangeRatio1 int `json:"exchange_ratio_1" xorm:"exchange_ratio_1 not null default 0 comment('兑换比例(扣除绿色积分)') INT(11)"`
ExchangeRatio2 int `json:"exchange_ratio_2" xorm:"exchange_ratio_2 not null default 0 comment('兑换比例(扣除贡献积分)') INT(11)"`
CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('创建时间') TIMESTAMP"`
UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('更新时间') TIMESTAMP"`
}

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

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

type GreenCoinDoubleChainExchangeRecords struct {
Id int64 `json:"id" xorm:"pk autoincr BIGINT(20)"`
Uid int `json:"uid" xorm:"not null default 0 comment('兑换用户id') INT(11)"`
ContributeUid1 int `json:"contribute_uid_1" xorm:"contribute_uid_1 not null default 0 comment('第1个贡献用户id') INT(11)"`
ContributeUid2 int `json:"contribute_uid_2" xorm:"contribute_uid_2 not null default 0 comment('第2个贡献用户id') INT(11)"`
CoinId1 int `json:"coin_id_1" xorm:"coin_id_1 not null default 0 comment('coinId_1(作用于绿色积分)') INT(11)"`
CoinId2 int `json:"coin_id_2" xorm:"coin_id_2 not null default 0 comment('coinId_2(作用于贡献积分)') INT(11)"`
Amount string `json:"amount" xorm:"not null default 0.00 comment('兑换金额') DECIMAL(8,2)"`
BeforeUserCoinAmount string `json:"before_user_coin_amount" xorm:"not null default 0.00 comment('用户兑换前金额') DECIMAL(8,2)"`
AfterUserCoinAmount string `json:"after_user_coin_amount" xorm:"not null default 0.00 comment('用户兑换后金额') DECIMAL(8,2)"`
BeforeCoinAmountContributeUser1 string `json:"before_coin_amount_contribute_user_1" xorm:"before_coin_amount_contribute_user_1 not null default 0.00 comment('第1个贡献用户兑换前金额') DECIMAL(8,2)"`
AfterCoinAmountContributeUser1 string `json:"after_coin_amount_contribute_user_1" xorm:"after_coin_amount_contribute_user_1 not null default 0.00 comment('第1个贡献用户兑换后金额') DECIMAL(8,2)"`
BeforeCoinAmountContributeUser2 string `json:"before_coin_amount_contribute_user_2" xorm:"before_coin_amount_contribute_user_2 not null default 0.00 comment('第2个贡献用户兑换前金额') DECIMAL(8,2)"`
AfterCoinAmountContributeUser2 string `json:"after_coin_amount_contribute_user_2" xorm:"after_coin_amount_contribute_user_2 not null default 0.00 comment('第2个贡献用户兑换后金额') DECIMAL(8,2)"`
CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('创建时间') DATETIME"`
UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('更新时间') DATETIME"`
}

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

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

type MoreNewcomersFreePriceType struct {
Id int `json:"id" xorm:"not null pk autoincr INT(10)"`
PriceName string `json:"price_name" xorm:"not null comment('价格类型') VARCHAR(255)"`
NeedQuan int `json:"need_quan" xorm:"not null default 0 comment('需要的福利券') INT(11)"`
CreatedAt int `json:"created_at" xorm:"not null default 0 INT(11)"`
UpdatedAt int `json:"updated_at" xorm:"not null default 0 INT(11)"`
IsShow int `json:"is_show" xorm:"not null default 1 comment('是否开启') TINYINT(1)"`
IsDel int `json:"is_del" xorm:"not null default 0 INT(11)"`
NeedUseQuan int `json:"need_use_quan" xorm:"not null default 1 INT(1)"`
NeedLimitBuy int `json:"need_limit_buy" xorm:"not null default 0 INT(1)"`
Auth string `json:"auth" xorm:"not null comment('权限') TEXT"`
LimitBuyCondition string `json:"limit_buy_condition" xorm:"not null comment('限购条件') TEXT"`
CommissionId string `json:"commission_id" xorm:"default '' VARCHAR(255)"`
CommissionData string `json:"commission_data" xorm:"default '' VARCHAR(500)"`
}

+ 39
- 0
db/model/one_circles_available_green_energy_points_flow.go View File

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

import (
"time"
)

type OneCirclesAvailableGreenEnergyPointsFlow 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:绿色能量兑换余额)') TINYINT(1)"`
Title string `json:"title" xorm:"not null default '' comment('标题') VARCHAR(255)"`
Amount string `json:"amount" xorm:"not null comment('变更数量') DECIMAL(28,10)"`
BeforeEcologicalApplicationValues string `json:"before_ecological_application_values" xorm:"not null default 0.0000000000 comment('变更前-生态应用区块币数量') DECIMAL(28,10)"`
AfterEcologicalApplicationValues string `json:"after_ecological_application_values" xorm:"not null default 0.0000000000 comment('变更后-生态应用区块币数量') DECIMAL(28,10)"`
BeforeTechnicalTeamValues string `json:"before_technical_team_values" xorm:"not null default 0.0000000000 comment('变更前-技术团队区块币数量') DECIMAL(28,10)"`
AfterTechnicalTeamValues string `json:"after_technical_team_values" xorm:"not null default 0.0000000000 comment('变更后-技术团队区块币数量') DECIMAL(28,10)"`
BeforeOperateTeamValues string `json:"before_operate_team_values" xorm:"not null default 0.0000000000 comment('变更前-运营团队区块币数量') DECIMAL(28,10)"`
AfterOperateTeamValues string `json:"after_operate_team_values" xorm:"not null default 0.0000000000 comment('变更后-运营团队区块币数量') DECIMAL(28,10)"`
BeforeActiveGiveawaysValues string `json:"before_active_giveaways_values" xorm:"not null default 0.0000000000 comment('变更前-活跃赠送区块币数量') DECIMAL(28,10)"`
AfterActiveGiveawaysValues string `json:"after_active_giveaways_values" xorm:"not null default 0.0000000000 comment('变更后-活跃赠送区块币数量') DECIMAL(28,10)"`
BeforeOriginalQuantityValues string `json:"before_original_quantity_values" xorm:"not null default 0.0000000000 comment('变更前-原始数量区块币数量') DECIMAL(28,10)"`
AfterOriginalQuantityValues string `json:"after_original_quantity_values" xorm:"not null default 0.0000000000 comment('变更后-原始数量区块币数量') DECIMAL(28,10)"`
BeforeOriginalQuantityFundValues string `json:"before_original_quantity_fund_values" xorm:"not null default 0.0000000000 comment('变更前-原始资金值') DECIMAL(28,10)"`
AfterOriginalQuantityFundValues string `json:"after_original_quantity_fund_values" xorm:"not null default 0.0000000000 comment('变更后-原始资金值') DECIMAL(28,10)"`
BeforeMarketplaceMerchantValues string `json:"before_marketplace_merchant_values" xorm:"not null default 0.0000000000 comment('变更前-市商区块币数量') DECIMAL(28,10)"`
AfterMarketplaceMerchantValues string `json:"after_marketplace_merchant_values" xorm:"not null default 0.0000000000 comment('变更后-市商区块币数量') DECIMAL(28,10)"`
BeforeMarketplaceMerchantFundValues string `json:"before_marketplace_merchant_fund_values" xorm:"not null default 0.0000000000 comment('变更前-市商资金值') DECIMAL(28,10)"`
AfterMarketplaceMerchantFundValues string `json:"after_marketplace_merchant_fund_values" xorm:"not null default 0.0000000000 comment('变更后-市商资金值') DECIMAL(28,10)"`
BeforeDevelopmentCommitteeValues string `json:"before_development_committee_values" xorm:"not null default 0.0000000000 comment('变更前-发展委员会区块币数量') DECIMAL(28,10)"`
AfterDevelopmentCommitteeValues string `json:"after_development_committee_values" xorm:"not null default 0.0000000000 comment('变更后-发展委员会区块币数量') DECIMAL(28,10)"`
BeforePublicWelfareAndCharityValues string `json:"before_public_welfare_and_charity_values" xorm:"not null default 0.0000000000 comment('变更前-公益慈善区块币数量') DECIMAL(28,10)"`
AfterPublicWelfareAndCharityValues string `json:"after_public_welfare_and_charity_values" xorm:"not null default 0.0000000000 comment('变更后-公益慈善区块币数量') DECIMAL(28,10)"`
BeforeStarLevelDividendsValues string `json:"before_star_level_dividends_values" xorm:"not null default 0.0000000000 comment('变更前-星级分红区块币数量') DECIMAL(28,10)"`
AfterStarLevelDividendsValues string `json:"after_star_level_dividends_values" xorm:"not null default 0.0000000000 comment('变更后-星级分红区块币数量') DECIMAL(28,10)"`
BeforeDestructionQuantityValues string `json:"before_destruction_quantity_values" xorm:"not null default 0.0000000000 comment('变更前-销毁区块币数量') DECIMAL(28,10)"`
AfterDestructionQuantityValues string `json:"after_destruction_quantity_values" xorm:"not null default 0.0000000000 comment('变更后-销毁区块币数量') DECIMAL(28,10)"`
CreateTime time.Time `json:"create_time" xorm:"default 'CURRENT_TIMESTAMP' comment('创建时间') DATETIME"`
}

+ 38
- 0
db/model/one_circles_green_energy_basic_setting.go View File

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

import (
"time"
)

type OneCirclesGreenEnergyBasicSetting struct {
Id int `json:"id" xorm:"not null pk autoincr INT(11)"`
IsOpen int `json:"is_open" xorm:"not null default 1 comment('是否开启(1:开启 0:关闭)') TINYINT(1)"`
PersonGreenEnergyCoinId int `json:"person_green_energy_coin_id" xorm:"not null default 0 comment('个人绿色能量对应虚拟币id') INT(11)"`
TeamGreenEnergyCoinId int `json:"team_green_energy_coin_id" xorm:"not null default 0 comment('团队绿色能量对应虚拟币id') INT(11)"`
TotalIssuanceAmount string `json:"total_issuance_amount" xorm:"not null comment('总发行量') DECIMAL(28,8)"`
EcologicalApplication string `json:"ecological_application" xorm:"not null comment('生态应用') DECIMAL(28,8)"`
TotalTechnologyTeam string `json:"total_technology_team" xorm:"not null comment('技术团队') DECIMAL(28,8)"`
TotalOperateTeam string `json:"total_operate_team" xorm:"not null comment('运营团队') DECIMAL(28,8)"`
TotalActiveGiveaways string `json:"total_active_giveaways" xorm:"not null comment('活跃赠送') DECIMAL(28,8)"`
OriginalQuantityNums string `json:"original_quantity_nums" xorm:"not null comment('原始数量') DECIMAL(28,8)"`
InitialPrice string `json:"initial_price" xorm:"not null comment('初始价格') DECIMAL(28,8)"`
NowPrice string `json:"now_price" xorm:"not null comment('当前价格') DECIMAL(28,8)"`
OriginalFunds string `json:"original_funds" xorm:"not null comment('原始资金') DECIMAL(28,8)"`
MarketplaceMerchantNums string `json:"marketplace_merchant_nums" xorm:"not null comment('市商数量') DECIMAL(28,8)"`
MarketplaceMerchantFunds string `json:"marketplace_merchant_funds" xorm:"not null comment('市商资金') DECIMAL(28,8)"`
DevelopmentCommittee string `json:"development_committee" xorm:"not null comment('发展委员会') DECIMAL(28,8)"`
PublicWelfareAndCharity string `json:"public_welfare_and_charity" xorm:"not null comment('公益慈善') DECIMAL(28,8)"`
StarLevelDividends string `json:"star_level_dividends" xorm:"not null comment('星级分红') DECIMAL(28,8)"`
DestructionQuantityNums string `json:"destruction_quantity_nums" xorm:"not null comment('销毁数量') DECIMAL(28,8)"`
DestructionSetting string `json:"destruction_setting" xorm:"not null comment('销毁设置') TEXT"`
IsLimitDividend int `json:"is_limit_dividend" xorm:"not null default 1 comment('是否限制分红(会员本人不活跃,没有绿色能量分红)') TINYINT(1)"`
SettlementQuantity int `json:"settlement_quantity" xorm:"not null default 0 comment('结算数量(百分比)') INT(11)"`
SignInReward string `json:"sign_in_reward" xorm:"not null comment('签到奖励') TEXT"`
TeamReward string `json:"team_reward" xorm:"not null comment('团队奖励') TEXT"`
PriceSetting string `json:"price_setting" xorm:"not null comment('价格设置') TEXT"`
WelfareOrdersLimit string `json:"welfare_orders_limit" xorm:"not null comment('福利订单抢购条件') TEXT"`
VipEquitySetting string `json:"vip_equity_setting" xorm:"not null comment('会员权益') TEXT"`
CreateAt time.Time `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"`
UpdateAt time.Time `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"`
IsOpenWelfareOrders int `json:"is_open_welfare_orders" xorm:"not null default 0 comment('是否开启福利订单') TINYINT(1)"`
}

+ 8
- 0
db/model/one_circles_green_energy_price.go View File

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

type OneCirclesGreenEnergyPrice struct {
Id int64 `json:"id" xorm:"pk autoincr BIGINT(20)"`
Price string `json:"price" xorm:"not null default 0.0000000000 comment('价格') DECIMAL(28,10)"`
Date string `json:"date" xorm:"not null default '0000-00-00' comment('日期') CHAR(50)"`
Hour string `json:"hour" xorm:"not null default '00' comment('小时') CHAR(50)"`
}

+ 9
- 0
db/model/one_circles_green_energy_sign_in.go View File

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

type OneCirclesGreenEnergySignIn struct {
Id int64 `json:"id" xorm:"pk autoincr BIGINT(20)"`
Uid int `json:"uid" xorm:"not null default 0 comment('用户id') INT(11)"`
StartTime string `json:"start_time" xorm:"not null default 'CURRENT_TIMESTAMP' comment('签到开始时间') DATETIME"`
EndTime string `json:"end_time" xorm:"not null default 'CURRENT_TIMESTAMP' comment('签到结束时间') DATETIME"`
IsCompleted int `json:"is_completed" xorm:"not null default 0 comment('是否完成(0:未完成 1:已完成)') TINYINT(1)"`
}

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

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

type OneCirclesPublicPlatoonBasicSetting struct {
Id int `json:"id" xorm:"not null pk autoincr INT(11)"`
IsOpen int `json:"is_open" xorm:"not null default 1 comment('是否开启(1:开启 0:关闭)') TINYINT(1)"`
ExchangeRules string `json:"exchange_rules" xorm:"not null comment('兑换规则') TEXT"`
PersonActivePointsCoinId int `json:"person_active_points_coin_id" xorm:"not null default 0 comment('个人活跃积分对应虚拟币id') INT(11)"`
TeamActivePointsCoinId int `json:"team_active_points_coin_id" xorm:"not null default 0 comment('团队活跃积分对应虚拟币id') INT(11)"`
OriginatorUid int `json:"originator_uid" xorm:"not null default 0 comment('创始人uid') INT(11)"`
SeveralTimes int `json:"several_times" xorm:"not null default 3 comment('几乘') TINYINT(3)"`
SeveralRows int `json:"several_rows" xorm:"not null default 3 comment('几排') TINYINT(3)"`
RevenueName string `json:"revenue_name" xorm:"not null default '' comment('收益名称') VARCHAR(255)"`
RewardSystem string `json:"reward_system" xorm:"not null comment('奖励机制') TEXT"`
VideoRewardIsOpen int `json:"video_reward_is_open" xorm:"not null default 1 comment('视屏奖励是否开启(1:开启 0:关闭)') TINYINT(1)"`
VideoRewardSystem string `json:"video_reward_system" xorm:"not null comment('视屏奖励机制') TEXT"`
SystemPunishReplace int `json:"system_punish_replace" xorm:"not null default 1 comment('是否位置滑落 被新用户替换 0否 1是') TINYINT(1)"`
SystemPunishReplaceValue int `json:"system_punish_replace_value" xorm:"not null default 0 comment('xx天未活跃,处罚滑落') INT(11)"`
IsSelfActiveGetTeamRevenue int `json:"is_self_active_get_team_revenue" xorm:"not null default 1 comment('会员本人没有日活,没有团队奖励(1:开启 0:关闭)') TINYINT(1)"`
CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"`
UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"`
}

+ 6
- 0
db/model/one_circles_public_platoon_free_punish_with_user.go View File

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

type OneCirclesPublicPlatoonFreePunishWithUser struct {
Id int `json:"id" xorm:"not null pk autoincr INT(11)"`
Uid int `json:"uid" xorm:"not null default 0 comment('用户id') INT(11)"`
}

+ 7
- 0
db/model/one_circles_public_platoon_records_punish_with_user.go View File

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

type OneCirclesPublicPlatoonRecordsPunishWithUser struct {
Id int `json:"id" xorm:"not null pk autoincr INT(11)"`
Uid int `json:"uid" xorm:"not null default 0 comment('用户id') INT(11)"`
Date string `json:"date" xorm:"default '0000-00-00' comment('处罚日期') CHAR(50)"`
}

+ 52
- 0
db/model/one_circles_public_platoon_user_relation.go View File

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

type OneCirclesPublicPlatoonUserRelation struct {
Id int `json:"id" xorm:"not null pk autoincr INT(11)"`
Uid int `json:"uid" xorm:"not null default 0 comment('用户id(若为-1,则代表等待新用户填充)') index INT(11)"`
RecommendUid int `json:"recommend_uid" xorm:"not null default 0 comment('推荐人id') INT(11)"`
FatherUid string `json:"father_uid" xorm:"not null default '' comment('父级uid(123456-563464-438384)') index VARCHAR(100)"`
FatherUid1 int `json:"father_uid1" xorm:"not null default 0 comment('父级uid_1') INT(11)"`
FatherUid2 int `json:"father_uid2" xorm:"not null default 0 comment('父级uid_2') INT(11)"`
FatherUid3 int `json:"father_uid3" xorm:"not null default 0 comment('父级uid_3') INT(11)"`
FatherUid4 int `json:"father_uid4" xorm:"not null default 0 comment('父级uid_4') INT(11)"`
FatherUid5 int `json:"father_uid5" xorm:"not null default 0 comment('父级uid_5') INT(11)"`
FatherUid6 int `json:"father_uid6" xorm:"not null default 0 comment('父级uid_6') INT(11)"`
FatherUid7 int `json:"father_uid7" xorm:"not null default 0 comment('父级uid_7') INT(11)"`
FatherUid8 int `json:"father_uid8" xorm:"not null default 0 comment('父级uid_8') INT(11)"`
FatherUid9 int `json:"father_uid9" xorm:"not null default 0 comment('父级uid_9') INT(11)"`
Pid1 int `json:"pid1" xorm:"not null default 0 comment('父级id_1') INT(11)"`
Pid2 int `json:"pid2" xorm:"not null default 0 comment('父级id_2') INT(11)"`
Pid3 int `json:"pid3" xorm:"not null default 0 comment('父级id_3') INT(11)"`
Pid4 int `json:"pid4" xorm:"not null default 0 comment('父级id_4') INT(11)"`
Pid5 int `json:"pid5" xorm:"not null default 0 comment('父级id_5') INT(11)"`
Pid6 int `json:"pid6" xorm:"not null default 0 comment('父级id_6') INT(11)"`
Pid7 int `json:"pid7" xorm:"not null default 0 comment('父级id_7') INT(11)"`
Pid8 int `json:"pid8" xorm:"not null default 0 comment('父级id_8') INT(11)"`
Pid9 int `json:"pid9" xorm:"not null default 0 comment('父级id_9') INT(11)"`
Position int `json:"position" xorm:"not null default 1 comment('位置(以自己为创始人)') INT(11)"`
Position1 int `json:"position1" xorm:"not null default 0 comment('位置_1(以pid1为创始人中网的位置)') INT(11)"`
Position2 int `json:"position2" xorm:"not null default 0 comment('位置_2') INT(11)"`
Position3 int `json:"position3" xorm:"not null default 0 comment('位置_3') INT(11)"`
Position4 int `json:"position4" xorm:"not null default 0 comment('位置_4') INT(11)"`
Position5 int `json:"position5" xorm:"not null default 0 comment('位置_5') INT(11)"`
Position6 int `json:"position6" xorm:"not null default 0 comment('位置_6') INT(11)"`
Position7 int `json:"position7" xorm:"not null default 0 comment('位置_7') INT(11)"`
Position8 int `json:"position8" xorm:"not null default 0 comment('位置_8') INT(11)"`
Position9 int `json:"position9" xorm:"not null default 0 comment('位置_9') INT(11)"`
Level int `json:"level" xorm:"not null default 1 comment('等级(以自己为创始人)') INT(11)"`
Level1 int `json:"level1" xorm:"not null default 0 comment('等级_1(以pid1为创始人中网的等级)') INT(11)"`
Level2 int `json:"level2" xorm:"not null default 0 comment('等级_2') INT(11)"`
Level3 int `json:"level3" xorm:"not null default 0 comment('等级_3') INT(11)"`
Level4 int `json:"level4" xorm:"not null default 0 comment('等级_4') INT(11)"`
Level5 int `json:"level5" xorm:"not null default 0 comment('等级_5') INT(11)"`
Level6 int `json:"level6" xorm:"not null default 0 comment('等级_6') INT(11)"`
Level7 int `json:"level7" xorm:"not null default 0 comment('等级_7') INT(11)"`
Level8 int `json:"level8" xorm:"not null default 0 comment('等级_8') INT(11)"`
Level9 int `json:"level9" xorm:"default 0 comment('等级_9') INT(11)"`
LevelTotal int `json:"level_total" xorm:"not null default 1 comment('等级(整个系统)') INT(11)"`
JoinAt string `json:"join_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('加入公排时间') DATETIME"`
HasSonNum int `json:"has_son_num" xorm:"not null default 0 comment('拥有直属下级数量') TINYINT(2)"`
IsAllowPunish int `json:"is_allow_punish" xorm:"not null default 1 comment('是否允许处罚(1:允许 2:不允许)') TINYINT(1)"`
CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"`
UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"`
}

+ 9
- 0
db/model/one_circles_star_level_dividends_records.go View File

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

type OneCirclesStarLevelDividendsRecords struct {
Id int64 `json:"id" xorm:"pk default 0 BIGINT(20)"`
Amount string `json:"amount" xorm:"not null default 0.00000000 comment('分红值') DECIMAL(20,8)"`
AlreadyDividendsAmount string `json:"already_dividends_amount" xorm:"not null default 0.00000000 comment('已分红值') DECIMAL(20,8)"`
NotDividendsAmount string `json:"not_dividends_amount" xorm:"not null default 0.00000000 comment('未分红值') DECIMAL(20,8)"`
Date string `json:"date" xorm:"not null default '0000-00-00' comment('日期') CHAR(50)"`
}

+ 7
- 0
db/model/one_circles_user_activity.go View File

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

type OneCirclesUserActivity struct {
Id int64 `json:"id" xorm:"pk autoincr BIGINT(20)"`
Uid int `json:"uid" xorm:"not null default 0 comment('用户id') INT(11)"`
Date string `json:"date" xorm:"not null default '0000-00-00' comment('日期') CHAR(50)"`
}

+ 18
- 0
db/model/one_circles_user_public_platoon_system_punish_records.go View File

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

import (
"time"
)

type OneCirclesUserPublicPlatoonSystemPunishRecords struct {
Id int64 `json:"id" xorm:"pk autoincr BIGINT(20)"`
Uid int `json:"uid" xorm:"not null comment('用户id') index INT(11)"`
OldPostion int `json:"old_postion" xorm:"not null default 0 comment('位置(旧)') INT(11)"`
NewPostion int `json:"new_postion" xorm:"not null default 0 comment('位置(新)') INT(11)"`
Date string `json:"date" xorm:"not null default '' comment('日期(0000-00)') VARCHAR(50)"`
Title string `json:"title" xorm:"not null default '' comment('标题') VARCHAR(100)"`
Reason string `json:"reason" xorm:"not null default '' comment('原因') VARCHAR(255)"`
Type int `json:"type" xorm:"not null default 1 comment('类型(1:大公排 2:小公排)') TINYINT(1)"`
CreateAt time.Time `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"`
UpdateAt time.Time `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"`
}

+ 14
- 0
db/model/one_circles_user_watch_records.go View File

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

import (
"time"
)

type OneCirclesUserWatchRecords struct {
Id int64 `json:"id" xorm:"pk autoincr BIGINT(20)"`
Uid int `json:"uid" xorm:"not null default 0 comment('用户id') INT(11)"`
NextWatchAdDate time.Time `json:"next_watch_ad_date" xorm:"not null default 'CURRENT_TIMESTAMP' comment('下一轮观看视屏时间') DATETIME"`
ResidueWatchAdNum int `json:"residue_watch_ad_num" xorm:"not null default 0 comment('剩余观看视屏数') INT(11)"`
CreateAt time.Time `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"`
UpdateAt time.Time `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"`
}

+ 17
- 14
db/model/subsidy_base.go View File

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

type SubsidyBase struct {
Id int `json:"id" xorm:"not null pk autoincr INT(11)"`
IsOpen int `json:"is_open" xorm:"default 0 comment('功能开关:') INT(1)"`
LvList string `json:"lv_list" xorm:"comment('json [] 兑换等级:') VARCHAR(255)"`
FloatSubsidyOpen int `json:"float_subsidy_open" xorm:"default 0 comment('浮动补贴比例:') INT(1)"`
BaseSubsidyMoney string `json:"base_subsidy_money" xorm:"default 0.00 comment('补贴基础金额设置:') DECIMAL(20,2)"`
ConsumptionIntegral string `json:"consumption_integral" xorm:"not null default 0.00 comment('消费积分数量') DECIMAL(20,2)"`
ConsumptionMoney string `json:"consumption_money" xorm:"default 0.00 comment('消费补贴') DECIMAL(20,2)"`
ExperienceIntegral string `json:"experience_integral" xorm:"default 0.00 comment('体验积分数量') DECIMAL(20,2)"`
ExperienceMoney string `json:"experience_money" xorm:"default 0.00 comment('体验补贴') DECIMAL(20,2)"`
ConsumptionDay int `json:"consumption_day" xorm:"default 0 comment('消费补贴兑换后第X天') INT(11)"`
ExperienceDay int `json:"experience_day" xorm:"comment('体贴补贴兑换后第X天') VARCHAR(255)"`
SettleTime string `json:"settle_time" xorm:"comment('每天 XX:xx') VARCHAR(255)"`
HolidaySettleOpen int `json:"holiday_settle_open" xorm:"default 0 comment('节假日是否结算') INT(1)"`
SettlementDate string `json:"settlement_date" xorm:"not null default '0000-00' comment('结算日期(0000-00)') CHAR(50)"`
Id int `json:"id" xorm:"not null pk autoincr INT(11)"`
IsOpen int `json:"is_open" xorm:"default 0 comment('功能开关:') INT(1)"`
LvId string `json:"lv_id" xorm:"comment('json [] 兑换等级:') VARCHAR(255)"`
FloatSubsidyOpen int `json:"float_subsidy_open" xorm:"default 0 comment('浮动补贴比例:') INT(1)"`
FloatSubsidyBili int `json:"float_subsidy_bili" xorm:"default 0 comment('浮动补贴比例:') INT(11)"`
BaseSubsidyMoney string `json:"base_subsidy_money" xorm:"default 0.00 comment('补贴基础金额设置:') DECIMAL(20,2)"`
ConsumptionIntegral string `json:"consumption_integral" xorm:"not null default 0.00 comment('消费积分数量') DECIMAL(20,2)"`
ConsumptionMoney string `json:"consumption_money" xorm:"default 0.00 comment('消费补贴') DECIMAL(20,2)"`
ConsumptionTotalMoney string `json:"consumption_total_money" xorm:"default 0.00 comment('资金池 消费补贴(元)') DECIMAL(20,2)"`
ExperienceIntegral string `json:"experience_integral" xorm:"default 0.00 comment('体验积分数量') DECIMAL(20,2)"`
ExperienceMoney string `json:"experience_money" xorm:"default 0.00 comment('体验补贴') DECIMAL(20,2)"`
ExperienceTotalMoney string `json:"experience_total_money" xorm:"default 0.00 comment('资金池 体验补贴(元)') DECIMAL(20,2)"`
ConsumptionDay int `json:"consumption_day" xorm:"default 0 comment('消费补贴兑换后第X天') INT(11)"`
ExperienceDay int `json:"experience_day" xorm:"comment('体贴补贴兑换后第X天') VARCHAR(255)"`
SettleTime string `json:"settle_time" xorm:"comment('每天 XX:xx') VARCHAR(255)"`
HolidaySettleOpen int `json:"holiday_settle_open" xorm:"default 0 comment('节假日是否结算') INT(1)"`
SettlementDate string `json:"settlement_date" xorm:"not null default '0000-00' comment('结算日期(0000-00)') CHAR(50)"`
}

+ 1
- 0
db/model/subsidy_with_user.go View File

@@ -11,4 +11,5 @@ type SubsidyWithUser struct {
Date string `json:"date" xorm:"not null default '0000-00-00' comment('购入日期') CHAR(50)"`
CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"`
UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"`
IsCanSubsidy int `json:"is_can_subsidy" xorm:"not null default 1 comment('()') INT(1)"`
}

+ 8
- 4
db/model/subsidy_with_user_flow.go View File

@@ -3,8 +3,12 @@ package model
type SubsidyWithUserFlow struct {
Id int `json:"id" xorm:"not null pk autoincr INT(11)"`
RecordsId int `json:"records_id" xorm:"not null default 0 comment('记录id') INT(11)"`
Amount string `json:"amount" xorm:"not null default 0.00 comment('金额') DECIMAL(6,2)"`
BalanceAmount string `json:"balance_amount" xorm:"not null default 0.00 comment('余额') DECIMAL(6,2)"`
CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"`
UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"`
Amount string `json:"amount" xorm:"not null default 0.00 comment('金额') DECIMAL(20,2)"`
BalanceAmount string `json:"balance_amount" xorm:"not null default 0.00 comment('余额') DECIMAL(20,2)"`
CreateAt string `json:"create_at" xorm:"not null default CURRENT_TIMESTAMP DATETIME"`
UpdateAt string `json:"update_at" xorm:"not null default CURRENT_TIMESTAMP DATETIME"`
Kind int `json:"kind" xorm:"default 1 comment('类型(1:消费补贴 2:体验补贴)') INT(1)"`
Month int `json:"month" xorm:"default 0 comment('202312') INT(11)"`
Uid int `json:"uid" xorm:"default 0 INT(11)"`
Date string `json:"date" xorm:"comment('2023-12-01') VARCHAR(255)"`
}

+ 9
- 0
db/model/subsidy_with_user_month.go View File

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

type SubsidyWithUserMonth struct {
Id int `json:"id" xorm:"not null pk autoincr INT(11)"`
Uid int `json:"uid" xorm:"default 0 INT(11)"`
Date string `json:"date" xorm:"comment('2023-12') VARCHAR(255)"`
ConsumeAmount string `json:"consume_amount" xorm:"default 0.00 DECIMAL(20,2)"`
ExperienceAmount string `json:"experience_amount" xorm:"default 0.00 DECIMAL(20,2)"`
}

+ 20
- 0
db/model/user_public_platoon_double_network_relation.go View File

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

import (
"time"
)

type UserPublicPlatoonDoubleNetworkRelation struct {
Id int `json:"id" xorm:"not null pk autoincr INT(11)"`
Uid int `json:"uid" xorm:"not null default 0 comment('用户id(若为-1,则代表等待新用户填充)') index INT(11)"`
FatherUid string `json:"father_uid" xorm:"not null default '' comment('父级id(123456-563464-438384)') index VARCHAR(100)"`
Pid int `json:"pid" xorm:"not null default 0 comment('父级id') INT(11)"`
RecommendUid int `json:"recommend_uid" xorm:"not null default 0 comment('推荐人id') INT(11)"`
Level int `json:"level" xorm:"not null default 1 comment('等级(整个系统)') INT(11)"`
Position int `json:"position" xorm:"not null default 1 comment('位置') unique INT(11)"`
UniqueIdentifier string `json:"unique_identifier" xorm:"not null default '' comment('唯一标识符(父级id-uid-等级-位置)') unique CHAR(100)"`
ReturnCommissionNum int `json:"return_commission_num" xorm:"not null default 0 comment('返佣次数') INT(11)"`
JoinAt time.Time `json:"join_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('加入公排时间') DATETIME"`
CreateAt time.Time `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"`
UpdateAt time.Time `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"`
}

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

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

import (
"time"
)

type UserPublicPlatoonDoubleNetworkSetting struct {
Id int `json:"id" xorm:"not null pk autoincr INT(11)"`
IsOpen int `json:"is_open" xorm:"not null default 0 comment('是否开启(0:关闭 1:开启)') TINYINT(1)"`
SeveralTimes int `json:"several_times" xorm:"not null default 0 comment('几乘') TINYINT(3)"`
SeveralRows int `json:"several_rows" xorm:"not null default 0 comment('几排') TINYINT(3)"`
OriginatorUid int `json:"originator_uid" xorm:"not null default -1 comment('创始人uid') INT(11)"`
LastSettlementDate string `json:"last_settlement_date" xorm:"not null default '0000-00-00' comment('上一次结算日期') CHAR(50)"`
SettlementDate string `json:"settlement_date" xorm:"not null default '0000-00-00' comment('结算日期') CHAR(50)"`
CoinId int `json:"coin_id" xorm:"not null default 0 comment('虚拟币id(作用于成长值)') INT(11)"`
Ext string `json:"ext" xorm:"comment('拓展字段(json存储)') TEXT"`
CreateAt time.Time `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"`
UpdateAt time.Time `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"`
}

+ 12
- 0
db/model/user_public_platoon_double_network_user_coin_record.go View File

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

type UserPublicPlatoonDoubleNetworkUserCoinRecord struct {
Id int `json:"id" xorm:"not null pk autoincr INT(11)"`
Uid int `json:"uid" xorm:"not null default 0 comment('uid') INT(11)"`
RecommendUid int `json:"recommend_uid" xorm:"not null default 0 comment('推荐人uid') INT(11)"`
LastAmount string `json:"last_amount" xorm:"not null default 0.0000 comment('上次金额') DECIMAL(10,4)"`
Amount string `json:"amount" xorm:"not null default 0.0000 comment('当前金额') DECIMAL(10,4)"`
CoinId int `json:"coin_id" xorm:"not null default 0 comment('虚拟币id(作用于成长值)') INT(11)"`
CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"`
UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"`
}

+ 6
- 0
enum/fin_user_flow.go View File

@@ -10,6 +10,12 @@ func FinUserFlowOrderActionString(kind int) string {
return "consume_subsidy"
case md.ExperienceSubsidyOrdActionForFinUserFlow:
return "experience_subsidy"
case md.GreenEnergyExchangeForBalanceForFinUserFlow:
return "green_energy_exchange_for_balance"
case md.BalanceExchangeForGreenEnergyForFinUserFlow:
return "balance_exchange_for_green_energy"
case md.GreenCoinDoubleChainExchangeForBalanceForFinUserFlow:
return "green_coin_double_chain_exchange_for_balance"
default:
return "unknown"
}


+ 1
- 0
go.mod View File

@@ -3,6 +3,7 @@ module code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git
go 1.15

require (
code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git v0.0.3 // indirect
github.com/go-redis/redis v6.15.9+incompatible
github.com/gomodule/redigo v1.8.9
github.com/jinzhu/copier v0.3.5


+ 4
- 0
go.sum View File

@@ -1,5 +1,7 @@
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git v0.0.3 h1:SPp5AswPmkDO2ML6WwGlzhIuls+/1dUfU40iOeH0dh4=
code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git v0.0.3/go.mod h1:TTcCnFn/LhBGapnutpezlW+GXkLRNPMWkziOoCsXQqY=
gitea.com/xorm/sqlfiddle v0.0.0-20180821085327-62ce714f951a h1:lSA0F4e9A2NcQSqGqTOXqu2aRi/XEQxDCBwM8yJtE6s=
gitea.com/xorm/sqlfiddle v0.0.0-20180821085327-62ce714f951a/go.mod h1:EXuID2Zs0pAQhH8yz+DNjUbjppKQzKFAn28TMYPB6IU=
gitee.com/travelliu/dm v1.8.11192/go.mod h1:DHTzyhCrM843x9VdKVbZ+GKXGRbKM2sJ4LxihRxShkE=
@@ -339,6 +341,8 @@ github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3
github.com/spf13/pflag v1.0.1/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
github.com/streadway/amqp v0.0.0-20190404075320-75d898a42a94/go.mod h1:AZpEONHx3DKn8O/DFsRAY58/XVQiIPMTMB1SddzLXVw=
github.com/streadway/amqp v0.0.0-20190827072141-edfb9018d271/go.mod h1:AZpEONHx3DKn8O/DFsRAY58/XVQiIPMTMB1SddzLXVw=
github.com/streadway/amqp v1.0.0 h1:kuuDrUJFZL1QYL9hUNuCxNObNzB0bV/ZG5jV3RWAQgo=
github.com/streadway/amqp v1.0.0/go.mod h1:AZpEONHx3DKn8O/DFsRAY58/XVQiIPMTMB1SddzLXVw=
github.com/streadway/handy v0.0.0-20190108123426-d5acb3125c2a/go.mod h1:qNTQ5P5JnDBl6z3cMAg/SywNDC5ABu5ApDIw6lUbRmI=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=


+ 1
- 1
lib/comm_plan/all.go View File

@@ -884,7 +884,7 @@ func CalVirtualCommissionMinus(a, b []*VirtualCoinCommission) (c []*VirtualCoinC
for _, coinA := range a {
for _, coinB := range b {
if coinA.Cid == coinB.Cid {
amount = coinA.Val - coinB.Val
amount = zhios_order_relate_utils.FloatFormat(coinA.Val-coinB.Val, 8)
if amount < 0 {
zeroList[coinA.Cid] = struct{}{}
amount = 0


+ 12
- 11
lib/comm_plan/init.go View File

@@ -3,17 +3,18 @@ package comm_plan
import "xorm.io/xorm"

var Fn = map[string]func(opt *PlanOpt, totalAmt, integralTotalAmt float64, userList *LvUser, pvd string, sysFee float64, integralSysFee float64, level, levelWeight int, eg *xorm.Engine) error{
"lv_all": CalcAll,
"niubei_commission": NiuBeiCalcAll,
"niubei_amount": NiuBeiCalcAll,
"lv_self": CalcSelf,
"lv_subsidy": CalcAll,
"lv_price": CalcAll,
"lv_price_public_platoon": CalcAll,
"lv_winery": CalcWinery,
"lv_winery_adv": CalcAdv,
"lv_price_other": CalcOther,
"lv_ds_check": CalcDsCheck,
"lv_all": CalcAll,
"niubei_commission": NiuBeiCalcAll,
"niubei_amount": NiuBeiCalcAll,
"lv_self": CalcSelf,
"lv_subsidy": CalcAll,
"lv_price": CalcAll,
"lv_price_public_platoon": CalcAll,
"lv_commission_public_platoon": CalcAll,
"lv_winery": CalcWinery,
"lv_winery_adv": CalcAdv,
"lv_price_other": CalcOther,
"lv_ds_check": CalcDsCheck,
}

type NiuBeiIntegralReleaseO2oRatio struct {


+ 40
- 1
md/block_star_chain.go View File

@@ -58,6 +58,25 @@ const (
NiuBeiCoinByReleaseCouponDestroyConsumeCoinNumTitleForUserVirtualCoinFlow = "释放抵扣劵数量-消耗消费积分数量"
NiuBeiCoinByReleaseOptionCoinNumTitleForUserVirtualCoinFlow = "牛贝积分-释放期权积分"
NiuBeiCoinByReleaseOptionDestroyConsumeCoinNumTitleForUserVirtualCoinFlow = "释放期权积分数量-消耗消费积分数量"

OneCirclesGreenEnergySignInSettlementPersonalReward = "签到奖励"
OneCirclesGreenEnergySignInSettlementTeamReward = "团队加速奖励"
OneCirclesWatchAdRewardPersonalActiveCoin = "浏览视频奖励"
OneCirclesWatchAdRewardTeamActiveCoin = "九维公排奖励"
OneCirclesBalanceExchangeForGreenEnergy = "账户余额兑换"
OneCirclesGreenEnergyExchangeForBalance = "兑换账户余额"
OneCirclesPersonalActiveCoinExchangeGreenEnergy = "B活跃积分兑换"
OneCirclesTeamActiveCoinExchangeGreenEnergy = "T活跃积分兑换"
OneCirclesSettlementGreenEnergyExchangeGreenEnergy = "绿色能量释放"
OneCirclesWelfareOrdersExchangeGreenEnergy = "福利订单兑换绿色能量"
OneCirclesConsumeOrdersExchangeGreenEnergy = "消费订单兑换绿色能量"
OneCirclesPersonalActiveCoinExchangeToBeGreenEnergy = "B兑换绿色能量"
OneCirclesTeamActiveCoinExchangeToBeGreenEnergy = "T兑换绿色能量"
OneCirclesSettlementGreenEnergyExchangeTobeGreenEnergy = "绿色能量释放"
OneCirclesSettlementStarLevelDividends = "绿色能量分红"

GreenCoinDoubleChainExchangeByCoin1 = "绿色积分双链兑换账户余额-减少绿色积分"
GreenCoinDoubleChainExchangeByCoin2 = "绿色积分双链兑换账户余额-减少贡献积分"
)

const (
@@ -114,9 +133,29 @@ const (
NiuBeiCoinByReleaseOptionDestroyConsumeCoinNumTransferTypeForUserVirtualCoinFlow = 150 //释放期权积分数量-消耗消费积分数量
NiuBeiCoinByExtendForUserVirtualCoinFlow = 151 //直推奖励
NiuBeiCoinByTeamForUserVirtualCoinFlow = 152 //团队奖励

OneCirclesGreenEnergySignInSettlementPersonalRewardForUserVirtualCoinFlow = 155 //签到奖励
OneCirclesGreenEnergySignInSettlementTeamRewardForUserVirtualCoinFlow = 156 //团队加速奖励
OneCirclesWatchAdRewardPersonalActiveCoinForUserVirtualCoinFlow = 156 //浏览视频奖励
OneCirclesWatchAdRewardTeamActiveCoinForUserVirtualCoinFlow = 157 //九维公排奖励
OneCirclesBalanceExchangeForGreenEnergyForUserVirtualCoinFlow = 158 //账户余额兑换
OneCirclesGreenEnergyExchangeForBalanceForUserVirtualCoinFlow = 159 //兑换账户余额
OneCirclesPersonalActiveCoinExchangeGreenEnergyForUserVirtualCoinFlow = 160 //B活跃积分兑换
OneCirclesTeamActiveCoinExchangeGreenEnergyForUserVirtualCoinFlow = 161 //T活跃积分兑换
OneCirclesSettlementGreenEnergyExchangeGreenEnergyForUserVirtualCoinFlow = 162 //绿色能量释放
OneCirclesWelfareOrdersExchangeGreenEnergyForUserVirtualCoinFlow = 163 //福利订单兑换绿色能量
OneCirclesConsumeOrdersExchangeGreenEnergyForUserVirtualCoinFlow = 164 //消费订单兑换绿色能量
OneCirclesPersonalActiveCoinExchangeToBeGreenEnergyForUserVirtualCoinFlow = 165 //B兑换绿色能量
OneCirclesTeamActiveCoinExchangeToBeGreenEnergyForUserVirtualCoinFlow = 166 //T兑换绿色能量
OneCirclesSettlementGreenEnergyExchangeTobeGreenEnergyForUserVirtualCoinFlow = 167 //绿色能量释放
OneCirclesSettlementStarLevelDividendsForUserVirtualCoinFlow = 168 //结算星级分红-得到结算绿色能量

GreenCoinDoubleChainExchangeByCoin1ForForUserVirtualCoinFlow = 169 //绿色积分双链兑换账户余额-减少绿色积分
GreenCoinDoubleChainExchangeByCoin2ForForUserVirtualCoinFlow = 170 //绿色积分双链兑换账户余额-减少贡献积分

)

const DealUserCoinRequestIdPrefix = "%s:block_star_chain_deal_user_coin:%d:uid:%d"
const DealUserCoinRequestIdPrefix = "%s:deal_user_coin:%d:uid:%d"
const DealUserCoinForGreenRequestIdPrefix = "%s:block_star_chain_deal_user_coin_for_green:%d:uid:%d"
const DealConsumeIntegralRequestIdPrefix = "consume_integral:%s:uid:%d"



+ 12
- 5
md/fin_user_flow.go View File

@@ -11,10 +11,13 @@ const (
)

const (
IntegralReleaseServiceRevenueTitleForFinUserFlow = "积分释放-服务收益"
IntegralReleaseServiceRevenueRefundTitleForFinUserFlow = "订单退款-服务收益扣除"
ConsumeSubsidyTitleForFinUserFlow = "消费补贴-收益"
ExperienceSubsidyTitleForFinUserFlow = "体验补贴-收益"
IntegralReleaseServiceRevenueTitleForFinUserFlow = "积分释放-服务收益"
IntegralReleaseServiceRevenueRefundTitleForFinUserFlow = "订单退款-服务收益扣除"
ConsumeSubsidyTitleForFinUserFlow = "消费补贴-收益"
ExperienceSubsidyTitleForFinUserFlow = "体验补贴-收益"
GreenEnergyExchangeForBalanceTitleForFinUserFlow = "兑换账户余额"
BalanceExchangeForGreenEnergyTitleForFinUserFlow = "账户余额兑换"
GreenCoinDoubleChainExchangeForBalanceTitleForFinUserFlow = "绿色积分双链兑换账户余额"
)

const (
@@ -22,10 +25,13 @@ const (
IntegralReleaseServiceRevenueOrderRefundTypeForFinUserFlow = 51 // 积分释放-服务收益退款
ConsumeSubsidyOrdActionForFinUserFlow = 110 // 消费补贴-收益
ExperienceSubsidyOrdActionForFinUserFlow = 111 // 体验补贴-收益
GreenEnergyExchangeForBalanceForFinUserFlow = 112 // 兑换账户余额
BalanceExchangeForGreenEnergyForFinUserFlow = 113 // 账户余额兑换
GreenCoinDoubleChainExchangeForBalanceForFinUserFlow = 114 // 绿色积分双链兑换账户余额
)

const DealUserAmountRequestIdPrefix = "%s:deal_user_amount:%d"
const UserAmountRedisKey = "%s:user_amount:%d"
const UserAmountRedisKey = "%s:rule_user_amount:%d"

type DealIntegralReleaseInterpositionUserAmountReq struct {
Kind string `json:"kind"`
@@ -46,4 +52,5 @@ type DealUserAmount struct {
OrdId string `json:"ord_id"`
Uid int `json:"uid"`
Amount float64 `json:"amount"`
Num string `json:"num"`
}

+ 13
- 0
md/mq.go View File

@@ -0,0 +1,13 @@
package md

const OneCirclesExchange = "one.circles"

const (
OneCirclesRoutKeyForSignIn = "sign_in" // 签到
)

type OneCirclesStructForSignIn struct {
MasterId string `json:"master_id"`
Uid int `json:"uid"`
Id int64 `json:"id"`
}

+ 6
- 0
md/one_circles_public_platoon_user_relation_commission.go View File

@@ -0,0 +1,6 @@
package md

type AddOneCirclesPublicPlatoonUserRelationCommissionReq struct {
Uid string `json:"uid"`
RecommendUid string `json:"recommend_uid"` //推荐人uid
}

+ 25
- 0
md/public_platoon_double_network_relate_commission.go View File

@@ -0,0 +1,25 @@
package md

// 公排结构
type DoubleNetworkLvGrade struct {
Lv int `json:"lv"` // 会员级别
LvName string `json:"lv_name"` // 会员名称
ReturnType []string `json:"return_type"` //返利类型
CommonWealthSystem map[string]string `json:"common_wealth_system"` //共富制度比例
SelfRateList map[string]string `json:"self_rate_list"` // 自购比例
DirectPush map[string]string `json:"direct_push"` // 直推奖励比例
}

type PublicPlatoonDoubleNetworkRelateCommissionReq struct {
Pvd string `json:"pvd"` //平台供应商 (taobao/jd/pdd/mall_goods ...)
Uid string `json:"uid"`
UserLevel string `json:"user_level"` //用户等级
PendingAmount string `json:"pending_amount"` //待处理金额
Oid string `json:"oid"` //订单id
PendingIntegral string `json:"pending_integral"` //待处理金额
}

type AddPublicPlatoonDoubleNetworkDoubleNetworkRelateCommissionReq struct {
Uid string `json:"uid"`
RecommendUid string `json:"recommend_uid"` //推荐人uid
}

+ 7
- 6
md/public_platoon_relate_commission.go View File

@@ -2,12 +2,13 @@ package md

// 公排结构
type LvGrade struct {
Lv int `json:"lv"` // 会员级别
LvName string `json:"lv_name"` // 会员名称
ReturnType []string `json:"return_type"` //返利类型
CommonWealthSystem map[string]string `json:"common_wealth_system"` //共富制度比例
SelfRateList map[string]string `json:"self_rate_list"` // 自购比例
DirectPush map[string]string `json:"direct_push"` // 直推奖励比例
Lv int `json:"lv"` // 会员级别
LvName string `json:"lv_name"` // 会员名称
ReturnType []string `json:"return_type"` //返利类型
CommonWealthSystem map[string]string `json:"common_wealth_system"` //共富制度比例
SelfRateList map[string]string `json:"self_rate_list"` // 自购比例
DirectPush map[string]string `json:"direct_push"` // 直推奖励比例
UserLvUpPublicPlatoonList []interface{} `json:"user_lv_up_public_platoon_list"` //会员费分销补贴相应方式的列表
}

type PublicPlatoonRelateCommissionReq struct {


+ 1
- 0
md/regional_agent.go View File

@@ -24,6 +24,7 @@ type InsertRegionalAgentOrdBelongData struct {
ProvinceId string `json:"province_id"`
CityId string `json:"city_id"`
CountyId string `json:"county_id"`
RegionRate float64 `json:"region_rate"`
SiteId string `json:"site_id"`
BelongType string `json:"belong_type"`
}


+ 0
- 77
rule/block_star_chain_settlement.go View File

@@ -13,7 +13,6 @@ import (
"errors"
"fmt"
"github.com/shopspring/decimal"
"strconv"
"time"
"xorm.io/xorm"
)
@@ -821,82 +820,6 @@ func DealDestroyCoin(session *xorm.Session, kind int, amount float64, title stri
return nil
}

// DealUserCoin 处理给用户虚拟币积分
func DealUserCoin(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
}

// DealLotteryDraw 处理抽奖
func DealLotteryDraw(session *xorm.Session, req md.DealLotteryDrawReq) (err error) {
defer func() {


+ 174
- 54
rule/consume_integral_settlement.go View File

@@ -25,7 +25,7 @@ func InitForConsumeIntegral(redisAddr string) (err error) {
return
}

const PessimismLockKeyForConsumeIntegral = "daily_settlement_consume_integral_lock_key"
const PessimismLockKeyForConsumeIntegral = "daily_settlement_consume_integral_lock_key:%s"
const PessimismLockValueForConsumeIntegral = "running"

// DailySettlementBlockConsumeIntegral 每日结算“消费积分”
@@ -34,6 +34,7 @@ func DailySettlementBlockConsumeIntegral(engine *xorm.Engine, mid string, isTask
defer func() {
session.Close()
if err := recover(); err != nil {

_ = zhios_order_relate_logx.Error(err)
}
}()
@@ -48,26 +49,31 @@ func DailySettlementBlockConsumeIntegral(engine *xorm.Engine, mid string, isTask
})

fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>", now.Hour())
settleTime, err := time.ParseInLocation("2006-01-02 15:04:05", today+subsidyBase.SettleTime, time.Local)
settleTime, err := time.ParseInLocation("2006-01-02 15:04:05", today+" "+subsidyBase.SettleTime+":00", time.Local)
if err != nil {
session.Rollback()
return
}
if isTask && (now.Hour() > 8) && now.After(settleTime) {
if isTask && (now.Hour() > 8 || now.Before(settleTime)) {
session.Rollback()
//TODO::结算时间 ~ 凌晨 8 点运行
return errors.New("非运行时间")
}

if isTask && zhios_order_relate_utils.InArr(now.Weekday().String(), []string{"Sunday", "Saturday"}) && subsidyBase.HolidaySettleOpen != 1 {
session.Rollback()
return errors.New("周末不运行")
}
if err != nil {
_ = session.Rollback()
return err
}
if subsidyBase.SettlementDate == today {
if isTask && subsidyBase.SettlementDate == today {
_ = session.Rollback()
return errors.New("今日“消费计费”已结算")
}
key := fmt.Sprintf(PessimismLockKeyForConsumeIntegral, mid)
//TODO::增加“悲观锁”防止串行
getString, _ := cache.GetString(PessimismLockKeyForConsumeIntegral)
getString, _ := cache.GetString(key)
//if err != nil {
// return err
//}
@@ -75,57 +81,92 @@ func DailySettlementBlockConsumeIntegral(engine *xorm.Engine, mid string, isTask
fmt.Println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", "上一次结算未执行完")
return errors.New("上一次结算未执行完")
}
cache.SetEx(PessimismLockKeyForConsumeIntegral, PessimismLockValueForConsumeIntegral, 3600*8) //8小时
cache.SetEx(key, PessimismLockValueForConsumeIntegral, 3600*8) //8小时

var consumeValueTotal, experienceValueTotal = decimal.NewFromInt(0), decimal.NewFromInt(0)
var consumeValue, experienceValue float64
//1、统计当前拥有多少份消费补贴
startAt := time.Now().Add(time.Duration(subsidyBase.ConsumptionDay) * -24 * time.Hour).Format("2006-01-02") //起始时间
var subsidyWithUserForConsumeList []model.SubsidyWithUser
hasConsumeTotal, err := session.Where("date <= ?", startAt).And("kind = ?", 1).FindAndCount(&subsidyWithUserForConsumeList)
if err != nil {
return
}
consumeValue, err := calcNowEverydayConsumeIntegral(subsidyBase, hasConsumeTotal)
hasConsumeTotal, err := session.Where("date <= ?", startAt).And("kind = ? and is_can_subsidy=?", 1, 1).FindAndCount(&subsidyWithUserForConsumeList)
if err != nil {
_ = session.Rollback()
return err
}

for _, v := range subsidyWithUserForConsumeList {
consumeValueTotal = consumeValueTotal.Add(decimal.NewFromFloat(consumeValue))
err1 := DealUserConsumeIntegral(session, &v, consumeValue, mid)
if err1 != nil {
return
}
var consumeTotalMap = make(map[int]decimal.Decimal)
var consumeTotalCountMap = make(map[int]int)
if hasConsumeTotal > 0 {
consumeValue, err = calcNowEverydayConsumeIntegral(subsidyBase, hasConsumeTotal)
if err != nil {
_ = session.Rollback()
return err1
return err
}
}

for _, v := range subsidyWithUserForConsumeList {
consumeTotalMap[v.Uid] = consumeTotalMap[v.Uid].Add(decimal.NewFromFloat(consumeValue))
consumeTotalCountMap[v.Uid]++
consumeValueTotal = consumeValueTotal.Add(decimal.NewFromFloat(consumeValue))
err1 := DealUserConsumeIntegral(session, &v, consumeValue, mid)
if err1 != nil {
_ = session.Rollback()
return err1
}
}
}
//加余额流水
if len(consumeTotalMap) > 0 {
for k, v := range consumeTotalMap {
err1 := DealUserConsumeAmountFlow(session, k, zhios_order_relate_utils.StrToFloat64(v.String()), mid, zhios_order_relate_utils.IntToStr(consumeTotalCountMap[k]))
if err1 != nil {
_ = session.Rollback()
return err1
}
}
}
//2、统计当前拥有多少份体验补贴
var subsidyWithUserForExperienceList []model.SubsidyWithUser
hasExperienceTotal, err := session.Where("date <= ?", startAt).And("kind = ?", 2).FindAndCount(&subsidyWithUserForExperienceList)
if err != nil {
return
}
experienceValue, err := calcNowEverydayExperienceIntegral(subsidyBase, hasExperienceTotal)
hasExperienceTotal, err := session.Where("date <= ?", startAt).And("kind = ? and is_can_subsidy=?", 2, 1).FindAndCount(&subsidyWithUserForExperienceList)
if err != nil {
_ = session.Rollback()
return err
return
}
for _, v := range subsidyWithUserForConsumeList {
experienceValueTotal = experienceValueTotal.Add(decimal.NewFromFloat(experienceValue))
err1 := DealUserExperienceIntegral(session, &v, experienceValue, mid)
if err1 != nil {
var experienceTotalMap = make(map[int]decimal.Decimal)
var experienceTotalCountMap = make(map[int]int)
if hasExperienceTotal > 0 && consumeValue > 0 {
experienceValue, err = calcNowEverydayExperienceIntegral(consumeValue)
if err != nil {
_ = session.Rollback()
return err1
return err
}
for _, v := range subsidyWithUserForExperienceList {
experienceTotalCountMap[v.Uid]++
experienceTotalMap[v.Uid] = experienceTotalMap[v.Uid].Add(decimal.NewFromFloat(experienceValue))
experienceValueTotal = experienceValueTotal.Add(decimal.NewFromFloat(experienceValue))
err1 := DealUserExperienceIntegral(session, &v, experienceValue, mid)
if err1 != nil {
_ = session.Rollback()
return err1
}
}
}
//加余额流水
if len(experienceTotalMap) > 0 {
for k, v := range experienceTotalMap {
err1 := DealUserExperienceAmountFlow(session, k, zhios_order_relate_utils.StrToFloat64(v.String()), mid, zhios_order_relate_utils.IntToStr(experienceTotalCountMap[k]))
if err1 != nil {
_ = session.Rollback()
return err1
}
}
}

//3、修改 subsidy_base 中 consumption_money、experience_money
consumeTotal, _ := consumeValueTotal.Float64()
experienceTotal, _ := experienceValueTotal.Float64()
subsidyBase.ConsumptionMoney = zhios_order_relate_utils.Float64ToStr(zhios_order_relate_utils.StrToFloat64(subsidyBase.ConsumptionMoney) - consumeTotal)
subsidyBase.ExperienceMoney = zhios_order_relate_utils.Float64ToStr(zhios_order_relate_utils.StrToFloat64(subsidyBase.ExperienceMoney) - experienceTotal)
updateAffected, err := db.SubsidyBaseUpdate(session, subsidyBase.Id, subsidyBase, "consumption_money", "experience_money")
subsidyBase.ConsumptionTotalMoney = zhios_order_relate_utils.Float64ToStr(zhios_order_relate_utils.StrToFloat64(subsidyBase.ConsumptionTotalMoney) - consumeTotal)
subsidyBase.ExperienceTotalMoney = zhios_order_relate_utils.Float64ToStr(zhios_order_relate_utils.StrToFloat64(subsidyBase.ExperienceTotalMoney) - experienceTotal)
subsidyBase.SettlementDate = today
updateAffected, err := db.SubsidyBaseUpdate(session, subsidyBase.Id, subsidyBase, "consumption_total_money", "experience_total_money", "settlement_date")
if err != nil {
_ = session.Rollback()
return
@@ -142,29 +183,36 @@ func DailySettlementBlockConsumeIntegral(engine *xorm.Engine, mid string, isTask
return errors.New("事务提交失败")
}

cache.Del(PessimismLockKeyForConsumeIntegral)
cache.Del(key)
fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>消费积分结束<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<")
return nil
}

//计算当前消费积分价值(公式 "((资金池的金额 * 浮动比例) / 消费补贴总数) + 基础补贴")
func calcNowEverydayConsumeIntegral(subsidyBase *model.SubsidyBase, hasConsumeTotal int64) (value float64, err error) {
consumptionMoney, _ := decimal.NewFromString(subsidyBase.ConsumptionMoney)
consumptionMoney, _ := decimal.NewFromString(subsidyBase.ConsumptionTotalMoney)
baseSubsidyMoney, _ := decimal.NewFromString(subsidyBase.BaseSubsidyMoney)
floatSubsidyOpen := decimal.NewFromInt(int64(subsidyBase.FloatSubsidyOpen) / 10000)
if subsidyBase.FloatSubsidyOpen == 0 { //没有浮动补贴情况
subsidyBase.FloatSubsidyBili = 0
}
floatSubsidyBili := decimal.NewFromFloat(float64(subsidyBase.FloatSubsidyBili) / 10000)
consumeTotal := decimal.NewFromInt(hasConsumeTotal)
value, _ = consumptionMoney.Mul(floatSubsidyOpen).Div(consumeTotal).Add(baseSubsidyMoney).Float64()
value, _ = consumptionMoney.Mul(floatSubsidyBili).Div(consumeTotal).Add(baseSubsidyMoney).RoundFloor(2).Float64()
return
}

//计算当前体验积分价值
func calcNowEverydayExperienceIntegral(subsidyBase *model.SubsidyBase, hasExperienceTotal int64) (value float64, err error) {
//2、通过公式计算 "((资金池的金额 * 浮动比例) / 体验补贴总数) + 基础补贴"
experienceMoney, _ := decimal.NewFromString(subsidyBase.ExperienceMoney)
baseSubsidyMoney, _ := decimal.NewFromString(subsidyBase.BaseSubsidyMoney)
floatSubsidyOpen := decimal.NewFromInt(int64(subsidyBase.FloatSubsidyOpen) / 10000)
consumeTotal := decimal.NewFromInt(hasExperienceTotal)
value, _ = experienceMoney.Mul(floatSubsidyOpen).Div(consumeTotal).Add(baseSubsidyMoney).Float64()
//计算当前体验积分价值(当前消费积分价值 * 10%)
func calcNowEverydayExperienceIntegral(consumeValue float64) (value float64, err error) {
value, _ = decimal.NewFromFloat(consumeValue * 0.1).RoundFloor(2).Float64()
////2、通过公式计算 "((资金池的金额 * 浮动比例) / 体验补贴总数) + 基础补贴"
//experienceMoney, _ := decimal.NewFromString(subsidyBase.ExperienceTotalMoney)
//baseSubsidyMoney, _ := decimal.NewFromString(subsidyBase.BaseSubsidyMoney)
//if subsidyBase.FloatSubsidyOpen == 0 { //没有浮动补贴情况
// subsidyBase.FloatSubsidyBili = 0
//}
//floatSubsidyBili := decimal.NewFromFloat(float64(subsidyBase.FloatSubsidyBili) / 10000)
//consumeTotal := decimal.NewFromInt(hasExperienceTotal)
//value, _ = experienceMoney.Mul(floatSubsidyBili).Div(consumeTotal).Add(baseSubsidyMoney).RoundFloor(2).Float64()
return
}

@@ -198,6 +246,10 @@ func DealUserConsumeIntegral(session *xorm.Session, subsidyWithUser *model.Subsi
BalanceAmount: zhios_order_relate_utils.Float64ToStr(afterAmount),
CreateAt: now.Format("2006-01-02 15:04:05"),
UpdateAt: now.Format("2006-01-02 15:04:05"),
Date: now.Format("2006-01-02"),
Uid: subsidyWithUser.Uid,
Kind: subsidyWithUser.Kind,
Month: zhios_order_relate_utils.StrToInt(now.Format("200601")),
}
insertAffected, err := db.SubsidyWithUserFlowInsert(session, subsidyWitUserFlow)
if err != nil {
@@ -206,8 +258,19 @@ func DealUserConsumeIntegral(session *xorm.Session, subsidyWithUser *model.Subsi
if insertAffected <= 0 {
return errors.New("新增 subsidy_with_user_flow 记录失败")
}

//3、给用户添加余额
//3、加入每月统计
if consumeIntegralValue > 0 {
var subsidyWitUserMonth = &model.SubsidyWithUserMonth{
Uid: subsidyWithUser.Uid,
ConsumeAmount: zhios_order_relate_utils.Float64ToStr(consumeIntegralValue),
Date: now.Format("2006-01"),
}
_, err1 := db.SubsidyWithMonthInsert(session, subsidyWitUserMonth)
if err1 != nil {
return err
}
}
//4、给用户添加余额
orderType := enum.FinUserFlowOrderActionString(md.ConsumeSubsidyOrdActionForFinUserFlow)
var dealUserAmount = md.DealUserAmount{
Kind: "add",
@@ -219,7 +282,7 @@ func DealUserConsumeIntegral(session *xorm.Session, subsidyWithUser *model.Subsi
Uid: subsidyWithUser.Uid,
Amount: consumeIntegralValue,
}
err = svc.DealUserAmount(session, dealUserAmount)
err = svc.DealUserAmountNew(session, dealUserAmount)
if err != nil {
return
}
@@ -252,9 +315,13 @@ func DealUserExperienceIntegral(session *xorm.Session, subsidyWithUser *model.Su
//2、新增 subsidy_with_user_flow 记录
var subsidyWitUserFlow = &model.SubsidyWithUserFlow{
RecordsId: subsidyWithUser.Id,
Uid: subsidyWithUser.Uid,
Kind: subsidyWithUser.Kind,
Amount: zhios_order_relate_utils.Float64ToStr(experienceIntegralValue),
BalanceAmount: zhios_order_relate_utils.Float64ToStr(afterAmount),
CreateAt: now.Format("2006-01-02 15:04:05"),
Date: now.Format("2006-01-02"),
Month: zhios_order_relate_utils.StrToInt(now.Format("200601")),
UpdateAt: now.Format("2006-01-02 15:04:05"),
}
insertAffected, err := db.SubsidyWithUserFlowInsert(session, subsidyWitUserFlow)
@@ -264,8 +331,19 @@ func DealUserExperienceIntegral(session *xorm.Session, subsidyWithUser *model.Su
if insertAffected <= 0 {
return errors.New("新增 subsidy_with_user_flow 记录失败")
}

//3、给用户添加余额
//3、加入每月统计
if experienceIntegralValue > 0 {
var subsidyWitUserMonth = &model.SubsidyWithUserMonth{
Uid: subsidyWithUser.Uid,
ExperienceAmount: zhios_order_relate_utils.Float64ToStr(experienceIntegralValue),
Date: now.Format("2006-01"),
}
_, err1 := db.SubsidyWithMonthInsert(session, subsidyWitUserMonth)
if err1 != nil {
return err
}
}
//4、给用户添加余额
orderType := enum.FinUserFlowOrderActionString(md.ExperienceSubsidyOrdActionForFinUserFlow)
var dealUserAmount = md.DealUserAmount{
Kind: "add",
@@ -277,11 +355,53 @@ func DealUserExperienceIntegral(session *xorm.Session, subsidyWithUser *model.Su
Uid: subsidyWithUser.Uid,
Amount: experienceIntegralValue,
}
err = svc.DealUserAmount(session, dealUserAmount)
err = svc.DealUserAmountNew(session, dealUserAmount)
if err != nil {
return
}
return nil

}

// DealUserConsumeIntegral 处理给用户发放消费补贴奖励 流水
func DealUserConsumeAmountFlow(session *xorm.Session, uid int, consumeIntegralValue float64, mid, num string) (err error) {
//4、给用户添加余额流水
orderType := enum.FinUserFlowOrderActionString(md.ConsumeSubsidyOrdActionForFinUserFlow)
var dealUserAmount = md.DealUserAmount{
Kind: "add",
Mid: mid,
Title: md.ConsumeSubsidyTitleForFinUserFlow,
OrderType: orderType,
OrdAction: md.ConsumeSubsidyOrdActionForFinUserFlow,
Uid: uid,
Amount: consumeIntegralValue,
Num: num,
}
err = svc.DealUserAmountFlow(session, dealUserAmount)
if err != nil {
return
}
return nil
}

// DealUserExperienceIntegral 处理给用户发放体验补贴奖励
func DealUserExperienceAmountFlow(session *xorm.Session, uid int, experienceIntegralValue float64, mid, num string) (err error) {
//4、给用户添加余额
orderType := enum.FinUserFlowOrderActionString(md.ExperienceSubsidyOrdActionForFinUserFlow)
var dealUserAmount = md.DealUserAmount{
Kind: "add",
Mid: mid,
Title: md.ExperienceSubsidyTitleForFinUserFlow,
OrderType: orderType,
OrdAction: md.ExperienceSubsidyOrdActionForFinUserFlow,
Uid: uid,
Amount: experienceIntegralValue,
Num: num,
}
err = svc.DealUserAmountFlow(session, dealUserAmount)
if err != nil {
return
}
return nil

}

+ 478
- 0
rule/green_coin_double_chain_settlement.go View File

@@ -0,0 +1,478 @@
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"
"github.com/shopspring/decimal"
"time"
"xorm.io/xorm"
)

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

func DealUserGreenCoinDoubleChainIntegral(Db *xorm.Engine, uid int, ordId, masterId string) (err error) {
//1、查找 `green_coin_double_chain` 基础设置
greenCoinDoubleChain, err := db.GreenCoinDoubleChainGetOneByParams(Db, map[string]interface{}{
"key": "is_use",
"value": 1,
})
if err != nil {
return
}
if greenCoinDoubleChain == nil {
return
}

//2、判断当前会员等级
user, err := db.DbsUserFindByUid(Db, uid)
if err != nil {
return
}
if user.Level < 2 {
//TODO::暂时写死(至少是银卡会员等级才能兑换)
return
}

//3、处理“贡献积分”作用于上级
err = HandleUserGreenCoinDoubleChainIntegralByParent(Db, uid, ordId, masterId, greenCoinDoubleChain)
if err != nil {
return err
}

//4、处理“绿色积分”作用于下级
err = HandleUserGreenCoinDoubleChainIntegralBySon(Db, uid, ordId, masterId, greenCoinDoubleChain)
if err != nil {
return err
}

return
}

func HandleUserGreenCoinDoubleChainIntegralByParent(Db *xorm.Engine, uid int, ordId, masterId string, greenCoinDoubleChain *model.GreenCoinDoubleChain) (err error) {
time.Sleep(time.Millisecond * 200) //TODO::等待100毫秒
//1、查找对应直推上级用户
parentUserRelate, err := db.GetUserParentUserRelate(Db, uid)
if err != nil {
return
}
if parentUserRelate == nil {
err = errors.New("未查询到直推上级")
return
}

//2、查询对应上级的虚拟币余额
parentAmount, err := svc.GetUserCoinAmount(Db.NewSession(), masterId, greenCoinDoubleChain.Coin1, parentUserRelate.ParentUid)
if err != nil {
return
}
parentAmountValue, _ := decimal.NewFromString(parentAmount)
if parentAmountValue.LessThanOrEqual(decimal.NewFromFloat(0)) {
//TODO::上级绿色积分小于0不需要进行兑换
return
}

//3、查询上级直推的所有下级用户
sonUserRelates, err := db.DbsUserRelateByParentUid(Db, parentUserRelate.ParentUid, 1)
if err != nil {
return
}
if sonUserRelates == nil {
//未查询到直推下级
return
}
var sonUserIds []int
for _, v := range *sonUserRelates {
sonUserIds = append(sonUserIds, v.Uid)
}

users, err := db.DbsUserFindByIds(Db, sonUserIds)
if err != nil {
return
}
var userIds []int
for _, v := range *users {
if v.Level >= 2 {
//TODO::暂时写死(至少是银卡会员等级才能兑换)
userIds = append(userIds, v.Uid)
}
}

//4、查询上级直推的所有下级用户的虚拟币金额(按升序)
var sonUserVirtualWallet []model.UserVirtualAmount
Db.Where(" coin_id = ? and amount > 0", greenCoinDoubleChain.Coin2).In("uid", userIds).Asc("amount").Find(&sonUserVirtualWallet)
if err != nil {
return
}

/*
TODO::5、进行“数据变更”
*/
var amount string
var lastUid int
session := Db.NewSession()
session.Begin()
defer func() {
session.Close()
if err := recover(); err != nil {
_ = zhios_order_relate_logx.Error(err)
}
}()
for _, v := range sonUserVirtualWallet {

userAmount, _ := decimal.NewFromString(v.Amount)
if amount == "" {
amount = userAmount.String()
lastUid = v.Uid
continue
}

amountValue, _ := decimal.NewFromString(amount)
//if userAmount.LessThan(amountValue) {
// //当前用户虚拟币金额小于上一个用户虚拟币金额
// amountValue = userAmount
//}

if parentAmountValue.LessThan(amountValue) {
//TODO::上级绿色积分小于当前需要兑换积分金额
amountValue = parentAmountValue
}

//5.1、上级减少amount 绿色积分
err = DealUserCoin(session, md.DealUserCoinReq{
Kind: "sub",
Mid: masterId,
Title: md.GreenCoinDoubleChainExchangeByCoin1,
TransferType: md.GreenCoinDoubleChainExchangeByCoin1ForForUserVirtualCoinFlow,
OrdId: ordId,
CoinId: greenCoinDoubleChain.Coin1,
Uid: parentUserRelate.ParentUid,
Amount: zhios_order_relate_utils.StrToFloat64(amountValue.String()),
})
if err != nil {
session.Rollback()
break
}

//5.2、用户减少amount 贡献积分
err = DealUserCoin(session, md.DealUserCoinReq{
Kind: "sub",
Mid: masterId,
Title: md.GreenCoinDoubleChainExchangeByCoin2,
TransferType: md.GreenCoinDoubleChainExchangeByCoin2ForForUserVirtualCoinFlow,
OrdId: ordId,
CoinId: greenCoinDoubleChain.Coin2,
Uid: v.Uid,
Amount: zhios_order_relate_utils.StrToFloat64(amountValue.String()),
})
if err != nil {
session.Rollback()
break
}
//5.3、另一下级减少amount 贡献积分
err = DealUserCoin(session, md.DealUserCoinReq{
Kind: "sub",
Mid: masterId,
Title: md.GreenCoinDoubleChainExchangeByCoin2,
TransferType: md.GreenCoinDoubleChainExchangeByCoin2ForForUserVirtualCoinFlow,
OrdId: ordId,
CoinId: greenCoinDoubleChain.Coin2,
Uid: lastUid,
Amount: zhios_order_relate_utils.StrToFloat64(amountValue.String()),
})
if err != nil {
session.Rollback()
break
}
//5.4上级余额增加
var coin model.VirtualCoin
_, err = session.Where("id = ?", greenCoinDoubleChain.Coin1).Get(&coin)
if err != nil {
session.Rollback()
break
}
coinExchangeRatioValue, _ := decimal.NewFromString(coin.ExchangeRatio)
exchangeAmount, _ := amountValue.Div(coinExchangeRatioValue).Float64()
orderType := enum.FinUserFlowOrderActionString(md.GreenCoinDoubleChainExchangeForBalanceForFinUserFlow)
err = svc.DealUserAmount(session, md.DealUserAmount{
Kind: "add",
Mid: masterId,
Title: md.GreenCoinDoubleChainExchangeForBalanceTitleForFinUserFlow,
OrderType: orderType,
OrdAction: md.GreenCoinDoubleChainExchangeForBalanceForFinUserFlow,
OrdId: ordId,
Uid: parentUserRelate.ParentUid,
Amount: exchangeAmount,
Num: "",
})
if err != nil {
session.Rollback()
break
}

//6、新增 green_coin_double_chain_exchange_records 记录
afterUserCoinAmount, err := svc.GetUserCoinAmount(session, masterId, greenCoinDoubleChain.Coin1, parentUserRelate.ParentUid)
if err != nil {
session.Rollback()
break
}
afterCoinAmountContributeUser1, err := svc.GetUserCoinAmount(session, masterId, greenCoinDoubleChain.Coin2, v.Uid)
if err != nil {
session.Rollback()
break
}
afterCoinAmountContributeUser2, err := svc.GetUserCoinAmount(session, masterId, greenCoinDoubleChain.Coin2, lastUid)
if err != nil {
session.Rollback()
break
}

now := time.Now()
_, err = db.GreenCoinDoubleChainExchangeRecordsInsert(Db, &model.GreenCoinDoubleChainExchangeRecords{
Uid: parentUserRelate.ParentUid,
ContributeUid1: v.Uid,
ContributeUid2: lastUid,
CoinId1: greenCoinDoubleChain.Coin1,
CoinId2: greenCoinDoubleChain.Coin2,
Amount: amountValue.String(),
BeforeUserCoinAmount: parentAmount,
AfterUserCoinAmount: afterUserCoinAmount,
BeforeCoinAmountContributeUser1: v.Amount,
AfterCoinAmountContributeUser1: afterCoinAmountContributeUser1,
BeforeCoinAmountContributeUser2: amountValue.String(),
AfterCoinAmountContributeUser2: afterCoinAmountContributeUser2,
CreateAt: now.Format("2006-01-02 15:04:05"),
UpdateAt: now.Format("2006-01-02 15:04:05"),
})
if err != nil {
session.Rollback()
break
}

if zhios_order_relate_utils.StrToFloat64(afterUserCoinAmount) == 0 {
break
} else {
amount = afterCoinAmountContributeUser1
lastUid = v.Uid
}
if zhios_order_relate_utils.StrToFloat64(amount) == 0 {
amount = ""
}
}
session.Commit()
return
}

func HandleUserGreenCoinDoubleChainIntegralBySon(Db *xorm.Engine, uid int, ordId, masterId string, greenCoinDoubleChain *model.GreenCoinDoubleChain) (err error) {
time.Sleep(time.Millisecond * 200) //TODO::等待100毫秒
//1、查询对应上级的虚拟币余额
parentAmount, err := svc.GetUserCoinAmount(Db.NewSession(), masterId, greenCoinDoubleChain.Coin1, uid)
if err != nil {
return
}
parentAmountValue, _ := decimal.NewFromString(parentAmount)
if parentAmountValue.LessThanOrEqual(decimal.NewFromFloat(0)) {
//TODO::上级绿色积分小于0不需要进行兑换
return
}

//2、查询上级直推的所有下级用户
sonUserRelates, err := db.DbsUserRelateByParentUid(Db, uid, 1)
if err != nil {
return
}
if sonUserRelates == nil {
//未查询到直推下级
return
}
var sonUserIds []int
for _, v := range *sonUserRelates {
sonUserIds = append(sonUserIds, v.Uid)
}

users, err := db.DbsUserFindByIds(Db, sonUserIds)
if err != nil {
return
}
var userIds []int
for _, v := range *users {
if v.Level >= 2 {
//TODO::暂时写死(至少是银卡会员等级才能兑换)
userIds = append(userIds, v.Uid)
}
}

//3、查询上级直推的所有下级用户的虚拟币金额(按升序)
var sonUserVirtualWallet []model.UserVirtualAmount
Db.Where(" coin_id = ? and amount > 0 ", greenCoinDoubleChain.Coin2).In("uid", userIds).Asc("amount").Find(&sonUserVirtualWallet)
if err != nil {
return
}

/*
TODO::4、进行“数据变更”
*/
var amount string
var lastUid int
session := Db.NewSession()
session.Begin()
defer func() {
session.Close()
if err := recover(); err != nil {
_ = zhios_order_relate_logx.Error(err)
}
}()
for _, v := range sonUserVirtualWallet {

userAmount, _ := decimal.NewFromString(v.Amount)
if amount == "" {
amount = userAmount.String()
lastUid = v.Uid
continue
}

amountValue, _ := decimal.NewFromString(amount)
//if userAmount.LessThan(amountValue) {
// //当前用户虚拟币金额小于上一个用户虚拟币金额
// amountValue = userAmount
//}

if parentAmountValue.LessThan(amountValue) {
//TODO::上级绿色积分小于当前需要兑换积分金额
amountValue = parentAmountValue
}

//4.1、上级减少amount 绿色积分
err = DealUserCoin(session, md.DealUserCoinReq{
Kind: "sub",
Mid: masterId,
Title: md.GreenCoinDoubleChainExchangeByCoin1,
TransferType: md.GreenCoinDoubleChainExchangeByCoin1ForForUserVirtualCoinFlow,
OrdId: ordId,
CoinId: greenCoinDoubleChain.Coin1,
Uid: uid,
Amount: zhios_order_relate_utils.StrToFloat64(amountValue.String()),
})
if err != nil {
session.Rollback()
break
}
//4.2、用户减少amount 贡献积分
err = DealUserCoin(session, md.DealUserCoinReq{
Kind: "sub",
Mid: masterId,
Title: md.GreenCoinDoubleChainExchangeByCoin2,
TransferType: md.GreenCoinDoubleChainExchangeByCoin2ForForUserVirtualCoinFlow,
OrdId: ordId,
CoinId: greenCoinDoubleChain.Coin2,
Uid: v.Uid,
Amount: zhios_order_relate_utils.StrToFloat64(amountValue.String()),
})
if err != nil {
session.Rollback()
break
}
//4.3、另一下级减少amount 贡献积分
err = DealUserCoin(session, md.DealUserCoinReq{
Kind: "sub",
Mid: masterId,
Title: md.GreenCoinDoubleChainExchangeByCoin2,
TransferType: md.GreenCoinDoubleChainExchangeByCoin2ForForUserVirtualCoinFlow,
OrdId: ordId,
CoinId: greenCoinDoubleChain.Coin2,
Uid: lastUid,
Amount: zhios_order_relate_utils.StrToFloat64(amountValue.String()),
})
if err != nil {
session.Rollback()
break
}
//4.4上级余额增加
var coin model.VirtualCoin
_, err = session.Where("id = ?", greenCoinDoubleChain.Coin1).Get(&coin)
if err != nil {
session.Rollback()
break
}
coinExchangeRatioValue, _ := decimal.NewFromString(coin.ExchangeRatio)
exchangeAmount, _ := amountValue.Div(coinExchangeRatioValue).Float64()
orderType := enum.FinUserFlowOrderActionString(md.GreenCoinDoubleChainExchangeForBalanceForFinUserFlow)
err = svc.DealUserAmount(session, md.DealUserAmount{
Kind: "add",
Mid: masterId,
Title: md.GreenCoinDoubleChainExchangeForBalanceTitleForFinUserFlow,
OrderType: orderType,
OrdAction: md.GreenCoinDoubleChainExchangeForBalanceForFinUserFlow,
OrdId: ordId,
Uid: uid,
Amount: exchangeAmount,
Num: "",
})
if err != nil {
session.Rollback()
break
}

//5、新增 green_coin_double_chain_exchange_records 记录
afterUserCoinAmount, err := svc.GetUserCoinAmount(session, masterId, greenCoinDoubleChain.Coin1, uid)
if err != nil {
session.Rollback()
break
}
afterCoinAmountContributeUser1, err := svc.GetUserCoinAmount(session, masterId, greenCoinDoubleChain.Coin2, v.Uid)
if err != nil {
session.Rollback()
break
}
afterCoinAmountContributeUser2, err := svc.GetUserCoinAmount(session, masterId, greenCoinDoubleChain.Coin2, lastUid)
if err != nil {
session.Rollback()
break
}
now := time.Now()
_, err = db.GreenCoinDoubleChainExchangeRecordsInsert(Db, &model.GreenCoinDoubleChainExchangeRecords{
Uid: uid,
ContributeUid1: v.Uid,
ContributeUid2: lastUid,
CoinId1: greenCoinDoubleChain.Coin1,
CoinId2: greenCoinDoubleChain.Coin2,
Amount: amountValue.String(),
BeforeUserCoinAmount: parentAmount,
AfterUserCoinAmount: afterUserCoinAmount,
BeforeCoinAmountContributeUser1: v.Amount,
AfterCoinAmountContributeUser1: afterCoinAmountContributeUser1,
BeforeCoinAmountContributeUser2: amountValue.String(),
AfterCoinAmountContributeUser2: afterCoinAmountContributeUser2,
CreateAt: now.Format("2006-01-02 15:04:05"),
UpdateAt: now.Format("2006-01-02 15:04:05"),
})
if err != nil {
session.Rollback()
break
}

if zhios_order_relate_utils.StrToFloat64(afterUserCoinAmount) == 0 {
break
} else {
amount = afterCoinAmountContributeUser1
lastUid = v.Uid
}
if zhios_order_relate_utils.StrToFloat64(amount) == 0 {
amount = ""
}
}
session.Commit()
return
}

+ 94
- 0
rule/one_circles/coin_settlement.go View File

@@ -0,0 +1,94 @@
package one_circles

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/md"
md2 "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule/one_circles/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"
"errors"
"fmt"
"github.com/shopspring/decimal"
"strconv"
"time"
"xorm.io/xorm"
)

const PessimismLockKey = "daily_settlement_block_star_chain_pessimism_lock_key"
const PessimismLockValue = "running"

// DealUserCoin 处理给用户虚拟币积分
func DealUserCoin(session *xorm.Session, req md.DealUserCoinReq) (err error) {
if req.Amount < 0 {
req.Amount = 0
}
//1、分布式锁阻拦
requestIdPrefix := fmt.Sprintf(md2.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(8)

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(8).String()
} else if req.Kind == "sub" {
userVirtualCoinFlow.Direction = 2
userVirtualCoinFlow.AfterAmout = coinAmountValue.Sub(amountValue).RoundFloor(8).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 + "不足")
}
//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
}

+ 41
- 0
rule/one_circles/enum/one_circles_available_green_energy_points_flow.go View File

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

// 可用绿色能量流水-种类
type OneCirclesAvailableGreenEnergyPointsFlowKind int

const (
PersonalActivePointRedemption OneCirclesAvailableGreenEnergyPointsFlowKind = iota
SettlementOfGreenEnergyRelease
SignInReward
AccountBalanceExchange
GreenEnergyExchangeBalance
TeamActivePointRedemption
SettlementStarLevelDividends
MarketplaceMerchantNumsAutoExchangeMarketplaceMerchantFunds
MarketplaceMerchantFundsAutoExchangeMarketplaceMerchantNums
)

func (kind OneCirclesAvailableGreenEnergyPointsFlowKind) String() string {
switch kind {
case PersonalActivePointRedemption:
return "个人活跃积分兑换"
case SettlementOfGreenEnergyRelease:
return "结算绿色能量释放"
case SignInReward:
return "签到奖励"
case AccountBalanceExchange:
return "账户余额兑换"
case GreenEnergyExchangeBalance:
return "兑换账户余额"
case TeamActivePointRedemption:
return "团队活跃积分兑换"
case SettlementStarLevelDividends:
return "绿色能量分红"
case MarketplaceMerchantNumsAutoExchangeMarketplaceMerchantFunds:
return "市商数量自动兑换市商资金"
case MarketplaceMerchantFundsAutoExchangeMarketplaceMerchantNums:
return "市商资金自动兑换市商数量"
default:
return "未知状态"
}
}

+ 51
- 0
rule/one_circles/md/one_circles_green_energy.go View File

@@ -0,0 +1,51 @@
package md

type VipEquitySettingStruct struct {
VipLevelId string `json:"vip_level_id"` //会员等级id
ExchangeAccountBalanceFee string `json:"exchange_account_balance_fee"` //兑换余额手续费
DividendRatio string `json:"dividend_ratio"` //分红比例
}

type TeamRewardSettingStruct struct {
RewardDecrementValue string `json:"reward_decrement_value"` //递减百分比
RewardEndValue string `json:"reward_end_value"` //奖励结束值
MemberSelfIsOpenGetTeamReward string `json:"member_self_is_open_get_team_reward"` //会员是否活跃得到团队奖励
OneRoundDuration string `json:"one_round_duration"` //一轮持续时间
}

type SignInRewardStruct struct {
VipMemberStartNums string `json:"vip_member_start_nums"` //会员起始数量
VipMemberEndNums string `json:"vip_member_end_nums"` //会员结束数量
RewardValue string `json:"reward_value"` //奖励值
}

type PriceSettingStruct struct {
PriceHigherThanValue string `json:"price_higher_than_value"` //高于x元
MarketplaceMerchantsNumsExchangeMarketplaceMerchantsFundValue string `json:"marketplace_merchants_nums_exchange_marketplace_merchants_fund_value"` //市商数量单笔x数量自动兑换
PriceBelowValue string `json:"price_below_value"` //低于x元
MarketplaceMerchantsFundExchangeMarketplaceMerchantsNumsValue string `json:"marketplace_merchants_fund_exchange_marketplace_merchants_nums_value"` //市商资金单笔x元自动兑换
}

type DestructionSettingStruct struct {
DestructionQuantity string `json:"destruction_quantity"` //销毁百分比
PublicWelfareAndCharity string `json:"public_welfare_and_charity"` //公益慈善百分比
DevelopmentCommittee string `json:"development_committee"` //发展委员会百分比
StarLevelDividends string `json:"star_level_dividends"` //星级分红百分比
MarketplaceMerchant string `json:"marketplace_merchant"` //市商数量百分比
}

type WelfareOrdersLimit struct {
ContinuousDailyActivityNums string `json:"continuous_daily_activity_nums"` //连续日活
DirectPushLimit struct {
DirectPushUserNums string `json:"direct_push_user_nums"` //直推用户数
ContinuousDailyActivityNums string `json:"continuous_daily_activity_nums"` //连续日活
} `json:"direct_push_limit"` //直推机制
WelfareOrdersProfitExchange string `json:"welfare_orders_profit_exchange"` //福利订单利润兑换率
SingleUserLimitBuyNums string `json:"single_user_limit_buy_nums"` //单个用户限购
PlatformMembers []struct {
From string `json:"from"`
To string `json:"to"`
} `json:"platform_members"` //平台会员
}

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

+ 21
- 0
rule/one_circles/md/one_circles_public_platoon.go View File

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

type VideoRewardSystemStruct struct {
RewardValue string `json:"reward_value"` //奖励X个活跃积分
RewardTotalNum string `json:"reward_total_num"` //一共X个奖励视屏
IntervalMinutes string `json:"interval_minutes"` //间隔X分钟
EachRoundHour string `json:"each_round_hour"` //每一轮X个小时
}

type RewardSystemStruct struct {
Level int `json:"level"` //圈层
RewardCondition string `json:"reward_condition"` //奖励条件
RewardValue string `json:"reward_value"` //奖励值
}

type ExchangeRulesStruct struct {
AutoExchangeNumsByPerson string `json:"auto_exchange_nums_by_person"` //个人数量X个,自动兑换可用绿色能量
AutoExchangeNumsByTeam string `json:"auto_exchange_nums_by_team"` //团队量X个,自动兑换结算绿色能量
}

const UserNextWatchAdDate = "%s:user_next_watch_date:%d"

+ 207
- 0
rule/one_circles/one_circles_activity_coin_auto_exchange_green_energy.go View File

@@ -0,0 +1,207 @@
package one_circles

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/md"
"code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule/one_circles/enum"
md2 "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule/one_circles/md"
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"
"encoding/json"
"errors"
"fmt"
"github.com/shopspring/decimal"
"xorm.io/xorm"
)

// ActivityCoinAutoExchangeGreenEnergy 活跃积分自动兑换成绿色能量
func ActivityCoinAutoExchangeGreenEnergy(engine *xorm.Engine, masterId string) (err error) {
//1、查找 `one_circles_green_energy_basic_setting` 基础设置 && `one_circles_public_platoon_basic_setting` 基础设置
oneCirclesGreenEnergyBasicSetting, err := db.OneCirclesGreenEnergyBasicSettingGetOneByParams(engine, map[string]interface{}{
"key": "is_open",
"value": 1,
})
if err != nil {
return
}

oneCirclesPublicPlatoonBasicSetting, err := db.OneCirclesPublicPlatoonBasicSettingGetOneByParams(engine, map[string]interface{}{
"key": "is_open",
"value": 1,
})
if err != nil {
return
}
if oneCirclesPublicPlatoonBasicSetting.ExchangeRules == "" {
err = errors.New("自动兑换未设置!")
return
}
var exchangeRulesStruct *md2.ExchangeRulesStruct
err = json.Unmarshal([]byte(oneCirclesPublicPlatoonBasicSetting.ExchangeRules), &exchangeRulesStruct)
if err != nil {
return
}
var autoExchangeNumsByPerson = zhios_order_relate_utils.StrToFloat64(exchangeRulesStruct.AutoExchangeNumsByPerson) //个人活跃积分X个自动兑换
var autoExchangeNumsByTeam = zhios_order_relate_utils.StrToFloat64(exchangeRulesStruct.AutoExchangeNumsByTeam) //团队活跃积分X个自动兑换
fmt.Println("autoExchangeNumsByPerson>>>>>>>>>>>>", autoExchangeNumsByPerson)
fmt.Println("autoExchangeNumsByTeam>>>>>>>>>>>>", autoExchangeNumsByTeam)

//2、获取"个人活跃积分" && 获取"团队活跃积分"
var coin1, coin2 model.VirtualCoin
_, err = engine.Where("id = ?", oneCirclesPublicPlatoonBasicSetting.PersonActivePointsCoinId).Get(&coin1)
if err != nil {
return err
}
_, err = engine.Where("id = ?", oneCirclesPublicPlatoonBasicSetting.TeamActivePointsCoinId).Get(&coin2)
if err != nil {
return err
}
personActivePointsCoinExchangeRatioValue, _ := decimal.NewFromString(coin1.ExchangeRatio)
teamActivePointsCoinExchangeRatioValue, _ := decimal.NewFromString(coin2.ExchangeRatio)

//3、当前 "个人活跃积分"可以自动兑换的用户数据 && "团队活跃积分"可以自动兑换的用户数据
var list1, list2 []model.UserVirtualAmount
err = engine.Where("coin_id = ?", oneCirclesPublicPlatoonBasicSetting.PersonActivePointsCoinId).And("amount >=?", autoExchangeNumsByPerson).Find(&list1)
if err != nil {
fmt.Println("err:::::1111", err)
return
}
err = engine.Where("coin_id = ?", oneCirclesPublicPlatoonBasicSetting.TeamActivePointsCoinId).And("amount >=?", autoExchangeNumsByTeam).Find(&list2)
if err != nil {
fmt.Println("err:::::2222", err)
return
}

session := engine.NewSession()
defer func() {
session.Close()
if err := recover(); err != nil {
_ = zhios_order_relate_logx.Error(err)
}
}()
session.Begin()

//4、处理"个人活跃积分"兑换
for _, v := range list1 {
autoExchangeNumsByPersonValue, _ := decimal.NewFromString(v.Amount)
autoExchangeNumsByPersonAmount := autoExchangeNumsByPersonValue.Div(personActivePointsCoinExchangeRatioValue).String()
//4.1计算涨价公式
err1, values, _, afterPriceValue := NewCalcPriceIncreaseFormula(autoExchangeNumsByPersonAmount, oneCirclesGreenEnergyBasicSetting)
if err1 != nil {
_ = session.Rollback()
return err1
}

//4.2给相应的用户加上个人的绿色积分(可用数量)
err = DealUserCoin(session, md.DealUserCoinReq{
Kind: "add",
Mid: masterId,
Title: md.OneCirclesPersonalActiveCoinExchangeGreenEnergy,
TransferType: md.OneCirclesPersonalActiveCoinExchangeGreenEnergyForUserVirtualCoinFlow,
OrdId: "",
CoinId: oneCirclesGreenEnergyBasicSetting.PersonGreenEnergyCoinId,
Uid: v.Uid,
Amount: zhios_order_relate_utils.StrToFloat64(values),
})
if err != nil {
_ = session.Rollback()
fmt.Println("err:::::33333", err)
return err
}

//4.3给相应的用户减去个人活跃积分
err = DealUserCoin(session, md.DealUserCoinReq{
Kind: "sub",
Mid: masterId,
Title: md.OneCirclesPersonalActiveCoinExchangeToBeGreenEnergy,
TransferType: md.OneCirclesPersonalActiveCoinExchangeToBeGreenEnergyForUserVirtualCoinFlow,
OrdId: "",
CoinId: oneCirclesPublicPlatoonBasicSetting.PersonActivePointsCoinId,
Uid: v.Uid,
Amount: zhios_order_relate_utils.StrToFloat64(v.Amount),
})
if err != nil {
_ = session.Rollback()
fmt.Println("err:::::33333", err)
return err
}

//4.4 减少“原始数量”中的绿色能量
err = DealAvailableGreenEnergyCoin(session, int(enum.PersonalActivePointRedemption), zhios_order_relate_utils.StrToFloat64(values), zhios_order_relate_utils.StrToFloat64(autoExchangeNumsByPersonAmount), enum.PersonalActivePointRedemption.String(), oneCirclesGreenEnergyBasicSetting, afterPriceValue)
if err != nil {
_ = session.Rollback()
fmt.Println("err:::::44444", err)
return err
}
}

//5、处理"团队活跃积分"兑换
for _, v := range list2 {
autoExchangeNumsByTeamValue, _ := decimal.NewFromString(v.Amount)
autoExchangeNumsByTeamAmount := autoExchangeNumsByTeamValue.Div(teamActivePointsCoinExchangeRatioValue).String()
//5.1计算涨价公式
err1, values, _, afterPriceValue := NewCalcPriceIncreaseFormula(autoExchangeNumsByTeamAmount, oneCirclesGreenEnergyBasicSetting)
if err1 != nil {
_ = session.Rollback()
return err1
}

//5.2给相应的用户加上个人的绿色积分(结算数量)
err = DealUserCoin(session, md.DealUserCoinReq{
Kind: "add",
Mid: masterId,
Title: md.OneCirclesTeamActiveCoinExchangeGreenEnergy,
TransferType: md.OneCirclesTeamActiveCoinExchangeGreenEnergyForUserVirtualCoinFlow,
OrdId: "",
CoinId: oneCirclesGreenEnergyBasicSetting.TeamGreenEnergyCoinId,
Uid: v.Uid,
Amount: zhios_order_relate_utils.StrToFloat64(values),
})
if err != nil {
_ = session.Rollback()
fmt.Println("err:::::33333", err)
return err
}

//5.3给相应的用户减去个人团队积分
err = DealUserCoin(session, md.DealUserCoinReq{
Kind: "sub",
Mid: masterId,
Title: md.OneCirclesTeamActiveCoinExchangeToBeGreenEnergy,
TransferType: md.OneCirclesTeamActiveCoinExchangeToBeGreenEnergyForUserVirtualCoinFlow,
OrdId: "",
CoinId: oneCirclesPublicPlatoonBasicSetting.TeamActivePointsCoinId,
Uid: v.Uid,
Amount: zhios_order_relate_utils.StrToFloat64(v.Amount),
})
if err != nil {
_ = session.Rollback()
fmt.Println("err:::::66666", err)
return err
}

//5.4 减少“原始数量”中的绿色能量
err = DealAvailableGreenEnergyCoin(session, int(enum.TeamActivePointRedemption), zhios_order_relate_utils.StrToFloat64(values), zhios_order_relate_utils.StrToFloat64(autoExchangeNumsByTeamAmount), enum.TeamActivePointRedemption.String(), oneCirclesGreenEnergyBasicSetting, afterPriceValue)
if err != nil {
_ = session.Rollback()
fmt.Println("err:::::44444", err)
return err
}
}

//6、修改 one_circles_green_energy_basic_setting 的 now_price
_, err = db.OneCirclesGreenEnergyBasicSettingUpdate(session, oneCirclesGreenEnergyBasicSetting.Id, oneCirclesGreenEnergyBasicSetting)
if err != nil {
_ = session.Rollback()
fmt.Println("err:::::77777", err)
return err
}

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

+ 94
- 0
rule/one_circles/one_circles_auto_adjust_prices.go View File

@@ -0,0 +1,94 @@
package one_circles

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/rule/one_circles/enum"
md2 "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule/one_circles/md"
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"
"encoding/json"
"errors"
"fmt"
"github.com/shopspring/decimal"
"time"
"xorm.io/xorm"
)

// AutoAdjustPrice 自动调整价格
func AutoAdjustPrice(engine *xorm.Engine, masterId string) (err error) {
now := time.Now()
fmt.Println(now.Hour())

//1、查找 `one_circles_green_energy_basic_setting` 基础设置
oneCirclesGreenEnergyBasicSetting, err := db.OneCirclesGreenEnergyBasicSettingGetOneByParams(engine, map[string]interface{}{
"key": "is_open",
"value": 1,
})
if err != nil {
return
}

var priceSettingStruct *md2.PriceSettingStruct
err = json.Unmarshal([]byte(oneCirclesGreenEnergyBasicSetting.PriceSetting), &priceSettingStruct)
if err != nil {
return
}
if priceSettingStruct.PriceHigherThanValue == "" || priceSettingStruct.MarketplaceMerchantsNumsExchangeMarketplaceMerchantsFundValue == "" || priceSettingStruct.PriceBelowValue == "" || priceSettingStruct.MarketplaceMerchantsFundExchangeMarketplaceMerchantsNumsValue == "" {
err = errors.New("价格设置未完全!")
return
}
session := engine.NewSession()
defer func() {
session.Close()
if err := recover(); err != nil {
_ = zhios_order_relate_logx.Error(err)
}
}()
session.Begin()

priceHigherThanValue, _ := decimal.NewFromString(priceSettingStruct.PriceHigherThanValue)
marketplaceMerchantsNumsExchangeMarketplaceMerchantsFundValue, _ := decimal.NewFromString(priceSettingStruct.MarketplaceMerchantsNumsExchangeMarketplaceMerchantsFundValue)
priceBelowValue, _ := decimal.NewFromString(priceSettingStruct.PriceBelowValue)
marketplaceMerchantsFundExchangeMarketplaceMerchantsNumsValue, _ := decimal.NewFromString(priceSettingStruct.MarketplaceMerchantsFundExchangeMarketplaceMerchantsNumsValue)
nowPriceValue, _ := decimal.NewFromString(oneCirclesGreenEnergyBasicSetting.NowPrice)
if nowPriceValue.GreaterThan(priceHigherThanValue) {
//当价格涨到设置某个价格时,自动执行 市商数量 兑换 市商资金 (降价公式)
err1, amount, _, afterPriceValue := NewCalcPriceReductionFormula(marketplaceMerchantsNumsExchangeMarketplaceMerchantsFundValue.String(), oneCirclesGreenEnergyBasicSetting)
if err1 != nil {
fmt.Println("err1111:::", err1)
_ = session.Rollback()
return err1
}

// 市商数量 减少、原始数量 增加、原始资金 减少、市商资金 增加
err = DealAvailableGreenEnergyCoin(session, int(enum.MarketplaceMerchantNumsAutoExchangeMarketplaceMerchantFunds), zhios_order_relate_utils.StrToFloat64(marketplaceMerchantsNumsExchangeMarketplaceMerchantsFundValue.String()), zhios_order_relate_utils.StrToFloat64(amount), enum.MarketplaceMerchantNumsAutoExchangeMarketplaceMerchantFunds.String(), oneCirclesGreenEnergyBasicSetting, afterPriceValue)
if err != nil {
fmt.Println("err:::::22222", err)
_ = session.Rollback()
return err
}
}
if nowPriceValue.LessThan(priceBelowValue) {
//当价格降到设置某个价格时,自动执行 市商资金 兑换 市商数量 (涨价公式)
err1, greenEnergy, _, afterPriceValue := NewCalcPriceIncreaseFormula(marketplaceMerchantsFundExchangeMarketplaceMerchantsNumsValue.String(), oneCirclesGreenEnergyBasicSetting)
if err1 != nil {
fmt.Println("err33333:::", err1)
_ = session.Rollback()
return err1
}
// 市商数量 增加、原始数量 减少、原始资金 增加、市商资金 减少
err = DealAvailableGreenEnergyCoin(session, int(enum.MarketplaceMerchantFundsAutoExchangeMarketplaceMerchantNums), zhios_order_relate_utils.StrToFloat64(greenEnergy), zhios_order_relate_utils.StrToFloat64(marketplaceMerchantsFundExchangeMarketplaceMerchantsNumsValue.String()), enum.MarketplaceMerchantFundsAutoExchangeMarketplaceMerchantNums.String(), oneCirclesGreenEnergyBasicSetting, afterPriceValue)
if err != nil {
fmt.Println("err:::::44444", err)
_ = session.Rollback()
return err
}
}

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

+ 111
- 0
rule/one_circles/one_circles_auto_release_green_energy.go View File

@@ -0,0 +1,111 @@
package one_circles

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/md"
"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"
"time"
"xorm.io/xorm"
)

const LockKey = "auto_release_exchange_green_energy_lock_key"

// AutoReleaseExchangeGreenEnergy 结算绿色能量自动释放成可用绿色能量
func AutoReleaseExchangeGreenEnergy(engine *xorm.Engine, masterId string) (err error) {
now := time.Now()
fmt.Println(now.Hour())
if !(now.Hour() > 1 && now.Hour() < 8) {
//TODO::只在凌晨一点 ~ 凌晨 8 点运行
return errors.New("非运行时间")
}
//TODO::增加“悲观锁”防止串行
getString, _ := cache.GetString(LockKey)
//if err != nil {
// return err
//}
if getString != "" {
fmt.Println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", "上一次结算未执行完")
return errors.New("上一次结算未执行完")
}
cache.SetEx(LockKey, "running", 3600*8) //8小时

//1、查找 `one_circles_green_energy_basic_setting` 基础设置 && `one_circles_public_platoon_basic_setting` 基础设置
oneCirclesGreenEnergyBasicSetting, err := db.OneCirclesGreenEnergyBasicSettingGetOneByParams(engine, map[string]interface{}{
"key": "is_open",
"value": 1,
})
if err != nil {
return
}

settlementQuantity := oneCirclesGreenEnergyBasicSetting.SettlementQuantity
fmt.Println("settlementQuantity>>>>>>>>>>>>", settlementQuantity)

//2、当前 "可用"绿色能量可以兑换的用户数据
var list1 []model.UserVirtualAmount
err = engine.Where("coin_id = ?", oneCirclesGreenEnergyBasicSetting.TeamGreenEnergyCoinId).And("amount > ?", 0).Find(&list1)
if err != nil {
fmt.Println("err:::::1111", err)
return
}

//4、处理释放
settlementQuantityRadio := decimal.NewFromFloat(100)
settlementQuantityValue := decimal.NewFromInt(int64(settlementQuantity)).Div(settlementQuantityRadio)
for _, v := range list1 {
userAmount, _ := decimal.NewFromString(v.Amount)
settlementQuantityAmount, _ := userAmount.Mul(settlementQuantityValue).Float64()
if settlementQuantityAmount > 0 {
session := engine.NewSession()
defer func() {
session.Close()
if err := recover(); err != nil {
_ = zhios_order_relate_logx.Error(err)
}
}()
session.Begin()

//4.2给相应的用户加上个人的绿色积分(可用数量)
err = DealUserCoin(session, md.DealUserCoinReq{
Kind: "add",
Mid: masterId,
Title: md.OneCirclesSettlementGreenEnergyExchangeGreenEnergy,
TransferType: md.OneCirclesSettlementGreenEnergyExchangeGreenEnergyForUserVirtualCoinFlow,
OrdId: "",
CoinId: oneCirclesGreenEnergyBasicSetting.PersonGreenEnergyCoinId,
Uid: v.Uid,
Amount: settlementQuantityAmount,
})

//4.2给相应的用户减少个人的绿色积分(结算数量)
err = DealUserCoin(session, md.DealUserCoinReq{
Kind: "sub",
Mid: masterId,
Title: md.OneCirclesSettlementGreenEnergyExchangeTobeGreenEnergy,
TransferType: md.OneCirclesSettlementGreenEnergyExchangeTobeGreenEnergyForUserVirtualCoinFlow,
OrdId: "",
CoinId: oneCirclesGreenEnergyBasicSetting.TeamGreenEnergyCoinId,
Uid: v.Uid,
Amount: settlementQuantityAmount,
})
if err != nil {
_ = session.Rollback()
fmt.Println("err:::::33333", err)
continue
}

err = session.Commit()
if err != nil {
_ = session.Rollback()
continue
}
}
}

return
}

+ 155
- 0
rule/one_circles/one_circles_available_green_energy_settlement.go View File

@@ -0,0 +1,155 @@
package one_circles

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"
md2 "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule/one_circles/md"
zhios_order_relate_utils "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/utils"
"encoding/json"
"errors"
"github.com/shopspring/decimal"
"time"
"xorm.io/xorm"
)

// CalcPriceIncreaseFormula 计算涨价公式(【用户资金 ÷(用户资金+原始资金)÷ 原始数量】 = 用户获得绿色能量个数)
func CalcPriceIncreaseFormula(engine *xorm.Engine, userAmountValue string) (err error, values, nowPriceValue, afterPriceValue string) {
//1、查找 `one_circles_green_energy_basic_setting` 基础设置
oneCirclesGreenEnergyBasicSetting, err := db.OneCirclesGreenEnergyBasicSettingGetOneByParams(engine, map[string]interface{}{
"key": "is_open",
"value": 1,
})
if err != nil {
return
}
userAmount, _ := decimal.NewFromString(userAmountValue) //用户资金
nowPrice, _ := decimal.NewFromString(oneCirclesGreenEnergyBasicSetting.NowPrice) //当前价格
originalQuantityNums, _ := decimal.NewFromString(oneCirclesGreenEnergyBasicSetting.OriginalQuantityNums) //原始数量
originalQuantityFunds, _ := decimal.NewFromString(oneCirclesGreenEnergyBasicSetting.OriginalFunds) //原始资金
afterPrice := (userAmount.Add(originalQuantityFunds)).Div(originalQuantityNums).Truncate(8) //涨价后的价格

values = userAmount.Div(afterPrice).Truncate(8).String() //用户得到绿色能量个数
nowPriceValue = nowPrice.String()
afterPriceValue = afterPrice.String()
return
}

// NewCalcPriceIncreaseFormula 计算涨价公式(【用户资金 ÷(用户资金+原始资金)÷ 原始数量】 = 用户获得绿色能量个数)
func NewCalcPriceIncreaseFormula(userAmountValue string, oneCirclesGreenEnergyBasicSetting *model.OneCirclesGreenEnergyBasicSetting) (err error, values, nowPriceValue, afterPriceValue string) {
userAmount, _ := decimal.NewFromString(userAmountValue) //用户资金
nowPrice, _ := decimal.NewFromString(oneCirclesGreenEnergyBasicSetting.NowPrice) //当前价格
originalQuantityNums, _ := decimal.NewFromString(oneCirclesGreenEnergyBasicSetting.OriginalQuantityNums) //原始数量
originalQuantityFunds, _ := decimal.NewFromString(oneCirclesGreenEnergyBasicSetting.OriginalFunds) //原始资金
afterPrice := (userAmount.Add(originalQuantityFunds)).Div(originalQuantityNums).Truncate(8) //涨价后的价格

values = userAmount.Div(afterPrice).Truncate(8).String() //用户得到绿色能量个数
nowPriceValue = nowPrice.String()
afterPriceValue = afterPrice.String()
return
}

// CalcPriceReductionFormula 计算降价公式(【用户需兑换绿能色量数量*{原始资金÷(用户需兑换绿色数量+原始数量}*(1 - 扣比例50% ~ 23%) = 用户获得钱)
func CalcPriceReductionFormula(engine *xorm.Engine, userExchangeNumsValue string, levelId string) (err error, values, greenEnergy, greenEnergyFee, nowPriceValue, afterPriceValue string) {
//1、查找 `one_circles_green_energy_basic_setting` 基础设置
oneCirclesGreenEnergyBasicSetting, err := db.OneCirclesGreenEnergyBasicSettingGetOneByParams(engine, map[string]interface{}{
"key": "is_open",
"value": 1,
})
if err != nil {
return
}
var vipEquitySetting []*md2.VipEquitySettingStruct
err = json.Unmarshal([]byte(oneCirclesGreenEnergyBasicSetting.VipEquitySetting), &vipEquitySetting)
if err != nil {
return
}
var exchangeAccountBalanceFeeValue string
for _, v := range vipEquitySetting {
if v.VipLevelId == levelId {
exchangeAccountBalanceFeeValue = v.ExchangeAccountBalanceFee
}
}
if exchangeAccountBalanceFeeValue == "" {
err = errors.New("未查询到当前会员等级兑换余额手续费")
return
}
decimalRate := decimal.NewFromInt(100) //百分比
exchangeAccountBalanceFee, _ := decimal.NewFromString(exchangeAccountBalanceFeeValue) //兑换手续费
userExchangeNums, _ := decimal.NewFromString(userExchangeNumsValue) //用户兑换绿色能量
originalQuantityNums, _ := decimal.NewFromString(oneCirclesGreenEnergyBasicSetting.OriginalQuantityNums) //原始数量
nowPrice, _ := decimal.NewFromString(oneCirclesGreenEnergyBasicSetting.NowPrice) //当前价格
originalQuantityFunds, _ := decimal.NewFromString(oneCirclesGreenEnergyBasicSetting.OriginalFunds) //原始资金
afterPrice := originalQuantityFunds.Div(userExchangeNums.Add(originalQuantityNums)) //降价后的价格

greenEnergyValues := userExchangeNums.Mul(afterPrice) //绿色能量个数
greenEnergyFeeValues := greenEnergyValues.Mul(exchangeAccountBalanceFee.Div(decimalRate)) //绿色能量个数扣除手续费价值

values = greenEnergyValues.Sub(greenEnergyFeeValues).Truncate(8).String() //用户实际得到的钱
greenEnergy = greenEnergyValues.Truncate(8).String() //原本兑换到的钱
greenEnergyFee = userExchangeNums.Mul(exchangeAccountBalanceFee.Div(decimalRate)).Truncate(8).String() //绿色能量手续费
nowPriceValue = nowPrice.String()
afterPriceValue = afterPrice.String()
return
}

// NewCalcPriceReductionFormula 计算降价公式(【用户需兑换绿能色量数量*{原始资金÷(用户需兑换绿色数量+原始数量}*(1 - 扣比例50% ~ 23%) = 用户获得钱)
func NewCalcPriceReductionFormula(userExchangeNumsValue string, oneCirclesGreenEnergyBasicSetting *model.OneCirclesGreenEnergyBasicSetting) (err error, greenEnergy, nowPriceValue, afterPriceValue string) {
userExchangeNums, _ := decimal.NewFromString(userExchangeNumsValue) //用户兑换绿色能量
originalQuantityNums, _ := decimal.NewFromString(oneCirclesGreenEnergyBasicSetting.OriginalQuantityNums) //原始数量
nowPrice, _ := decimal.NewFromString(oneCirclesGreenEnergyBasicSetting.NowPrice) //当前价格
originalQuantityFunds, _ := decimal.NewFromString(oneCirclesGreenEnergyBasicSetting.OriginalFunds) //原始资金
afterPrice := originalQuantityFunds.Div(userExchangeNums.Add(originalQuantityNums)) //降价后的价格

greenEnergyValues := userExchangeNums.Mul(afterPrice) //用户获得的钱

greenEnergy = greenEnergyValues.Truncate(8).String()
nowPriceValue = nowPrice.String()
afterPriceValue = afterPrice.String()
return
}

// JudgeUserIsCanBuyWelfareOrders 判断用户是否可以购买福利订单
func JudgeUserIsCanBuyWelfareOrders(engine *xorm.Engine, uid int) (err error) {
now := time.Now()
//1、查找 `one_circles_green_energy_basic_setting` 基础设置
var oneCirclesGreenEnergyBasicSetting model.OneCirclesGreenEnergyBasicSetting
has, err := engine.Where("is_open = 1").Get(&oneCirclesGreenEnergyBasicSetting)
if err != nil {
return
}
if !has {
return
}
var welfareOrdersLimit *md2.WelfareOrdersLimit
err = json.Unmarshal([]byte(oneCirclesGreenEnergyBasicSetting.WelfareOrdersLimit), &welfareOrdersLimit)
if err != nil {
return
}

//2、计算当前用户连续日活
startDate := now.AddDate(0, 0, -7).Format("2006-01-02")
endDate := now.Format("2006-01-02")
err, days, isContinuousDailyActivity := CalcUserContinuousDailyActivityDays(engine, "", uid, startDate, endDate)
if err != nil {
return
}
if !isContinuousDailyActivity {
err = errors.New("未连续日活不可购买")
return
}
if days < zhios_order_relate_utils.StrToInt(welfareOrdersLimit.ContinuousDailyActivityNums) {
err = errors.New("连续日活天数不够")
return
}

//3、计算直推人数
userRelates, err := db.DbsUserRelateByParentUid(engine, uid, 1)
if err != nil {
return
}
if len(*userRelates) < zhios_order_relate_utils.StrToInt(welfareOrdersLimit.DirectPushLimit.DirectPushUserNums) {
err = errors.New("直推人数不够")
}

return
}

+ 436
- 0
rule/one_circles/one_circles_deal_available_green_energy_points.go View File

@@ -0,0 +1,436 @@
package one_circles

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/rule/one_circles/enum"
md2 "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule/one_circles/md"
zhios_order_relate_utils "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/utils"
"encoding/json"
"errors"
"github.com/shopspring/decimal"
"time"
"xorm.io/xorm"
)

func DealAvailableGreenEnergyCoin(session *xorm.Session, kind int, amount, amountFee float64, title string, chain *model.OneCirclesGreenEnergyBasicSetting, nowPriceValue string) error {
amountValue := decimal.NewFromFloat(amount)
now := time.Now()
var oneCirclesAvailableGreenEnergyPointsFlow model.OneCirclesAvailableGreenEnergyPointsFlow
oneCirclesAvailableGreenEnergyPointsFlow.CoinId = chain.PersonGreenEnergyCoinId
oneCirclesAvailableGreenEnergyPointsFlow.Kind = kind
oneCirclesAvailableGreenEnergyPointsFlow.Title = title
oneCirclesAvailableGreenEnergyPointsFlow.Amount = amountValue.RoundFloor(8).String()
oneCirclesAvailableGreenEnergyPointsFlow.CreateTime = now

nowPrice, _ := decimal.NewFromString(nowPriceValue)
switch kind {
case int(enum.PersonalActivePointRedemption): //个人活跃积分兑换
beforeOriginalQuantity, _ := decimal.NewFromString(chain.OriginalQuantityNums)
oneCirclesAvailableGreenEnergyPointsFlow.Direction = 1
oneCirclesAvailableGreenEnergyPointsFlow.BeforeEcologicalApplicationValues = chain.EcologicalApplication //生态应用
oneCirclesAvailableGreenEnergyPointsFlow.AfterEcologicalApplicationValues = chain.EcologicalApplication
oneCirclesAvailableGreenEnergyPointsFlow.BeforeTechnicalTeamValues = chain.TotalTechnologyTeam //技术团队
oneCirclesAvailableGreenEnergyPointsFlow.AfterTechnicalTeamValues = chain.TotalTechnologyTeam
oneCirclesAvailableGreenEnergyPointsFlow.BeforeOperateTeamValues = chain.TotalOperateTeam //运营团队
oneCirclesAvailableGreenEnergyPointsFlow.AfterOperateTeamValues = chain.TotalOperateTeam
oneCirclesAvailableGreenEnergyPointsFlow.BeforeActiveGiveawaysValues = chain.TotalActiveGiveaways //活跃赠送
oneCirclesAvailableGreenEnergyPointsFlow.AfterActiveGiveawaysValues = chain.TotalActiveGiveaways
oneCirclesAvailableGreenEnergyPointsFlow.BeforeOriginalQuantityValues = chain.OriginalQuantityNums //原始数量
oneCirclesAvailableGreenEnergyPointsFlow.AfterOriginalQuantityValues = beforeOriginalQuantity.Sub(amountValue).RoundFloor(8).String()
oneCirclesAvailableGreenEnergyPointsFlow.BeforeMarketplaceMerchantValues = chain.MarketplaceMerchantNums //市商数量
oneCirclesAvailableGreenEnergyPointsFlow.AfterMarketplaceMerchantValues = chain.MarketplaceMerchantNums
oneCirclesAvailableGreenEnergyPointsFlow.BeforeDevelopmentCommitteeValues = chain.DevelopmentCommittee //发展委员会
oneCirclesAvailableGreenEnergyPointsFlow.AfterDevelopmentCommitteeValues = chain.DevelopmentCommittee
oneCirclesAvailableGreenEnergyPointsFlow.BeforePublicWelfareAndCharityValues = chain.PublicWelfareAndCharity //公益慈善
oneCirclesAvailableGreenEnergyPointsFlow.AfterPublicWelfareAndCharityValues = chain.PublicWelfareAndCharity
oneCirclesAvailableGreenEnergyPointsFlow.BeforeStarLevelDividendsValues = chain.StarLevelDividends //星级分红
oneCirclesAvailableGreenEnergyPointsFlow.AfterStarLevelDividendsValues = chain.StarLevelDividends
oneCirclesAvailableGreenEnergyPointsFlow.BeforeDestructionQuantityValues = chain.DestructionQuantityNums //销毁数量
oneCirclesAvailableGreenEnergyPointsFlow.AfterDestructionQuantityValues = chain.DestructionQuantityNums

amountFeeValue := decimal.NewFromFloat(amountFee) //积分价值
originalFunds, _ := decimal.NewFromString(chain.OriginalFunds) //原始资金
afterOriginalFundValues := originalFunds.Add(amountFeeValue).RoundFloor(8).String()
oneCirclesAvailableGreenEnergyPointsFlow.BeforeOriginalQuantityFundValues = chain.OriginalFunds //原始资金
oneCirclesAvailableGreenEnergyPointsFlow.AfterOriginalQuantityFundValues = afterOriginalFundValues

oneCirclesAvailableGreenEnergyPointsFlow.BeforeMarketplaceMerchantFundValues = chain.MarketplaceMerchantFunds //市商资金
oneCirclesAvailableGreenEnergyPointsFlow.AfterMarketplaceMerchantFundValues = chain.MarketplaceMerchantFunds
break
case int(enum.TeamActivePointRedemption): //团队活跃积分兑换
beforeOriginalQuantity, _ := decimal.NewFromString(chain.OriginalQuantityNums)
oneCirclesAvailableGreenEnergyPointsFlow.Direction = 1
oneCirclesAvailableGreenEnergyPointsFlow.BeforeEcologicalApplicationValues = chain.EcologicalApplication //生态应用
oneCirclesAvailableGreenEnergyPointsFlow.AfterEcologicalApplicationValues = chain.EcologicalApplication
oneCirclesAvailableGreenEnergyPointsFlow.BeforeTechnicalTeamValues = chain.TotalTechnologyTeam //技术团队
oneCirclesAvailableGreenEnergyPointsFlow.AfterTechnicalTeamValues = chain.TotalTechnologyTeam
oneCirclesAvailableGreenEnergyPointsFlow.BeforeOperateTeamValues = chain.TotalOperateTeam //运营团队
oneCirclesAvailableGreenEnergyPointsFlow.AfterOperateTeamValues = chain.TotalOperateTeam
oneCirclesAvailableGreenEnergyPointsFlow.BeforeActiveGiveawaysValues = chain.TotalActiveGiveaways //活跃赠送
oneCirclesAvailableGreenEnergyPointsFlow.AfterActiveGiveawaysValues = chain.TotalActiveGiveaways
oneCirclesAvailableGreenEnergyPointsFlow.BeforeOriginalQuantityValues = chain.OriginalQuantityNums //原始数量
oneCirclesAvailableGreenEnergyPointsFlow.AfterOriginalQuantityValues = beforeOriginalQuantity.Sub(amountValue).RoundFloor(8).String()
oneCirclesAvailableGreenEnergyPointsFlow.BeforeMarketplaceMerchantValues = chain.MarketplaceMerchantNums //市商数量
oneCirclesAvailableGreenEnergyPointsFlow.AfterMarketplaceMerchantValues = chain.MarketplaceMerchantNums
oneCirclesAvailableGreenEnergyPointsFlow.BeforeDevelopmentCommitteeValues = chain.DevelopmentCommittee //发展委员会
oneCirclesAvailableGreenEnergyPointsFlow.AfterDevelopmentCommitteeValues = chain.DevelopmentCommittee
oneCirclesAvailableGreenEnergyPointsFlow.BeforePublicWelfareAndCharityValues = chain.PublicWelfareAndCharity //公益慈善
oneCirclesAvailableGreenEnergyPointsFlow.AfterPublicWelfareAndCharityValues = chain.PublicWelfareAndCharity
oneCirclesAvailableGreenEnergyPointsFlow.BeforeStarLevelDividendsValues = chain.StarLevelDividends //星级分红
oneCirclesAvailableGreenEnergyPointsFlow.AfterStarLevelDividendsValues = chain.StarLevelDividends
oneCirclesAvailableGreenEnergyPointsFlow.BeforeDestructionQuantityValues = chain.DestructionQuantityNums //销毁数量
oneCirclesAvailableGreenEnergyPointsFlow.AfterDestructionQuantityValues = chain.DestructionQuantityNums

amountFeeValue := decimal.NewFromFloat(amountFee) //积分价值
originalFunds, _ := decimal.NewFromString(chain.OriginalFunds) //原始资金
afterOriginalFundValues := originalFunds.Add(amountFeeValue).RoundFloor(8).String()
oneCirclesAvailableGreenEnergyPointsFlow.BeforeOriginalQuantityFundValues = chain.OriginalFunds //原始资金
oneCirclesAvailableGreenEnergyPointsFlow.AfterOriginalQuantityFundValues = afterOriginalFundValues

oneCirclesAvailableGreenEnergyPointsFlow.BeforeMarketplaceMerchantFundValues = chain.MarketplaceMerchantFunds //市商资金
oneCirclesAvailableGreenEnergyPointsFlow.AfterMarketplaceMerchantFundValues = chain.MarketplaceMerchantFunds
break
case int(enum.SettlementOfGreenEnergyRelease): //结算绿色能量释放
oneCirclesAvailableGreenEnergyPointsFlow.Direction = 1
oneCirclesAvailableGreenEnergyPointsFlow.BeforeEcologicalApplicationValues = chain.EcologicalApplication //生态应用
oneCirclesAvailableGreenEnergyPointsFlow.AfterEcologicalApplicationValues = chain.EcologicalApplication
oneCirclesAvailableGreenEnergyPointsFlow.BeforeTechnicalTeamValues = chain.TotalTechnologyTeam //技术团队
oneCirclesAvailableGreenEnergyPointsFlow.AfterTechnicalTeamValues = chain.TotalTechnologyTeam
oneCirclesAvailableGreenEnergyPointsFlow.BeforeOperateTeamValues = chain.TotalOperateTeam //运营团队
oneCirclesAvailableGreenEnergyPointsFlow.AfterOperateTeamValues = chain.TotalOperateTeam
oneCirclesAvailableGreenEnergyPointsFlow.BeforeActiveGiveawaysValues = chain.TotalActiveGiveaways //活跃赠送
oneCirclesAvailableGreenEnergyPointsFlow.AfterActiveGiveawaysValues = chain.TotalActiveGiveaways
oneCirclesAvailableGreenEnergyPointsFlow.BeforeOriginalQuantityValues = chain.OriginalQuantityNums //原始数量
oneCirclesAvailableGreenEnergyPointsFlow.AfterOriginalQuantityValues = chain.OriginalQuantityNums
oneCirclesAvailableGreenEnergyPointsFlow.BeforeMarketplaceMerchantValues = chain.MarketplaceMerchantNums //市商数量
oneCirclesAvailableGreenEnergyPointsFlow.AfterMarketplaceMerchantValues = chain.MarketplaceMerchantNums
oneCirclesAvailableGreenEnergyPointsFlow.BeforeDevelopmentCommitteeValues = chain.DevelopmentCommittee //发展委员会
oneCirclesAvailableGreenEnergyPointsFlow.AfterDevelopmentCommitteeValues = chain.DevelopmentCommittee
oneCirclesAvailableGreenEnergyPointsFlow.BeforePublicWelfareAndCharityValues = chain.PublicWelfareAndCharity //公益慈善
oneCirclesAvailableGreenEnergyPointsFlow.AfterPublicWelfareAndCharityValues = chain.PublicWelfareAndCharity
oneCirclesAvailableGreenEnergyPointsFlow.BeforeStarLevelDividendsValues = chain.StarLevelDividends //星级分红
oneCirclesAvailableGreenEnergyPointsFlow.AfterStarLevelDividendsValues = chain.StarLevelDividends
oneCirclesAvailableGreenEnergyPointsFlow.BeforeDestructionQuantityValues = chain.DestructionQuantityNums //销毁数量
oneCirclesAvailableGreenEnergyPointsFlow.AfterDestructionQuantityValues = chain.DestructionQuantityNums
oneCirclesAvailableGreenEnergyPointsFlow.BeforeOriginalQuantityFundValues = chain.OriginalFunds //原始资金
oneCirclesAvailableGreenEnergyPointsFlow.AfterOriginalQuantityFundValues = chain.OriginalFunds
oneCirclesAvailableGreenEnergyPointsFlow.BeforeMarketplaceMerchantFundValues = chain.MarketplaceMerchantFunds //市商资金
oneCirclesAvailableGreenEnergyPointsFlow.AfterMarketplaceMerchantFundValues = chain.MarketplaceMerchantFunds
break
case int(enum.SignInReward): //签到奖励
beforeTotalActiveGiveaways, _ := decimal.NewFromString(chain.TotalActiveGiveaways)
oneCirclesAvailableGreenEnergyPointsFlow.Direction = 1
oneCirclesAvailableGreenEnergyPointsFlow.BeforeEcologicalApplicationValues = chain.EcologicalApplication //生态应用
oneCirclesAvailableGreenEnergyPointsFlow.AfterEcologicalApplicationValues = chain.EcologicalApplication
oneCirclesAvailableGreenEnergyPointsFlow.BeforeTechnicalTeamValues = chain.TotalTechnologyTeam //技术团队
oneCirclesAvailableGreenEnergyPointsFlow.AfterTechnicalTeamValues = chain.TotalTechnologyTeam
oneCirclesAvailableGreenEnergyPointsFlow.BeforeOperateTeamValues = chain.TotalOperateTeam //运营团队
oneCirclesAvailableGreenEnergyPointsFlow.AfterOperateTeamValues = chain.TotalOperateTeam
oneCirclesAvailableGreenEnergyPointsFlow.BeforeActiveGiveawaysValues = chain.TotalActiveGiveaways //活跃赠送
oneCirclesAvailableGreenEnergyPointsFlow.AfterActiveGiveawaysValues = beforeTotalActiveGiveaways.Sub(amountValue).RoundFloor(8).String()
oneCirclesAvailableGreenEnergyPointsFlow.BeforeOriginalQuantityValues = chain.OriginalQuantityNums //原始数量
oneCirclesAvailableGreenEnergyPointsFlow.AfterOriginalQuantityValues = chain.OriginalQuantityNums
oneCirclesAvailableGreenEnergyPointsFlow.BeforeMarketplaceMerchantValues = chain.MarketplaceMerchantNums //市商数量
oneCirclesAvailableGreenEnergyPointsFlow.AfterMarketplaceMerchantValues = chain.MarketplaceMerchantNums
oneCirclesAvailableGreenEnergyPointsFlow.BeforeDevelopmentCommitteeValues = chain.DevelopmentCommittee //发展委员会
oneCirclesAvailableGreenEnergyPointsFlow.AfterDevelopmentCommitteeValues = chain.DevelopmentCommittee
oneCirclesAvailableGreenEnergyPointsFlow.BeforePublicWelfareAndCharityValues = chain.PublicWelfareAndCharity //公益慈善
oneCirclesAvailableGreenEnergyPointsFlow.AfterPublicWelfareAndCharityValues = chain.PublicWelfareAndCharity
oneCirclesAvailableGreenEnergyPointsFlow.BeforeStarLevelDividendsValues = chain.StarLevelDividends //星级分红
oneCirclesAvailableGreenEnergyPointsFlow.AfterStarLevelDividendsValues = chain.StarLevelDividends
oneCirclesAvailableGreenEnergyPointsFlow.BeforeDestructionQuantityValues = chain.DestructionQuantityNums //销毁数量
oneCirclesAvailableGreenEnergyPointsFlow.AfterDestructionQuantityValues = chain.DestructionQuantityNums
oneCirclesAvailableGreenEnergyPointsFlow.BeforeMarketplaceMerchantFundValues = chain.MarketplaceMerchantFunds //市商资金
oneCirclesAvailableGreenEnergyPointsFlow.AfterMarketplaceMerchantFundValues = chain.MarketplaceMerchantFunds
oneCirclesAvailableGreenEnergyPointsFlow.BeforeOriginalQuantityFundValues = chain.OriginalFunds //原始资金
oneCirclesAvailableGreenEnergyPointsFlow.AfterOriginalQuantityFundValues = chain.OriginalFunds
oneCirclesAvailableGreenEnergyPointsFlow.BeforeMarketplaceMerchantFundValues = chain.MarketplaceMerchantFunds //市商资金
oneCirclesAvailableGreenEnergyPointsFlow.AfterMarketplaceMerchantFundValues = chain.MarketplaceMerchantFunds
break
case int(enum.AccountBalanceExchange): //账户余额兑换
beforeOriginalQuantity, _ := decimal.NewFromString(chain.OriginalQuantityNums)
oneCirclesAvailableGreenEnergyPointsFlow.Direction = 1
oneCirclesAvailableGreenEnergyPointsFlow.BeforeEcologicalApplicationValues = chain.EcologicalApplication //生态应用
oneCirclesAvailableGreenEnergyPointsFlow.AfterEcologicalApplicationValues = chain.EcologicalApplication
oneCirclesAvailableGreenEnergyPointsFlow.BeforeTechnicalTeamValues = chain.TotalTechnologyTeam //技术团队
oneCirclesAvailableGreenEnergyPointsFlow.AfterTechnicalTeamValues = chain.TotalTechnologyTeam
oneCirclesAvailableGreenEnergyPointsFlow.BeforeOperateTeamValues = chain.TotalOperateTeam //运营团队
oneCirclesAvailableGreenEnergyPointsFlow.AfterOperateTeamValues = chain.TotalOperateTeam
oneCirclesAvailableGreenEnergyPointsFlow.BeforeActiveGiveawaysValues = chain.TotalActiveGiveaways //活跃赠送
oneCirclesAvailableGreenEnergyPointsFlow.AfterActiveGiveawaysValues = chain.TotalActiveGiveaways
oneCirclesAvailableGreenEnergyPointsFlow.BeforeOriginalQuantityValues = chain.OriginalQuantityNums //原始数量
oneCirclesAvailableGreenEnergyPointsFlow.AfterOriginalQuantityValues = beforeOriginalQuantity.Sub(amountValue).RoundFloor(8).String()
oneCirclesAvailableGreenEnergyPointsFlow.BeforeMarketplaceMerchantValues = chain.MarketplaceMerchantNums //市商数量
oneCirclesAvailableGreenEnergyPointsFlow.AfterMarketplaceMerchantValues = chain.MarketplaceMerchantNums
oneCirclesAvailableGreenEnergyPointsFlow.BeforeDevelopmentCommitteeValues = chain.DevelopmentCommittee //发展委员会
oneCirclesAvailableGreenEnergyPointsFlow.AfterDevelopmentCommitteeValues = chain.DevelopmentCommittee
oneCirclesAvailableGreenEnergyPointsFlow.BeforePublicWelfareAndCharityValues = chain.PublicWelfareAndCharity //公益慈善
oneCirclesAvailableGreenEnergyPointsFlow.AfterPublicWelfareAndCharityValues = chain.PublicWelfareAndCharity
oneCirclesAvailableGreenEnergyPointsFlow.BeforeStarLevelDividendsValues = chain.StarLevelDividends //星级分红
oneCirclesAvailableGreenEnergyPointsFlow.AfterStarLevelDividendsValues = chain.StarLevelDividends
oneCirclesAvailableGreenEnergyPointsFlow.BeforeDestructionQuantityValues = chain.DestructionQuantityNums //销毁数量
oneCirclesAvailableGreenEnergyPointsFlow.AfterDestructionQuantityValues = chain.DestructionQuantityNums

amountFeeValue := decimal.NewFromFloat(amountFee) //余额价值
originalFunds, _ := decimal.NewFromString(chain.OriginalFunds) //原始资金
afterOriginalFundValues := originalFunds.Add(amountFeeValue).RoundFloor(8).String()
oneCirclesAvailableGreenEnergyPointsFlow.BeforeOriginalQuantityFundValues = chain.OriginalFunds //原始资金
oneCirclesAvailableGreenEnergyPointsFlow.AfterOriginalQuantityFundValues = afterOriginalFundValues

oneCirclesAvailableGreenEnergyPointsFlow.BeforeMarketplaceMerchantFundValues = chain.MarketplaceMerchantFunds //市商资金
oneCirclesAvailableGreenEnergyPointsFlow.AfterMarketplaceMerchantFundValues = chain.MarketplaceMerchantFunds
break
case int(enum.GreenEnergyExchangeBalance): //兑换账户余额
var destructionSetting *md2.DestructionSettingStruct
err := json.Unmarshal([]byte(chain.DestructionSetting), &destructionSetting)
if err != nil {
return err
}
decimalRate := decimal.NewFromInt(100) //百分比
amountFeeValue := decimal.NewFromFloat(amountFee) //手续费

marketplaceMerchantNums, _ := decimal.NewFromString(chain.MarketplaceMerchantNums)
marketplaceMerchant, _ := decimal.NewFromString(destructionSetting.MarketplaceMerchant) //市商数量百分比
afterMarketplaceMerchantValues := marketplaceMerchantNums.Add(amountFeeValue.Mul(marketplaceMerchant.Div(decimalRate))).RoundFloor(8).String()

developmentCommitteeNums, _ := decimal.NewFromString(chain.DevelopmentCommittee)
developmentCommittee, _ := decimal.NewFromString(destructionSetting.DevelopmentCommittee) //发展委员会百分比
afterDevelopmentCommitteeValues := developmentCommitteeNums.Add(amountFeeValue.Mul(developmentCommittee.Div(decimalRate))).RoundFloor(8).String()

publicWelfareAndCharityNums, _ := decimal.NewFromString(chain.PublicWelfareAndCharity)
publicWelfareAndCharity, _ := decimal.NewFromString(destructionSetting.PublicWelfareAndCharity) //公益慈善百分比
afterPublicWelfareAndCharityValues := publicWelfareAndCharityNums.Add(amountFeeValue.Mul(publicWelfareAndCharity.Div(decimalRate))).RoundFloor(8).String()

starLevelDividendsNums, _ := decimal.NewFromString(chain.StarLevelDividends)
starLevelDividends, _ := decimal.NewFromString(destructionSetting.StarLevelDividends) //星级分红百分比
afterStarLevelDividendsValues := starLevelDividendsNums.Add(amountFeeValue.Mul(starLevelDividends.Div(decimalRate))).RoundFloor(8).String()

destructionQuantityNums, _ := decimal.NewFromString(chain.DestructionQuantityNums)
destructionQuantity, _ := decimal.NewFromString(destructionSetting.DestructionQuantity) //销毁百分比
afterDestructionQuantityValues := destructionQuantityNums.Add(amountFeeValue.Mul(destructionQuantity.Div(decimalRate))).RoundFloor(8).String()

originalQuantityNums, _ := decimal.NewFromString(chain.OriginalQuantityNums) //原始数量
afterOriginalQuantityValues := originalQuantityNums.Add(amountValue.Sub(amountFeeValue)).RoundFloor(8).String()

originalFunds, _ := decimal.NewFromString(chain.OriginalFunds) //原始资金
afterOriginalFundValues := originalFunds.Sub(nowPrice.Mul(amountValue.Sub(amountFeeValue))).RoundFloor(8).String()

oneCirclesAvailableGreenEnergyPointsFlow.Direction = 1
oneCirclesAvailableGreenEnergyPointsFlow.BeforeEcologicalApplicationValues = chain.EcologicalApplication //生态应用
oneCirclesAvailableGreenEnergyPointsFlow.AfterEcologicalApplicationValues = chain.EcologicalApplication
oneCirclesAvailableGreenEnergyPointsFlow.BeforeTechnicalTeamValues = chain.TotalTechnologyTeam //技术团队
oneCirclesAvailableGreenEnergyPointsFlow.AfterTechnicalTeamValues = chain.TotalTechnologyTeam
oneCirclesAvailableGreenEnergyPointsFlow.BeforeOperateTeamValues = chain.TotalOperateTeam //运营团队
oneCirclesAvailableGreenEnergyPointsFlow.AfterOperateTeamValues = chain.TotalOperateTeam
oneCirclesAvailableGreenEnergyPointsFlow.BeforeActiveGiveawaysValues = chain.TotalActiveGiveaways //活跃赠送
oneCirclesAvailableGreenEnergyPointsFlow.AfterActiveGiveawaysValues = chain.TotalActiveGiveaways
oneCirclesAvailableGreenEnergyPointsFlow.BeforeOriginalQuantityValues = chain.OriginalQuantityNums //原始数量
oneCirclesAvailableGreenEnergyPointsFlow.AfterOriginalQuantityValues = afterOriginalQuantityValues
oneCirclesAvailableGreenEnergyPointsFlow.BeforeMarketplaceMerchantValues = chain.MarketplaceMerchantNums //市商数量
oneCirclesAvailableGreenEnergyPointsFlow.AfterMarketplaceMerchantValues = afterMarketplaceMerchantValues
oneCirclesAvailableGreenEnergyPointsFlow.AfterMarketplaceMerchantValues = afterMarketplaceMerchantValues
oneCirclesAvailableGreenEnergyPointsFlow.BeforeDevelopmentCommitteeValues = chain.DevelopmentCommittee //发展委员会
oneCirclesAvailableGreenEnergyPointsFlow.AfterDevelopmentCommitteeValues = afterDevelopmentCommitteeValues
oneCirclesAvailableGreenEnergyPointsFlow.BeforePublicWelfareAndCharityValues = chain.PublicWelfareAndCharity //公益慈善
oneCirclesAvailableGreenEnergyPointsFlow.AfterPublicWelfareAndCharityValues = afterPublicWelfareAndCharityValues
oneCirclesAvailableGreenEnergyPointsFlow.BeforeStarLevelDividendsValues = chain.StarLevelDividends //星级分红
oneCirclesAvailableGreenEnergyPointsFlow.AfterStarLevelDividendsValues = afterStarLevelDividendsValues
oneCirclesAvailableGreenEnergyPointsFlow.BeforeDestructionQuantityValues = chain.DestructionQuantityNums //销毁数量
oneCirclesAvailableGreenEnergyPointsFlow.AfterDestructionQuantityValues = afterDestructionQuantityValues

oneCirclesAvailableGreenEnergyPointsFlow.BeforeMarketplaceMerchantFundValues = chain.MarketplaceMerchantFunds //市商资金
oneCirclesAvailableGreenEnergyPointsFlow.AfterMarketplaceMerchantFundValues = chain.MarketplaceMerchantFunds
oneCirclesAvailableGreenEnergyPointsFlow.BeforeOriginalQuantityFundValues = chain.OriginalFunds //原始资金
oneCirclesAvailableGreenEnergyPointsFlow.AfterOriginalQuantityFundValues = afterOriginalFundValues

//TODO::新增 / 更新 one_circles_star_level_dividends_records 记录
oneCirclesStarLevelDividendsRecords, err := db.OneCirclesStarLevelDividendsRecordsGetOneByParamsBySession(session, map[string]interface{}{
"key": "date",
"value": now.Format("2006-01-02"),
})
if err != nil {
return err
}
if oneCirclesStarLevelDividendsRecords == nil {
oneCirclesStarLevelDividendsRecords = &model.OneCirclesStarLevelDividendsRecords{
Amount: amountFeeValue.Mul(starLevelDividends.Div(decimalRate)).String(),
AlreadyDividendsAmount: "",
NotDividendsAmount: "",
Date: now.Format("2006-01-02"),
}
_, err = db.OneCirclesStarLevelDividendsRecordsInsertBySession(session, oneCirclesStarLevelDividendsRecords)
if err != nil {
return err
}
} else {
oneCirclesStarLevelDividendsRecordsAmountValue, _ := decimal.NewFromString(oneCirclesStarLevelDividendsRecords.Amount)
oneCirclesStarLevelDividendsRecordsAmountValue = oneCirclesStarLevelDividendsRecordsAmountValue.Add(amountFeeValue.Mul(starLevelDividends.Div(decimalRate)))
oneCirclesStarLevelDividendsRecords.Amount = oneCirclesStarLevelDividendsRecordsAmountValue.String()
_, err = db.OneCirclesStarLevelDividendsRecordsUpdateBySession(session, oneCirclesStarLevelDividendsRecords.Id, oneCirclesStarLevelDividendsRecords, "amount")
if err != nil {
return err
}
}
break
case int(enum.SettlementStarLevelDividends): //星级分红
beforeStarLevelDividends, _ := decimal.NewFromString(chain.StarLevelDividends)
oneCirclesAvailableGreenEnergyPointsFlow.Direction = 1
oneCirclesAvailableGreenEnergyPointsFlow.BeforeEcologicalApplicationValues = chain.EcologicalApplication //生态应用
oneCirclesAvailableGreenEnergyPointsFlow.AfterEcologicalApplicationValues = chain.EcologicalApplication
oneCirclesAvailableGreenEnergyPointsFlow.BeforeTechnicalTeamValues = chain.TotalTechnologyTeam //技术团队
oneCirclesAvailableGreenEnergyPointsFlow.AfterTechnicalTeamValues = chain.TotalTechnologyTeam
oneCirclesAvailableGreenEnergyPointsFlow.BeforeOperateTeamValues = chain.TotalOperateTeam //运营团队
oneCirclesAvailableGreenEnergyPointsFlow.AfterOperateTeamValues = chain.TotalOperateTeam
oneCirclesAvailableGreenEnergyPointsFlow.BeforeActiveGiveawaysValues = chain.TotalActiveGiveaways //活跃赠送
oneCirclesAvailableGreenEnergyPointsFlow.AfterActiveGiveawaysValues = chain.TotalActiveGiveaways
oneCirclesAvailableGreenEnergyPointsFlow.BeforeOriginalQuantityValues = chain.OriginalQuantityNums //原始数量
oneCirclesAvailableGreenEnergyPointsFlow.AfterOriginalQuantityValues = chain.OriginalQuantityNums
oneCirclesAvailableGreenEnergyPointsFlow.BeforeMarketplaceMerchantValues = chain.MarketplaceMerchantNums //市商数量
oneCirclesAvailableGreenEnergyPointsFlow.AfterMarketplaceMerchantValues = chain.MarketplaceMerchantNums
oneCirclesAvailableGreenEnergyPointsFlow.BeforeDevelopmentCommitteeValues = chain.DevelopmentCommittee //发展委员会
oneCirclesAvailableGreenEnergyPointsFlow.AfterDevelopmentCommitteeValues = chain.DevelopmentCommittee
oneCirclesAvailableGreenEnergyPointsFlow.BeforePublicWelfareAndCharityValues = chain.PublicWelfareAndCharity //公益慈善
oneCirclesAvailableGreenEnergyPointsFlow.AfterPublicWelfareAndCharityValues = chain.PublicWelfareAndCharity
oneCirclesAvailableGreenEnergyPointsFlow.BeforeStarLevelDividendsValues = chain.StarLevelDividends //星级分红
oneCirclesAvailableGreenEnergyPointsFlow.AfterStarLevelDividendsValues = beforeStarLevelDividends.Sub(amountValue).RoundFloor(8).String()
oneCirclesAvailableGreenEnergyPointsFlow.BeforeDestructionQuantityValues = chain.DestructionQuantityNums //销毁数量
oneCirclesAvailableGreenEnergyPointsFlow.AfterDestructionQuantityValues = chain.DestructionQuantityNums

oneCirclesAvailableGreenEnergyPointsFlow.BeforeOriginalQuantityFundValues = chain.OriginalFunds //原始资金
oneCirclesAvailableGreenEnergyPointsFlow.AfterOriginalQuantityFundValues = chain.OriginalFunds

oneCirclesAvailableGreenEnergyPointsFlow.BeforeMarketplaceMerchantFundValues = chain.MarketplaceMerchantFunds //市商资金
oneCirclesAvailableGreenEnergyPointsFlow.AfterMarketplaceMerchantFundValues = chain.MarketplaceMerchantFunds
break
case int(enum.MarketplaceMerchantNumsAutoExchangeMarketplaceMerchantFunds): //市商数量自动兑换市商资金
beforeOriginalQuantityNums, _ := decimal.NewFromString(chain.OriginalQuantityNums)
beforeMarketplaceMerchantNums, _ := decimal.NewFromString(chain.MarketplaceMerchantNums)
beforeOriginalFunds, _ := decimal.NewFromString(chain.OriginalFunds)
beforeMarketplaceMerchantFunds, _ := decimal.NewFromString(chain.MarketplaceMerchantFunds)

oneCirclesAvailableGreenEnergyPointsFlow.Direction = 1
oneCirclesAvailableGreenEnergyPointsFlow.BeforeEcologicalApplicationValues = chain.EcologicalApplication //生态应用
oneCirclesAvailableGreenEnergyPointsFlow.AfterEcologicalApplicationValues = chain.EcologicalApplication
oneCirclesAvailableGreenEnergyPointsFlow.BeforeTechnicalTeamValues = chain.TotalTechnologyTeam //技术团队
oneCirclesAvailableGreenEnergyPointsFlow.AfterTechnicalTeamValues = chain.TotalTechnologyTeam
oneCirclesAvailableGreenEnergyPointsFlow.BeforeOperateTeamValues = chain.TotalOperateTeam //运营团队
oneCirclesAvailableGreenEnergyPointsFlow.AfterOperateTeamValues = chain.TotalOperateTeam
oneCirclesAvailableGreenEnergyPointsFlow.BeforeActiveGiveawaysValues = chain.TotalActiveGiveaways //活跃赠送
oneCirclesAvailableGreenEnergyPointsFlow.AfterActiveGiveawaysValues = chain.TotalActiveGiveaways
oneCirclesAvailableGreenEnergyPointsFlow.BeforeOriginalQuantityValues = chain.OriginalQuantityNums //原始数量
oneCirclesAvailableGreenEnergyPointsFlow.AfterOriginalQuantityValues = beforeOriginalQuantityNums.Add(amountValue).String()
oneCirclesAvailableGreenEnergyPointsFlow.BeforeMarketplaceMerchantValues = chain.MarketplaceMerchantNums //市商数量
oneCirclesAvailableGreenEnergyPointsFlow.AfterMarketplaceMerchantValues = beforeMarketplaceMerchantNums.Sub(amountValue).String()
oneCirclesAvailableGreenEnergyPointsFlow.BeforeDevelopmentCommitteeValues = chain.DevelopmentCommittee //发展委员会
oneCirclesAvailableGreenEnergyPointsFlow.AfterDevelopmentCommitteeValues = chain.DevelopmentCommittee
oneCirclesAvailableGreenEnergyPointsFlow.BeforePublicWelfareAndCharityValues = chain.PublicWelfareAndCharity //公益慈善
oneCirclesAvailableGreenEnergyPointsFlow.AfterPublicWelfareAndCharityValues = chain.PublicWelfareAndCharity
oneCirclesAvailableGreenEnergyPointsFlow.BeforeStarLevelDividendsValues = chain.StarLevelDividends //星级分红
oneCirclesAvailableGreenEnergyPointsFlow.AfterStarLevelDividendsValues = chain.StarLevelDividends //星级分红
oneCirclesAvailableGreenEnergyPointsFlow.BeforeDestructionQuantityValues = chain.DestructionQuantityNums //销毁数量
oneCirclesAvailableGreenEnergyPointsFlow.AfterDestructionQuantityValues = chain.DestructionQuantityNums

amountFeeValue := decimal.NewFromFloat(amountFee) //金额
oneCirclesAvailableGreenEnergyPointsFlow.BeforeOriginalQuantityFundValues = chain.OriginalFunds //原始资金
oneCirclesAvailableGreenEnergyPointsFlow.AfterOriginalQuantityFundValues = beforeOriginalFunds.Sub(amountFeeValue).String()

oneCirclesAvailableGreenEnergyPointsFlow.BeforeMarketplaceMerchantFundValues = chain.MarketplaceMerchantFunds //市商资金
oneCirclesAvailableGreenEnergyPointsFlow.AfterMarketplaceMerchantFundValues = beforeMarketplaceMerchantFunds.Add(amountFeeValue).String()
break
case int(enum.MarketplaceMerchantFundsAutoExchangeMarketplaceMerchantNums): //市商资金自动兑换市商数量
beforeOriginalQuantityNums, _ := decimal.NewFromString(chain.OriginalQuantityNums)
beforeMarketplaceMerchantNums, _ := decimal.NewFromString(chain.MarketplaceMerchantNums)
beforeOriginalFunds, _ := decimal.NewFromString(chain.OriginalFunds)
beforeMarketplaceMerchantFunds, _ := decimal.NewFromString(chain.MarketplaceMerchantFunds)

oneCirclesAvailableGreenEnergyPointsFlow.Direction = 1
oneCirclesAvailableGreenEnergyPointsFlow.BeforeEcologicalApplicationValues = chain.EcologicalApplication //生态应用
oneCirclesAvailableGreenEnergyPointsFlow.AfterEcologicalApplicationValues = chain.EcologicalApplication
oneCirclesAvailableGreenEnergyPointsFlow.BeforeTechnicalTeamValues = chain.TotalTechnologyTeam //技术团队
oneCirclesAvailableGreenEnergyPointsFlow.AfterTechnicalTeamValues = chain.TotalTechnologyTeam
oneCirclesAvailableGreenEnergyPointsFlow.BeforeOperateTeamValues = chain.TotalOperateTeam //运营团队
oneCirclesAvailableGreenEnergyPointsFlow.AfterOperateTeamValues = chain.TotalOperateTeam
oneCirclesAvailableGreenEnergyPointsFlow.BeforeActiveGiveawaysValues = chain.TotalActiveGiveaways //活跃赠送
oneCirclesAvailableGreenEnergyPointsFlow.AfterActiveGiveawaysValues = chain.TotalActiveGiveaways
oneCirclesAvailableGreenEnergyPointsFlow.BeforeOriginalQuantityValues = chain.OriginalQuantityNums //原始数量
oneCirclesAvailableGreenEnergyPointsFlow.AfterOriginalQuantityValues = beforeOriginalQuantityNums.Sub(amountValue).String()
oneCirclesAvailableGreenEnergyPointsFlow.BeforeMarketplaceMerchantValues = chain.MarketplaceMerchantNums //市商数量
oneCirclesAvailableGreenEnergyPointsFlow.AfterMarketplaceMerchantValues = beforeMarketplaceMerchantNums.Add(amountValue).String()
oneCirclesAvailableGreenEnergyPointsFlow.BeforeDevelopmentCommitteeValues = chain.DevelopmentCommittee //发展委员会
oneCirclesAvailableGreenEnergyPointsFlow.AfterDevelopmentCommitteeValues = chain.DevelopmentCommittee
oneCirclesAvailableGreenEnergyPointsFlow.BeforePublicWelfareAndCharityValues = chain.PublicWelfareAndCharity //公益慈善
oneCirclesAvailableGreenEnergyPointsFlow.AfterPublicWelfareAndCharityValues = chain.PublicWelfareAndCharity
oneCirclesAvailableGreenEnergyPointsFlow.BeforeStarLevelDividendsValues = chain.StarLevelDividends //星级分红
oneCirclesAvailableGreenEnergyPointsFlow.AfterStarLevelDividendsValues = chain.StarLevelDividends //星级分红
oneCirclesAvailableGreenEnergyPointsFlow.BeforeDestructionQuantityValues = chain.DestructionQuantityNums //销毁数量
oneCirclesAvailableGreenEnergyPointsFlow.AfterDestructionQuantityValues = chain.DestructionQuantityNums

amountFeeValue := decimal.NewFromFloat(amountFee) //金额
oneCirclesAvailableGreenEnergyPointsFlow.BeforeOriginalQuantityFundValues = chain.OriginalFunds //原始资金
oneCirclesAvailableGreenEnergyPointsFlow.AfterOriginalQuantityFundValues = beforeOriginalFunds.Add(amountFeeValue).String()

oneCirclesAvailableGreenEnergyPointsFlow.BeforeMarketplaceMerchantFundValues = chain.MarketplaceMerchantFunds //市商资金
oneCirclesAvailableGreenEnergyPointsFlow.AfterMarketplaceMerchantFundValues = beforeMarketplaceMerchantFunds.Sub(amountFeeValue).String()
break
}

chain.EcologicalApplication = oneCirclesAvailableGreenEnergyPointsFlow.AfterEcologicalApplicationValues //生态应用
chain.TotalTechnologyTeam = oneCirclesAvailableGreenEnergyPointsFlow.AfterTechnicalTeamValues //技术团队
chain.TotalOperateTeam = oneCirclesAvailableGreenEnergyPointsFlow.AfterOperateTeamValues //运营团队
chain.TotalActiveGiveaways = oneCirclesAvailableGreenEnergyPointsFlow.AfterActiveGiveawaysValues //活跃赠送
chain.OriginalQuantityNums = oneCirclesAvailableGreenEnergyPointsFlow.AfterOriginalQuantityValues //原始数量
chain.MarketplaceMerchantNums = oneCirclesAvailableGreenEnergyPointsFlow.AfterMarketplaceMerchantValues //市商数量
chain.DevelopmentCommittee = oneCirclesAvailableGreenEnergyPointsFlow.AfterDevelopmentCommitteeValues //发展委员会
chain.PublicWelfareAndCharity = oneCirclesAvailableGreenEnergyPointsFlow.AfterPublicWelfareAndCharityValues //公益慈善
chain.StarLevelDividends = oneCirclesAvailableGreenEnergyPointsFlow.AfterStarLevelDividendsValues //星级分红
chain.DestructionQuantityNums = oneCirclesAvailableGreenEnergyPointsFlow.AfterDestructionQuantityValues //销毁数量

chain.OriginalFunds = oneCirclesAvailableGreenEnergyPointsFlow.AfterOriginalQuantityFundValues //原始资金
chain.MarketplaceMerchantFunds = oneCirclesAvailableGreenEnergyPointsFlow.AfterMarketplaceMerchantFundValues //市商资金
//更新 `one_circles_green_energy_basic_setting` 表
if chain.NowPrice != nowPriceValue {
chain.NowPrice = nowPriceValue
// 新增 / 更新 one_circles_green_energy_price 记录
date := now.Format("2006-01-02")
hour := zhios_order_relate_utils.IntToStr(now.Hour())
oneCirclesGreenEnergyPrice, err := db.OneCirclesGreenEnergyPriceGetOneByParamsBySession(session, date, hour)
if err != nil {
return err
}
if oneCirclesGreenEnergyPrice == nil {
oneCirclesGreenEnergyPrice = &model.OneCirclesGreenEnergyPrice{
Price: nowPriceValue,
Date: date,
Hour: hour,
}
insertId, err1 := db.OneCirclesGreenEnergyPriceInsertBySession(session, oneCirclesGreenEnergyPrice)
if err1 != nil {
return err1
}
if insertId <= 0 {
return errors.New("插入 one_circles_green_energy_price 失败")
}
} else {
oneCirclesGreenEnergyPrice.Price = nowPriceValue
updateAffected, err1 := db.OneCirclesGreenEnergyPriceUpdate(session, oneCirclesGreenEnergyPrice.Id, oneCirclesGreenEnergyPrice, "price")
if err1 != nil {
return err1
}
if updateAffected <= 0 {
return errors.New("更新 one_circles_green_energy_price 失败")
}
}
}
_, err := db.OneCirclesGreenEnergyBasicSettingUpdate(session, chain.Id, chain)
if err != nil {
return err
}

//插入 `one_circles_available_green_energy_points_flow` 记录
_, err = db.OneCirclesAvailableGreenEnergyPointsFlowInsert(session, &oneCirclesAvailableGreenEnergyPointsFlow)
if err != nil {
return err
}
return nil
}

+ 14
- 0
rule/one_circles/one_circles_init.go View File

@@ -0,0 +1,14 @@
package one_circles

import (
"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/utils/cache"
)

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

+ 242
- 0
rule/one_circles/one_circles_public_platoon_give_activty_coin.go View File

@@ -0,0 +1,242 @@
package one_circles

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/md"
md2 "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule/one_circles/md"
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"
"encoding/json"
"errors"
"fmt"
"strings"
"time"
"xorm.io/xorm"
)

// SettlementPublicGiveActivityCoin 计算观看激励视屏得到活跃积分
func SettlementPublicGiveActivityCoin(engine *xorm.Engine, masterId string, uid int) (err error) {
//1、查找 `one_circles_public_platoon_basic_setting` 基础设置
oneCirclesPublicPlatoonBasicSetting, err := db.OneCirclesPublicPlatoonBasicSettingGetOneByParams(engine, map[string]interface{}{
"key": "is_open",
"value": 1,
})
if err != nil {
return
}
if oneCirclesPublicPlatoonBasicSetting.VideoRewardIsOpen == 1 {
var videoRewardSystem *md2.VideoRewardSystemStruct
err = json.Unmarshal([]byte(oneCirclesPublicPlatoonBasicSetting.VideoRewardSystem), &videoRewardSystem)
if err != nil {
return
}
if videoRewardSystem.RewardValue == "" || videoRewardSystem.RewardTotalNum == "" || videoRewardSystem.IntervalMinutes == "" || videoRewardSystem.EachRoundHour == "" {
err = errors.New("视屏奖励机制设置未完全!")
return
}
var rewardSystem []*md2.RewardSystemStruct
err = json.Unmarshal([]byte(oneCirclesPublicPlatoonBasicSetting.RewardSystem), &rewardSystem)
if err != nil {
return
}
if len(rewardSystem) == 0 {
err = errors.New("未设置奖励机制!")
return
}
rewardValue := zhios_order_relate_utils.StrToFloat64(videoRewardSystem.RewardValue) //奖励多少个活跃积分
var rewardSystemMap = map[int]*md2.RewardSystemStruct{}
for _, v := range rewardSystem {
rewardSystemMap[v.Level] = v
}
oneCirclesPublicPlatoonUserRelation, err1 := db.OneCirclesPublicPlatoonUserRelationGetOneByParams(engine, map[string]interface{}{
"key": "uid",
"value": uid,
})
if err1 != nil {
return err1
}

var rewardFather []struct {
Uid int `json:"uid"` //用户id
RewardValue float64 `json:"reward_value"` //奖励值
}

var fatherUids []string
if oneCirclesPublicPlatoonUserRelation != nil {
fatherUids = strings.Split(oneCirclesPublicPlatoonUserRelation.FatherUid, "-")
}
for k, id := range fatherUids {
tmpOneCirclesPublicPlatoonUserRelation, err11 := db.OneCirclesPublicPlatoonUserRelationGetOneByParams(engine, map[string]interface{}{
"key": "id",
"value": id,
})
if err11 != nil {
return err11
}
if tmpOneCirclesPublicPlatoonUserRelation == nil {
continue
}
if tmpOneCirclesPublicPlatoonUserRelation.Uid <= 0 {
//待填充位
continue
}

fatherUid := zhios_order_relate_utils.IntToStr(tmpOneCirclesPublicPlatoonUserRelation.Uid)
fatherReward := rewardSystemMap[k+1]
//TODO::判断是否活跃
var m model.OneCirclesGreenEnergySignIn
has, err33 := engine.Where("uid =?", fatherUid).And("end_time >=?", time.Now().Format("2006-01-02 15:04:05")).Get(&m)
if err33 != nil {
return err33
}
if !has {
//不活跃不需要奖励
continue
}
//判断是否满足奖励条件
userCount, _, err2 := db.SumUserRelateByParentUid(engine, fatherUid)
if err2 != nil {
return err2
}

if fatherReward != nil && userCount >= zhios_order_relate_utils.StrToInt64(fatherReward.RewardCondition) {
fatherRewardValue := rewardValue * (zhios_order_relate_utils.StrToFloat64(fatherReward.RewardValue) / 100)
rewardFather = append(rewardFather, struct {
Uid int `json:"uid"` //用户id
RewardValue float64 `json:"reward_value"` //奖励值
}{
Uid: zhios_order_relate_utils.StrToInt(fatherUid),
RewardValue: fatherRewardValue,
})
}
}

//增加 one_circles_user_watch_records 记录
oneCirclesUserWatchRecords, err1 := db.OneCirclesUserWatchRecordsGetOneByParams(engine, map[string]interface{}{
"key": "uid",
"value": uid,
})
if err1 != nil {
return err1
}
now := time.Now()
if oneCirclesUserWatchRecords == nil {
residueWatchAdNum := zhios_order_relate_utils.StrToInt(videoRewardSystem.RewardTotalNum) - 1
if residueWatchAdNum < 0 {
residueWatchAdNum = zhios_order_relate_utils.StrToInt(videoRewardSystem.RewardTotalNum)
}
_, err2 := db.OneCirclesUserWatchRecordsInsert(engine, &model.OneCirclesUserWatchRecords{
Uid: uid,
NextWatchAdDate: now.Add(time.Hour * time.Duration(zhios_order_relate_utils.StrToInt(videoRewardSystem.EachRoundHour))),
ResidueWatchAdNum: zhios_order_relate_utils.StrToInt(videoRewardSystem.RewardTotalNum) - 1,
CreateAt: now,
UpdateAt: now,
})
if err2 != nil {
return err2
}
} else {
residueWatchAdNum := oneCirclesUserWatchRecords.ResidueWatchAdNum - 1
nextWatchAdDate := oneCirclesUserWatchRecords.NextWatchAdDate
if residueWatchAdNum == 0 { //最后一条广告
residueWatchAdNum = zhios_order_relate_utils.StrToInt(videoRewardSystem.RewardTotalNum)
}
if residueWatchAdNum == zhios_order_relate_utils.StrToInt(videoRewardSystem.RewardTotalNum)-1 { //第一条广告
nextWatchAdDate = now.Add(time.Hour * time.Duration(zhios_order_relate_utils.StrToInt(videoRewardSystem.EachRoundHour)))
}
oneCirclesUserWatchRecords.ResidueWatchAdNum = residueWatchAdNum
oneCirclesUserWatchRecords.NextWatchAdDate = nextWatchAdDate
_, err2 := db.OneCirclesUserWatchRecordsUpdate(engine, oneCirclesUserWatchRecords.Id, oneCirclesUserWatchRecords, "residue_watch_ad_num", "next_watch_ad_date")
if err2 != nil {
return err2
}
}

session := engine.NewSession()
defer func() {
session.Close()
if err := recover(); err != nil {
_ = zhios_order_relate_logx.Error(err)
}
}()
session.Begin()

//给相应的用户加上"个人"活跃积分
err = DealUserCoin(session, md.DealUserCoinReq{
Kind: "add",
Mid: masterId,
Title: md.OneCirclesWatchAdRewardPersonalActiveCoin,
TransferType: md.OneCirclesWatchAdRewardPersonalActiveCoinForUserVirtualCoinFlow,
OrdId: "",
CoinId: oneCirclesPublicPlatoonBasicSetting.PersonActivePointsCoinId,
Uid: uid,
Amount: rewardValue,
})
if err != nil {
_ = session.Rollback()
fmt.Println("err:::::2222", err)
return err
}

//给相应的用户加上"团队"活跃积分
for _, vv := range rewardFather {
err = DealUserCoin(session, md.DealUserCoinReq{
Kind: "add",
Mid: masterId,
Title: md.OneCirclesWatchAdRewardTeamActiveCoin,
TransferType: md.OneCirclesWatchAdRewardTeamActiveCoinForUserVirtualCoinFlow,
OrdId: "",
CoinId: oneCirclesPublicPlatoonBasicSetting.TeamActivePointsCoinId,
Uid: vv.Uid,
Amount: vv.RewardValue,
})
if err != nil {
_ = session.Rollback()
fmt.Println("err:::::2222", err)
return err
}
}
err = session.Commit()
if err != nil {
_ = session.Rollback()
return errors.New("事务提交失败")
}

redisKey := fmt.Sprintf(md2.UserNextWatchAdDate, masterId, uid)
var watchAdDate string
if oneCirclesUserWatchRecords.ResidueWatchAdNum == zhios_order_relate_utils.StrToInt(videoRewardSystem.RewardTotalNum) {
if oneCirclesUserWatchRecords.NextWatchAdDate.Before(time.Now()) {
watchAdDate = ""
} else {
watchAdDate = oneCirclesUserWatchRecords.NextWatchAdDate.Format("2006-01-02 15:04:05")
}
} else {
watchAdDate = time.Now().Add(time.Duration(zhios_order_relate_utils.StrToInt64(videoRewardSystem.IntervalMinutes)) * time.Minute).Format("2006-01-02 15:04:05")
//watchAdDate = oneCirclesUserWatchRecords.NextWatchAdDate.Format("2006-01-02 15:04:05")
}
cache.SetEx(redisKey, watchAdDate, 60*60*24) //TODO::默认缓存1小时
}
return
}

// CalcUserContinuousDailyActivityDays 计算用户连续活跃天数
func CalcUserContinuousDailyActivityDays(engine *xorm.Engine, masterId string, uid int, startDate string, endDate string) (err error, days int, isContinuousDailyActivity bool) {
startAt, err := time.ParseInLocation("2006-01-02", startDate, time.Local) //起始时间
endAt, err := time.ParseInLocation("2006-01-02", endDate, time.Local) //起始时间
var list []model.OneCirclesUserActivity
err = engine.Where("date >= ?", startAt.Format("2006-01-02")).
And("date < ?", endAt.Format("2006-01-02")).
And("uid =?", uid).Find(&list)
if err != nil {
fmt.Println("err:::::1111", err)
return
}
days = len(list)
diffDays := zhios_order_relate_utils.GetDiffDays(endAt, startAt) //相差天数
if days == diffDays {
isContinuousDailyActivity = true
}
return
}

+ 909
- 0
rule/one_circles/one_circles_public_platoon_user_relation_commission.go View File

@@ -0,0 +1,909 @@
package one_circles

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/md"
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"
"math"
"strconv"
"strings"
"time"
"xorm.io/xorm"
)

// AddOneCirclesPublicPlatoonUserRelationCommission 新增公排用户关系记录
func AddOneCirclesPublicPlatoonUserRelationCommission(engine *xorm.Engine, AddOneCirclesPublicPlatoonUserRelationCommissionReqList []*md.AddOneCirclesPublicPlatoonUserRelationCommissionReq) (map[string]*model.OneCirclesPublicPlatoonUserRelation, error) {
var resp = map[string]*model.OneCirclesPublicPlatoonUserRelation{}
//查找 `one_circles_public_platoon_basic_setting` 基础设置
oneCirclesPublicPlatoonBasicSetting, err := db.OneCirclesPublicPlatoonBasicSettingGetOneByParams(engine, map[string]interface{}{
"key": "is_open",
"value": 1,
})
if err != nil {
return nil, err
}
if oneCirclesPublicPlatoonBasicSetting == nil {
return nil, errors.New("公排制度未开启")
}

for _, param := range AddOneCirclesPublicPlatoonUserRelationCommissionReqList {
isHasOneCirclesPublicPlatoonUserRelation, err11 := db.OneCirclesPublicPlatoonUserRelationGetOneByParams(engine, map[string]interface{}{
"key": "uid",
"value": param.Uid,
})
if err11 != nil {
return nil, err11
}
if isHasOneCirclesPublicPlatoonUserRelation != nil {
return nil, errors.New("当前用户已加入公排")
}

//1、判断是否有推荐人
if param.RecommendUid != "" {
//2、有推荐人
//判断是否有uid为-1 (代表等待新用户填充) 的记录
oneCirclesPublicPlatoonUserRelation, err1 := db.OneCirclesPublicPlatoonUserRelationGetOneByPid(engine, param.RecommendUid, map[string]interface{}{
"key": "uid",
"value": -1,
})
if err1 != nil {
return nil, err1
}
if oneCirclesPublicPlatoonUserRelation != nil {
now := time.Now()
oldUid := oneCirclesPublicPlatoonUserRelation.Uid
oneCirclesPublicPlatoonUserRelation.Uid = zhios_order_relate_utils.StrToInt(param.Uid)
oneCirclesPublicPlatoonUserRelation.RecommendUid = zhios_order_relate_utils.StrToInt(param.RecommendUid)
oneCirclesPublicPlatoonUserRelation.CreateAt = now.Format("2006-01-02 15:04:05")
oneCirclesPublicPlatoonUserRelation.UpdateAt = now.Format("2006-01-02 15:04:05")
oneCirclesPublicPlatoonUserRelation.JoinAt = now.Format("2006-01-02 15:04:05")
updateAffected, err2 := db.OneCirclesPublicPlatoonUserRelationUpdate(engine.NewSession(), oneCirclesPublicPlatoonUserRelation.Id, oneCirclesPublicPlatoonUserRelation)
if err2 != nil {
return nil, err2
}
if updateAffected == 0 {
err = errors.New("更新 one_circles_public_platoon_user_relation 记录失败")
return nil, err
} else {
for n := 1; n <= 9; n++ {
str := "father_uid" + strconv.Itoa(n)
sql := fmt.Sprintf("UPDATE `one_circles_public_platoon_user_relation` SET %s=%s where %s=%s", str, param.Uid, str, strconv.Itoa(oldUid))
fmt.Println(">>>>>>>sql>>>>>>>", sql)
_, err = engine.Exec(sql)
if err != nil {
return nil, err
}
}
resp[param.Uid] = oneCirclesPublicPlatoonUserRelation
}
continue
}
res, err := OneCirclesPublicPlatoon(engine, zhios_order_relate_utils.StrToInt(param.Uid), zhios_order_relate_utils.StrToInt(param.RecommendUid), *oneCirclesPublicPlatoonBasicSetting)
if err != nil {
return nil, err
}
resp[param.Uid] = &res
}
}
return resp, nil
}

/*
公排方法
TODO 相关公式:
1: 每个等级的起始值(1+5^0+5^1+5^2+...+5^x-2), 每个等级的结束值(`5^0+5^1+5^2+...+5^x-1)
2: 根据position查找父级position { (position-1)/5 }
3: 根据position查找等级level {position-5^0-5^1-5^2-...-5^x 是否 <0 ? => x+1 }
4: 根据最新自增`id` 逆向推导 position {levelFirstPosition + (position-1)%5}
*/
func OneCirclesPublicPlatoon(engine *xorm.Engine, uid, recommendUid int, oneCirclesPublicPlatoonBasicSetting model.OneCirclesPublicPlatoonBasicSetting) (model.OneCirclesPublicPlatoonUserRelation, error) {
var standardSmallPublicPlatoonRelation md.StandardSmallPublicPlatoonRelation
var oneCirclesPublicPlatoonUserRelation model.OneCirclesPublicPlatoonUserRelation
var fatherUid int
//1、 查找当前 one_circles_public_platoon_user_relation 中 recommendUid 的记录
m, err := db.OneCirclesPublicPlatoonUserRelationGetOneByParams(engine, map[string]interface{}{
"key": "uid",
"value": recommendUid,
})
if err != nil {
return model.OneCirclesPublicPlatoonUserRelation{}, err
}

//2、 查找当前 one_circles_public_platoon_user_relation 中 recommendUid 所有的子记录
oneCirclesPublicPlatoonUserRelations, err := db.OneCirclesPublicPlatoonUserRelationFindByPid(engine, m.Uid, "father_uid1", "position1")
if err != nil {
return model.OneCirclesPublicPlatoonUserRelation{}, err
}

if len(oneCirclesPublicPlatoonUserRelations) == 0 {
fatherUid = m.Uid

//证明是第一个
standardSmallPublicPlatoonRelation.FatherUid1 = m.Uid
standardSmallPublicPlatoonRelation.FatherUid2 = m.FatherUid1
standardSmallPublicPlatoonRelation.FatherUid3 = m.FatherUid2
standardSmallPublicPlatoonRelation.FatherUid4 = m.FatherUid3
standardSmallPublicPlatoonRelation.FatherUid5 = m.FatherUid4
standardSmallPublicPlatoonRelation.FatherUid6 = m.FatherUid5
standardSmallPublicPlatoonRelation.FatherUid7 = m.FatherUid6
standardSmallPublicPlatoonRelation.FatherUid8 = m.FatherUid7
standardSmallPublicPlatoonRelation.FatherUid9 = m.FatherUid8

standardSmallPublicPlatoonRelation.Pid1 = m.Position
standardSmallPublicPlatoonRelation.Pid2 = m.Position1
standardSmallPublicPlatoonRelation.Pid3 = m.Position2
standardSmallPublicPlatoonRelation.Pid4 = m.Position3
standardSmallPublicPlatoonRelation.Pid5 = m.Position4
standardSmallPublicPlatoonRelation.Pid6 = m.Position5
standardSmallPublicPlatoonRelation.Pid7 = m.Position6
standardSmallPublicPlatoonRelation.Pid8 = m.Position7
standardSmallPublicPlatoonRelation.Pid9 = m.Position8

standardSmallPublicPlatoonRelation.Position1 = oneCirclesSmallSearchPositionFirstSonPosition(m.Position, oneCirclesPublicPlatoonBasicSetting.SeveralTimes)
standardSmallPublicPlatoonRelation.Position2 = oneCirclesSmallReverseDeductionPositionByFather(m.Position1, m.Level1, oneCirclesPublicPlatoonBasicSetting.SeveralTimes, 0)
standardSmallPublicPlatoonRelation.Position3 = oneCirclesSmallReverseDeductionPositionByFather(m.Position2, m.Level2, oneCirclesPublicPlatoonBasicSetting.SeveralTimes, 0)
standardSmallPublicPlatoonRelation.Position4 = oneCirclesSmallReverseDeductionPositionByFather(m.Position3, m.Level3, oneCirclesPublicPlatoonBasicSetting.SeveralTimes, 0)
standardSmallPublicPlatoonRelation.Position5 = oneCirclesSmallReverseDeductionPositionByFather(m.Position4, m.Level4, oneCirclesPublicPlatoonBasicSetting.SeveralTimes, 0)
standardSmallPublicPlatoonRelation.Position6 = oneCirclesSmallReverseDeductionPositionByFather(m.Position5, m.Level5, oneCirclesPublicPlatoonBasicSetting.SeveralTimes, 0)
standardSmallPublicPlatoonRelation.Position7 = oneCirclesSmallReverseDeductionPositionByFather(m.Position6, m.Level6, oneCirclesPublicPlatoonBasicSetting.SeveralTimes, 0)
standardSmallPublicPlatoonRelation.Position8 = oneCirclesSmallReverseDeductionPositionByFather(m.Position7, m.Level7, oneCirclesPublicPlatoonBasicSetting.SeveralTimes, 0)
standardSmallPublicPlatoonRelation.Position9 = oneCirclesSmallReverseDeductionPositionByFather(m.Position8, m.Level8, oneCirclesPublicPlatoonBasicSetting.SeveralTimes, 0)

if m.Level1 == 0 {
m.Level1--
}
if m.Level2 == 0 {
m.Level2--
}
if m.Level3 == 0 {
m.Level3--
}
if m.Level4 == 0 {
m.Level4--
}
if m.Level5 == 0 {
m.Level5--
}
if m.Level6 == 0 {
m.Level6--
}
if m.Level7 == 0 {
m.Level7--
}
if m.Level8 == 0 {
m.Level8--
}
if m.Level9 == 0 {
m.Level9--
}

standardSmallPublicPlatoonRelation.Level1 = m.Level + 1
standardSmallPublicPlatoonRelation.Level2 = m.Level1 + 1
standardSmallPublicPlatoonRelation.Level3 = m.Level2 + 1
standardSmallPublicPlatoonRelation.Level4 = m.Level3 + 1
standardSmallPublicPlatoonRelation.Level5 = m.Level4 + 1
standardSmallPublicPlatoonRelation.Level6 = m.Level5 + 1
standardSmallPublicPlatoonRelation.Level7 = m.Level6 + 1
standardSmallPublicPlatoonRelation.Level8 = m.Level7 + 1
standardSmallPublicPlatoonRelation.Level9 = m.Level8 + 1
standardSmallPublicPlatoonRelation.LevelTotal = m.LevelTotal + 1
} else {
//TODO::判断直属下级是否排满
if len(oneCirclesPublicPlatoonUserRelations) >= oneCirclesPublicPlatoonBasicSetting.SeveralTimes {
var fatherLevel float64
smallMakeSearchLevel(&m.Position, float64(oneCirclesPublicPlatoonBasicSetting.SeveralTimes), &fatherLevel)
var times = 0
data, father, err := oneCirclesSmallFindSuitablePosition(engine, &m.Position, float64(oneCirclesPublicPlatoonBasicSetting.SeveralTimes), m.Uid, int(fatherLevel), &times)
if err != nil {
return model.OneCirclesPublicPlatoonUserRelation{}, err
}
fatherUid = father
standardSmallPublicPlatoonRelation = data
} else {
fatherUid = m.Uid

standardSmallPublicPlatoonRelation.FatherUid1 = oneCirclesPublicPlatoonUserRelations[0].FatherUid1
standardSmallPublicPlatoonRelation.FatherUid2 = oneCirclesPublicPlatoonUserRelations[0].FatherUid2
standardSmallPublicPlatoonRelation.FatherUid3 = oneCirclesPublicPlatoonUserRelations[0].FatherUid3
standardSmallPublicPlatoonRelation.FatherUid4 = oneCirclesPublicPlatoonUserRelations[0].FatherUid4
standardSmallPublicPlatoonRelation.FatherUid5 = oneCirclesPublicPlatoonUserRelations[0].FatherUid5
standardSmallPublicPlatoonRelation.FatherUid6 = oneCirclesPublicPlatoonUserRelations[0].FatherUid6
standardSmallPublicPlatoonRelation.FatherUid7 = oneCirclesPublicPlatoonUserRelations[0].FatherUid7
standardSmallPublicPlatoonRelation.FatherUid8 = oneCirclesPublicPlatoonUserRelations[0].FatherUid8
standardSmallPublicPlatoonRelation.FatherUid9 = oneCirclesPublicPlatoonUserRelations[0].FatherUid9

standardSmallPublicPlatoonRelation.Pid1 = oneCirclesPublicPlatoonUserRelations[0].Pid1
standardSmallPublicPlatoonRelation.Pid2 = oneCirclesPublicPlatoonUserRelations[0].Pid2
standardSmallPublicPlatoonRelation.Pid3 = oneCirclesPublicPlatoonUserRelations[0].Pid3
standardSmallPublicPlatoonRelation.Pid4 = oneCirclesPublicPlatoonUserRelations[0].Pid4
standardSmallPublicPlatoonRelation.Pid5 = oneCirclesPublicPlatoonUserRelations[0].Pid5
standardSmallPublicPlatoonRelation.Pid6 = oneCirclesPublicPlatoonUserRelations[0].Pid6
standardSmallPublicPlatoonRelation.Pid7 = oneCirclesPublicPlatoonUserRelations[0].Pid7
standardSmallPublicPlatoonRelation.Pid8 = oneCirclesPublicPlatoonUserRelations[0].Pid8
standardSmallPublicPlatoonRelation.Pid9 = oneCirclesPublicPlatoonUserRelations[0].Pid9

standardSmallPublicPlatoonRelation.Position1 = oneCirclesPublicPlatoonUserRelations[0].Position1 + 1
if oneCirclesPublicPlatoonUserRelations[0].Position2 != 0 {
standardSmallPublicPlatoonRelation.Position2 = oneCirclesPublicPlatoonUserRelations[0].Position2 + 1
}
if oneCirclesPublicPlatoonUserRelations[0].Position3 != 0 {
standardSmallPublicPlatoonRelation.Position3 = oneCirclesPublicPlatoonUserRelations[0].Position3 + 1
}
if oneCirclesPublicPlatoonUserRelations[0].Position4 != 0 {
standardSmallPublicPlatoonRelation.Position4 = oneCirclesPublicPlatoonUserRelations[0].Position4 + 1
}
if oneCirclesPublicPlatoonUserRelations[0].Position5 != 0 {
standardSmallPublicPlatoonRelation.Position5 = oneCirclesPublicPlatoonUserRelations[0].Position5 + 1
}
if oneCirclesPublicPlatoonUserRelations[0].Position6 != 0 {
standardSmallPublicPlatoonRelation.Position6 = oneCirclesPublicPlatoonUserRelations[0].Position6 + 1
}
if oneCirclesPublicPlatoonUserRelations[0].Position7 != 0 {
standardSmallPublicPlatoonRelation.Position7 = oneCirclesPublicPlatoonUserRelations[0].Position7 + 1
}
if oneCirclesPublicPlatoonUserRelations[0].Position8 != 0 {
standardSmallPublicPlatoonRelation.Position8 = oneCirclesPublicPlatoonUserRelations[0].Position8 + 1
}
if oneCirclesPublicPlatoonUserRelations[0].Position9 != 0 {
standardSmallPublicPlatoonRelation.Position9 = oneCirclesPublicPlatoonUserRelations[0].Position9 + 1
}

standardSmallPublicPlatoonRelation.Level1 = oneCirclesPublicPlatoonUserRelations[0].Level1
standardSmallPublicPlatoonRelation.Level2 = oneCirclesPublicPlatoonUserRelations[0].Level2
standardSmallPublicPlatoonRelation.Level3 = oneCirclesPublicPlatoonUserRelations[0].Level3
standardSmallPublicPlatoonRelation.Level4 = oneCirclesPublicPlatoonUserRelations[0].Level4
standardSmallPublicPlatoonRelation.Level5 = oneCirclesPublicPlatoonUserRelations[0].Level5
standardSmallPublicPlatoonRelation.Level6 = oneCirclesPublicPlatoonUserRelations[0].Level6
standardSmallPublicPlatoonRelation.Level7 = oneCirclesPublicPlatoonUserRelations[0].Level7
standardSmallPublicPlatoonRelation.Level8 = oneCirclesPublicPlatoonUserRelations[0].Level8
standardSmallPublicPlatoonRelation.Level9 = oneCirclesPublicPlatoonUserRelations[0].Level9
standardSmallPublicPlatoonRelation.LevelTotal = oneCirclesPublicPlatoonUserRelations[0].LevelTotal

}

}

//2、查找对应pid的 one_circles_public_platoon_user_relation 记录
var m1 model.OneCirclesPublicPlatoonUserRelation
if has, err := engine.Where("uid=?", fatherUid).Get(&m1); err != nil || has == false {
return oneCirclesPublicPlatoonUserRelation, err
}
var fatherUidStr string
if m1.FatherUid == "" {
//TODO::顶级
fatherUidStr = zhios_order_relate_utils.IntToStr(m1.Id)
} else {
fatherUids := strings.Split(m1.FatherUid, "-")
if len(fatherUids) >= oneCirclesPublicPlatoonBasicSetting.SeveralRows {
fatherUidStr = zhios_order_relate_utils.IntToStr(m1.Id) + "-" + strings.Join(fatherUids[0:oneCirclesPublicPlatoonBasicSetting.SeveralRows:len(fatherUids)], "-")
} else {
fatherUidStr = zhios_order_relate_utils.IntToStr(m1.Id) + "-" + m1.FatherUid
}
}

// 3、插入 one_circles_public_platoon_user_relation 记录
now := time.Now()
oneCirclesPublicPlatoonUserRelation.Uid = uid
oneCirclesPublicPlatoonUserRelation.FatherUid = fatherUidStr

oneCirclesPublicPlatoonUserRelation.FatherUid1 = standardSmallPublicPlatoonRelation.FatherUid1
oneCirclesPublicPlatoonUserRelation.FatherUid2 = standardSmallPublicPlatoonRelation.FatherUid2
oneCirclesPublicPlatoonUserRelation.FatherUid3 = standardSmallPublicPlatoonRelation.FatherUid3
oneCirclesPublicPlatoonUserRelation.FatherUid4 = standardSmallPublicPlatoonRelation.FatherUid4
oneCirclesPublicPlatoonUserRelation.FatherUid5 = standardSmallPublicPlatoonRelation.FatherUid5
oneCirclesPublicPlatoonUserRelation.FatherUid6 = standardSmallPublicPlatoonRelation.FatherUid6
oneCirclesPublicPlatoonUserRelation.FatherUid7 = standardSmallPublicPlatoonRelation.FatherUid7
oneCirclesPublicPlatoonUserRelation.FatherUid8 = standardSmallPublicPlatoonRelation.FatherUid8
oneCirclesPublicPlatoonUserRelation.FatherUid9 = standardSmallPublicPlatoonRelation.FatherUid9
oneCirclesPublicPlatoonUserRelation.Pid1 = standardSmallPublicPlatoonRelation.Pid1
oneCirclesPublicPlatoonUserRelation.Pid2 = standardSmallPublicPlatoonRelation.Pid2
oneCirclesPublicPlatoonUserRelation.Pid3 = standardSmallPublicPlatoonRelation.Pid3
oneCirclesPublicPlatoonUserRelation.Pid4 = standardSmallPublicPlatoonRelation.Pid4
oneCirclesPublicPlatoonUserRelation.Pid5 = standardSmallPublicPlatoonRelation.Pid5
oneCirclesPublicPlatoonUserRelation.Pid6 = standardSmallPublicPlatoonRelation.Pid6
oneCirclesPublicPlatoonUserRelation.Pid7 = standardSmallPublicPlatoonRelation.Pid7
oneCirclesPublicPlatoonUserRelation.Pid8 = standardSmallPublicPlatoonRelation.Pid8
oneCirclesPublicPlatoonUserRelation.Pid9 = standardSmallPublicPlatoonRelation.Pid9
oneCirclesPublicPlatoonUserRelation.Position = 1
oneCirclesPublicPlatoonUserRelation.Position1 = standardSmallPublicPlatoonRelation.Position1
oneCirclesPublicPlatoonUserRelation.Position2 = standardSmallPublicPlatoonRelation.Position2
oneCirclesPublicPlatoonUserRelation.Position3 = standardSmallPublicPlatoonRelation.Position3
oneCirclesPublicPlatoonUserRelation.Position4 = standardSmallPublicPlatoonRelation.Position4
oneCirclesPublicPlatoonUserRelation.Position5 = standardSmallPublicPlatoonRelation.Position5
oneCirclesPublicPlatoonUserRelation.Position6 = standardSmallPublicPlatoonRelation.Position6
oneCirclesPublicPlatoonUserRelation.Position7 = standardSmallPublicPlatoonRelation.Position7
oneCirclesPublicPlatoonUserRelation.Position8 = standardSmallPublicPlatoonRelation.Position8
oneCirclesPublicPlatoonUserRelation.Position9 = standardSmallPublicPlatoonRelation.Position9
oneCirclesPublicPlatoonUserRelation.Level = 1
oneCirclesPublicPlatoonUserRelation.Level1 = standardSmallPublicPlatoonRelation.Level1
oneCirclesPublicPlatoonUserRelation.Level2 = standardSmallPublicPlatoonRelation.Level2
oneCirclesPublicPlatoonUserRelation.Level3 = standardSmallPublicPlatoonRelation.Level3
oneCirclesPublicPlatoonUserRelation.Level4 = standardSmallPublicPlatoonRelation.Level4
oneCirclesPublicPlatoonUserRelation.Level5 = standardSmallPublicPlatoonRelation.Level5
oneCirclesPublicPlatoonUserRelation.Level6 = standardSmallPublicPlatoonRelation.Level6
oneCirclesPublicPlatoonUserRelation.Level7 = standardSmallPublicPlatoonRelation.Level7
oneCirclesPublicPlatoonUserRelation.Level8 = standardSmallPublicPlatoonRelation.Level8
oneCirclesPublicPlatoonUserRelation.Level9 = standardSmallPublicPlatoonRelation.Level9
oneCirclesPublicPlatoonUserRelation.LevelTotal = standardSmallPublicPlatoonRelation.LevelTotal
oneCirclesPublicPlatoonUserRelation.RecommendUid = recommendUid
oneCirclesPublicPlatoonUserRelation.JoinAt = now.Format("2006-01-02 15:04:05")
oneCirclesPublicPlatoonUserRelation.CreateAt = now.Format("2006-01-02 15:04:05")
oneCirclesPublicPlatoonUserRelation.UpdateAt = now.Format("2006-01-02 15:04:05")
oneCirclesPublicPlatoonUserRelation.HasSonNum = 0
_, err = db.OneCirclesPublicPlatoonUserRelationInsert(engine, &oneCirclesPublicPlatoonUserRelation)
if err != nil {
return model.OneCirclesPublicPlatoonUserRelation{}, err
}

// 4、改变直属父级的 has_son_num 数量
update, err := engine.Where("uid = ?", fatherUid).SetExpr("has_son_num", "has_son_num + 1").Update(new(model.OneCirclesPublicPlatoonUserRelation))
if err != nil {
return oneCirclesPublicPlatoonUserRelation, err
}
if update == 0 {
return oneCirclesPublicPlatoonUserRelation, errors.New("更新has_son_num数据出错")
}
return oneCirclesPublicPlatoonUserRelation, nil
}

// oneCirclesSmallReverseDeductionPosition 逆向推导 position
func oneCirclesSmallReverseDeductionPosition(calcPosition, levelFirstPosition, severalTimes int) (position int) {
remainder := (calcPosition - 1) % severalTimes
position = levelFirstPosition + remainder
return
}

func oneCirclesSmallReverseDeductionPositionByFather(fatherPosition, level, severalTimes, remainder int) (position int) {
if fatherPosition == 0 {
position = 0
return
}
firstPosition := oneCirclesSmallGetLevelForFirstPosition(level, severalTimes)
endPosition := firstPosition + int(math.Pow(float64(severalTimes), float64(level-1))) - 1
position = fatherPosition + (fatherPosition-firstPosition)*severalTimes + (endPosition - fatherPosition) + 1
return
}

func oneCirclesSmallFindSuitablePosition(engine *xorm.Engine, position *int, severalTimes float64, fuid, fatherLevel int, times *int) (standardSmallPublicPlatoonRelation md.StandardSmallPublicPlatoonRelation, fatherUid int, err error) {
*times++
positionName := "position" + zhios_order_relate_utils.IntToStr(*times)
fatherName := "father_uid" + zhios_order_relate_utils.IntToStr(*times)
firstSonPosition := oneCirclesSmallSearchPositionFirstSonPosition(*position, int(severalTimes))
var tempLevel float64
smallMakeSearchLevel(&firstSonPosition, severalTimes, &tempLevel)
firstSonLevel := int(tempLevel)
endSonPosition := firstSonPosition + int(math.Pow(severalTimes, float64(firstSonLevel-fatherLevel))) - 1
list, _, err := db.OneCirclesPublicPlatoonUserRelationFindCountByPosition(engine, fuid, fatherName, positionName, int64(firstSonPosition), int64(endSonPosition))
if err != nil {
return standardSmallPublicPlatoonRelation, fatherUid, err
}

if list[0].HasSonNum == int(severalTimes) {
//TODO::则证明该层直属下级无空位
position = &firstSonPosition
return oneCirclesSmallFindSuitablePosition(engine, position, severalTimes, fuid, fatherLevel, times)
} else if list[0].HasSonNum == 0 {
fatherUid = list[0].Uid

//TODO::新的一层
standardSmallPublicPlatoonRelation.FatherUid1 = list[0].Uid
standardSmallPublicPlatoonRelation.FatherUid2 = list[0].FatherUid1
standardSmallPublicPlatoonRelation.FatherUid3 = list[0].FatherUid2
standardSmallPublicPlatoonRelation.FatherUid4 = list[0].FatherUid3
standardSmallPublicPlatoonRelation.FatherUid5 = list[0].FatherUid4
standardSmallPublicPlatoonRelation.FatherUid6 = list[0].FatherUid5
standardSmallPublicPlatoonRelation.FatherUid7 = list[0].FatherUid6
standardSmallPublicPlatoonRelation.FatherUid8 = list[0].FatherUid7
standardSmallPublicPlatoonRelation.FatherUid9 = list[0].FatherUid8

standardSmallPublicPlatoonRelation.Pid1 = list[0].Position
standardSmallPublicPlatoonRelation.Pid2 = list[0].Position1
standardSmallPublicPlatoonRelation.Pid3 = list[0].Position2
standardSmallPublicPlatoonRelation.Pid4 = list[0].Position3
standardSmallPublicPlatoonRelation.Pid5 = list[0].Position4
standardSmallPublicPlatoonRelation.Pid6 = list[0].Position5
standardSmallPublicPlatoonRelation.Pid7 = list[0].Position6
standardSmallPublicPlatoonRelation.Pid8 = list[0].Position7
standardSmallPublicPlatoonRelation.Pid9 = list[0].Position8

standardSmallPublicPlatoonRelation.Position1 = oneCirclesSmallSearchPositionFirstSonPosition(list[0].Position, int(severalTimes))
standardSmallPublicPlatoonRelation.Position2 = oneCirclesSmallReverseDeductionPositionByFather(list[0].Position1, list[0].Level1, int(severalTimes), 0)
standardSmallPublicPlatoonRelation.Position3 = oneCirclesSmallReverseDeductionPositionByFather(list[0].Position2, list[0].Level2, int(severalTimes), 0)
standardSmallPublicPlatoonRelation.Position4 = oneCirclesSmallReverseDeductionPositionByFather(list[0].Position3, list[0].Level3, int(severalTimes), 0)
standardSmallPublicPlatoonRelation.Position5 = oneCirclesSmallReverseDeductionPositionByFather(list[0].Position4, list[0].Level4, int(severalTimes), 0)
standardSmallPublicPlatoonRelation.Position6 = oneCirclesSmallReverseDeductionPositionByFather(list[0].Position5, list[0].Level5, int(severalTimes), 0)
standardSmallPublicPlatoonRelation.Position7 = oneCirclesSmallReverseDeductionPositionByFather(list[0].Position6, list[0].Level6, int(severalTimes), 0)
standardSmallPublicPlatoonRelation.Position8 = oneCirclesSmallReverseDeductionPositionByFather(list[0].Position7, list[0].Level7, int(severalTimes), 0)
standardSmallPublicPlatoonRelation.Position9 = oneCirclesSmallReverseDeductionPositionByFather(list[0].Position8, list[0].Level8, int(severalTimes), 0)

if list[0].Level1 == 0 {
list[0].Level1--
}
if list[0].Level2 == 0 {
list[0].Level2--
}
if list[0].Level3 == 0 {
list[0].Level3--
}
if list[0].Level4 == 0 {
list[0].Level4--
}
if list[0].Level5 == 0 {
list[0].Level5--
}
if list[0].Level6 == 0 {
list[0].Level6--
}
if list[0].Level7 == 0 {
list[0].Level7--
}
if list[0].Level8 == 0 {
list[0].Level8--
}
if list[0].Level9 == 0 {
list[0].Level9--
}
standardSmallPublicPlatoonRelation.Level1 = list[0].Level + 1
standardSmallPublicPlatoonRelation.Level2 = list[0].Level1 + 1
standardSmallPublicPlatoonRelation.Level3 = list[0].Level2 + 1
standardSmallPublicPlatoonRelation.Level4 = list[0].Level3 + 1
standardSmallPublicPlatoonRelation.Level5 = list[0].Level4 + 1
standardSmallPublicPlatoonRelation.Level6 = list[0].Level5 + 1
standardSmallPublicPlatoonRelation.Level7 = list[0].Level6 + 1
standardSmallPublicPlatoonRelation.Level8 = list[0].Level7 + 1
standardSmallPublicPlatoonRelation.Level9 = list[0].Level8 + 1
standardSmallPublicPlatoonRelation.LevelTotal = list[0].LevelTotal + 1
} else {
fatherUid = list[0].Uid

_, _, _, _, getPositionName, _, _, _ := oneCirclesGetPosition(list[0], *times+1)
//oneCirclesPublicPlatoonUserRelations, err := db.OneCirclesPublicPlatoonUserRelationFindByPid(engine, m.Position, m.Uid, "pid1", "father_uid1", "position1")

oneCirclesPublicPlatoonUserRelations, err := db.OneCirclesPublicPlatoonUserRelationFindByPid(engine, list[0].Uid, "father_uid1", getPositionName)

if err != nil {
return standardSmallPublicPlatoonRelation, fatherUid, err
}

if oneCirclesPublicPlatoonUserRelations[0].Position2 == 0 {
oneCirclesPublicPlatoonUserRelations[0].Position2 = -1
}
if oneCirclesPublicPlatoonUserRelations[0].Position3 == 0 {
standardSmallPublicPlatoonRelation.Position3 = -1
}
if oneCirclesPublicPlatoonUserRelations[0].Position4 == 0 {
standardSmallPublicPlatoonRelation.Position4 = -1
}
if oneCirclesPublicPlatoonUserRelations[0].Position5 == 0 {
standardSmallPublicPlatoonRelation.Position5 = -1
}
if oneCirclesPublicPlatoonUserRelations[0].Position6 == 0 {
standardSmallPublicPlatoonRelation.Position6 = -1
}
if oneCirclesPublicPlatoonUserRelations[0].Position7 == 0 {
standardSmallPublicPlatoonRelation.Position7 = -1
}
if oneCirclesPublicPlatoonUserRelations[0].Position8 == 0 {
standardSmallPublicPlatoonRelation.Position8 = -1
}
if oneCirclesPublicPlatoonUserRelations[0].Position9 == 0 {
standardSmallPublicPlatoonRelation.Position9 = -1
}

standardSmallPublicPlatoonRelation = md.StandardSmallPublicPlatoonRelation{
FatherUid1: oneCirclesPublicPlatoonUserRelations[0].FatherUid1,
FatherUid2: oneCirclesPublicPlatoonUserRelations[0].FatherUid2,
FatherUid3: oneCirclesPublicPlatoonUserRelations[0].FatherUid3,
FatherUid4: oneCirclesPublicPlatoonUserRelations[0].FatherUid4,
FatherUid5: oneCirclesPublicPlatoonUserRelations[0].FatherUid5,
FatherUid6: oneCirclesPublicPlatoonUserRelations[0].FatherUid6,
FatherUid7: oneCirclesPublicPlatoonUserRelations[0].FatherUid7,
FatherUid8: oneCirclesPublicPlatoonUserRelations[0].FatherUid8,
FatherUid9: oneCirclesPublicPlatoonUserRelations[0].FatherUid9,
Pid1: oneCirclesPublicPlatoonUserRelations[0].Pid1,
Pid2: oneCirclesPublicPlatoonUserRelations[0].Pid2,
Pid3: oneCirclesPublicPlatoonUserRelations[0].Pid3,
Pid4: oneCirclesPublicPlatoonUserRelations[0].Pid4,
Pid5: oneCirclesPublicPlatoonUserRelations[0].Pid5,
Pid6: oneCirclesPublicPlatoonUserRelations[0].Pid6,
Pid7: oneCirclesPublicPlatoonUserRelations[0].Pid7,
Pid8: oneCirclesPublicPlatoonUserRelations[0].Pid8,
Pid9: oneCirclesPublicPlatoonUserRelations[0].Pid9,
Position1: oneCirclesPublicPlatoonUserRelations[0].Position1 + 1,
Position2: oneCirclesPublicPlatoonUserRelations[0].Position2 + 1,
Position3: oneCirclesPublicPlatoonUserRelations[0].Position3 + 1,
Position4: oneCirclesPublicPlatoonUserRelations[0].Position4 + 1,
Position5: oneCirclesPublicPlatoonUserRelations[0].Position5 + 1,
Position6: oneCirclesPublicPlatoonUserRelations[0].Position6 + 1,
Position7: oneCirclesPublicPlatoonUserRelations[0].Position7 + 1,
Position8: oneCirclesPublicPlatoonUserRelations[0].Position8 + 1,
Position9: oneCirclesPublicPlatoonUserRelations[0].Position9 + 1,
Level1: oneCirclesPublicPlatoonUserRelations[0].Level1,
Level2: oneCirclesPublicPlatoonUserRelations[0].Level2,
Level3: oneCirclesPublicPlatoonUserRelations[0].Level3,
Level4: oneCirclesPublicPlatoonUserRelations[0].Level4,
Level5: oneCirclesPublicPlatoonUserRelations[0].Level5,
Level6: oneCirclesPublicPlatoonUserRelations[0].Level6,
Level7: oneCirclesPublicPlatoonUserRelations[0].Level7,
Level8: oneCirclesPublicPlatoonUserRelations[0].Level8,
Level9: oneCirclesPublicPlatoonUserRelations[0].Level9,
LevelTotal: oneCirclesPublicPlatoonUserRelations[0].LevelTotal,
}
return standardSmallPublicPlatoonRelation, fatherUid, nil
}
return
}

func oneCirclesGetPosition(m model.OneCirclesPublicPlatoonUserRelation, times int) (position, pid, level, fatherUid int, positionName, pidName, levelName, fatherUidName string) {
if times == 1 {
position = m.Position1
positionName = "position1"
pid = m.Pid1
pidName = "pid1"
level = m.Level1
levelName = "level1"
fatherUid = m.FatherUid1
fatherUidName = "father_uid1"
}
if times == 2 {
position = m.Position2
positionName = "position2"
pid = m.Pid2
pidName = "pid2"
level = m.Level2
levelName = "level2"
fatherUid = m.FatherUid2
fatherUidName = "father_uid2"
}
if times == 3 {
position = m.Position3
positionName = "position3"
pid = m.Pid3
pidName = "pid3"
level = m.Level3
levelName = "level3"
fatherUid = m.FatherUid3
fatherUidName = "father_uid3"
}
if times == 4 {
position = m.Position4
positionName = "position4"
pid = m.Pid4
pidName = "pid4"
level = m.Level4
levelName = "level4"
fatherUid = m.FatherUid4
fatherUidName = "father_uid4"
}
if times == 5 {
position = m.Position5
positionName = "position5"
pid = m.Pid5
pidName = "pid5"
level = m.Level5
levelName = "level5"
fatherUid = m.FatherUid5
fatherUidName = "father_uid5"
}
if times == 6 {
position = m.Position6
positionName = "position6"
pid = m.Pid6
pidName = "pid6"
level = m.Level6
levelName = "level6"
fatherUid = m.FatherUid6
fatherUidName = "father_uid6"
}
if times == 7 {
position = m.Position7
positionName = "position7"
pid = m.Pid7
pidName = "pid7"
level = m.Level7
levelName = "level7"
fatherUid = m.FatherUid7
fatherUidName = "father_uid7"
}
if times == 8 {
position = m.Position8
positionName = "position8"
pid = m.Pid8
pidName = "pid8"
level = m.Level8
levelName = "level8"
fatherUid = m.FatherUid8
fatherUidName = "father_uid8"
}
if times == 9 {
position = m.Position9
positionName = "position9"
pid = m.Pid9
pidName = "pid9"
level = m.Level9
levelName = "level9"
fatherUid = m.FatherUid9
fatherUidName = "father_uid9"
}

return
}

// oneCirclesSmallGetLevelForFirstPosition 返回当前等级的起始值
func oneCirclesSmallGetLevelForFirstPosition(level, severalTimes int) (position int) {
position = position + 1
for n := 0; n <= (level - 2); n++ {
position += int(math.Pow(float64(severalTimes), float64(n)))
}
return
}

//递归查找等级
func oneCirclesSmallMakeSearchLevel(position *int, rows float64, times *float64) (level int) {
difference := *position - int(math.Pow(rows, *times))
*times++
if difference <= 0 {
return int(*times)
} else {
position = &difference
return oneCirclesSmallMakeSearchLevel(position, rows, times)
}
}

//查找归属父级id
func oneCirclesSmallMakeSearchPid(position int, row int) (pid int) {
divisionValue := (position - 1) / row
if divisionValue == 0 {
pid = 1
return
} else {
if (divisionValue*row + 1) == position {
pid = divisionValue
return
} else {
pid = divisionValue + 1
return
}
}
}

//查找当前位置下的第一个子集位置
func oneCirclesSmallSearchPositionFirstSonPosition(position int, times int) (sonPosition int) {
sonPosition = (position * times) - (times - 2)
return
}

//查找当前位位置相当于父级的等级
func oneCirclesSmallSearchPositionSonForLevel(fatherUid string, fatherPosition int) (level int) {
fatherUids := strings.Split(fatherUid, "-")
for key, item := range fatherUids {
if item == strconv.Itoa(fatherPosition) {
level = key + 1
break
}
}
return
}

// OneCirclesSmallFindWaitForDealUsers 查询待处理的用户
func OneCirclesSmallFindWaitForDealUsers(engine *xorm.Engine, page, pageSize int) (err error, resp []int) {
now := time.Now().Format("2006-01-02")
lists, err := db.OneCirclesPublicPlatoonUserRelationFindByParamsByPage(engine, map[string]interface{}{
"key": "wait_for_settlement_date",
"value": now,
}, page, pageSize)
if err != nil {
return
}
for _, list := range *lists {
resp = append(resp, list.Uid)
}
return
}

//递归查找等级
func smallMakeSearchLevel(position *int, rows float64, times *float64) (level int) {
difference := *position - int(math.Pow(rows, *times))
*times++
if difference <= 0 {
return int(*times)
} else {
position = &difference
return smallMakeSearchLevel(position, rows, times)
}
}

// OneCirclesDealCommonWealthPunish 处理公排处罚
func OneCirclesDealCommonWealthPunish(engine *xorm.Engine, uid int, reason string) (err error, resp []map[string]string) {
session := engine.NewSession()
defer func() {
session.Close()
if err := recover(); err != nil {
_ = zhios_order_relate_logx.Error(err)
}
}()
session.Begin()

//1、查找 `user_public_platoon_setting` 基础设置
oneCirclesPublicPlatoonBasicSetting, err := db.OneCirclesPublicPlatoonBasicSettingGetOneByParams(engine, map[string]interface{}{
"key": "is_open",
"value": 1,
})
if err != nil {
_ = session.Rollback()
return
}

//2、查询出 `one_circles_public_platoon_user_relation` 中相关记录 && 将该记录的uid置为 -1
params, err := db.OneCirclesPublicPlatoonUserRelationGetOneByParams(engine, map[string]interface{}{
"key": "uid",
"value": uid,
})
if err != nil {
_ = session.Rollback()
return
}
if params == nil {
fmt.Println("未查询到公排关系记录!!!!!!!", uid)
return
}

//TODO::判断是否为推荐用户
if params.RecommendUid == 0 {
params.Uid = params.Uid - int(time.Now().Unix())
} else {
params.Uid = params.Uid - int(time.Now().Unix())
}

for n := 1; n <= 9; n++ {
str := "father_uid" + strconv.Itoa(n)
sql := fmt.Sprintf("UPDATE `one_circles_public_platoon_user_relation` SET %s=%s where %s=%s", str, strconv.Itoa(params.Uid), str, strconv.Itoa(uid))
fmt.Println(">>>>>>>sql>>>>>>>", sql)
_, err = session.Exec(sql)
if err != nil {
_ = session.Rollback()
return
}
}

updateAffected, err := db.OneCirclesPublicPlatoonUserRelationUpdate(session, params.Id, params)
if err != nil {
_ = session.Rollback()
return
}
if updateAffected == 0 {
err = errors.New("更新 one_circles_public_platoon_user_relation 记录失败")
_ = session.Rollback()
return
}

//3、新增一条 `one_circles_public_platoon_user_relation` 记录
params.Uid = uid
res, err := OneCirclesPublicPlatoon(engine, params.Uid, params.RecommendUid, *oneCirclesPublicPlatoonBasicSetting)
if err != nil {
_ = session.Rollback()
return
}

//4、新增一条 `one_circles_user_public_platoon_system_punish_records` 记录
now := time.Now()
insertAffected, err := db.OneCirclesUserPublicPlatoonSystemPunishRecordsInsert(session, &model.OneCirclesUserPublicPlatoonSystemPunishRecords{
Uid: params.Uid,
OldPostion: params.Position,
NewPostion: res.Position,
Date: now.AddDate(0, 0, 30).Format("2006-01-02"),
Title: "共富收益-系统处罚记录",
Reason: reason,
Type: 2,
CreateAt: now,
UpdateAt: now,
})
if err != nil {
_ = session.Rollback()
return
}
if insertAffected == 0 {
err = errors.New("新增 one_circles_user_public_platoon_system_punish_records 记录失败")
_ = session.Rollback()
return
}

err = session.Commit()
return
}

const OneCirclesDealUserPublicPlatoonPunishLockKey = "one_circles_deal_user_public_platoon_lock_key"

// OneCirclesDealUserPublicPlatoonPunish 处理公排处罚
func OneCirclesDealUserPublicPlatoonPunish(engine *xorm.Engine, masterId string) (err error) {
now := time.Now()
fmt.Println(now.Hour())
if !(now.Hour() > 22 && now.Hour() < 24) {
//TODO::只在凌晨一点 ~ 凌晨 8 点运行
return errors.New("非运行时间")
}
//TODO::增加“悲观锁”防止串行
getString, _ := cache.GetString(OneCirclesDealUserPublicPlatoonPunishLockKey)
if getString != "" {
fmt.Println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", "上一次结算未执行完")
return errors.New("上一次结算未执行完")
}
cache.SetEx(OneCirclesDealUserPublicPlatoonPunishLockKey, "running", 3600*8) //8小时

//查找 `one_circles_public_platoon_basic_setting` 基础设置
oneCirclesPublicPlatoonBasicSetting, err := db.OneCirclesPublicPlatoonBasicSettingGetOneByParams(engine, map[string]interface{}{
"key": "is_open",
"value": 1,
})
if err != nil {
return err
}
if oneCirclesPublicPlatoonBasicSetting == nil {
return errors.New("公排制度未开启")
}
mapOneCirclesPublicPlatoonFreePunishWithUser, err := db.FindAllOneCirclesPublicPlatoonFreePunishWithUser(engine)
if err != nil {
return err
}
if oneCirclesPublicPlatoonBasicSetting.SystemPunishReplace == 1 {
systemPunishReplaceValue := oneCirclesPublicPlatoonBasicSetting.SystemPunishReplaceValue
startDate := now.AddDate(0, 0, -systemPunishReplaceValue).Format("2006-01-02") + " 00:00:00"
var page = 1
var pageSize = 100
for {
var users []model.User
err = engine.Limit(pageSize, (page-1)*pageSize).Desc("uid").Find(&users)
if err != nil {
return err
}
if len(users) <= 0 {
break
}
for _, user := range users {
var list []model.OneCirclesGreenEnergySignIn
err = engine.Where("start_time >= ?", startDate).And("uid = ?", user.Uid).Find(&list)
if len(list) <= 0 && mapOneCirclesPublicPlatoonFreePunishWithUser[user.Uid] == nil {
var oneCirclesPublicPlatoonRecordsPunishWithUser model.OneCirclesPublicPlatoonRecordsPunishWithUser
has, err1 := engine.Where("uid = ?", user.Uid).Get(&oneCirclesPublicPlatoonRecordsPunishWithUser)
if err1 != nil {
return err1
}
oneCirclesPublicPlatoonRecordsPunishWithUserDate, _ := time.ParseInLocation("2006-01-02", oneCirclesPublicPlatoonRecordsPunishWithUser.Date, time.Local)
if has && now.AddDate(0, 0, -7).After(oneCirclesPublicPlatoonRecordsPunishWithUserDate) {
//TODO::不进行重复处罚
continue
}
//进行处罚
err, _ = OneCirclesDealCommonWealthPunish(engine, user.Uid, "公排处罚")
if err != nil {
return err
}

//添加 one_circles_public_platoon_records_punish_with_user 记录
if has {
oneCirclesPublicPlatoonRecordsPunishWithUser.Date = now.Format("2006-01-02")
_, err2 := db.OneCirclesPublicPlatoonRecordsPunishWithUserUpdate(engine, oneCirclesPublicPlatoonRecordsPunishWithUser.Id, &oneCirclesPublicPlatoonRecordsPunishWithUser, "date")
if err2 != nil {
return err2
}
} else {
_, err2 := db.OneCirclesPublicPlatoonRecordsPunishWithUserInsert(engine, &model.OneCirclesPublicPlatoonRecordsPunishWithUser{
Uid: user.Uid,
Date: now.Format("2006-01-02"),
})
if err2 != nil {
return err2
}
}
}
}
page++
}
}
return
}

+ 268
- 0
rule/one_circles/one_circles_sign_in_green_energy_settlement.go View File

@@ -0,0 +1,268 @@
package one_circles

import (
"code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit"
"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/md"
"code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule/one_circles/enum"
md2 "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule/one_circles/md"
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"
"encoding/json"
"errors"
"fmt"
"github.com/shopspring/decimal"
"math/rand"
"time"
"xorm.io/xorm"
)

// SettlementSignInGreenEnergy 计算签到得到绿色能量
func SettlementSignInGreenEnergy(engine *xorm.Engine, masterId string, ch *rabbit.Channel) (err error) {
//1、查找 `one_circles_green_energy_basic_setting` 基础设置
oneCirclesGreenEnergyBasicSetting, err := db.OneCirclesGreenEnergyBasicSettingGetOneByParams(engine, map[string]interface{}{
"key": "is_open",
"value": 1,
})
if err != nil {
return
}
if oneCirclesGreenEnergyBasicSetting == nil {
return errors.New("开关未开!!")
}
//3、统计签到结束的用户数据
now := time.Now()
var page = 1
var pageSize = 100
for {
var list []model.OneCirclesGreenEnergySignIn
err = engine.Where("end_time <= ?", now.Format("2006-01-02 15:04:05")).And("is_completed =?", 0).Limit(pageSize, (page-1)*pageSize).Asc("id").Find(&list)
if err != nil {
fmt.Println("err:::::1111", err)
return
}
if len(list) <= 0 {
break
}

var ids []int64
for _, v := range list {
//TODO::推入rabbitmq 异步处理
ch.Publish(md.OneCirclesExchange, md.OneCirclesStructForSignIn{
MasterId: masterId,
Uid: v.Uid,
Id: v.Id,
}, md.OneCirclesRoutKeyForSignIn)
ids = append(ids, v.Id)
}
//6、更新 `one_circles_green_energy_sign_in` 中的 is_completed 状态
if len(ids) > 0 {
_, err = engine.In("id", ids).Update(&model.OneCirclesGreenEnergySignIn{
IsCompleted: 1,
})
}
page++
time.Sleep(time.Millisecond * time.Duration(rand.Intn(1000)))
}

return
}

func HandleSettlementSignInGreenEnergy(engine *xorm.Engine, masterId string, id int64, uid int) (err error) {
//1、查找 `one_circles_green_energy_basic_setting` 基础设置
oneCirclesGreenEnergyBasicSetting, err := db.OneCirclesGreenEnergyBasicSettingGetOneByParams(engine, map[string]interface{}{
"key": "is_open",
"value": 1,
})
if err != nil {
return
}
var teamRewardSetting *md2.TeamRewardSettingStruct
err = json.Unmarshal([]byte(oneCirclesGreenEnergyBasicSetting.TeamReward), &teamRewardSetting)
if err != nil {
return
}
if teamRewardSetting.RewardDecrementValue == "" || teamRewardSetting.RewardEndValue == "" || teamRewardSetting.MemberSelfIsOpenGetTeamReward == "" || teamRewardSetting.OneRoundDuration == "" {
err = errors.New("团队奖励设置未完全!")
return
}
var oneRoundDuration = zhios_order_relate_utils.StrToInt(teamRewardSetting.OneRoundDuration)
var rewardDecrement = zhios_order_relate_utils.StrToFloat64(teamRewardSetting.RewardDecrementValue) / 100 //递减百分比
var rewardEndValue = zhios_order_relate_utils.StrToFloat64(teamRewardSetting.RewardEndValue) //奖励结束值
fmt.Println("rewardDecrement>>>>>>>>>>>>", rewardDecrement)
fmt.Println("rewardEndValue>>>>>>>>>>>>", rewardEndValue)

//2、获取当前签到收益
err, reward := CalcNowSignInGreenEnergy(engine, oneCirclesGreenEnergyBasicSetting)
if err != nil {
return err
}
rewardValue := zhios_order_relate_utils.Float64ToStrPrec8(zhios_order_relate_utils.StrToFloat64(reward) * float64(oneRoundDuration) * 60 * 60)

//3、统计签到结束的用户数据
session := engine.NewSession()
defer func() {
session.Close()
if err := recover(); err != nil {
_ = zhios_order_relate_logx.Error(err)
}
}()
session.Begin()

var reduceTotalGreenEnergy float64
//4.2给相应的用户加上个人的绿色积分(可用数量)
err = DealUserCoin(session, md.DealUserCoinReq{
Kind: "add",
Mid: masterId,
Title: md.OneCirclesGreenEnergySignInSettlementPersonalReward,
TransferType: md.OneCirclesGreenEnergySignInSettlementPersonalRewardForUserVirtualCoinFlow,
OrdId: "",
CoinId: oneCirclesGreenEnergyBasicSetting.PersonGreenEnergyCoinId,
Uid: uid,
Amount: zhios_order_relate_utils.StrToFloat64(rewardValue),
})
if err != nil {
_ = session.Rollback()
fmt.Println("err:::::2222", err)
return err
}
reduceTotalGreenEnergy += zhios_order_relate_utils.StrToFloat64(rewardValue)

//4.2给相应的上级用户加上团队奖励的绿色积分(结算数量)
relates, err1 := db.DbsUserRelate(engine, uid, 0)
if err1 != nil {
_ = session.Rollback()
fmt.Println("err:::::3333", err1)
return err1
}
var parentRewardValue = zhios_order_relate_utils.StrToFloat64(rewardValue)
if relates != nil {
for _, relate := range *relates {
if parentRewardValue <= rewardEndValue {
break
}
parentRewardValue = parentRewardValue * rewardDecrement
//TODO::判断是否活跃
var m model.OneCirclesGreenEnergySignIn
has, err3333333 := engine.Where("uid =?", relate.ParentUid).And("end_time >=?", time.Now().Format("2006-01-02 15:04:05")).Get(&m)
if err3333333 != nil {
_ = session.Rollback()
fmt.Println("err:::::3333333", err3333333)
return err3333333
}
if !has {
//不活跃不需要奖励
continue
}
err = DealUserCoin(session, md.DealUserCoinReq{
Kind: "add",
Mid: masterId,
Title: md.OneCirclesGreenEnergySignInSettlementTeamReward,
TransferType: md.OneCirclesGreenEnergySignInSettlementTeamRewardForUserVirtualCoinFlow,
OrdId: "",
CoinId: oneCirclesGreenEnergyBasicSetting.TeamGreenEnergyCoinId,
Uid: relate.ParentUid,
Amount: parentRewardValue,
})
if err != nil {
_ = session.Rollback()
fmt.Println("err:::::44444", err)
return err
}
reduceTotalGreenEnergy += parentRewardValue
}
}

//5、减少“活跃赠送” 中的绿色能量
if reduceTotalGreenEnergy > 0 {
err = DealAvailableGreenEnergyCoin(session, int(enum.SignInReward), reduceTotalGreenEnergy, 0, enum.SignInReward.String(), oneCirclesGreenEnergyBasicSetting, oneCirclesGreenEnergyBasicSetting.NowPrice)
if err != nil {
_ = session.Rollback()
fmt.Println("err:::::55555", err)
return err
}
}

if err != nil {
_ = session.Rollback()
fmt.Println("err:::::1111", err)
return
}

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

return
}

// CalcNowSignInGreenEnergy 计算当前签到拿多少绿色能量/秒
func CalcNowSignInGreenEnergy(engine *xorm.Engine, oneCirclesGreenEnergyBasicSetting *model.OneCirclesGreenEnergyBasicSetting) (err error, rewardValue string) {
if oneCirclesGreenEnergyBasicSetting == nil {
//1、查找 `one_circles_green_energy_basic_setting` 基础设置
oneCirclesGreenEnergyBasicSetting, err = db.OneCirclesGreenEnergyBasicSettingGetOneByParams(engine, map[string]interface{}{
"key": "is_open",
"value": 1,
})
if err != nil {
return
}
}

var signInRewards []*md2.SignInRewardStruct
err = json.Unmarshal([]byte(oneCirclesGreenEnergyBasicSetting.SignInReward), &signInRewards)
if err != nil {
return
}
if len(signInRewards) == 0 {
err = errors.New("未设置签到奖励!")
return
}

//2、统计全网用户数
sqlStr := "SELECT COUNT(*) AS total FROM user "
nativeString, _ := db.QueryNativeString(engine, sqlStr)
userCount := zhios_order_relate_utils.StrToInt64(nativeString[0]["total"])

for _, v := range signInRewards {
if zhios_order_relate_utils.StrToInt64(v.VipMemberEndNums) >= userCount && userCount >= zhios_order_relate_utils.StrToInt64(v.VipMemberStartNums) {
//rewardValue = zhios_order_relate_utils.Float64ToStrPrec8(zhios_order_relate_utils.StrToFloat64(v.RewardValue) * float64(oneRoundDuration) * 60 * 60)
rewardValue = v.RewardValue
}
}
return
}

// CalcTodayGreenEnergyPriceRises 计算绿色能量今日价格涨幅
func CalcTodayGreenEnergyPriceRises(engine *xorm.Engine, oneCirclesGreenEnergyBasicSetting *model.OneCirclesGreenEnergyBasicSetting) (err error, rises float64, isRises bool) {
now := time.Now()
if oneCirclesGreenEnergyBasicSetting == nil {
//1、查找 `one_circles_green_energy_basic_setting` 基础设置
oneCirclesGreenEnergyBasicSetting, err = db.OneCirclesGreenEnergyBasicSettingGetOneByParams(engine, map[string]interface{}{
"key": "is_open",
"value": 1,
})
if err != nil {
return
}
}

//2、查找昨日价格
var m model.OneCirclesGreenEnergyPrice
if has, err1 := engine.Where("date =?", now.AddDate(0, 0, -1).Format("2006-01-02")).And("hour = 23").Get(&m); err1 != nil || has == false {
err = err1
return
}
yesterdayPrice, _ := decimal.NewFromString(m.Price)
todayPrice, _ := decimal.NewFromString(oneCirclesGreenEnergyBasicSetting.NowPrice)
if todayPrice.GreaterThanOrEqual(yesterdayPrice) {
isRises = true
rises, _ = todayPrice.Sub(yesterdayPrice).Div(yesterdayPrice).Float64()
} else {
rises, _ = yesterdayPrice.Sub(todayPrice).Div(todayPrice).Float64()
}
return
}

+ 205
- 0
rule/one_circles/one_circles_star_level_dividends.go View File

@@ -0,0 +1,205 @@
package one_circles

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/md"
"code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule/one_circles/enum"
md2 "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule/one_circles/md"
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"
"encoding/json"
"errors"
"fmt"
"github.com/shopspring/decimal"
"time"
"xorm.io/xorm"
)

const SettlementStarLevelDividendsLockKey = "settlement_star_level_dividends_lock_key"

// SettlementStarLevelDividends 绿色能量分红
func SettlementStarLevelDividends(engine *xorm.Engine, masterId string) (err error) {
now := time.Now()
fmt.Println(now.Hour())
if !(now.Hour() > 2 && now.Hour() < 8) {
//TODO::只在凌晨一点 ~ 凌晨 8 点运行
return errors.New("非运行时间")
}
//TODO::增加“悲观锁”防止串行
getString, _ := cache.GetString(SettlementStarLevelDividendsLockKey)
if getString != "" {
fmt.Println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", "上一次结算未执行完")
return errors.New("上一次结算未执行完")
}
cache.SetEx(SettlementStarLevelDividendsLockKey, "running", 3600*8) //8小时

//1、查找 `one_circles_green_energy_basic_setting` 基础设置
oneCirclesGreenEnergyBasicSetting, err := db.OneCirclesGreenEnergyBasicSettingGetOneByParams(engine, map[string]interface{}{
"key": "is_open",
"value": 1,
})
if err != nil {
return
}

isLimitDividend := oneCirclesGreenEnergyBasicSetting.IsLimitDividend
if isLimitDividend != 1 {
return errors.New("必须开启限制分红!")
}
startDate := now.AddDate(0, 0, -1).Format("2006-01-02") + " 00:00:00"
endDate := now.Format("2006-01-02") + " 00:00:00"
var list []model.OneCirclesGreenEnergySignIn
err = engine.Where("start_time >= ?", startDate).And("start_time <=?", endDate).Find(&list)
if err != nil {
fmt.Println("err:::::1111", err)
return
}
if len(list) <= 0 {
return errors.New("无须参与星级分红用户!")
}
var userSignInMap = map[int]string{}
var userSignInArr []int
for _, v := range list {
userSignInMap[v.Uid] = "true"
userSignInArr = append(userSignInArr, v.Uid)
}

var vipEquitySetting []*md2.VipEquitySettingStruct
err = json.Unmarshal([]byte(oneCirclesGreenEnergyBasicSetting.VipEquitySetting), &vipEquitySetting)
if err != nil {
fmt.Println("err:::::22222", err)
return
}

allUserLevel, err := db.UserLevlEgAll(engine)
if err != nil {
return err
}
var allUserLevelMap = map[int]model.UserLevel{}
for _, v := range allUserLevel {
allUserLevelMap[v.Id] = *v
}

session := engine.NewSession()
defer func() {
session.Close()
if err := recover(); err != nil {
_ = zhios_order_relate_logx.Error(err)
}
}()
session.Begin()

//2、查找 `one_circles_star_level_dividends_records` 基础设置
oneCirclesStarLevelDividendsRecords, err := db.OneCirclesStarLevelDividendsRecordsGetOneByParamsBySession(session, map[string]interface{}{
"key": "date",
"value": now.AddDate(0, 0, -1).Format("2006-01-02"),
})
if err != nil {
fmt.Println("err:::::33333", err)
return
}
if oneCirclesStarLevelDividendsRecords == nil {
return errors.New("今日无分红积分!")
}

//3、统计各等级人数
dividendAmountValue, _ := decimal.NewFromString(oneCirclesStarLevelDividendsRecords.Amount)
decimalRate := decimal.NewFromInt(100) //百分比
var vipLevelUserTotalMap = map[string]map[string]int64{}
var vipEquitySettingMap = map[string]string{}
for _, v := range vipEquitySetting {
dividendRatioValue, _ := decimal.NewFromString(v.DividendRatio)
dividendRatioValue = dividendRatioValue.Div(decimalRate) //分红比例
vipEquitySettingMap[v.VipLevelId] = dividendAmountValue.Mul(dividendRatioValue).String() //TODO::计算各会员等级能得到多少分红

userLevel, err1 := db.UserLevelByID(engine, v.VipLevelId)
if err1 != nil {
fmt.Println("err:::::444444", err1)
return err1
}
var ms []*model.UserLevel
err1 = session.Where("is_use=1").Where("level_weight > ?", userLevel.LevelWeight).Find(&ms)
if err1 != nil {
fmt.Println("err:::::55555", err1)
return err1
}

var tmpVipLevelId = []string{v.VipLevelId}
for _, m := range ms {
tmpVipLevelId = append(tmpVipLevelId, zhios_order_relate_utils.IntToStr(m.Id))
}
var users model.User
count, err1 := session.In("level", tmpVipLevelId).Count(&users)
if err1 != nil {
fmt.Println("err:::::66666", err1)
return err1
}
vipLevelUserTotalMap[v.VipLevelId] = map[string]int64{}
vipLevelUserTotalMap[v.VipLevelId]["count"] = count
vipLevelUserTotalMap[v.VipLevelId]["weight"] = int64(userLevel.LevelWeight)
}

//4、处理分红
var users []*model.User
err = session.In("uid", userSignInArr).Find(&users)
if err != nil {
fmt.Println("err:::::7777777", err)
return err
}

var totalDividendValue = decimal.Decimal{}
for _, item := range users {
var siginDividendValue = decimal.Decimal{}
for k, v := range vipLevelUserTotalMap {
if int(v["weight"]) > allUserLevelMap[item.Level].LevelWeight {
continue
}
if vipEquitySettingMap[k] != "" && vipLevelUserTotalMap[k]["count"] > 0 {
dividendValue, _ := decimal.NewFromString(vipEquitySettingMap[k])
userTotal := decimal.NewFromInt(vipLevelUserTotalMap[k]["count"])
siginDividendValue = siginDividendValue.Add(dividendValue.Div(userTotal))
}
}
siginDividend, _ := siginDividendValue.Float64()
if siginDividend > 0 {
//给相应的用户加上个人的绿色积分(结算数量)
err = DealUserCoin(session, md.DealUserCoinReq{
Kind: "add",
Mid: masterId,
Title: md.OneCirclesSettlementStarLevelDividends,
TransferType: md.OneCirclesSettlementStarLevelDividendsForUserVirtualCoinFlow,
OrdId: "",
CoinId: oneCirclesGreenEnergyBasicSetting.TeamGreenEnergyCoinId,
Uid: item.Uid,
Amount: siginDividend,
})
}
totalDividendValue = totalDividendValue.Add(siginDividendValue)
}

//5、更新 one_circles_star_level_dividends_records 记录
oneCirclesStarLevelDividendsRecords.AlreadyDividendsAmount = totalDividendValue.String()
oneCirclesStarLevelDividendsRecords.NotDividendsAmount = dividendAmountValue.Sub(totalDividendValue).String()
_, err = db.OneCirclesStarLevelDividendsRecordsUpdateBySession(session, oneCirclesStarLevelDividendsRecords.Id, oneCirclesStarLevelDividendsRecords, "already_dividends_amount", "not_dividends_amount")
if err != nil {
fmt.Println("err:::::8888888", err)
return err
}

//6、 减少“星级分红”中的绿色能量
totalDividend, _ := totalDividendValue.Float64()
err = DealAvailableGreenEnergyCoin(session, int(enum.SettlementStarLevelDividends), totalDividend, 0, enum.SettlementStarLevelDividends.String(), oneCirclesGreenEnergyBasicSetting, oneCirclesGreenEnergyBasicSetting.NowPrice)
if err != nil {
_ = session.Rollback()
fmt.Println("err:::::9999999", err)
return err
}
err = session.Commit()
if err != nil {
_ = session.Rollback()
return errors.New("事务提交失败")
}
return
}

+ 367
- 0
rule/public_platoon_double_network_relate_commission.go View File

@@ -0,0 +1,367 @@
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/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"
"math/rand"
"strconv"
"time"
"xorm.io/xorm"
)

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

/*
EstimateUserPosition 预估用户位置
total 排名总数
level 预估排名层级
levelRank 用户当前层级排名
rank 用户总排名
previousRow 上一层级
diffValue 距离上一层级差值
*/
func EstimateUserPosition(engine *xorm.Engine, uid int, dbName string) (total, level, levelRank, rank, previousRow int, diffValue string, err error) {
//1、查找 `user_public_platoon_setting` 基础设置
userPublicPlatoonSetting, err := db.UserPublicPlatoonSettingGetOneByParams(engine, map[string]interface{}{
"key": "is_open",
"value": 1,
})
if err != nil {
return
}
if userPublicPlatoonSetting == nil {
return
}
//2、查询排名
rank, total, userAmount, err := CalcUserRank(engine, zhios_order_relate_utils.IntToStr(uid))
if err != nil {
return
}
if rank == 0 {
userPublicPlatoonDoubleNetworkSetting, err1 := db.UserPublicPlatoonDoubleNetworkSettingGetOneByParams(engine, map[string]interface{}{
"key": "is_open",
"value": 1,
})
if err1 != nil {
err = err1
return
}
coinAmount, err2 := svc.GetUserCoinAmount(engine.NewSession(), dbName, userPublicPlatoonDoubleNetworkSetting.CoinId, uid)
if err2 != nil {
err = err2
return
}
userProfile, err3 := db.UserProfileFindByID(engine, uid)
if err3 != nil {
err = err3
return
}
_, err4 := db.UserPublicPlatoonDoubleNetworkUserCoinRecordInsert(engine, &model.UserPublicPlatoonDoubleNetworkUserCoinRecord{
Uid: uid,
LastAmount: coinAmount,
Amount: coinAmount,
RecommendUid: userProfile.ParentUid,
CoinId: userPublicPlatoonDoubleNetworkSetting.CoinId,
CreateAt: time.Now().Format("2006-01-02 15:04:05"),
UpdateAt: time.Now().Format("2006-01-02 15:04:05"),
})
if err4 != nil {
err = err4
return
}
}
rows := float64(userPublicPlatoonSetting.SeveralRows)
times := float64(userPublicPlatoonSetting.SeveralTimes)
level = makeSearchLevelByPosition(&rank, rows, &times)
levelPosition1 := getLevelForFirstPosition(level, userPublicPlatoonSetting.SeveralTimes)
levelRank = rank - levelPosition1 + 1

//3、计算与前排差距
previousRow = level - 1
if previousRow > 0 {
previousRowPosition1 := getLevelForLastPosition(previousRow, userPublicPlatoonSetting.SeveralTimes)
previousRowAmount, err1 := GetUserRankAmount(engine, strconv.Itoa(previousRowPosition1))
if err1 != nil {
err = err1
return
}
userAmountValue, _ := decimal.NewFromString(userAmount)
previousRowAmountValue, _ := decimal.NewFromString(previousRowAmount)
diffValue = previousRowAmountValue.Sub(userAmountValue).String()
}
return
}

/*
NowUserPosition 当前用户位置
level 当前排名
levelRank 用户当前层级排名
*/
func NowUserPosition(engine *xorm.Engine, uid int, dbName string) (level, levelRank int, err error) {
//1、查找 `user_public_platoon_setting` 基础设置
userPublicPlatoonSetting, err := db.UserPublicPlatoonSettingGetOneByParams(engine, map[string]interface{}{
"key": "is_open",
"value": 1,
})
if err != nil {
return
}
if userPublicPlatoonSetting == nil {
return
}
//2、查询出 `user_public_platoon_relation` 中相关记录
userPublicPlatoonRelation, err := db.UserPublicPlatoonRelationGetOneByParams(engine, map[string]interface{}{
"key": "uid",
"value": uid,
})
if err != nil {
return
}
if userPublicPlatoonRelation == nil {
err = errors.New("未查询到当前用户公网记录")
return
}
level = userPublicPlatoonRelation.Level
levelPosition1 := getLevelForFirstPosition(level, userPublicPlatoonSetting.SeveralTimes)
levelRank = userPublicPlatoonRelation.Position - levelPosition1 + 1
return
}

func CalcUserRank(engine *xorm.Engine, uid string) (rank, total int, amount string, err error) {
sql := "SELECT id, uid, amount, @rank := @rank + 1 AS rank FROM `user_public_platoon_double_network_user_coin_record`, (SELECT @rank:=0) r ORDER BY amount DESC;"
nativeString, _ := db.QueryNativeString(engine, sql)
total = len(nativeString)
if total <= 0 {
err = errors.New("当前无排名数据")
return
}
for _, v := range nativeString {
if uid == v["uid"] {
rank = zhios_order_relate_utils.StrToInt(v["rank"])
amount = v["amount"]
break
}
}
return
}

func GetUserRankAmount(engine *xorm.Engine, rank string) (amount string, err error) {
sql := "SELECT id, uid, amount, @rank := @rank + 1 AS rank FROM `user_public_platoon_double_network_user_coin_record`, (SELECT @rank:=0) r ORDER BY amount DESC;"
nativeString, _ := db.QueryNativeString(engine, sql)
if len(nativeString) <= 0 {
err = errors.New("当前无排名数据")
return
}
for _, v := range nativeString {
if rank == v["rank"] {
amount = v["amount"]
break
}
}
return
}

const ResetPublicPlatoonDoubleNetworkPessimismLockKey = "reset_public_platoon_double_network_lock_key"
const PessimismLResetPublicPlatoonDoubleNetworkPessimismLockValue = "running"

func ResetPublicPlatoonDoubleNetwork(engine *xorm.Engine, dbName string) (err error) {
fmt.Println("!!!!!!!!!!!!!!!!!!!!!!!dbName!!!!!!!!!!!!!!!!!!!!", dbName)

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

//1、查找 `user_public_platoon_double_network_setting` 基础设置
now := time.Now()
userPublicPlatoonDoubleNetworkSetting, err := db.UserPublicPlatoonDoubleNetworkSettingGetOneByParams(engine, map[string]interface{}{
"key": "is_open",
"value": 1,
})
if err != nil {
return err
}
if userPublicPlatoonDoubleNetworkSetting.IsOpen != 1 {
return errors.New("未开启公排双网!")
}
if userPublicPlatoonDoubleNetworkSetting.SettlementDate != now.Format("2006-01-02") {
return errors.New("非重置日期!")
}

session := engine.NewSession()
defer func() {
session.Close()
if err := recover(); err != nil {
_ = zhios_order_relate_logx.Error(err)
}
}()

session.Begin()
//2、进行数据清理
sql1 := "DROP TABLE `user_public_platoon_relation_1`" //删除备份表
sql2 := "CREATE TABLE `user_public_platoon_relation_1` LIKE `user_public_platoon_relation`" //复制表结构
sql3 := "INSERT INTO `user_public_platoon_relation_1` SELECT * FROM `user_public_platoon_relation`" //复制表数据
sql4 := "TRUNCATE TABLE `user_public_platoon_relation`;" //截断表
_, err = db.ExecuteOriginalSqlBySession(engine.NewSession(), sql1)
if err != nil {
_ = session.Rollback()
fmt.Println("err___SQl1", err.Error())
}
time.Sleep(time.Millisecond * time.Duration(rand.Intn(1000)))
_, err = db.ExecuteOriginalSqlBySession(engine.NewSession(), sql2)
if err != nil {
_ = session.Rollback()
return err
}
time.Sleep(time.Millisecond * time.Duration(rand.Intn(1000)))
_, err = db.ExecuteOriginalSqlBySession(engine.NewSession(), sql3)
if err != nil {
_ = session.Rollback()
return err
}
time.Sleep(time.Millisecond * time.Duration(rand.Intn(1000)))
_, err = db.ExecuteOriginalSqlBySession(engine.NewSession(), sql4)
if err != nil {
_ = session.Rollback()
return err
}

sql5 := "DROP TABLE `user_public_platoon_double_network_user_coin_record_1`" //删除备份表
sql6 := "CREATE TABLE `user_public_platoon_double_network_user_coin_record_1` LIKE `user_public_platoon_double_network_user_coin_record`" //复制表结构
sql7 := "INSERT INTO `user_public_platoon_double_network_user_coin_record_1` SELECT * FROM `user_public_platoon_double_network_user_coin_record`" //复制表数据

time.Sleep(time.Millisecond * time.Duration(rand.Intn(1000)))
_, err = db.ExecuteOriginalSqlBySession(engine.NewSession(), sql5)
if err != nil {
_ = session.Rollback()
return err
}
time.Sleep(time.Millisecond * time.Duration(rand.Intn(1000)))
_, err = db.ExecuteOriginalSqlBySession(engine.NewSession(), sql6)
if err != nil {
_ = session.Rollback()
return err
}
time.Sleep(time.Millisecond * time.Duration(rand.Intn(1000)))
_, err = db.ExecuteOriginalSqlBySession(engine.NewSession(), sql7)
if err != nil {
_ = session.Rollback()
return err
}

//2、先插入创始人
//2.1 查找 `user_public_platoon_setting` 基础设置
userPublicPlatoonSetting, err := db.UserPublicPlatoonSettingGetOneByParams(engine, map[string]interface{}{
"key": "is_open",
"value": 1,
})
if err != nil {
_ = session.Rollback()
return err
}
//2.2 插入数据
_, err = db.UserPublicPlatoonRelationInsertBySession(session, &model.UserPublicPlatoonRelation{
Uid: userPublicPlatoonSetting.OriginatorUid,
FatherUid: "",
Pid: 0,
RecommendUid: 0,
Level: 1,
Position: 1,
UniqueIdentifier: "0-" + zhios_order_relate_utils.IntToStr(userPublicPlatoonDoubleNetworkSetting.OriginatorUid) + "-1-1",
ReturnCommissionNum: 0,
JoinAt: now,
WaitForSettlementDate: now.AddDate(0, 0, userPublicPlatoonSetting.SettleDay).Format("2006-01-02"),
CreateAt: now,
UpdateAt: now,
})
if err != nil {
_ = session.Rollback()
return err
}
err = session.Commit()
if err != nil {
_ = session.Rollback()
return err
}

//3、计算排名数据
sql := "SELECT id, uid,recommend_uid, amount, @rank := @rank + 1 AS rank FROM `user_public_platoon_double_network_user_coin_record`, (SELECT @rank:=0) r ORDER BY amount DESC;"
nativeString, _ := db.QueryNativeString(engine, sql)
if len(nativeString) <= 0 {
return errors.New("当前无排名数据")
}
for _, v := range nativeString {
if v["uid"] == zhios_order_relate_utils.IntToStr(userPublicPlatoonSetting.OriginatorUid) {
//TODO::创始人不需要重排
continue
}
//3.1 加入公排
_, err1 := AddPublicPlatoonRelateCommission(engine, []*md.AddPublicPlatoonRelateCommissionReq{
{
Uid: v["uid"],
RecommendUid: v["recommend_uid"],
},
})
if err1 != nil {
return err1
}
//3.2将`user_public_platoon_double_network_user_coin_record` 中 amount 置0
var tmpSql = fmt.Sprintf("UPDATE user_public_platoon_double_network_user_coin_record SET amount = 0 WHERE id=%s", v["id"])
_, err2 := db.ExecuteOriginalSql(engine, tmpSql)
if err2 != nil {
return err2
}
}

//4、修改 user_public_platoon_relation 中的 wait_for_settlement_date 待结算时间
sql8 := "SELECT * FROM `user_public_platoon_relation_1`"
nativeString1, _ := db.QueryNativeString(engine, sql8)
if len(nativeString1) >= 0 {
var oldWaitForSettlementDateMap = map[string]string{}
for _, v := range nativeString1 {
oldWaitForSettlementDateMap[v["uid"]] = v["wait_for_settlement_date"]
}
sql9 := "SELECT * FROM `user_public_platoon_relation`"
nativeString2, _ := db.QueryNativeString(engine, sql9)
for _, v := range nativeString2 {
if oldWaitForSettlementDateMap[v["uid"]] != "" {
tmpSql := fmt.Sprintf("update `user_public_platoon_relation` set wait_for_settlement_date = '%s' where uid = %s", oldWaitForSettlementDateMap[v["uid"]], v["uid"])
db.ExecuteOriginalSql(engine, tmpSql)
time.Sleep(time.Millisecond * time.Duration(rand.Intn(100)))
}
}
}

//5、修改 user_public_platoon_double_network_setting 中的结算时间
userPublicPlatoonDoubleNetworkSetting.SettlementDate = now.AddDate(0, 1, 0).Format("2006-01-02")
userPublicPlatoonDoubleNetworkSetting.LastSettlementDate = now.Format("2006-01-02")
updateAffected, err := db.UserPublicPlatoonDoubleNetworkSettingUpdate(engine, userPublicPlatoonDoubleNetworkSetting.Id, userPublicPlatoonDoubleNetworkSetting, "settlement_date", "last_settlement_date")
if err != nil {
return err
}
if updateAffected <= 0 {
fmt.Println("updateAffected:::::::::", updateAffected)
return errors.New("更新结算时间失败")
}
return
}

+ 13
- 0
rule/public_platoon_relate_commission.go View File

@@ -206,6 +206,19 @@ func makeSearchLevel(position *int, rows float64, times *float64) (level int) {
}
}

//递归查找等级
func makeSearchLevelByPosition(position *int, rows float64, times *float64) (level int) {
for {
level++
positionStart := getLevelForFirstPosition(level, int(*times))
positionEnd := getLevelForLastPosition(level, int(*times))
if positionStart <= *position && *position <= positionEnd {
break
}
}
return
}

//查找归属父级id
func makeSearchPid(position int, row int) (pid int) {
divisionValue := (position - 1) / row


+ 91
- 0
rule/user_amount.go View File

@@ -0,0 +1,91 @@
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/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"
"errors"
"fmt"
"github.com/shopspring/decimal"
"strconv"
"time"
"xorm.io/xorm"
)

// DealUserCoin 处理给用户虚拟币积分
func DealUserCoin(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
}

+ 55
- 7
svc/get_plan_cfg.go View File

@@ -60,7 +60,31 @@ func GetAllPlan(eg *xorm.Engine, dbName string) (map[string]*model.PlanReward, m
plan[tmp.Pvd] = tmp
}
}

moreList, _ := db.MoreGetAllPriceTypeList(eg)
for _, v := range moreList {
var oneRewardPlan map[string]string
err := json.Unmarshal([]byte(v.CommissionData), &oneRewardPlan)
if err == nil {
var tmp = &model.PlanReward{
Id: 0,
Pvd: "moreFree_" + zhios_order_relate_utils.IntToStr(v.Id),
PvdRate: zhios_order_relate_utils.StrToFloat32(oneRewardPlan["pvd_rate"]) / 100,
SysRate: zhios_order_relate_utils.StrToFloat32(oneRewardPlan["sys_rate"]) / 100,
RegionRate: zhios_order_relate_utils.StrToFloat32(oneRewardPlan["region_rate"]) / 100,
GlobalRate: zhios_order_relate_utils.StrToFloat32(oneRewardPlan["global_rate"]) / 100,
SettleMode: zhios_order_relate_utils.StrToInt(oneRewardPlan["settle_mode"]),
PlanCommissionId: zhios_order_relate_utils.StrToInt(oneRewardPlan["plan_commission_id"]),
PlanSettleId: zhios_order_relate_utils.StrToInt(oneRewardPlan["plan_settle_id"]),
State: 1,
Source: 1,
IntegralOpen: zhios_order_relate_utils.StrToInt(oneRewardPlan["integral_open"]),
MerchantRate: zhios_order_relate_utils.StrToFloat32(oneRewardPlan["merchant_rate"]) / 100,
PushHandRate: zhios_order_relate_utils.StrToFloat32(oneRewardPlan["push_hand_rate"]) / 100,
OrderBeforeRate: zhios_order_relate_utils.StrToFloat32(oneRewardPlan["order_before_rate"]) / 100,
}
plan[tmp.Pvd] = tmp
}
}
commission := make(map[int]*model.PlanCommission, 0)
commissions := db.DbsPlanCommissionByIds(eg)
for _, v := range commissions {
@@ -74,11 +98,10 @@ func GetPlanCfg(eg *xorm.Engine, pvd, masterId string, rewardOpts map[string]*mo
opt := &comm_plan.PlanOpt{}
// 根据供应商
rewardOpt := rewardOpts[pvd]
if strings.Contains(pvd, "seFree") == false {
if pvd == "tikTok" && rmd.IsTikTokTeamOrder == "1" && rewardOpts["tikTokTeam"] != nil && rewardOpts["tikTokTeam"].PlanCommissionId > 0 {
if strings.Contains(pvd, "seFree") == false && strings.Contains(pvd, "moreFree") == false {
if (pvd == "tikTok" || pvd == "csjp") && rmd.IsTikTokTeamOrder == "1" && rewardOpts["tikTokTeam"] != nil && rewardOpts["tikTokTeam"].PlanCommissionId > 0 {
rewardOpt = rewardOpts["tikTokTeam"]
}

if pvd == "kuaishou" && rmd.IsTikTokTeamOrder == "1" && rewardOpts["kuaishouTeam"] != nil && rewardOpts["kuaishouTeam"].PlanCommissionId > 0 {
rewardOpt = rewardOpts["kuaishouTeam"]
}
@@ -99,7 +122,7 @@ func GetPlanCfg(eg *xorm.Engine, pvd, masterId string, rewardOpts map[string]*mo
if commissionOpt == nil || commissionOpt.Id == 0 {
return nil, errors.New("佣金方案有误")
}
if _, ok := comm_plan.Fn[commissionOpt.Mode]; !ok && zhios_order_relate_utils.InArr(commissionOpt.Mode, []string{"public_platoon", "extend_price", "lv_integral_release"}) == false {
if _, ok := comm_plan.Fn[commissionOpt.Mode]; !ok && zhios_order_relate_utils.InArr(commissionOpt.Mode, []string{"public_platoon_level", "public_platoon", "extend_price", "lv_integral_release"}) == false {
return nil, zhios_order_relate_logx.Warn("分佣模式不存在")
}
opt.Pvd = pvd
@@ -133,7 +156,7 @@ func GetPlanCfg(eg *xorm.Engine, pvd, masterId string, rewardOpts map[string]*mo
} else {
opt.VirtualCoinMoneyRatioList = virtualCoinMoneyRate
}
if zhios_order_relate_utils.InArr(commissionOpt.Mode, []string{"public_platoon", "extend_price", "lv_integral_release"}) { //公排
if zhios_order_relate_utils.InArr(commissionOpt.Mode, []string{"public_platoon_level", "public_platoon", "extend_price", "lv_integral_release"}) { //公排
return opt, nil
}

@@ -195,7 +218,7 @@ func GetPlanCfg(eg *xorm.Engine, pvd, masterId string, rewardOpts map[string]*mo

return opt, nil
}
if zhios_order_relate_utils.InArr(commissionOpt.Mode, []string{"lv_price_public_platoon"}) {
if zhios_order_relate_utils.InArr(commissionOpt.Mode, []string{"lv_price_public_platoon", "lv_commission_public_platoon"}) {
if err := json.Unmarshal([]byte(commissionOpt.Data), &subsidyTmpPricePublic); err != nil {
return nil, zhios_order_relate_logx.Warn(fmt.Sprintf("%s:分佣方案数据设置错误", masterId))
}
@@ -271,6 +294,31 @@ func PlanOpts(eg *xorm.Engine) map[string]*comm_plan.PlanOpt {
allRewardPlan = append(allRewardPlan, tmp)
}
}
moreList, _ := db.MoreGetAllPriceTypeList(eg)
for _, v := range moreList {
var oneRewardPlan map[string]string
err := json.Unmarshal([]byte(v.CommissionData), &oneRewardPlan)
if err == nil {
var tmp = &model.PlanReward{
Id: 0,
Pvd: "moreFree_" + zhios_order_relate_utils.IntToStr(v.Id),
PvdRate: zhios_order_relate_utils.StrToFloat32(oneRewardPlan["pvd_rate"]) / 100,
SysRate: zhios_order_relate_utils.StrToFloat32(oneRewardPlan["sys_rate"]) / 100,
RegionRate: zhios_order_relate_utils.StrToFloat32(oneRewardPlan["region_rate"]) / 100,
GlobalRate: zhios_order_relate_utils.StrToFloat32(oneRewardPlan["global_rate"]) / 100,
SettleMode: zhios_order_relate_utils.StrToInt(oneRewardPlan["settle_mode"]),
PlanCommissionId: zhios_order_relate_utils.StrToInt(oneRewardPlan["plan_commission_id"]),
PlanSettleId: zhios_order_relate_utils.StrToInt(oneRewardPlan["plan_settle_id"]),
State: 1,
Source: 1,
IntegralOpen: zhios_order_relate_utils.StrToInt(oneRewardPlan["integral_open"]),
MerchantRate: zhios_order_relate_utils.StrToFloat32(oneRewardPlan["merchant_rate"]) / 100,
PushHandRate: zhios_order_relate_utils.StrToFloat32(oneRewardPlan["push_hand_rate"]) / 100,
OrderBeforeRate: zhios_order_relate_utils.StrToFloat32(oneRewardPlan["order_before_rate"]) / 100,
}
allRewardPlan = append(allRewardPlan, tmp)
}
}
opts := map[string]*comm_plan.PlanOpt{}
for _, v := range allRewardPlan {
if _, ok := commissionPlans[v.PlanCommissionId]; ok && v.State == 1 && v.PlanCommissionId > 0 {


+ 131
- 3
svc/public_platoon_relate_commission.go View File

@@ -56,9 +56,9 @@ func BatchGetPublicPlatoonRelateCommissionByOrder(engine *xorm.Engine, masterId
if zhios_order_relate_utils.StrToInt(coinId) > 0 { //积分更换基数
pendingAmount = param.PendingIntegral
}
selfRateList[coinId] = zhios_order_relate_utils.Float64ToStr(zhios_order_relate_utils.StrToFloat64(lvGrade.SelfRateList[coinId]) * zhios_order_relate_utils.StrToFloat64(pendingAmount) / 100)
commonWealthSystem[coinId] = zhios_order_relate_utils.Float64ToStr(zhios_order_relate_utils.StrToFloat64(lvGrade.CommonWealthSystem[coinId]) * zhios_order_relate_utils.StrToFloat64(pendingAmount) / 100)
directPush[coinId] = zhios_order_relate_utils.Float64ToStr(zhios_order_relate_utils.StrToFloat64(lvGrade.DirectPush[coinId]) * zhios_order_relate_utils.StrToFloat64(pendingAmount) / 100)
selfRateList[coinId] = zhios_order_relate_utils.Float64ToStrByPrec(zhios_order_relate_utils.StrToFloat64(lvGrade.SelfRateList[coinId])*zhios_order_relate_utils.StrToFloat64(pendingAmount)/100, 9)
commonWealthSystem[coinId] = zhios_order_relate_utils.Float64ToStrByPrec(zhios_order_relate_utils.StrToFloat64(lvGrade.CommonWealthSystem[coinId])*zhios_order_relate_utils.StrToFloat64(pendingAmount)/100, 9)
directPush[coinId] = zhios_order_relate_utils.Float64ToStrByPrec(zhios_order_relate_utils.StrToFloat64(lvGrade.DirectPush[coinId])*zhios_order_relate_utils.StrToFloat64(pendingAmount)/100, 9)
}
}
nowBenefitUid, _, err := benefitUidByBig(engine, param)
@@ -143,3 +143,131 @@ func benefitUidByBig(engine *xorm.Engine, param *md.PublicPlatoonRelateCommissio
return nowBenefitUid, nil, nil

}

func BatchGetPublicPlatoonRelateCommissionByOrderLevel(engine *xorm.Engine, masterId string, PublicPlatoonRelateCommissionReqList []*md.PublicPlatoonRelateCommissionReq) (map[string]*md.PublicPlatoonRelateCommissionResp, error) {
var resp = make(map[string]*md.PublicPlatoonRelateCommissionResp)
for _, param := range PublicPlatoonRelateCommissionReqList {
// 根据供应商
rewardOpt, err := db.DbsPlanRewardByPvd(engine, param.Pvd)
if err != nil {
return nil, err
}
if rewardOpt == nil {
return nil, zhios_order_relate_logx.Warn("找不到方案记录")
}
if rewardOpt.State == 0 {
return nil, zhios_order_relate_logx.Warn("抽成方案未开启")
}
if rewardOpt.PlanCommissionId == 0 {
return nil, zhios_order_relate_logx.Warn("抽成方案未设置佣金方案id")
}
fmt.Println("抽成设置:", zhios_order_relate_utils.SerializeStr(rewardOpt))
fmt.Println("commission id:", rewardOpt.PlanCommissionId)

//TODO::计算共富收益
commissionOpt, err := db.DbsPlanCommissionById(engine, rewardOpt.PlanCommissionId)
if err != nil || commissionOpt == nil || commissionOpt.Id == 0 {
return nil, err
}
var subsidyTmp = make(map[string]*md.LvGrade)
var tmp map[string]*md.LvGrade
if err := json.Unmarshal([]byte(commissionOpt.Data), &tmp); err != nil {
return nil, zhios_order_relate_logx.Warn(fmt.Sprintf("%s:分佣方案数据设置错误", masterId))
}
for _, v := range tmp {
subsidyTmp[zhios_order_relate_utils.IntToStr(v.Lv)] = v
}
lvGrade := subsidyTmp[param.UserLevel]
var directPush = make(map[string]string)
var selfRateList = make(map[string]string)
var commonWealthSystem = make(map[string]string)
if lvGrade != nil {
for _, coinId := range lvGrade.ReturnType {
var pendingAmount = param.PendingAmount
if zhios_order_relate_utils.StrToInt(coinId) > 0 { //积分更换基数
pendingAmount = param.PendingIntegral
}
selfRateList[coinId] = zhios_order_relate_utils.Float64ToStrByPrec(zhios_order_relate_utils.StrToFloat64(lvGrade.SelfRateList[coinId])*zhios_order_relate_utils.StrToFloat64(pendingAmount)/100, 9)
}
}
nowBenefitUid, _, err := benefitUidByBig(engine, param)
if err != nil {
return nil, err
}
recommendUid := ""
userProfile, _ := db.UserProfileFindByID(engine, param.Uid)
if userProfile != nil && userProfile.ParentUid > 0 {
recommendUid = zhios_order_relate_utils.IntToStr(userProfile.ParentUid)
}
//直推獎勵
if zhios_order_relate_utils.StrToInt(recommendUid) > 0 {
parentUid, _ := db.UserFindByID(engine, recommendUid)
lvGrade := subsidyTmp[zhios_order_relate_utils.IntToStr(parentUid.Level)]
if lvGrade != nil {
for _, coinId := range lvGrade.ReturnType {
var pendingAmount = param.PendingAmount
if zhios_order_relate_utils.StrToInt(coinId) > 0 { //积分更换基数
pendingAmount = param.PendingIntegral
}
directPush[coinId] = zhios_order_relate_utils.Float64ToStrByPrec(zhios_order_relate_utils.StrToFloat64(lvGrade.DirectPush[coinId])*zhios_order_relate_utils.StrToFloat64(pendingAmount)/100, 9)
}
}
}
//共富简历
if zhios_order_relate_utils.StrToInt(nowBenefitUid) > 0 {
parentUid, _ := db.UserFindByID(engine, nowBenefitUid)
lvGrade := subsidyTmp[zhios_order_relate_utils.IntToStr(parentUid.Level)]
if lvGrade != nil {
//判断购买人是哪个等级
UserLvUpPublicPlatoonList := make(map[string]interface{})
if len(lvGrade.UserLvUpPublicPlatoonList) > 0 {
for _, v1 := range lvGrade.UserLvUpPublicPlatoonList {
v2 := v1.(map[string]interface{})
if zhios_order_relate_utils.AnyToInt64(v2["lv"]) == zhios_order_relate_utils.StrToInt64(param.UserLevel) {
rateList, ok := v2["rate_list"].(map[string]interface{})
if ok {
UserLvUpPublicPlatoonList = rateList
} else {
rateList, ok := v2["rate_list"].([]interface{})
if ok {
for k, v := range rateList {
UserLvUpPublicPlatoonList[zhios_order_relate_utils.AnyToString(k)] = v
}
}
}
}
}
}
for _, coinId := range lvGrade.ReturnType {
var pendingAmount = param.PendingAmount
if zhios_order_relate_utils.StrToInt(coinId) > 0 { //积分更换基数
pendingAmount = param.PendingIntegral
}
bili := lvGrade.CommonWealthSystem[coinId]
//判断购买人是哪个等级 读对应的比例
if UserLvUpPublicPlatoonList != nil {
newBili, ok := UserLvUpPublicPlatoonList[coinId]
if ok {
bili = zhios_order_relate_utils.AnyToString(newBili)
}
}
commonWealthSystem[coinId] = zhios_order_relate_utils.Float64ToStrByPrec(zhios_order_relate_utils.StrToFloat64(bili)*zhios_order_relate_utils.StrToFloat64(pendingAmount)/100, 9)
}
}
}

///
resp[param.Oid] = &md.PublicPlatoonRelateCommissionResp{
Uid: param.Uid,
CommonWealthBenefitUid: nowBenefitUid,
DirectPushBenefitUid: recommendUid,
PendingAmount: param.PendingAmount,
PendingIntegral: param.PendingIntegral,
Oid: param.Oid,
SelfRateList: selfRateList,
CommonWealthSystem: commonWealthSystem,
DirectPush: directPush,
}
}
return resp, nil
}

+ 3
- 4
svc/reward_commission.go View File

@@ -117,7 +117,7 @@ func GetRewardCommission(engine *xorm.Engine, rmd *md.CommissionParam, isShare b
if rmd.IsGoods == "1" {
order, err = BatchSmallGetPublicPlatoonRelateByGoods(engine, masterId, PublicPlatoonRelateCommissionReqList)
} else {
order, err = BatchSmallGetPublicPlatoonRelateCommission(engine, masterId, PublicPlatoonRelateCommissionReqList)
order, err = BatchSmallGetPublicPlatoonRelateCommissionLevel(engine, masterId, PublicPlatoonRelateCommissionReqList)
}
if err != nil || order[rmd.Oid] == nil {
return 0, 0, 0, 0, nil, nil
@@ -142,7 +142,7 @@ func GetRewardCommission(engine *xorm.Engine, rmd *md.CommissionParam, isShare b
if rmd.IsGoods == "1" {
order, err = BatchGetPublicPlatoonRelateCommissionByGoods(engine, masterId, PublicPlatoonRelateCommissionReqList)
} else {
order, err = BatchGetPublicPlatoonRelateCommissionByOrder(engine, masterId, PublicPlatoonRelateCommissionReqList)
order, err = BatchGetPublicPlatoonRelateCommissionByOrderLevel(engine, masterId, PublicPlatoonRelateCommissionReqList)
}
if err != nil || order[rmd.Oid] == nil {
return 0, 0, 0, 0, nil, nil
@@ -261,7 +261,7 @@ func GetRewardCommission(engine *xorm.Engine, rmd *md.CommissionParam, isShare b
if ulink == nil {
return 0, 0, 0, 0, nil, nil
}
if cfg.Mode == "lv_price_public_platoon" {
if cfg.Mode == "lv_price_public_platoon" || cfg.Mode == "lv_commission_public_platoon" {
ulink = public(engine, ulink, cfg, newProvider, uid, comf, price, rmd)
}
comm(commArr, ulink)
@@ -322,7 +322,6 @@ func public(engine *xorm.Engine, ulinkParent *comm_plan.LvUser, cfg *comm_plan.P
CommonWealthSystems, ok := grade.CommonWealthSystem.(map[string]string)
if ok {
commonWealthSystem[coinId] = zhios_order_relate_utils.Float64ToStr(zhios_order_relate_utils.StrToFloat64(CommonWealthSystems[coinId]) * zhios_order_relate_utils.StrToFloat64(pendingAmount) / 100)

}
}
}


+ 133
- 3
svc/small_public_platoon_relate_commission.go View File

@@ -58,9 +58,9 @@ func BatchSmallGetPublicPlatoonRelateCommission(engine *xorm.Engine, masterId st
if zhios_order_relate_utils.StrToInt(coinId) > 0 { //积分更换基数
pendingAmount = param.PendingIntegral
}
selfRateList[coinId] = zhios_order_relate_utils.Float64ToStr(zhios_order_relate_utils.StrToFloat64(lvGrade.SelfRateList[coinId]) * zhios_order_relate_utils.StrToFloat64(pendingAmount) / 100)
commonWealthSystem[coinId] = zhios_order_relate_utils.Float64ToStr(zhios_order_relate_utils.StrToFloat64(lvGrade.CommonWealthSystem[coinId]) * zhios_order_relate_utils.StrToFloat64(pendingAmount) / 100)
directPush[coinId] = zhios_order_relate_utils.Float64ToStr(zhios_order_relate_utils.StrToFloat64(lvGrade.DirectPush[coinId]) * zhios_order_relate_utils.StrToFloat64(pendingAmount) / 100)
selfRateList[coinId] = zhios_order_relate_utils.Float64ToStrByPrec(zhios_order_relate_utils.StrToFloat64(lvGrade.SelfRateList[coinId])*zhios_order_relate_utils.StrToFloat64(pendingAmount)/100, 9)
commonWealthSystem[coinId] = zhios_order_relate_utils.Float64ToStrByPrec(zhios_order_relate_utils.StrToFloat64(lvGrade.CommonWealthSystem[coinId])*zhios_order_relate_utils.StrToFloat64(pendingAmount)/100, 9)
directPush[coinId] = zhios_order_relate_utils.Float64ToStrByPrec(zhios_order_relate_utils.StrToFloat64(lvGrade.DirectPush[coinId])*zhios_order_relate_utils.StrToFloat64(pendingAmount)/100, 9)
}
}

@@ -355,3 +355,133 @@ func BatchSmallGetPublicPlatoonRelateByGoods(engine *xorm.Engine, masterId strin
}
return resp, nil
}

func BatchSmallGetPublicPlatoonRelateCommissionLevel(engine *xorm.Engine, masterId string, PublicPlatoonRelateCommissionReqList []*md.SmallPublicPlatoonRelateCommissionReq) (map[string]*md.SmallPublicPlatoonRelateCommissionResp, error) {
var resp = make(map[string]*md.SmallPublicPlatoonRelateCommissionResp)
for _, param := range PublicPlatoonRelateCommissionReqList {
// 根据供应商
rewardOpt, err := db.DbsPlanRewardByPvd(engine, param.Pvd)
if err != nil {
return nil, err
}
if rewardOpt == nil {
return nil, zhios_order_relate_logx.Warn("找不到方案记录")
}
if rewardOpt.State == 0 {
return nil, zhios_order_relate_logx.Warn("抽成方案未开启")
}
if rewardOpt.PlanCommissionId == 0 {
return nil, zhios_order_relate_logx.Warn("抽成方案未设置佣金方案id")
}
fmt.Println("抽成设置:", zhios_order_relate_utils.SerializeStr(rewardOpt))
fmt.Println("commission id:", rewardOpt.PlanCommissionId)

//TODO::计算共富收益
commissionOpt, err := db.DbsPlanCommissionById(engine, rewardOpt.PlanCommissionId)
if err != nil || commissionOpt == nil || commissionOpt.Id == 0 {
return nil, err
}
var subsidyTmp = make(map[string]*md.LvGrade)
var tmp map[string]*md.LvGrade
if err := json.Unmarshal([]byte(commissionOpt.Data), &tmp); err != nil {
return nil, zhios_order_relate_logx.Warn(fmt.Sprintf("%s:分佣方案数据设置错误", masterId))
}
for _, v := range tmp {
subsidyTmp[zhios_order_relate_utils.IntToStr(v.Lv)] = v
}
var directPush = make(map[string]string)
var selfRateList = make(map[string]string)
var commonWealthSystem = make(map[string]string)
lvGrade := subsidyTmp[param.UserLevel]
if lvGrade != nil {
for _, coinId := range lvGrade.ReturnType {
var pendingAmount = param.PendingAmount
if zhios_order_relate_utils.StrToInt(coinId) > 0 { //积分更换基数
pendingAmount = param.PendingIntegral
}
selfRateList[coinId] = zhios_order_relate_utils.Float64ToStrByPrec(zhios_order_relate_utils.StrToFloat64(lvGrade.SelfRateList[coinId])*zhios_order_relate_utils.StrToFloat64(pendingAmount)/100, 9)
}
}
//TODO::本次消费产生的共富收益给到谁
nowBenefitUid, _, err := benefitUid(engine, param)
if err != nil {
return nil, err
}
recommendUid := ""
userProfile, _ := db.UserProfileFindByID(engine, param.Uid)
if userProfile != nil && userProfile.ParentUid > 0 {
recommendUid = zhios_order_relate_utils.IntToStr(userProfile.ParentUid)
}
//直推獎勵
if zhios_order_relate_utils.StrToInt(recommendUid) > 0 {
parentUid, _ := db.UserFindByID(engine, recommendUid)
lvGrade := subsidyTmp[zhios_order_relate_utils.IntToStr(parentUid.Level)]
if lvGrade != nil {
for _, coinId := range lvGrade.ReturnType {
var pendingAmount = param.PendingAmount
if zhios_order_relate_utils.StrToInt(coinId) > 0 { //积分更换基数
pendingAmount = param.PendingIntegral
}
directPush[coinId] = zhios_order_relate_utils.Float64ToStrByPrec(zhios_order_relate_utils.StrToFloat64(lvGrade.DirectPush[coinId])*zhios_order_relate_utils.StrToFloat64(pendingAmount)/100, 9)
}
}
}
//共富简历
if zhios_order_relate_utils.StrToInt(nowBenefitUid) > 0 {
parentUid, _ := db.UserFindByID(engine, nowBenefitUid)
if parentUid != nil {
lvGrade := subsidyTmp[zhios_order_relate_utils.IntToStr(parentUid.Level)]
if lvGrade != nil {
//判断购买人是哪个等级
UserLvUpPublicPlatoonList := make(map[string]interface{})
if len(lvGrade.UserLvUpPublicPlatoonList) > 0 {
for _, v1 := range lvGrade.UserLvUpPublicPlatoonList {
v2 := v1.(map[string]interface{})
if zhios_order_relate_utils.AnyToInt64(v2["lv"]) == zhios_order_relate_utils.StrToInt64(param.UserLevel) {
rateList, ok := v2["rate_list"].(map[string]interface{})
if ok {
UserLvUpPublicPlatoonList = rateList
} else {
rateList, ok := v2["rate_list"].([]interface{})
if ok {
for k, v := range rateList {
UserLvUpPublicPlatoonList[zhios_order_relate_utils.AnyToString(k)] = v
}
}
}
}
}
}
for _, coinId := range lvGrade.ReturnType {
var pendingAmount = param.PendingAmount
if zhios_order_relate_utils.StrToInt(coinId) > 0 { //积分更换基数
pendingAmount = param.PendingIntegral
}
bili := lvGrade.CommonWealthSystem[coinId]
//判断购买人是哪个等级 读对应的比例
if UserLvUpPublicPlatoonList != nil {
newBili, ok := UserLvUpPublicPlatoonList[coinId]
if ok {
bili = zhios_order_relate_utils.AnyToString(newBili)
}
}
commonWealthSystem[coinId] = zhios_order_relate_utils.Float64ToStrByPrec(zhios_order_relate_utils.StrToFloat64(bili)*zhios_order_relate_utils.StrToFloat64(pendingAmount)/100, 9)
}
}
}

}

resp[param.Oid] = &md.SmallPublicPlatoonRelateCommissionResp{
Uid: param.Uid,
CommonWealthBenefitUid: nowBenefitUid,
DirectPushBenefitUid: recommendUid,
PendingAmount: param.PendingAmount,
Oid: param.Oid,
SelfRateList: selfRateList,
CommonWealthSystem: commonWealthSystem,
DirectPush: directPush,
}
}
return resp, nil
}

+ 88
- 0
svc/svc_deal_user_amount.go View File

@@ -51,6 +51,7 @@ func DealUserAmount(session *xorm.Session, req md.DealUserAmount) (err error) {
State: 1,
CreateAt: now,
UpdateAt: now,
Date: now.Format("2006-01-02"),
}
if req.Kind == "add" {
finUserFlow.Type = 0
@@ -88,6 +89,93 @@ func DealUserAmount(session *xorm.Session, req md.DealUserAmount) (err error) {

return nil
}
func DealUserAmountNew(session *xorm.Session, req md.DealUserAmount) (err error) {
if req.Amount < 0 {
req.Amount = 0
}
//1、分布式锁阻拦
requestIdPrefix := fmt.Sprintf(md.DealUserAmountRequestIdPrefix, req.Mid, req.Uid)
cb, err := HandleBalanceDistributedLockForAmount(req.Mid, strconv.Itoa(req.Uid), requestIdPrefix)
if err != nil {
return err
}
if cb != nil {
defer cb() // 释放锁
}

//2、计算&&组装数据
userAmount, err := GetUserAmount(session, req.Mid, req.Uid)
if err != nil {
return err
}
userAmountValue := decimal.NewFromFloat(zhios_order_relate_utils.StrToFloat64(userAmount))
amountValue := decimal.NewFromFloat(req.Amount).RoundFloor(8)
AfterAmount := ""
if req.Kind == "add" {
AfterAmount = userAmountValue.Add(amountValue).RoundFloor(8).String()
} else if req.Kind == "sub" {
AfterAmount = userAmountValue.Sub(amountValue).RoundFloor(8).String()
} else {
err = errors.New("错误的kind类型")
return err
}
//4、修改 `user_profile`的fin_valid值 && 及缓存
err = SetCacheUserAmount(session, req.Mid, AfterAmount, req.Uid, true)
if err != nil {
return err
}

return nil
}
func DealUserAmountFlow(session *xorm.Session, req md.DealUserAmount) (err error) {
if req.Amount < 0 {
req.Amount = 0
}
//2、计算&&组装数据
now := time.Now()
userAmount, err := GetUserAmount(session, req.Mid, req.Uid)
if err != nil {
return err
}
userAmountValue := decimal.NewFromFloat(zhios_order_relate_utils.StrToFloat64(userAmount))
amountValue := decimal.NewFromFloat(req.Amount).RoundFloor(8)

var finUserFlow = model.FinUserFlow{
Uid: req.Uid,
Amount: amountValue.String(),
AfterAmount: userAmount,
OrdType: req.OrderType,
OrdId: req.OrdId,
OrdTitle: req.Title,
OrdAction: req.OrdAction,
OrdTime: int(now.Unix()),
State: 1,
CreateAt: now,
UpdateAt: now,
Memo: req.Num,
Date: now.Format("2006-01-02"),
}
finUserFlow.Type = 0
finUserFlow.BeforeAmount = userAmountValue.Sub(amountValue).RoundFloor(8).String()
if zhios_order_relate_utils.StrToFloat64(finUserFlow.AfterAmount) < 0 {
zhios_order_relate_utils.FilePutContents("user_amount_not", zhios_order_relate_utils.SerializeStr(map[string]interface{}{
"uid": finUserFlow.Uid,
"amount": finUserFlow.Amount,
"before_amount": finUserFlow.BeforeAmount,
"title": finUserFlow.OrdTitle,
"mid": req.Mid,
}))
return errors.New("用户余额不足")
}

//3、插入 `fin_user_flow` 记录
affected, err := session.Insert(&finUserFlow)
if affected == 0 || err != nil {
_ = zhios_order_relate_logx.Warn(err)
return err
}
return nil
}

// GetUserAmount 获取用户余额
func GetUserAmount(session *xorm.Session, masterId string, uid int) (amount string, err error) {


+ 3
- 0
utils/convert.go View File

@@ -290,6 +290,9 @@ func Float64ToStrPrec4(f float64) string {
func Float64ToStrPrec10(f float64) string {
return strconv.FormatFloat(f, 'f', 10, 64)
}
func Float64ToStrPrec8(f float64) string {
return strconv.FormatFloat(f, 'f', 8, 64)
}

func Float64ToStrPrec6(f float64) string {
return strconv.FormatFloat(f, 'f', 6, 64)


Loading…
Cancel
Save