huangjiajun преди 1 година
родител
ревизия
ee6a296216
променени са 11 файла, в които са добавени 675 реда и са изтрити 1 реда
  1. +32
    -0
      db/db_regional_sub_agent_user_belong.go
  2. +1
    -0
      db/model/regional_agent_region.go
  3. +1
    -0
      db/model/regional_agent_scheme.go
  4. +25
    -0
      db/model/regional_agent_sub_user.go
  5. +19
    -0
      db/model/regional_sub_agent_calc_system_relate.go
  6. +23
    -0
      db/model/regional_sub_agent_ord_belong.go
  7. +1
    -0
      db/model/user.go
  8. +2
    -0
      lib/comm_plan/all.go
  9. +246
    -0
      lib/comm_plan/ds_check.go
  10. +4
    -1
      lib/comm_plan/init.go
  11. +321
    -0
      rule/regional_sub_agent.go

+ 32
- 0
db/db_regional_sub_agent_user_belong.go Целия файл

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

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

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

func RegionalSubAgentUserFindByValid(Db *xorm.Engine, regionId string) (*[]model.RegionalAgentSubUser, error) {
var m []model.RegionalAgentSubUser
err := Db.Where("region_id=? and deleted_time IS NULL", regionId).Find(&m)
if err != nil {
return nil, err
}
return &m, nil
}

func RegionalSubAgentCalcSystemRelateInsert(Db *xorm.Engine, RegionalSubAgentCalcSystemRelate *model.RegionalSubAgentCalcSystemRelate) (int64, error) {
_, err := Db.InsertOne(RegionalSubAgentCalcSystemRelate)
if err != nil {
return 0, err
}
return RegionalSubAgentCalcSystemRelate.Id, nil
}

+ 1
- 0
db/model/regional_agent_region.go Целия файл

@@ -22,6 +22,7 @@ type RegionalAgentRegion struct {
RenewalQuarterAgPrice string `json:"renewal_quarter_ag_price" xorm:"not null comment('续费季度代理价格') DECIMAL(12,2)"`
RenewalYearAgPrice string `json:"renewal_year_ag_price" xorm:"not null comment('续费年代理价格') DECIMAL(12,2)"`
CommissionRate string `json:"commission_rate" xorm:"not null comment('分佣比例') DECIMAL(6,4)"`
SubCommissionRate string `json:"sub_commission_rate" xorm:"not null comment('分佣比例') DECIMAL(6,4)"`
ReturnedRate string `json:"returned_rate" xorm:"not null comment('返佣比例') DECIMAL(6,4)"`
VirtualCurrencyRate string `json:"virtual_currency_rate" xorm:"not null comment('虚拟币比例') DECIMAL(6,4)"`
LimitPerson int `json:"limit_person" xorm:"not null comment('限制人数(默认为0则不限制)') INT(11) "`


+ 1
- 0
db/model/regional_agent_scheme.go Целия файл

@@ -13,6 +13,7 @@ type RegionalAgentScheme struct {
Label string `json:"label" xorm:"not null default '0' comment('别名,给前端使用') VARCHAR(255)"`
IsUnify int `json:"is_unify" xorm:"not null default 0 comment('是否统一佣金比例(否:0;是:1)') TINYINT(1)"`
UnifyCommissionRate string `json:"unify_commission_rate" xorm:"not null default 0.0000 comment('统一佣金比例') DECIMAL(6,4)"`
SubUnifyCommissionRate string `json:"sub_unify_commission_rate" xorm:"not null default 0.0000 comment('统一佣金比例') DECIMAL(6,4)"`
FistAutoAudit int `json:"fist_auto_audit" xorm:"not null default 1 comment('初次购买审核方式(1自动,2手动)') TINYINT(1)"`
RenewalAutoAudit int `json:"renewal_auto_audit" xorm:"not null default 0 comment('续费审核方式(1自动,2手动)') TINYINT(1)"`
IsUnifyAgentPrice int `json:"is_unify_agent_price" xorm:"default 0 comment('是否统一代理价格(1统一价格,2按区域设置不用价格)') TINYINT(1)"`


+ 25
- 0
db/model/regional_agent_sub_user.go Целия файл

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

import (
"time"
)

type RegionalAgentSubUser struct {
Id int64 `json:"id" xorm:"pk autoincr BIGINT(20)"`
SchemeId int `json:"scheme_id" xorm:"not null comment('方案id') INT(11)"`
Uid int `json:"uid" xorm:"not null comment('参与区域代理的用户id') index(mgbgu_uid_ord_id_group_id_index) INT(11)"`
RegionId int `json:"region_id" xorm:"not null comment('区域id') index(mgbgu_uid_ord_id_group_id_index) INT(11)"`
IsFailure int `json:"is_failure" xorm:"not null default 0 comment('是否已失效:0否 1是') TINYINT(1)"`
FailureTime int `json:"failure_time" xorm:"not null comment('剩下失效时间(单位:月)0代表永久') INT(11)"`
ProvinceId int64 `json:"province_id" xorm:"comment('省级区域id') BIGINT(20)"`
CityId int64 `json:"city_id" xorm:"comment('市级区域id') BIGINT(20)"`
DistrictId int64 `json:"district_id" xorm:"comment('区/县级id') BIGINT(20)"`
SiteId int64 `json:"site_id" xorm:"comment('网点id') BIGINT(20)"`
RegionalName string `json:"regional_name" xorm:"not null comment('地区名:(例如:广东省;广东省-珠海市;广东省-珠海市-香洲区;广东省-珠海市-香洲区-港湾一号)') VARCHAR(255)"`
Level int `json:"level" xorm:"not null default 0 comment('等级(1:省级;2:市级;3:区/县 级;4:网点)') TINYINT(1)"`
CreateTime time.Time `json:"create_time" xorm:"not null default 'CURRENT_TIMESTAMP' comment('创建时间') index(mgbgu_uid_ord_id_group_id_index) TIMESTAMP"`
UpdateTime time.Time `json:"update_time" xorm:"not null default 'CURRENT_TIMESTAMP' comment('更新时间') TIMESTAMP"`
DeletedTime time.Time `json:"deleted_time" xorm:"comment('删除时间') TIMESTAMP"`
DateType int `json:"date_type" xorm:"not null comment('1:包月,2:包季,3:包年,4:永久') TINYINT(1)"`
AutoRenewal int `json:"auto_renewal" xorm:"not null comment('是否自动续费0否 1是') TINYINT(1)"`
}

+ 19
- 0
db/model/regional_sub_agent_calc_system_relate.go Целия файл

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

import (
"time"
)

type RegionalSubAgentCalcSystemRelate struct {
Id int64 `json:"id" xorm:"pk autoincr BIGINT(11)"`
Uid int `json:"uid" xorm:"not null comment('用户Id') INT(11)"`
DivideAmount float64 `json:"divide_amount" xorm:"not null comment('分佣所得金额') DOUBLE"`
DivideVirtualCurrency string `json:"divide_virtual_currency" xorm:"comment('分佣所得虚拟币详情') TEXT"`
Ext string `json:"ext" xorm:"comment('额外字段') TEXT"`
Status int `json:"status" xorm:"not null default 1 comment('状态(1:未结算,2:已结算)') TINYINT(3)"`
Type int `json:"type" xorm:"not null default 1 comment('1:分佣记录 2:返佣记录') TINYINT(1)"`
BelongOrdId string `json:"belong_ord_id" xorm:"not null comment('所属订单id') VARCHAR(255)"`
Pvd string `json:"pvd" xorm:"not null comment('渠道') VARCHAR(255)"`
CreatedAt time.Time `json:"created_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('创建时间') TIMESTAMP"`
UpdatedAt time.Time `json:"updated_at" xorm:"default 'CURRENT_TIMESTAMP' comment('更新时间') TIMESTAMP"`
}

+ 23
- 0
db/model/regional_sub_agent_ord_belong.go Целия файл

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

import (
"time"
)

type RegionalSubAgentOrdBelong struct {
Id int64 `json:"id" xorm:"pk autoincr BIGINT(20)"`
Uid int `json:"uid" xorm:"not null comment('用户id') index(mgbgu_uid_ord_id_group_id_index) INT(11)"`
Pvd string `json:"pvd" xorm:"not null comment('渠道:自营,导购,o2o。。。。') VARCHAR(255)"`
OrderId int64 `json:"order_id" xorm:"not null comment('订单id') BIGINT(20)"`
CurrencyType int `json:"currency_type" xorm:"not null default 1 comment('币种类型:(1:佣金,2:积分,3:区块币,4:...)') INT(3)"`
Commission string `json:"commission" xorm:"not null comment('订单区域代理总佣金') DECIMAL(12,4)"`
RegionId int `json:"region_id" xorm:"not null comment('区域id') INT(11)"`
RegionalName string `json:"regional_name" xorm:"not null comment('地区名:(例如:广东省;广东省-珠海市;广东省-珠海市-香洲区;广东省-珠海市-香洲区-港湾一号)') VARCHAR(255)"`
ProvinceId int64 `json:"province_id" xorm:"comment('省级区域id') BIGINT(20)"`
CityId int64 `json:"city_id" xorm:"comment('市级区域id') BIGINT(20)"`
DistrictId int64 `json:"district_id" xorm:"comment('区/县级id') BIGINT(20)"`
SiteId int64 `json:"site_id" xorm:"comment('网点id') BIGINT(20)"`
CreateTime time.Time `json:"create_time" xorm:"not null default 'CURRENT_TIMESTAMP' comment('创建时间') index(mgbgu_uid_ord_id_group_id_index) TIMESTAMP"`
UpdateTime time.Time `json:"update_time" xorm:"not null default 'CURRENT_TIMESTAMP' comment('更新时间') TIMESTAMP"`
Level int `json:"level" xorm:"not null default 0 comment('等级(1:省级;2:市级;3:区/县 级;4:网点)') TINYINT(1)"`
}

+ 1
- 0
db/model/user.go Целия файл

@@ -26,4 +26,5 @@ type User struct {
SalePhone string `json:"sale_phone" xorm:"not null default '' comment('') VARCHAR(100)"`
IsFake int `json:"is_fake" xorm:"not null default 0 comment('0真实 1虚拟') TINYINT(1)"`
IsMarketer int `json:"is_marketer" xorm:"not null default 0 comment('是否市商 0否 1是') TINYINT(1)"`
LvWhite int `json:"lv_white" xorm:"not null default 0 comment('是否市商 0否 1是') INT(1)"`
}

+ 2
- 0
lib/comm_plan/all.go Целия файл

@@ -726,6 +726,8 @@ func getVirtualCoinRatio(typ string, level, peerNum int, grade map[int]*LvGrade,
ratio = zhios_order_relate_utils.Float64ToStrByPrec(zhios_order_relate_utils.StrToFloat64(ratio)/100, 4)
case "same_lv":
ratio, ok = grade[level].PeerRateList[peerNum][coinId]
case "same_extend":
ratio, ok = grade[level].SameExtend[peerNum][coinId]
default:
ratio, ok = grade[level].SelfRateList[coinId]
}


+ 246
- 0
lib/comm_plan/ds_check.go Целия файл

@@ -0,0 +1,246 @@
package comm_plan

import (
"code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/db"
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"
"fmt"
"xorm.io/xorm"
)

func CalReturnAmountAndRatioDs(level, ownbuyReturnType, peerNum int, userType string, fee, integralFee float64, opt *PlanOpt) (commission, commissionRatio float64, amountList, ratioList []*VirtualCoinCommission) {
var maxReturnTypeCount = 0
var returnType = make([]string, 0)
for _, v := range opt.UserRate {
if v.ReturnType != nil {
if len(v.ReturnType) > maxReturnTypeCount {
maxReturnTypeCount = len(v.ReturnType)
returnType = v.ReturnType
}
}
}
// 新版支持多种虚拟币 支持的种类id保存在ReturnType id=0代表现金佣金 其他为虚拟币
if returnType != nil { //返佣类型
for _, coinId := range returnType {
newFee := integralFee
if coinId == "0" {
newFee = fee
}
ratio := getVirtualCoinRatio(userType, level, peerNum, opt.UserRate, coinId, 0)
amount := getCoinAmount(ratio, zhios_order_relate_utils.StrToInt(coinId), newFee, opt.VirtualCoinMoneyRatioList)
if coinId == "0" { //
commission = amount
continue
}
amountList = append(amountList, &VirtualCoinCommission{
Cid: coinId,
Val: amount,
})
ratioList = append(ratioList, &VirtualCoinCommission{
Cid: coinId,
Val: zhios_order_relate_utils.AnyToFloat64(ratio),
})
}
}

if ownbuyReturnType == 1 { //自购不返利
commission = 0
for i := range amountList {
amountList[i].Val = 0
}
}
commission = zhios_order_relate_utils.FloatFormat(commission, 2)

for i, coin := range amountList {
amountList[i].Val = zhios_order_relate_utils.FloatFormat(coin.Val, 6)
}

return commission, commissionRatio, amountList, ratioList
}
func CalReturnAmountAndRatioDsSecond(level, ownbuyReturnType, peerNum int, userType string, opt *PlanOpt, node *LvUser) (commission, commissionRatio float64, amountList, ratioList []*VirtualCoinCommission) {
var maxReturnTypeCount = 0
var returnType = make([]string, 0)
for _, v := range opt.UserRate {
if v.ReturnType != nil {
if len(v.ReturnType) > maxReturnTypeCount {
maxReturnTypeCount = len(v.ReturnType)
returnType = v.ReturnType
}
}
}
// 新版支持多种虚拟币 支持的种类id保存在ReturnType id=0代表现金佣金 其他为虚拟币
if returnType != nil { //返佣类型
ratioListMap := convertList2Map(node.ProfitList)
for _, coinId := range returnType {
newFee := ratioListMap[coinId]
if coinId == "0" {
newFee = node.Profit
}
ratio := getVirtualCoinRatio(userType, level, peerNum, opt.UserRate, coinId, 0)
amount := getCoinAmount(ratio, zhios_order_relate_utils.StrToInt(coinId), newFee, opt.VirtualCoinMoneyRatioList)
if coinId == "0" { //
commission = amount
continue
}
amountList = append(amountList, &VirtualCoinCommission{
Cid: coinId,
Val: amount,
})
ratioList = append(ratioList, &VirtualCoinCommission{
Cid: coinId,
Val: zhios_order_relate_utils.AnyToFloat64(ratio),
})
}
}

if ownbuyReturnType == 1 { //自购不返利
commission = 0
for i := range amountList {
amountList[i].Val = 0
}
}
commission = zhios_order_relate_utils.FloatFormat(commission, 2)

for i, coin := range amountList {
amountList[i].Val = zhios_order_relate_utils.FloatFormat(coin.Val, 6)
}

return commission, commissionRatio, amountList, ratioList
}

// 按总佣金的比例进行划分计算
func CalcDsCheck(opt *PlanOpt, totalAmt, integralTotalAmt float64, userList *LvUser, pvd string, sysFee float64, integralSysFee float64, level, levelWeight int, eg *xorm.Engine) error {
grade := opt.UserRate
if len(grade) == 0 {
return zhios_order_relate_logx.Warn("level grade is not set")
}

//查出用户自购佣金
commission, commissionRatio, amountList, ratioList := CalReturnAmountAndRatio(userList.Lv, userList.OwnbuyReturnType, 0, "own", totalAmt, integralTotalAmt, opt)
userList.Profit = commission // 另外出来的佣金 兼容旧的
userList.ProfitList = amountList // 各币种分佣
userList.SubsidyFee = 0
ratioListMap := convertList2Map(ratioList)

for k, v := range userList.ProfitList {
userList.ProfitList[k].Val = ratioListMap[v.Cid] * v.Val
}
// 各种币换算出总的额度
totalAmtList := make([]*VirtualCoinCommission, 0)
for coinId, rate := range opt.VirtualCoinMoneyRatioList {
var amount float64
if coinId == 0 {
amount = totalAmt
} else {
amount = integralTotalAmt * zhios_order_relate_utils.AnyToFloat64(rate)
}
totalAmtList = append(totalAmtList, &VirtualCoinCommission{
Cid: zhios_order_relate_utils.AnyToString(coinId),
Val: amount,
})
}

var (
node = userList
maxLv = node.Lv // 当前等级
maxLevelWeight = node.LevelWeight // 当前权重
peerNum = 0 // 存在同级数
peerRate float64 = 0 // 同级累计比例
peerRateList = make([]*VirtualCoinCommission, 0) // 各虚拟币同级累计
restAmtList = make([]*VirtualCoinCommission, 0) // 各虚拟币剩余额度
accumulateRatioList = make([]*VirtualCoinCommission, 0) // 各虚拟币累计比例
restAmt = totalAmt - userList.Profit // 剩余比例
totalCommissionRatio = commissionRatio // 累计佣金比例
)
// 计算剩余额度
restAmtList, _ = CalVirtualCommissionMinus(totalAmtList, amountList)
// 累计比例
accumulateRatioList = ratioList
restAmt = zhios_order_relate_utils.FloatFormat(restAmt, 2)

Loop:
for node.ParentUser != nil { //查找上级用户
node.ParentUser.Profit = 0
// 如果父级比当前级别低, 跳过
// 同级奖, 如果父级别与当前级别一致,并且设置了对应比例
count := 1
var isBreak bool
zeroList := make(map[string]struct{})
isOnlySubsidyFee := 0
// 同级奖
if node.ParentUser.LevelWeight == maxLevelWeight && count > peerNum {
//如果设置了直推奖励 就拿前一个用户的佣金
//同级奖励比例 需要满足直推 X个以上同等级用户
if len(opt.UserRate[maxLv].SameUserCount) > peerNum {
userCount := opt.UserRate[maxLv].SameUserCount[peerNum]
sql := `SELECT COUNT(*) as count FROM user_profile up
LEFT JOIN user u on u.uid=up.uid
WHERE up.parent_uid=? and u.level=?;
`
nativeString, _ := db.QueryNativeString(eg, sql, node.ParentUser.Uid, maxLv)
if len(nativeString) > 0 && zhios_order_relate_utils.StrToInt(nativeString[0]["count"]) >= zhios_order_relate_utils.StrToInt(userCount) {
commission, _, amountList, _ := CalReturnAmountAndRatioDs(maxLv, userList.OwnbuyReturnType, peerNum, "same_lv", totalAmt, integralTotalAmt, opt)
//佣金 (lv, isOnlySubsidy int, restAmt, profit, peerRate, totalRatio, restRatio, subsidyFee, subsidyBili float64, opt *PlanOpt)
node.ParentUser.Profit = commission
node.ParentUser.ProfitList = amountList
}
}
userData, _ := db.UserFindByID(eg, node.Uid)
if userData.LvWhite != 1 { //不在白名单就要分
commission, _, amountList, _ := CalReturnAmountAndRatioDsSecond(maxLv, userList.OwnbuyReturnType, peerNum, "same_extend", opt, node)
if commission > 0 {
node.Profit = node.Profit - commission
node.ParentUser.Profit = node.ParentUser.Profit + commission
}
ratioListMap := convertList2Map(amountList)
ratioParentListMap := convertList2Map(node.ParentUser.ProfitList)
for k, v := range node.ProfitList { //被推荐人的 扣掉返给推荐人的
integralAmount := ratioListMap[v.Cid]
if integralAmount <= 0 {
continue
}
node.ProfitList[k].Val = node.ProfitList[k].Val - integralAmount
}
if len(amountList) > 0 {
for k, v := range amountList {
integralAmount := ratioParentListMap[v.Cid]
amountList[k].Val = amountList[k].Val + integralAmount
}
node.ParentUser.ProfitList = amountList
}
}

// 全部都没得分了
if isBreak && len(zeroList) == len(opt.UserRate[maxLv].ReturnType) {
break Loop
}
peerNum++
} else if node.ParentUser.LevelWeight > maxLevelWeight {
if _, ok := grade[node.Lv]; !ok {
return zhios_order_relate_logx.Warn("level grade node.Lv is not set")
}
if _, ok := grade[node.ParentUser.Lv]; !ok {
return zhios_order_relate_logx.Warn("level grade node.ParentUser.Lv is not set")
}
commission, _, amountList, teamRatioList := CalReturnAmountAndRatio(node.ParentUser.Lv, userList.OwnbuyReturnType, peerNum, "team", totalAmt, integralTotalAmt, opt)
//佣金
node.ParentUser.Profit = commission
node.ParentUser.Profit, restAmt, totalCommissionRatio, node.ParentUser.SubsidyFee, isBreak = teamDiffMoney(node.ParentUser.Profit, grade[node.Lv].PayMode, isOnlySubsidyFee, totalAmt, restAmt, grade[node.ParentUser.Lv].TeamRate, totalCommissionRatio, peerRate, node.ParentUser.SubsidyFee, 0)
//积分
node.ParentUser.ProfitList = amountList
// profitList []*VirtualCoinCommission, payMode, isOnlySubsidy int, totalAmtList, restAmtList, teamRatioList, totalRatioList, peerRateList, subsidyFeeList, subsidyRatioList []*VirtualCoinCommission
node.ParentUser.ProfitList, restAmtList, accumulateRatioList, node.ParentUser.SubsidyFeeList, zeroList = teamDiffMoneyV2(node.ParentUser.ProfitList, grade[node.Lv].PayMode, isOnlySubsidyFee, totalAmtList, restAmtList, teamRatioList, accumulateRatioList, peerRateList, []*VirtualCoinCommission{}, []*VirtualCoinCommission{})

// 没得分了 就结束
if isBreak && len(zeroList) == len(opt.UserRate[maxLv].ReturnType) {
break Loop
}
// 等级往上升则置0
maxLevelWeight, maxLv, peerRate, peerRateList, peerNum = node.ParentUser.LevelWeight, node.ParentUser.Lv, 0, nil, 0
}
node.Profit = zhios_order_relate_utils.StrToFloat64(fmt.Sprintf("%.4f", node.Profit))
node = node.ParentUser
}

return nil
}

+ 4
- 1
lib/comm_plan/init.go Целия файл

@@ -11,6 +11,7 @@ var Fn = map[string]func(opt *PlanOpt, totalAmt, integralTotalAmt float64, userL
"lv_price": CalcAll,
"lv_winery": CalcWinery,
"lv_price_other": CalcOther,
"lv_ds_check": CalcDsCheck,
}

type NiuBeiIntegralReleaseO2oRatio struct {
@@ -65,7 +66,9 @@ type LvGrade struct {
NewTeamList map[string]string `json:"new_team_list"` // 新团队比例
NewExtendList map[string]string `json:"new_extend_list"` // 直推比例
SecondExtendList map[string]string `json:"second_extend_list"` // 直推比例
SubsidyModeList map[string]interface{} `json:"subsidy_mode_list"` // 各币种返佣模式:bili:比例 money:固定金额
SameUserCount []string `json:"same_user_count"`
SameExtend []map[string]string `json:"same_extend"`
SubsidyModeList map[string]interface{} `json:"subsidy_mode_list"` // 各币种返佣模式:bili:比例 money:固定金额
//SubsidyBlockIconsMode string `json:"subsidy_block_icons_mode"` //分销 区块币返利类型 bili 比例 money 固定金额
//SubsidyCommissionMode string `json:"subsidy_commission_mode"` //分销 佣金返利类型 bili 比例 money 固定金额
//SubsidyIntegralMode string `json:"subsidy_integral_mode"` //分销 积分返利类型 bili 比例 money 固定金额


+ 321
- 0
rule/regional_sub_agent.go Целия файл

@@ -0,0 +1,321 @@
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"
zhios_order_relate_utils "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/utils"
"encoding/json"
"fmt"
"time"
"xorm.io/xorm"
)

func BindUserOrdToSubAgent(eg *xorm.Engine, dbName string, data *md.InsertRegionalAgentOrdBelongData) {
CommRegionalSubAgentInsert(eg, data)
}

//公共调用
func CommRegionalSubAgentInsert(engine *xorm.Engine, args *md.InsertRegionalAgentOrdBelongData) int {
res, userBelong := InsertRegionalSubAgentOrdBelong(engine, args)
if !res {
return 0
}
//todo::调用 “计算制度” 方法
_, res = HandleSubCommissionDistributionSystem(engine, &md.RegionalAgentSystemArgs{
Uid: zhios_order_relate_utils.AnyToString(args.Uid),
Amount: args.Commission,
OrdId: zhios_order_relate_utils.AnyToString(args.OrderId),
Pvd: args.Pvd,
CommPvd: args.CommPvd,
Status: args.Status,
Type: "2",
RegionId: zhios_order_relate_utils.AnyToString(userBelong.RegionId),
})
if !res {
return 2
}
return 1
}

func HandleSubCommissionDistributionSystem(engine *xorm.Engine, args *md.RegionalAgentSystemArgs) ([]map[string]interface{}, bool) {
amount := zhios_order_relate_utils.AnyToFloat64(args.Amount)
var regionId string
if args.Type == "1" {
//获取当前用户的 归属
userBelong, err := db.GetCountByRegionalAgentUserBelongById(engine, args.Uid, args.Pvd, args.CommPvd)
fmt.Println(err)
fmt.Println(userBelong)
if err != nil || userBelong == nil {
return nil, false
}
regionId = zhios_order_relate_utils.AnyToString(userBelong.RegionId)
} else {
regionId = args.RegionId
}

//查询用户所属 “代理网点” 信息
regionalAgentRegion, err := db.RegionalAgentRegionGetOneByParams(engine, map[string]interface{}{
"key": "id",
"value": zhios_order_relate_utils.AnyToInt64(regionId),
})
if err != nil {
return nil, false
}
if regionalAgentRegion == nil {
return nil, true
}
//查询 regional_agent_base 表获取虚拟币相关配置信息
agentBase, err := db.GetCountByRegionalAgentBase(engine)
if err != nil {
return nil, false
}
var coinSet = md.CoinSet{}
err = json.Unmarshal([]byte(agentBase.CoinSet), &coinSet)
if err != nil {
return nil, false
}

//查询 virtual_coin 获取虚拟货币的 “兑换比例”
virtualCoin, err := db.VirtualCoinFindByParams(engine, map[string]interface{}{})
if err != nil {
return nil, false
}
var virtualCoinMap = map[int]string{}
for _, v := range *virtualCoin {
virtualCoinMap[v.Id] = v.ExchangeRatio
}
//查询代理网点的代理(网点、区、市、省)信息
var parents, tempParents []map[string]interface{}
//tempParents, amount, _, err = makeSubSystemData(engine, regionalAgentRegion, &coinSet, virtualCoinMap, parents, amount, md.SITE)
//if err != nil {
// return nil, false
//}
//if tempParents != nil {
// parents = tempParents
//}
//
//tempParents, amount, _, err = makeSubSystemData(engine, regionalAgentRegion, &coinSet, virtualCoinMap, parents, amount, md.COUNTRY)
//if err != nil {
// return nil, false
//}
//if tempParents != nil {
// parents = tempParents
//}

tempParents, amount, _, err = makeSubSystemData(engine, args, regionalAgentRegion, &coinSet, virtualCoinMap, parents, amount, md.CITY)
if err != nil {
return nil, false
}
if tempParents != nil {
parents = tempParents
}

//tempParents, amount, _, err = makeSubSystemData(engine, regionalAgentRegion, &coinSet, virtualCoinMap, parents, amount, md.PROVINCE)
//if err != nil {
// return nil, false
//}
//if tempParents != nil {
// parents = tempParents
//}

fmt.Println("区域代理")
fmt.Println(parents)

for _, v := range parents {
var divideVirtualCurrency = ""
if !zhios_order_relate_utils.IsNil(v["divide_virtual_currency"]) {
jsonStr, err := json.Marshal(v["divide_virtual_currency"])
if err != nil {
fmt.Println("虚拟币查询")
fmt.Println(err)
return nil, false
}
divideVirtualCurrency = string(jsonStr)
}
status := 1
if args.Status == "0" { //导购的一开始不用返的 导购结算才返
status = 0
}
var insertData = model.RegionalSubAgentCalcSystemRelate{
Uid: v["uid"].(int),
DivideAmount: zhios_order_relate_utils.AnyToFloat64(v["divide_amount"]),
DivideVirtualCurrency: divideVirtualCurrency,
BelongOrdId: args.OrdId,
Pvd: args.Pvd,
Status: status,
Type: zhios_order_relate_utils.StrToInt(args.Type),
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
_, err := db.RegionalSubAgentCalcSystemRelateInsert(engine, &insertData)
if err != nil {
return nil, false
}
}
return parents, true
}

func makeSubSystemData(engine *xorm.Engine, args *md.RegionalAgentSystemArgs, regionalAgentRegion *model.RegionalAgentRegion, coinSet *md.CoinSet, virtualCoin map[int]string, parents []map[string]interface{}, amount float64, level string) ([]map[string]interface{}, float64, float64, error) {
var value string
coinSetDetail := coinSet.SiteAgent
if regionalAgentRegion.Level == md.CityKey {
switch level {
case md.PROVINCE:
value = zhios_order_relate_utils.AnyToString(regionalAgentRegion.ProvinceId)
break
case md.CITY:
value = zhios_order_relate_utils.AnyToString(regionalAgentRegion.Id)
break
case md.COUNTRY:
value = zhios_order_relate_utils.AnyToString(0)
break
case md.SITE:
value = zhios_order_relate_utils.AnyToString(0)
break
}
//获得虚拟币的比例
coinSetDetail = coinSet.CityAgent
}
fmt.Println("地区ID:", value)
fmt.Println("余额:", amount)
if value == "0" {
return nil, amount, 0, nil
}

//查询代理地区
regionalAgentRegionData, err := db.RegionalAgentRegionGetOneByParams(engine, map[string]interface{}{
"key": "id",
"value": value,
})
//查询代理地区用户
agentUser, err := db.RegionalSubAgentUserFindByValid(engine, value)
if err != nil {
return nil, amount, 0, err
}
var divideAmount float64 = 0
//查询对应的等级方案
scheme, err := db.GetCountByRegionalAgentSchemeInfoByParams(engine, map[string]interface{}{
"key": "agent_type",
"value": regionalAgentRegionData.Level,
})
if scheme == nil || err != nil {
return nil, amount, 0, err
}
var commissionRate string
if scheme.IsUnify == 1 {
commissionRate = regionalAgentRegionData.SubCommissionRate
} else {
commissionRate = scheme.SubUnifyCommissionRate
}
parentUser, _ := db.UserProfileFindByID(engine, args.Uid)
parentUid := 0
if parentUser != nil {
parentUid = parentUser.Uid
}
parents, amount, divideAmount, err = SubCommAmount(parentUid, zhios_order_relate_utils.AnyToFloat64(commissionRate), amount, agentUser, coinSetDetail, virtualCoin, parents, false)
if err != nil {
return nil, amount, 0, err
}
return parents, amount, divideAmount, nil

}

//公共处理佣金
func SubCommAmount(parentUid int, CommissionRate float64, amount float64, agentUser *[]model.RegionalAgentSubUser, coinSetDetail []md.CoinSetDetail, virtualCoin map[int]string, parents []map[string]interface{}, isTest bool) ([]map[string]interface{}, float64, float64, error) {

var divideAmount float64 = 0
if amount == 0 {
for _, v := range *agentUser {
var temp = map[string]interface{}{}
temp["uid"] = v.Uid
temp["divide"] = 0
parents = append(parents, temp)
}
} else {
isParent := 0
for _, v := range *agentUser {
if v.Uid == parentUid {
isParent = 1
}
}
rate := CommissionRate / 100
fmt.Println("比例:", rate)
divideAmount = rate * amount
personNum := len(*agentUser)
if isParent == 1 {
personNum = 1
}
fmt.Println("人数:", personNum)
if personNum == 0 && isTest == false {
return nil, amount, divideAmount, nil
}
everyPersonDivideAmount := divideAmount / zhios_order_relate_utils.AnyToFloat64(personNum)
for _, v := range *agentUser {
if v.Uid != parentUid && isParent == 1 {
continue
}
var temp = map[string]interface{}{}
temp["uid"] = v.Uid
if amount == 0 {
temp["divide_amount"] = 0
} else {
temp["divide_amount"] = everyPersonDivideAmount
var coinSetDetailMap []map[string]interface{}
for _, v := range coinSetDetail {
var exchangeRatio float64
if zhios_order_relate_utils.AnyToFloat64(virtualCoin[v.CoinID]) != 0 {
exchangeRatio = zhios_order_relate_utils.AnyToFloat64(virtualCoin[v.CoinID])
} else {
exchangeRatio = 0
}
coinSetDetailMap = append(coinSetDetailMap, map[string]interface{}{
"coin_id": v.CoinID,
"coin_name": v.CoinName,
"divide_value": zhios_order_relate_utils.AnyToFloat64(temp["divide_amount"]) * (zhios_order_relate_utils.AnyToFloat64(v.Value) / 100) * exchangeRatio,
})
}
temp["divide_virtual_currency"] = coinSetDetailMap
}
parents = append(parents, temp)
}
if amount-divideAmount <= 0 {
amount = 0
} else {
amount = amount - divideAmount
}
}
return parents, amount, divideAmount, nil
}

//InsertRegionalAgentOrdBelong 插入 regional_agent_ord_belong (用户订单归属表) 数据
func InsertRegionalSubAgentOrdBelong(engine *xorm.Engine, data *md.InsertRegionalAgentOrdBelongData) (bool, *model.RegionalAgentUserBelong) {
// 查询 regional_agent_user_belong 得到用户归属的区域代理
userBelong, err := db.GetCountByRegionalAgentUserBelongById(engine, data.Uid, data.Pvd, data.CommPvd)

if err != nil || userBelong == nil {
return false, nil
}
date := time.Now()
_, err = db.RegionalSubAgentOrdBelongInsert(engine, &model.RegionalSubAgentOrdBelong{
Uid: int(zhios_order_relate_utils.AnyToInt64(data.Uid)),
Pvd: data.Pvd,
OrderId: data.OrderId,
CurrencyType: 1,
Commission: data.Commission,
RegionId: userBelong.RegionId,
RegionalName: userBelong.RegionalName,
ProvinceId: userBelong.ProvinceId,
CityId: userBelong.CityId,
DistrictId: userBelong.DistrictId,
SiteId: userBelong.SiteId,
CreateTime: date,
UpdateTime: date,
Level: userBelong.Level,
})
if err != nil {
return false, nil
}

return true, userBelong
}

Зареждане…
Отказ
Запис