From f3b93cc126bd0b9c58313a69c04b1ea0d14d67ab Mon Sep 17 00:00:00 2001 From: huangjiajun <582604932@qq.com> Date: Tue, 9 Jul 2024 15:25:38 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/db/db_fin_user_flow.go | 15 + app/db/db_guide_order_month_total.go | 15 + app/db/db_withdraw_month_total.go | 15 + app/db/model/guide_order_month_total.go | 15 + app/db/model/ord_list.go | 1 + app/db/model/withdraw_month_total.go | 15 + ...canal_fin_withdraw_apply_for_statistics.go | 109 +++ ...canal_guide_order_by_user_up_lv_consume.go | 83 --- consume/canal_guide_order_consume.go | 234 ------ consume/canal_guide_order_for_statistics.go | 140 ++++ consume/canal_mall_ord_for_you_mi_shang.go | 123 ---- consume/canal_order_consume.go | 221 ------ .../canal_user_virtual_coin_flow_consume.go | 130 ---- consume/cloud_issuance_async_mlogin.go | 125 ---- consume/cloud_issuance_msg_callback.go | 72 -- consume/consume.go | 77 -- .../dou_shen_user_register_for_my_my_fans.go | 146 ---- ...hen_user_register_for_my_my_recommender.go | 207 ------ ...shen_user_register_for_official_consume.go | 194 ----- ...shen_user_register_for_operation_center.go | 289 -------- ...n_user_register_for_user_register_up_lv.go | 68 -- consume/init.go | 86 +-- consume/mall_add_supply_goods.go | 91 --- consume/md/consume_key.go | 565 +-------------- .../md/md_canal_fin_withdraw_apply_consume.go | 22 + consume/md/md_canal_guide_order_consume.go | 5 + ...coin_auto_exchange_green_energy_consume.go | 159 ---- ..._exchange_green_energy_for_team_consume.go | 160 ----- ...settlement_public_activity_coin_consume.go | 100 --- consume/one_circles_sign_in_consume.go | 66 -- consume/one_circles_sign_in_copy_consume.go | 66 -- ...ne_circles_start_level_dividend_consume.go | 97 --- consume/super_cloud_issuance_async_mlogin.go | 125 ---- consume/super_cloud_issuance_msg_callback.go | 72 -- .../supply_cloud_chain_fenxiao_new_change.go | 227 ------ consume/withdraw_consume.go | 100 --- consume/withdraw_consume_gongmao.go | 165 ----- consume/withdraw_consume_pupiao.go | 185 ----- consume/zhios_acquisition_condition.go | 679 ------------------ consume/zhios_acquisition_condition_dev.go | 59 -- consume/zhios_appreciation.go | 326 --------- consume/zhios_capital_pool_order_total.go | 168 ----- consume/zhios_express_order_fail.go | 263 ------- consume/zhios_fast_return_order_pay.go | 217 ------ consume/zhios_fast_return_order_refund.go | 168 ----- .../zhios_fast_return_order_refund_second.go | 163 ----- consume/zhios_fast_return_order_success.go | 100 --- consume/zhios_guide_store_order_success.go | 315 -------- ...installment_payment_auto_repaid_consume.go | 67 -- consume/zhios_integral_proxy_recharge.go | 138 ---- consume/zhios_mall_green_coin_consume.go | 90 --- consume/zhios_one_circles_coin_consume.go | 120 ---- consume/zhios_order_buckle.go | 646 ----------------- consume/zhios_order_free.go | 623 ---------------- consume/zhios_order_hjy.go | 373 ---------- consume/zhios_order_settle_total.go | 190 ----- consume/zhios_order_total.go | 166 ----- consume/zhios_order_total_second.go | 313 -------- consume/zhios_recharge_order_fail.go | 258 ------- consume/zhios_recharge_order_fail_dev.go | 154 ---- consume/zhios_supplier_after_order.go | 214 ------ consume/zhios_task_total.go | 102 --- consume/zhios_tikTok_goods_update.go | 160 ----- consume/zhios_user_relate.go | 160 ----- consume/zhios_user_up_lv.go | 86 --- .../zhios_user_visit_ip_address_consume.go | 172 ----- consume/zhios_valid_user.go | 187 ----- consume/zhios_withdraw_reward.go | 144 ---- consume/zhios_youmishang_exchange_store.go | 75 -- 69 files changed, 362 insertions(+), 11119 deletions(-) create mode 100644 app/db/db_fin_user_flow.go create mode 100644 app/db/db_guide_order_month_total.go create mode 100644 app/db/db_withdraw_month_total.go create mode 100644 app/db/model/guide_order_month_total.go create mode 100644 app/db/model/withdraw_month_total.go create mode 100644 consume/canal_fin_withdraw_apply_for_statistics.go delete mode 100644 consume/canal_guide_order_by_user_up_lv_consume.go delete mode 100644 consume/canal_guide_order_consume.go create mode 100644 consume/canal_guide_order_for_statistics.go delete mode 100644 consume/canal_mall_ord_for_you_mi_shang.go delete mode 100644 consume/canal_order_consume.go delete mode 100644 consume/canal_user_virtual_coin_flow_consume.go delete mode 100644 consume/cloud_issuance_async_mlogin.go delete mode 100644 consume/cloud_issuance_msg_callback.go delete mode 100644 consume/consume.go delete mode 100644 consume/dou_shen_user_register_for_my_my_fans.go delete mode 100644 consume/dou_shen_user_register_for_my_my_recommender.go delete mode 100644 consume/dou_shen_user_register_for_official_consume.go delete mode 100644 consume/dou_shen_user_register_for_operation_center.go delete mode 100644 consume/dou_shen_user_register_for_user_register_up_lv.go delete mode 100644 consume/mall_add_supply_goods.go create mode 100644 consume/md/md_canal_fin_withdraw_apply_consume.go delete mode 100644 consume/one_circles_activity_coin_auto_exchange_green_energy_consume.go delete mode 100644 consume/one_circles_activity_coin_auto_exchange_green_energy_for_team_consume.go delete mode 100644 consume/one_circles_settlement_public_activity_coin_consume.go delete mode 100644 consume/one_circles_sign_in_consume.go delete mode 100644 consume/one_circles_sign_in_copy_consume.go delete mode 100644 consume/one_circles_start_level_dividend_consume.go delete mode 100644 consume/super_cloud_issuance_async_mlogin.go delete mode 100644 consume/super_cloud_issuance_msg_callback.go delete mode 100644 consume/supply_cloud_chain_fenxiao_new_change.go delete mode 100644 consume/withdraw_consume.go delete mode 100644 consume/withdraw_consume_gongmao.go delete mode 100644 consume/withdraw_consume_pupiao.go delete mode 100644 consume/zhios_acquisition_condition.go delete mode 100644 consume/zhios_acquisition_condition_dev.go delete mode 100644 consume/zhios_appreciation.go delete mode 100644 consume/zhios_capital_pool_order_total.go delete mode 100644 consume/zhios_express_order_fail.go delete mode 100644 consume/zhios_fast_return_order_pay.go delete mode 100644 consume/zhios_fast_return_order_refund.go delete mode 100644 consume/zhios_fast_return_order_refund_second.go delete mode 100644 consume/zhios_fast_return_order_success.go delete mode 100644 consume/zhios_guide_store_order_success.go delete mode 100644 consume/zhios_installment_payment_auto_repaid_consume.go delete mode 100644 consume/zhios_integral_proxy_recharge.go delete mode 100644 consume/zhios_mall_green_coin_consume.go delete mode 100644 consume/zhios_one_circles_coin_consume.go delete mode 100644 consume/zhios_order_buckle.go delete mode 100644 consume/zhios_order_free.go delete mode 100644 consume/zhios_order_hjy.go delete mode 100644 consume/zhios_order_settle_total.go delete mode 100644 consume/zhios_order_total.go delete mode 100644 consume/zhios_order_total_second.go delete mode 100644 consume/zhios_recharge_order_fail.go delete mode 100644 consume/zhios_recharge_order_fail_dev.go delete mode 100644 consume/zhios_supplier_after_order.go delete mode 100644 consume/zhios_task_total.go delete mode 100644 consume/zhios_tikTok_goods_update.go delete mode 100644 consume/zhios_user_relate.go delete mode 100644 consume/zhios_user_up_lv.go delete mode 100644 consume/zhios_user_visit_ip_address_consume.go delete mode 100644 consume/zhios_valid_user.go delete mode 100644 consume/zhios_withdraw_reward.go delete mode 100644 consume/zhios_youmishang_exchange_store.go diff --git a/app/db/db_fin_user_flow.go b/app/db/db_fin_user_flow.go new file mode 100644 index 0000000..15785f9 --- /dev/null +++ b/app/db/db_fin_user_flow.go @@ -0,0 +1,15 @@ +package db + +import ( + "applet/app/db/model" + "xorm.io/xorm" +) + +func GetFinUserFlow(sess *xorm.Session, id string) *model.FinUserFlow { + var data model.FinUserFlow + get, err := sess.Where("id=?", id).Get(&data) + if get == false || err != nil { + return nil + } + return &data +} diff --git a/app/db/db_guide_order_month_total.go b/app/db/db_guide_order_month_total.go new file mode 100644 index 0000000..3f6c321 --- /dev/null +++ b/app/db/db_guide_order_month_total.go @@ -0,0 +1,15 @@ +package db + +import ( + "applet/app/db/model" + "xorm.io/xorm" +) + +func GetGuideOrderMonthTotal(sess *xorm.Session, month, unionType string) *model.GuideOrderMonthTotal { + var data model.GuideOrderMonthTotal + get, err := sess.Where("month=? and union_type=?", month, unionType).Get(&data) + if get == false || err != nil { + return nil + } + return &data +} diff --git a/app/db/db_withdraw_month_total.go b/app/db/db_withdraw_month_total.go new file mode 100644 index 0000000..af1299c --- /dev/null +++ b/app/db/db_withdraw_month_total.go @@ -0,0 +1,15 @@ +package db + +import ( + "applet/app/db/model" + "xorm.io/xorm" +) + +func GetWithdrawMonthTotal(sess *xorm.Session, month string) *model.WithdrawMonthTotal { + var data model.WithdrawMonthTotal + get, err := sess.Where("month=? ", month).Get(&data) + if get == false || err != nil { + return nil + } + return &data +} diff --git a/app/db/model/guide_order_month_total.go b/app/db/model/guide_order_month_total.go new file mode 100644 index 0000000..e6cc732 --- /dev/null +++ b/app/db/model/guide_order_month_total.go @@ -0,0 +1,15 @@ +package model + +import ( + "time" +) + +type GuideOrderMonthTotal struct { + Id int `json:"id" xorm:"not null pk autoincr INT(11)"` + Month int `json:"month" xorm:"default 0 comment('202407') INT(11)"` + UnionSettleAmount string `json:"union_settle_amount" xorm:"default 0.00 comment('联盟结算') DECIMAL(20,2)"` + StationSettleAmount string `json:"station_settle_amount" xorm:"default 0.000000 comment('平台结算') DECIMAL(20,6)"` + UnionType string `json:"union_type" xorm:"default 0.000000 comment('平台结算') VARCHAR(255)"` + CreateAt time.Time `json:"create_at" xorm:"DATETIME"` + UpdateAt time.Time `json:"update_at" xorm:"DATETIME"` +} diff --git a/app/db/model/ord_list.go b/app/db/model/ord_list.go index d130225..5e3c7d9 100644 --- a/app/db/model/ord_list.go +++ b/app/db/model/ord_list.go @@ -60,4 +60,5 @@ type OrdList struct { OrderFormType int `xorm:"not null default 0 INT(1)" json:"order_form_type"` HjyOid int `xorm:"not null default 0 INT(11)" json:"hjy_oid"` TikTokTeamRealCommission string `json:"tik_tok_team_real_commission" xorm:"not null default 0.00 comment('') DECIMAL(20,8)"` + Ext string `json:"ext" xorm:"not null default 0.00 comment('') varchar(255)"` } diff --git a/app/db/model/withdraw_month_total.go b/app/db/model/withdraw_month_total.go new file mode 100644 index 0000000..ff80e2c --- /dev/null +++ b/app/db/model/withdraw_month_total.go @@ -0,0 +1,15 @@ +package model + +import ( + "time" +) + +type WithdrawMonthTotal struct { + Id int `json:"id" xorm:"not null pk autoincr INT(11)"` + Month int `json:"month" xorm:"default 0 comment('202407') INT(11)"` + WithdrawAmount string `json:"withdraw_amount" xorm:"default 0.00 comment('平台提现') DECIMAL(20,2)"` + CreateAt time.Time `json:"create_at" xorm:"DATETIME"` + UpdateAt time.Time `json:"update_at" xorm:"DATETIME"` + RealWithdrawAmount string `json:"real_withdraw_amount" xorm:"default 0.00 DECIMAL(20,2)"` + Fee string `json:"fee" xorm:"default 0.00 DECIMAL(20,2)"` +} diff --git a/consume/canal_fin_withdraw_apply_for_statistics.go b/consume/canal_fin_withdraw_apply_for_statistics.go new file mode 100644 index 0000000..1cf04e7 --- /dev/null +++ b/consume/canal_fin_withdraw_apply_for_statistics.go @@ -0,0 +1,109 @@ +package consume + +import ( + "applet/app/db" + "applet/app/db/model" + "applet/app/utils" + "applet/app/utils/logx" + "applet/consume/md" + "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" + "encoding/json" + "errors" + "fmt" + "github.com/cc14514/go-geoip2" + geoip2db "github.com/cc14514/go-geoip2-db" + "github.com/streadway/amqp" + "strings" + "time" +) + +func CanalFinWithdrawApplyForStatistics(queue md.MqQueue) { + fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") + ch, err := rabbit.Cfg.Pool.GetChannel() + if err != nil { + logx.Error(err) + return + } + defer ch.Release() + //1、将自己绑定到交换机上 + ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) + //2、取出数据进行消费 + ch.Qos(500) + delivery := ch.Consume(queue.Name, true) //设置自动应答 + + geoIp2db, _ := geoip2db.NewGeoipDbByStatik() + defer geoIp2db.Close() + + var res amqp.Delivery + var ok bool + for { + res, ok = <-delivery + if ok == true { + //fmt.Println(string(res.Body)) + fmt.Println(">>>>>>>>>>>>>>>>>>CanalGuideOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") + err = CanalFinWithdrawApplyForStatisticsDetail(res.Body, geoIp2db) + //_ = res.Reject(false) + //_ = res.Ack(true) + } else { + panic(errors.New("error getting message")) + } + } + fmt.Println("get msg done") +} + +func CanalFinWithdrawApplyForStatisticsDetail(msg []byte, geoIp2db *geoip2.DBReader) error { + //1、解析canal采集至mq中queue的数据结构体 + var canalMsg *md.CanalFinWithdrawApplyMessage[md.CanalFinWithdrawApply] + err := json.Unmarshal(msg, &canalMsg) + if err != nil { + return err + } + + //2、判断操作(目前只针对insert进行修改) + if canalMsg.Type == md.CanalMsgUpdateSqlType { + //4、构造数据结构体 && 插入es文档 + masterId := strings.Split(canalMsg.Database, "_")[1] + sess := db.DBs[masterId].NewSession() + defer sess.Close() + sess.Begin() + for _, data := range canalMsg.Data { + if utils.InArr(data.State, []string{"2", "3"}) { + flow := db.GetFinUserFlow(sess, data.Id) + fee := "0" + if flow != nil { + fee = flow.SysFee + } + WithdrawAmount := data.Amount + RealWithdrawAmount := data.Amount + if data.FeeType == "1" { + RealWithdrawAmount = utils.Float64ToStrByPrec(utils.StrToFloat64(RealWithdrawAmount)-utils.StrToFloat64(fee), 6) + } + month := time.Unix(utils.StrToInt64(data.CreateAt), 0).Format("200601") + total := db.GetWithdrawMonthTotal(sess, month) + if total == nil { + total = &model.WithdrawMonthTotal{ + Month: utils.StrToInt(month), + WithdrawAmount: "", + CreateAt: time.Unix(utils.StrToInt64(data.CreateAt), 0), + UpdateAt: time.Now(), + } + _, err = sess.Insert(total) + if err != nil { + sess.Rollback() + return err + } + } + total.Fee = utils.Float64ToStrByPrec(utils.StrToFloat64(total.Fee)+utils.StrToFloat64(fee), 6) + total.WithdrawAmount = utils.Float64ToStrByPrec(utils.StrToFloat64(total.WithdrawAmount)+utils.StrToFloat64(WithdrawAmount), 6) + total.RealWithdrawAmount = utils.Float64ToStrByPrec(utils.StrToFloat64(total.RealWithdrawAmount)+utils.StrToFloat64(RealWithdrawAmount), 6) + _, err = sess.Where("id=?", total.Id).Update(total) + if err != nil { + sess.Rollback() + return err + } + } + } + sess.Commit() + } + return nil +} diff --git a/consume/canal_guide_order_by_user_up_lv_consume.go b/consume/canal_guide_order_by_user_up_lv_consume.go deleted file mode 100644 index 0e6a59d..0000000 --- a/consume/canal_guide_order_by_user_up_lv_consume.go +++ /dev/null @@ -1,83 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "strings" -) - -func CanalGuideOrderByUserUpLvConsume(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1000) - delivery := ch.Consume(queue.Name, true) //设置自动应答 - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>>>CanalGuideOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - handleCanalGuideOrderByUserUpLvConsume(res.Body) - //_ = res.Reject(false) - //_ = res.Ack(true) - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleCanalGuideOrderByUserUpLvConsume(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.CanalOrderMessage[md.CanalGuideOrder] - err := json.Unmarshal(msg, &canalMsg) - if err != nil { - return nil - } - - masterId := strings.Split(canalMsg.Database, "_")[1] - uids := make([]string, 0) - for _, data := range canalMsg.Data { - uids = append(uids, data.Uid) - } - eg := db.DBs[masterId] - if eg == nil { - return nil - } - levelList, _ := db.UserLevlEgAll(eg) - isAuto := 0 - for _, v := range levelList { - if v.AutoUpdate == 1 { - isAuto = 1 - } - } - if isAuto == 0 { - return nil - } - for _, v := range uids { - FindUser(eg, v, masterId, levelList) - oneUser, _ := db.UserProfileFindByID(eg, v) - if oneUser == nil || (oneUser != nil && oneUser.ParentUid == 0) { - continue - } - FindUser(eg, utils.IntToStr(oneUser.ParentUid), masterId, levelList) - } - return nil -} diff --git a/consume/canal_guide_order_consume.go b/consume/canal_guide_order_consume.go deleted file mode 100644 index c4b60ee..0000000 --- a/consume/canal_guide_order_consume.go +++ /dev/null @@ -1,234 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - esMd "applet/es/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_es.git/es" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/cc14514/go-geoip2" - geoip2db "github.com/cc14514/go-geoip2-db" - "github.com/streadway/amqp" - "net" - "strings" - "time" - "xorm.io/xorm" -) - -func CanalGuideOrderConsume(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(500) - delivery := ch.Consume(queue.Name, true) //设置自动应答 - - geoIp2db, _ := geoip2db.NewGeoipDbByStatik() - defer geoIp2db.Close() - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>>>CanalGuideOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleGuideOrdTable(res.Body, geoIp2db) - //_ = res.Reject(false) - //_ = res.Ack(true) - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleGuideOrdTable(msg []byte, geoIp2db *geoip2.DBReader) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.CanalOrderMessage[md.CanalGuideOrder] - err := json.Unmarshal(msg, &canalMsg) - if err != nil { - return err - } - - //2、判断操作(目前只针对insert进行修改) - if canalMsg.Type == md.CanalMsgInsertSqlType { - //3、TODO::判断es索引是否创建(因为这里我已经手动创建了,省略此步骤) - //err := es.CreateIndexIfNotExists(esMd.ZhiosOrdersEsIndex, esMd.ZhiosOrdersEsMapping) - //if err != nil { - // panic(err) - //} - - //4、构造数据结构体 && 插入es文档 - masterId := strings.Split(canalMsg.Database, "_")[1] - for _, data := range canalMsg.Data { - var uniqueId = masterId + "_" + data.OrdId //es的唯一键,每个文档必须要有唯一键 - user, err := db.UserFindByID(db.DBs[masterId], data.Uid) - if err != nil { - return err - } - provinceId, cityId, countyId, provinceName, cityName, countyName := getUserAddress(db.DBs[masterId], data.Uid, geoIp2db) - now := time.Now() - esData := esMd.ZhiosOrdersEs{ - OrdKind: "guide", - MasterId: utils.StrToInt(masterId), - OrdId: data.OrdId, - MainOrdId: data.ParentOrdId, - StoreOrdId: data.PvdOid, - GoodsId: data.ItemId, - Uid: data.Uid, - BuyerPhone: user.Phone, - CostPrice: utils.StrToFloat64(data.PaidPrice), - //Gmv: utils.StrToFloat64(data.CostPrice) * float64(utils.StrToInt(data.ItemNum)), - Gmv: utils.StrToFloat64(data.PaidPrice), - State: int32(utils.StrToInt(data.State)), - StateZh: md.CanalGuideOrderState(int32(utils.StrToInt(data.State))).String(), - GoodsNum: utils.StrToInt(data.ItemNum), - PayChannel: 0, - PayChannelZh: "", - ReceiverPhone: user.Phone, - ReceiverName: user.Nickname, - ReceiverAddressDetail: "", - ProvinceId: provinceId, - CityId: cityId, - CountyId: countyId, - Province: provinceName, - City: cityName, - County: countyName, - OrderType: int32(utils.StrToInt(data.OrderType)), - EstimateCommission: utils.StrToFloat64(data.SysCommission), - LogisticCompany: "", - PayTime: "", - OrdCreateTime: utils.TimeToStr(data.CreateAt), - CreatedAt: now.Format("2006-01-02 15:04:05"), - UpdatedAt: now.Format("2006-01-02 15:04:05"), - } - if esData.GoodsNum == 0 { - esData.GoodsNum = 1 - } - if esData.PayTime == "" { - esData.PayTime = "1970-01-01 00:00:00" - } - createDocRet, err := es.CreateDoc(esMd.ZhiosOrdersEsIndex, uniqueId, esData) - if err != nil { - return err - } - fmt.Printf("CreateDoc CanalGuide ==> %+v \n\n", createDocRet) - } - } - return nil -} - -func getUserAddress(Db *xorm.Engine, uid string, geoIp2db *geoip2.DBReader) (provinceId, cityId, countyId, provinceName, cityName, countyName string) { - regionalAgentUserBelong, err := db.RegionalAgentUserBelongGetOneByParams(Db, map[string]interface{}{ - "key": "uid", - "value": uid, - }) - if err != nil { - return - } - if regionalAgentUserBelong == nil { - //TODO::没开区域代理的,使用用户ip归属地 - userLoginIpList, err := db.UserLoginIpListGetOneByParams(Db, map[string]interface{}{ - "key": "uid", - "value": uid, - }) - if err != nil || userLoginIpList == nil { - provinceName = "广东省" - provinceId = "440000000000" - return - } - - utils.FilePutContents("getUserAddress", utils.SerializeStr(userLoginIpList)) - record, _ := geoIp2db.City(net.ParseIP(userLoginIpList.NowIp)) - if record.Country.Names != nil && record.Subdivisions != nil && record.City.Names != nil { - province, err := db.ProvinceGetOneByName(record.Subdivisions[0].Names["zh-CN"]) - if err != nil { - return - } - provinceId = province.Id - provinceName = province.Name - - city, err := db.CityGetOneByName(record.City.Names["zh-CN"]) - if err != nil { - return - } - cityId = city.Id - cityName = city.Name - return - } - //TODO::没开区域代理的,默认归属到广东 - provinceName = "广东省" - provinceId = "440000000000" - return - } - var regionalId int64 - if regionalAgentUserBelong.DistrictId != 0 { - regionalId = regionalAgentUserBelong.DistrictId - } else { - regionalId = int64(regionalAgentUserBelong.RegionId) - } - regionalAgentRegion, err := db.RegionalAgentRegionGetOneByParams(Db, map[string]interface{}{ - "key": "id", - "value": regionalId, - }) - if err != nil || regionalAgentRegion.WebsiteRegionId == "" { - return "", "", "", "", "", "" - } - switch regionalAgentRegion.Level { - case 1: - province, err := db.ProvinceGetOne(regionalAgentRegion.WebsiteRegionId) - if err != nil { - return "", "", "", "", "", "" - } - provinceId = province.Id - provinceName = province.Name - break - case 2: - city, err := db.CityGetOne(regionalAgentRegion.WebsiteRegionId) - if err != nil { - return "", "", "", "", "", "" - } - province, err := db.ProvinceGetOne(city.ProvinceId) - if err != nil { - return "", "", "", "", "", "" - } - provinceId = province.Id - provinceName = province.Name - cityId = city.Id - cityName = city.Name - break - case 3: - county, err := db.CountyGetOne(regionalAgentRegion.WebsiteRegionId) - if err != nil { - return "", "", "", "", "", "" - } - city, err := db.CityGetOne(county.CityId) - if err != nil { - return "", "", "", "", "", "" - } - province, err := db.ProvinceGetOne(city.ProvinceId) - if err != nil { - return "", "", "", "", "", "" - } - provinceId = province.Id - provinceName = province.Name - cityId = city.Id - cityName = city.Name - countyId = county.Id - countyName = county.Name - break - } - return -} diff --git a/consume/canal_guide_order_for_statistics.go b/consume/canal_guide_order_for_statistics.go new file mode 100644 index 0000000..557cdea --- /dev/null +++ b/consume/canal_guide_order_for_statistics.go @@ -0,0 +1,140 @@ +package consume + +import ( + "applet/app/db" + "applet/app/db/model" + "applet/app/utils" + "applet/app/utils/logx" + "applet/consume/md" + "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" + "encoding/json" + "errors" + "fmt" + "github.com/cc14514/go-geoip2" + geoip2db "github.com/cc14514/go-geoip2-db" + "github.com/streadway/amqp" + "strings" + "time" + "xorm.io/xorm" +) + +func CanalGuideOrderForStatistics(queue md.MqQueue) { + fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") + ch, err := rabbit.Cfg.Pool.GetChannel() + if err != nil { + logx.Error(err) + return + } + defer ch.Release() + //1、将自己绑定到交换机上 + ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) + //2、取出数据进行消费 + ch.Qos(500) + delivery := ch.Consume(queue.Name, true) //设置自动应答 + + geoIp2db, _ := geoip2db.NewGeoipDbByStatik() + defer geoIp2db.Close() + + var res amqp.Delivery + var ok bool + for { + res, ok = <-delivery + if ok == true { + //fmt.Println(string(res.Body)) + fmt.Println(">>>>>>>>>>>>>>>>>>CanalGuideOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") + err = CanalGuideOrderForStatisticsDetail(res.Body, geoIp2db) + //_ = res.Reject(false) + //_ = res.Ack(true) + } else { + panic(errors.New("error getting message")) + } + } + fmt.Println("get msg done") +} + +func CanalGuideOrderForStatisticsDetail(msg []byte, geoIp2db *geoip2.DBReader) error { + //1、解析canal采集至mq中queue的数据结构体 + var canalMsg *md.CanalOrderMessage[md.CanalGuideOrder] + err := json.Unmarshal(msg, &canalMsg) + if err != nil { + return err + } + + //2、判断操作(目前只针对update进行修改) + if canalMsg.Type == md.CanalMsgUpdateSqlType { + //4、构造数据结构体 && 插入es文档 + masterId := strings.Split(canalMsg.Database, "_")[1] + sess := db.DBs[masterId].NewSession() + defer sess.Close() + sess.Begin() + for _, data := range canalMsg.Data { + + if utils.StrToInt(data.PvdSettleAt) > 0 && strings.Contains(data.Ext, "pvd_settle_at") == false { + err = comm(sess, data.OrdId, data.BenefitAll, "pvd_settle", data.PvdSettleAt, data.Pvd) + if err != nil { + sess.Rollback() + return err + } + } + if utils.StrToInt(data.SettleAt) > 0 && strings.Contains(data.Ext, "settle_at") == false { + err = comm(sess, data.OrdId, data.BenefitAll, "settle", data.SettleAt, data.Pvd) + if err != nil { + sess.Rollback() + return err + } + } + } + sess.Commit() + } + return nil +} +func comm(sess *xorm.Session, oid, commission, types, times, pvd string) error { + byOid, _ := db.OrderListByOid(sess, oid) + if byOid == nil { + return nil + } + if strings.Contains(byOid.Ext, "settle_at") && types == "settle" { + return nil + } + if strings.Contains(byOid.Ext, "pvd_settle_at") && types == "pvd_settle" { + return nil + } + extData := make(map[string]interface{}) + json.Unmarshal([]byte(byOid.Ext), &extData) + extData[types] = types + byOid.Ext = utils.SerializeStr(extData) + _, err2 := sess.Where("ord_id=?", byOid.OrdId).Cols("ext").Update(byOid) + if err2 != nil { + return err2 + } + month := time.Unix(utils.StrToInt64(times), 0).Format("200601") + total := db.GetGuideOrderMonthTotal(sess, month, pvd) + if total == nil { + total = &model.GuideOrderMonthTotal{ + Month: utils.StrToInt(month), + UnionType: pvd, + CreateAt: time.Unix(utils.StrToInt64(times), 0), + UpdateAt: time.Now(), + } + _, err := sess.Insert(total) + if err != nil { + return err + } + } + if types == "settle" { + sql := `select sum(amount) as amount from ord_list_relate where oid=%s ` + sql = fmt.Sprintf(sql, oid) + data, _ := db.QueryNativeStringWithSession(sess, sql) + if len(data) > 0 { + total.StationSettleAmount = utils.Float64ToStrByPrec(utils.StrToFloat64(total.StationSettleAmount)+utils.StrToFloat64(data[0]["amount"]), 6) + } + } + if types == "pvd_settle" { + total.UnionSettleAmount = utils.Float64ToStrByPrec(utils.StrToFloat64(total.UnionSettleAmount)+utils.StrToFloat64(commission), 6) + } + _, err := sess.Where("id=?", total.Id).Update(total) + if err != nil { + return err + } + return nil +} diff --git a/consume/canal_mall_ord_for_you_mi_shang.go b/consume/canal_mall_ord_for_you_mi_shang.go deleted file mode 100644 index 25f82ec..0000000 --- a/consume/canal_mall_ord_for_you_mi_shang.go +++ /dev/null @@ -1,123 +0,0 @@ -package consume - -import ( - "applet/app/db" - model2 "applet/app/db/model" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_condition_statistics.git/db/model" - zyos_go_condition_hdl "code.fnuoos.com/go_rely_warehouse/zyos_go_condition_statistics.git/hdl" - md2 "code.fnuoos.com/go_rely_warehouse/zyos_go_condition_statistics.git/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/jinzhu/copier" - "github.com/streadway/amqp" - "strings" - "xorm.io/xorm" -) - -func CanalMallOrdForYouMiShang(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(10) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleCanalMallOrdForYouMiShang(res.Body) - //_ = res.Reject(false) - _ = res.Ack(true) - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleCanalMallOrdForYouMiShang(msg []byte) error { - var canalMsg *md.CanalMallOrdForYouMiShang - err := json.Unmarshal(msg, &canalMsg) - if err != nil { - fmt.Println("=======================", err) - return err - } - database := strings.ReplaceAll(canalMsg.Database, "zhios_", "") - if utils.InArr(database, []string{"88164961"}) == false { - - return nil - } - fmt.Println("==========================", 123333) - - eg := db.DBs[database] - levelList, _ := db.UserLevlEgAll(eg) - userId := make(map[string]string, 0) - for _, v := range canalMsg.Data { - if utils.StrToInt(v.Uid) == 0 || utils.InArr(v.State, []string{"1", "2", "3"}) == false { - continue - } - userId[v.Uid] = v.Uid - } - fmt.Println(userId) - for _, v := range userId { - FindUser(eg, v, database, levelList) - oneUser, _ := db.UserProfileFindByID(eg, v) - if oneUser == nil || (oneUser != nil && oneUser.ParentUid == 0) { - continue - } - FindUser(eg, utils.IntToStr(oneUser.ParentUid), database, levelList) - } - return nil -} -func FindUser(eg *xorm.Engine, uid string, dbName string, levelList []*model2.UserLevel) { - oneUser, _ := db.UserFindByID(eg, uid) - if oneUser == nil { - return - } - if oneUser.IsNotUpLevel == 1 { - return - } - levelWeight := 0 - for _, v1 := range levelList { - if v1.Id == oneUser.Level { - levelWeight = v1.LevelWeight - } - } - nextLv := "" - for _, v1 := range levelList { - if v1.LevelWeight <= levelWeight || v1.AutoUpdate == 0 { //小于当前等级或没开自动升级的都跳过 - continue - } - if nextLv == "" { - nextLv = utils.IntToStr(v1.Id) - } - } - if nextLv != "" { - DataDetail1 := md2.DataDetail{ - AgentType: nextLv, - Comment: "自动等级", - MasterId: dbName, - Uid: utils.IntToStr(oneUser.Uid), - IsChangeTime: "1", - } - var info model.User - copier.Copy(&info, &oneUser) - fmt.Println(DataDetail1) - zyos_go_condition_hdl.CommUplv(map[string]string{}, "", eg, dbName, &info, oneUser.Level, DataDetail1) - } -} diff --git a/consume/canal_order_consume.go b/consume/canal_order_consume.go deleted file mode 100644 index dfa0c2c..0000000 --- a/consume/canal_order_consume.go +++ /dev/null @@ -1,221 +0,0 @@ -package consume - -import ( - "applet/app/db" - model2 "applet/app/db/gim/model" - "applet/app/db/model" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - esMd "applet/es/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_es.git/es" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "strings" - "time" -) - -func CanalOrderConsumev2(queue md.MqQueue) { - var list []model.DouShenImGroup - err := db.Db.Where("kind =2 and id = 43140").Find(&list) - eg := db.DBs["68823769"] - for _, v := range list { - var m model.RegionalAgentUser - has, err := eg.Where("uid =?", v.Uid).Get(&m) - if err != nil { - panic(err) - } - if !has { - fmt.Println(">>>", v) - } - var group model2.Group - has, err = db.ImDb.Where("id =?", v.GroupId).Get(&group) - if err != nil { - panic(err) - } - if !has { - fmt.Println("<<<", v) - } - regionalAgentRegion, err := db.RegionalAgentRegionGetOneByParams(eg, map[string]interface{}{ - "key": "id", - "value": m.RegionId, - }) - if err != nil { - panic(err) - } - groupName := "抖省" + regionalAgentRegion.Name + "运营中心【1】群" - group.Name = groupName - _, err = db.ImDb.Where("id =?", v.GroupId).Cols("name").Update(group) - if err != nil { - panic(err) - } - - v.Name = groupName - _, err = db.Db.Where("id =?", v.Id).Cols("name").Update(v) - if err != nil { - panic(err) - } - } - - return - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleMallOrdTable(res.Body) - //_ = res.Reject(false) - _ = res.Ack(true) - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func CanalOrderConsume(queue md.MqQueue) { - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(100) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleMallOrdTable(res.Body) - //_ = res.Reject(false) - _ = res.Ack(true) - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleMallOrdTable(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.CanalOrderMessage[md.CanalOrder] - err := json.Unmarshal(msg, &canalMsg) - if err != nil { - return err - } - //2、判断操作(目前只针对insert进行修改) - if canalMsg.Type == md.CanalMsgInsertSqlType { - //3、TODO::判断es索引是否创建(因为这里我已经手动创建了,省略此步骤) - //err := es.CreateIndexIfNotExists(esMd.ZhiosOrdersEsIndex, esMd.ZhiosOrdersEsMapping) - //if err != nil { - // panic(err) - //} - - //4、构造数据结构体 && 插入es文档 - masterId := strings.Split(canalMsg.Database, "_")[1] - - var ordList []string - for _, data := range canalMsg.Data { - ordList = append(ordList, data.OrdId) - } - ordItemList, err := db.MallOrdItemFindByParams(db.DBs[masterId], map[string]interface{}{ - "key": "ord_id", - "value": ordList, - }) - if err != nil { - return err - } - var ordItemListMap = map[string]int{} - for _, item := range *ordItemList { - ordItemListMap[utils.AnyToString(item.OrdId)] = item.GoodsNum - } - - for _, data := range canalMsg.Data { - var uniqueId = masterId + "_" + data.OrdId //es的唯一键,每个文档必须要有唯一键 - province, err := db.ProvinceGetOne(data.ProvinceId) - if err != nil { - return err - } - city, err := db.CityGetOne(data.CityId) - if err != nil { - return err - } - county, err := db.CountyGetOne(data.CountyId) - if err != nil { - return err - } - now := time.Now() - var goodsNum = 1 - if ordItemListMap[data.OrdId] != 0 { - goodsNum = ordItemListMap[data.OrdId] - } - esData := esMd.ZhiosOrdersEs{ - OrdKind: "mall", - MasterId: utils.StrToInt(masterId), - OrdId: data.OrdId, - MainOrdId: data.MainOrdId, - StoreOrdId: data.StoreOrdId, - GoodsId: data.GoodsId, - Uid: data.Uid, - BuyerPhone: data.BuyerPhone, - CostPrice: utils.StrToFloat64(data.CostPrice), - Gmv: utils.StrToFloat64(data.CostPrice) * float64(goodsNum), - State: int32(utils.StrToInt(data.State)), - StateZh: md.CanalOrderState(int32(utils.StrToInt(data.State))).String(), - PayChannel: int32(utils.StrToInt(data.PayChannel)), - PayChannelZh: md.CanalOrderPayChannel(int32(utils.StrToInt(data.PayChannel))).String(), - ReceiverPhone: data.ReceiverPhone, - ReceiverName: data.ReceiverName, - ReceiverAddressDetail: data.ReceiverAddressDetail, - ProvinceId: data.ProvinceId, - CityId: data.CityId, - CountyId: data.CountyId, - Province: province.Name, - City: city.Name, - County: county.Name, - OrderType: int32(utils.StrToInt(data.OrderType)), - GoodsNum: goodsNum, - EstimateCommission: utils.StrToFloat64(data.EstimateCommission), - LogisticCompany: data.LogisticCompany, - PayTime: data.PayTime, - OrdCreateTime: data.CreateTime, - CreatedAt: now.Format("2006-01-02 15:04:05"), - UpdatedAt: now.Format("2006-01-02 15:04:05"), - } - if esData.PayTime == "" { - esData.PayTime = "1970-01-01 00:00:00" - } - createDocRet, err := es.CreateDoc(esMd.ZhiosOrdersEsIndex, uniqueId, esData) - if err != nil { - return err - } - fmt.Printf("CreateDoc CanalOrder ==> %+v \n\n", createDocRet) - } - } - return nil -} diff --git a/consume/canal_user_virtual_coin_flow_consume.go b/consume/canal_user_virtual_coin_flow_consume.go deleted file mode 100644 index 9513de2..0000000 --- a/consume/canal_user_virtual_coin_flow_consume.go +++ /dev/null @@ -1,130 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/db/model" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/shopspring/decimal" - "github.com/streadway/amqp" - "strings" - "time" -) - -func CanalUserVirtualCoinFlowConsume(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>CanalUserVirtualCoinFlowConsume>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalUserVirtualCoinFlowConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleCanalUserVirtualCoinFlow(res.Body) - if err != nil { - fmt.Println("handleCanalUserVirtualCoinFlow_ERR:::::", err.Error()) - } - //_ = res.Reject(false) - err = res.Ack(true) - fmt.Println("err ::: ", err) - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleCanalUserVirtualCoinFlow(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.CanalUserVirtualCoinFlowOrderMessage[md.CanalUserVirtualCoinFlowOrder] - err := json.Unmarshal(msg, &canalMsg) - if err != nil { - return err - } - - masterId := strings.Split(canalMsg.Database, "_")[1] - if masterId != "32053480" { - return nil - } - engine := db.DBs[masterId] - now := time.Now() - - //2、查找 one_circles_green_energy_basic_setting 基础设置 - userPublicPlatoonDoubleNetworkSetting, err := db.UserPublicPlatoonDoubleNetworkSettingGetOneByParams(engine, map[string]interface{}{ - "key": "is_open", - "value": 1, - }) - if err != nil { - return err - } - if userPublicPlatoonDoubleNetworkSetting == nil { - return errors.New("公排双网未开启") - } - if canalMsg.Type == md.CanalMsgInsertSqlType { - if canalMsg.Data[0].CoinId == utils.IntToStr(userPublicPlatoonDoubleNetworkSetting.CoinId) { - //3、查找 user_public_platoon_double_network_user_coin_record - userPublicPlatoonDoubleNetworkUserCoinRecord, err1 := db.UserPublicPlatoonDoubleNetworkUserCoinRecordGetOneByParams(engine, map[string]interface{}{ - "key": "uid", - "value": canalMsg.Data[0].Uid, - }) - if err1 != nil { - return err1 - } - if userPublicPlatoonDoubleNetworkUserCoinRecord == nil { - userProfile, err2 := db.UserProfileFindByIDSess(engine.NewSession(), canalMsg.Data[0].Uid) - if userProfile == nil { - return errors.New("用户不存在") - } - if err2 != nil { - return err2 - } - //新增记录 - _, err3 := db.UserPublicPlatoonDoubleNetworkUserCoinRecordInsert(engine, &model.UserPublicPlatoonDoubleNetworkUserCoinRecord{ - Uid: utils.StrToInt(canalMsg.Data[0].Uid), - LastAmount: canalMsg.Data[0].AfterAmout, - Amount: canalMsg.Data[0].AfterAmout, - RecommendUid: userProfile.ParentUid, - CoinId: utils.StrToInt(canalMsg.Data[0].CoinId), - CreateAt: now.Format("2006-01-02 15:04:05"), - UpdateAt: now.Format("2006-01-02 15:04:05"), - }) - if err3 != nil { - return err3 - } - } else { - //更新记录 - afterAmount, _ := decimal.NewFromString(canalMsg.Data[0].AfterAmout) - amount, _ := decimal.NewFromString(userPublicPlatoonDoubleNetworkUserCoinRecord.Amount) - lastAmount, _ := decimal.NewFromString(userPublicPlatoonDoubleNetworkUserCoinRecord.LastAmount) - if canalMsg.Data[0].Direction == "1" || canalMsg.Data[0].Direction == "2" { - //收入 && 支出 - userPublicPlatoonDoubleNetworkUserCoinRecord.Amount = amount.Add(afterAmount.Sub(lastAmount)).String() - } - userPublicPlatoonDoubleNetworkUserCoinRecord.LastAmount = canalMsg.Data[0].AfterAmout - _, err2 := db.UserPublicPlatoonDoubleNetworkUserCoinRecordUpdate(engine, userPublicPlatoonDoubleNetworkUserCoinRecord.Id, userPublicPlatoonDoubleNetworkUserCoinRecord, "amount", "last_amount") - if err2 != nil { - return err2 - } - } - } - } - - return nil -} diff --git a/consume/cloud_issuance_async_mlogin.go b/consume/cloud_issuance_async_mlogin.go deleted file mode 100644 index ad1686d..0000000 --- a/consume/cloud_issuance_async_mlogin.go +++ /dev/null @@ -1,125 +0,0 @@ -package consume - -import ( - "applet/app/cfg" - "applet/app/db" - "applet/app/utils" - "applet/app/utils/cache" - tool "applet/app/utils/cloud_issuance" - "applet/app/utils/logx" - md2 "applet/cloud_issuance/md" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "strconv" - "time" -) - -func CloudIssuanceAsyncMLoginConsume(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - fmt.Println(">>>>>>>>>>>>>>>>CloudIssuanceAsyncMLoginConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - //解析mq中queue的数据结构体 - var msg *md2.CloudIssuanceAsyncMLogin - err = json.Unmarshal(res.Body, &msg) - if err != nil { - panic(err) - } - go func() { - err := handleAsyncMLogin(msg.WId, msg.MasterId, msg.UserId, msg.RobotId) - if err != nil { - fmt.Println("<<<<<<<<<<<< handleAsyncMLogin err>>>>>>>>", err.Error()) - } - }() - _ = res.Ack(true) - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleAsyncMLogin(wId, masterId, userId string, robotId int) error { - var timeTotal = 0 - for { - err, resp := robotAsyncMacLogin(md2.RobotAsyncMacLoginRequest{ - WId: wId, - RobotId: robotId, - }) - if err == nil { - fmt.Println("success <<<<<<<", resp) - if cfg.Prd { - engine := db.DBs[masterId] - cloudIssuanceUserRobotDb := db.CloudIssuanceUserRobotDb{} - cloudIssuanceUserRobotDb.Set(engine, utils.StrToInt(userId)) - robot, err := cloudIssuanceUserRobotDb.GetCloudIssuanceUserRobot() - if err != nil { - return err - } - if robot == nil { - return errors.New("未查询到机器人记录") - } - robot.WcId = resp.WcId - robot.WcNickname = resp.NickName - robot.WcHeadUrl = resp.HeadUrl - robot.LoginStatus = 1 - _, err = cloudIssuanceUserRobotDb.SaveCloudIssuanceUserRobot(robot.Id, robot, "wc_id", "wc_nickname", "wc_head_url", "login_status") - if err != nil { - return err - } - } else { - //TODO::测试环境, 简化操作 通过redis 桥接 - cache.SetEx(fmt.Sprintf("cloud_issuance_async_login_success:%s:%s", masterId, userId), utils.SerializeStr(resp), 60*5) - } - return nil - } - - fmt.Println("err>>>>>>>>", err.Error()) - if err != nil && err.Error() != "未登录" { - return err - } - //TODO::休眠5s - time.Sleep(time.Duration(5) * time.Second) - timeTotal += 5 - if timeTotal >= 240 { - return errors.New("超时未登录") - } - } -} - -func robotAsyncMacLogin(args md2.RobotAsyncMacLoginRequest) (err error, result md2.RobotAsyncMacLoginResponse) { // 同步登录状态 - url := tool.HttpBuild("itaoke.robot.async.mlogin", "127.0.0.1", map[string]string{ - "robot_id": strconv.Itoa(args.RobotId), - "wId": args.WId, - }) - data, err := tool.SendPost(url, args) - if err != nil { - return - } - resByte, err := json.Marshal(data.Data) - if err != nil { - return - } - err = json.Unmarshal(resByte, &result) - if err != nil { - return - } - return -} diff --git a/consume/cloud_issuance_msg_callback.go b/consume/cloud_issuance_msg_callback.go deleted file mode 100644 index d9521c6..0000000 --- a/consume/cloud_issuance_msg_callback.go +++ /dev/null @@ -1,72 +0,0 @@ -package consume - -import ( - "applet/app/utils" - "applet/app/utils/logx" - db "applet/cloud_issuance/db/official" - md2 "applet/cloud_issuance/md" - "applet/cloud_issuance/svc" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/gin-gonic/gin" - "github.com/streadway/amqp" - "time" -) - -func CloudIssuanceMsgCallBackConsume(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //2、取出数据进行消费 - ch.Qos(10) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - fmt.Println(">>>>>>>>>>>>>>>>CloudIssuanceMsgCallBackConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - //解析mq中queue的数据结构体 - var msg *md2.CallbackRequest - err = json.Unmarshal(res.Body, &msg) - if err != nil { - panic(err) - } - randInt := utils.RandIntRand(100, 200) - time.Sleep(time.Millisecond * time.Duration(randInt)) // 等待100 ~ 200毫秒 - go func() { - //设置masterId - cloudIssuanceRobotRecords, err := db.CloudIssuanceRobotRecordsGetOneByParams(map[string]interface{}{ - "key": "robot_id", - "value": msg.RobotId, - }) - if err != nil { - fmt.Println("CallBackErr:::::", err.Error()) - return - } - if cloudIssuanceRobotRecords == nil { - //TODO::未查询到机器人,不需要处理 - utils.FilePutContents("cloud_issuance_call_back_not_found", utils.SerializeStr(msg)) - return - } - var c = &gin.Context{} - c.Set("mid", cloudIssuanceRobotRecords.MasterId) - dealCloudIssuanceCallBackService := svc.DealCloudIssuanceCallBackService{} - dealCloudIssuanceCallBackService.Set(c) - dealCloudIssuanceCallBackService.DealCallBack(c, *msg) - }() - _ = res.Ack(true) - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} diff --git a/consume/consume.go b/consume/consume.go deleted file mode 100644 index 1810586..0000000 --- a/consume/consume.go +++ /dev/null @@ -1,77 +0,0 @@ -package consume - -import ( - "applet/app/utils" - "applet/app/utils/logx" - "bytes" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - jsoniter "github.com/json-iterator/go" - "github.com/streadway/amqp" - "log" - "strings" -) - -var Json = jsoniter.ConfigCompatibleWithStandardLibrary - -type Message struct { - MessageType string `json:"message_type"` - Data int `json:"data"` -} - -func WorkReceive(name string) { - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //接收消息时,指定 - msgs := ch.Consume(name, false) - for msg := range msgs { - var message2 Message - jsonStr := string(msg.Body) - jsonStr = strings.Trim(jsonStr, "\"") - jsonStr = strings.ReplaceAll(jsonStr, "\\", "") - utils.Unserialize([]byte(jsonStr), &message2) - switch message2.MessageType { - case "test": - go func(msg *amqp.Delivery) { - log.Printf("recevie1 Received a message: %s", msg.Body) - msg.Ack(true) - }(&msg) - } - - } -} - -func TestWorkSend() { - // 推入rabbitMq - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - } - defer ch.Release() - var message struct { - MessageType string `json:"message_type"` - Data int `json:"data"` - } - message.MessageType = "test" - message.Data = 1 - for message.Data < 2 { - ch.Publish("test_work_queue_processor", utils.SerializeStr(message), "") - message.Data += 1 - //time.Sleep(time.Second * 5) - } -} - -// 去除json中的转义字符 -func disableEscapeHtml(data interface{}) (string, error) { - bf := bytes.NewBuffer([]byte{}) - jsonEncoder := json.NewEncoder(bf) - jsonEncoder.SetEscapeHTML(true) - if err := jsonEncoder.Encode(data); err != nil { - return "", err - } - return bf.String(), nil -} diff --git a/consume/dou_shen_user_register_for_my_my_fans.go b/consume/dou_shen_user_register_for_my_my_fans.go deleted file mode 100644 index 0ebeaf1..0000000 --- a/consume/dou_shen_user_register_for_my_my_fans.go +++ /dev/null @@ -1,146 +0,0 @@ -package consume - -import ( - "applet/app/cfg" - "applet/app/db" - db2 "applet/app/db/gim" - model2 "applet/app/db/gim/model" - "applet/app/db/model" - utils2 "applet/app/utils" - "applet/app/utils/logx" - utils "applet/app/utils/rpc" - "applet/consume/md" - "applet/pkg/pb" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "strconv" - "time" -) - -func DouShenUserRegisterConsumeForMyFans(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>DouShenUserRegisterConsumeForMyFans>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") - err = handleDouShenUserRegisterConsumeForMyFans(res.Body) - if err != nil { - fmt.Println("!!!!!!!err!!!!!!!", err) - _ = res.Reject(false) - - utils2.FilePutContents("douShenUserRegisterConsumeForMyFans_err", "[err]:"+err.Error()) - if err.Error() == "用户暂未注册im系统" { - //TODO::重新推回队列末尾,避免造成队列堵塞 - var msg *md.DouShenUserRegisterMessageStructForMyFans - json.Unmarshal(res.Body, &msg) - ch.Publish(queue.ExchangeName, msg, queue.RoutKey) - } - } else { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleDouShenUserRegisterConsumeForMyFans(msgData []byte) error { - time.Sleep(time.Duration(15) * time.Second) - //1、解析mq中queue的数据结构体 - var msg *md.DouShenUserRegisterMessageStructForMyFans - err := json.Unmarshal(msgData, &msg) - if err != nil { - return err - } - //2、查找用户对应im系统中的数据 - gimUser, err := db2.UserGetOneByParams(db.ImDb, msg.MasterId, map[string]interface{}{ - "key": "phone_number", - "value": msg.Phone, - }) - if err != nil { - return err - } - if gimUser == nil { - if db.DBs[msg.MasterId] == nil { - return nil - } - user, err := db.UserFindByMobile(db.DBs[msg.MasterId], strconv.FormatInt(msg.Phone, 10)) - if err != nil { - return err - } - userProfile, err := db.UserProfileFindByID(db.DBs[msg.MasterId], user.Uid) - if err != nil { - return err - } - - gimUserId, err := db2.UserInsert(db.ImDb, &model2.User{ - PhoneNumber: strconv.FormatInt(msg.Phone, 10), - Nickname: user.Nickname, - AvatarUrl: userProfile.AvatarUrl, - Sex: userProfile.Gender, - CreateTime: time.Now().Format("2006-01-02 15:04:05"), - UpdateTime: time.Now().Format("2006-01-02 15:04:05"), - MasterId: utils2.StrToInt64(msg.MasterId), - IsAutoAddedFriends: 0, - }) - if err != nil { - return errors.New("用户暂未注册im系统") - } - gimUser, err = db2.UserGetOneByParams(db.ImDb, msg.MasterId, map[string]interface{}{ - "key": "id", - "value": gimUserId, - }) - if gimUser == nil { - return errors.New("用户暂未注册im系统") - } - } - - groupName := "我的粉丝【1】群" - //3、创建群 - resp, err := utils.GetLogicExtClient(cfg.ImLogicRpc.URL, cfg.ImLogicRpc.PORT).CreateGroup(utils.GetCtx("", utils2.Int64ToStr(gimUser.Id), "", msg.MasterId), &pb.CreateGroupReq{ - Name: groupName, - AvatarUrl: "", - //Introduction: gimUser.Nickname + "的粉丝群", - Introduction: "", - Extra: "", - MemberIds: nil, - }) - if err != nil { - return err - } - //插入 dou_shen_im_group 记录 - now := time.Now() - _, err = db.DouShenImGroupInsert(db.Db, &model.DouShenImGroup{ - Kind: 3, - Uid: int(msg.Uid), - GroupId: int(resp.GroupId), - IsFull: 0, - Name: groupName, - CreateTime: now, - UpdateTime: now, - }) - if err != nil { - return err - } - - return nil -} diff --git a/consume/dou_shen_user_register_for_my_my_recommender.go b/consume/dou_shen_user_register_for_my_my_recommender.go deleted file mode 100644 index bfe6303..0000000 --- a/consume/dou_shen_user_register_for_my_my_recommender.go +++ /dev/null @@ -1,207 +0,0 @@ -package consume - -import ( - "applet/app/cfg" - "applet/app/db" - db2 "applet/app/db/gim" - "applet/app/db/gim/model" - model2 "applet/app/db/model" - utils2 "applet/app/utils" - "applet/app/utils/logx" - utils "applet/app/utils/rpc" - "applet/consume/md" - "applet/pkg/pb" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "strconv" - "time" -) - -func DouShenUserRegisterConsumeForMyRecommender(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>DouShenUserRegisterConsumeForMyRecommender>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") - err = handleDouShenUserRegisterConsumeForMyRecommender(res.Body) - if err != nil { - fmt.Println("!!!!!!!err!!!!!!!", err) - _ = res.Reject(false) - - utils2.FilePutContents("douShenUserRegisterConsumeForMyRecommender_err", "[err]:"+err.Error()) - if err.Error() == "用户暂未注册im系统" { - //TODO::重新推回队列末尾,避免造成队列堵塞 - var msg *md.DouShenUserRegisterMessageStructForMyRecommender - json.Unmarshal(res.Body, &msg) - ch.Publish(queue.ExchangeName, msg, queue.RoutKey) - } - } else { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleDouShenUserRegisterConsumeForMyRecommender(msgData []byte) error { - time.Sleep(time.Duration(20) * time.Second) - //1、解析mq中queue的数据结构体 - var msg *md.DouShenUserRegisterMessageStructForMyRecommender - err := json.Unmarshal(msgData, &msg) - if err != nil { - return err - } - //2、查找用户对应im系统中的数据 - gimUser, err := db2.UserGetOneByParams(db.ImDb, msg.MasterId, map[string]interface{}{ - "key": "phone_number", - "value": msg.Phone, - }) - if err != nil { - return err - } - - if gimUser == nil { - if db.DBs[msg.MasterId] == nil { - return nil - } - user, err := db.UserFindByMobile(db.DBs[msg.MasterId], strconv.FormatInt(msg.Phone, 10)) - if err != nil { - return err - } - userProfile, err := db.UserProfileFindByID(db.DBs[msg.MasterId], user.Uid) - if err != nil { - return err - } - gimUserId, err := db2.UserInsert(db.ImDb, &model.User{ - PhoneNumber: strconv.FormatInt(msg.Phone, 10), - Nickname: user.Nickname, - AvatarUrl: userProfile.AvatarUrl, - Sex: userProfile.Gender, - CreateTime: time.Now().Format("2006-01-02 15:04:05"), - UpdateTime: time.Now().Format("2006-01-02 15:04:05"), - MasterId: utils2.StrToInt64(msg.MasterId), - IsAutoAddedFriends: 0, - }) - if err != nil { - return errors.New("用户暂未注册im系统") - } - gimUser, err = db2.UserGetOneByParams(db.ImDb, msg.MasterId, map[string]interface{}{ - "key": "id", - "value": gimUserId, - }) - if gimUser == nil { - return errors.New("用户暂未注册im系统") - } - } - - //2、查找是否有群 - var fansGroup model2.DouShenImGroup - fansGroups, err := db.DouShenImGroupFindByParamsByKind(db.Db, 3, map[string]interface{}{ - "key": "uid", - "value": msg.RecommenderUid, - }) - if err != nil { - return err - } - for _, group := range *fansGroups { - //统计当前群有多少人 - userGroups, err := db2.GroupUserFindByParams(db.ImDb, map[string]interface{}{ - "key": "group_id", - "value": group.GroupId, - }) - if err != nil { - return err - } - if len(*userGroups) < 500 { - fansGroup = group - } - } - - if fansGroup.GroupId == 0 { - recommenderUser, err := db.UserFindByID(db.DBs[msg.MasterId], msg.RecommenderUid) - if err != nil { - return err - } - recommenderGimUser, err := db2.UserGetOneByParams(db.ImDb, msg.MasterId, map[string]interface{}{ - "key": "phone_number", - "value": recommenderUser.Phone, - }) - if recommenderGimUser == nil { - return errors.New("当前推荐人信息有误,请联系管理员!!!") - } - - groupName := "我的粉丝【" + utils2.AnyToString(len(*fansGroups)+1) + "】群" - //3、创建群 - resp, err := utils.GetLogicExtClient(cfg.ImLogicRpc.URL, cfg.ImLogicRpc.PORT).CreateGroup(utils.GetCtx("", strconv.FormatInt(recommenderGimUser.Id, 10), "0", msg.MasterId), &pb.CreateGroupReq{ - Name: groupName, - AvatarUrl: "", - //Introduction: "官方群", - Introduction: "", - Extra: "", - MemberIds: []int64{}, - }) - if err != nil { - return err - } - - //插入 dou_shen_im_group 记录 - now := time.Now() - _, err = db.DouShenImGroupInsert(db.Db, &model2.DouShenImGroup{ - Kind: 3, - Uid: int(msg.RecommenderUid), - GroupId: int(resp.GroupId), - IsFull: 0, - Name: groupName, - CreateTime: now, - UpdateTime: now, - }) - if err != nil { - return err - } - tempFansGroup, err := db.DouShenImGroupGetOneByParams(db.Db, 2, map[string]interface{}{ - "group_id": resp.GroupId, - }) - if err != nil { - return err - } - fansGroup = *tempFansGroup - } - userGroup, err2 := db2.GroupUserGetOneByParams(db.ImDb, 1, map[string]interface{}{ - "key": "group_id", - "value": fansGroup.GroupId, - }) - if err2 != nil { - return err2 - } - if userGroup == nil { - return errors.New("当前推荐人群暂未设置群主,请联系管理员!!!") - } - - //加入群 - _, err = utils.GetLogicExtClient(cfg.ImLogicRpc.URL, cfg.ImLogicRpc.PORT).AddGroupMembers( - utils.GetCtx("", strconv.FormatInt(userGroup.UserId, 10), "", msg.MasterId), - &pb.AddGroupMembersReq{ - GroupId: int64(fansGroup.GroupId), - UserIds: []int64{gimUser.Id}, - }) - return nil -} diff --git a/consume/dou_shen_user_register_for_official_consume.go b/consume/dou_shen_user_register_for_official_consume.go deleted file mode 100644 index 7c391b2..0000000 --- a/consume/dou_shen_user_register_for_official_consume.go +++ /dev/null @@ -1,194 +0,0 @@ -package consume - -import ( - "applet/app/cfg" - "applet/app/db" - db2 "applet/app/db/gim" - model2 "applet/app/db/gim/model" - "applet/app/db/model" - utils2 "applet/app/utils" - "applet/app/utils/logx" - utils "applet/app/utils/rpc" - "applet/consume/md" - "applet/pkg/pb" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "strconv" - "time" -) - -func DouShenUserRegisterConsumeForOfficial(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>DouShenUserRegisterConsumeForOfficial>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") - err = handleDouShenUserRegisterConsumeForOfficial(res.Body) - if err != nil { - fmt.Println("!!!!!!!err!!!!!!!", err) - _ = res.Reject(false) - - utils2.FilePutContents("douShenUserRegisterConsumeForOfficial_err", "[err]:"+err.Error()) - if err.Error() == "用户暂未注册im系统" { - //TODO::重新推回队列末尾,避免造成队列堵塞 - var msg *md.DouShenUserRegisterMessageStructForOfficial - json.Unmarshal(res.Body, &msg) - ch.Publish(queue.ExchangeName, msg, queue.RoutKey) - } - } else { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleDouShenUserRegisterConsumeForOfficial(msgData []byte) error { - time.Sleep(time.Duration(5) * time.Second) - //1、解析mq中queue的数据结构体 - var msg *md.DouShenUserRegisterMessageStructForOfficial - err := json.Unmarshal(msgData, &msg) - if err != nil { - return err - } - //2、查找用户对应im系统中的数据 - gimUser, err := db2.UserGetOneByParams(db.ImDb, msg.MasterId, map[string]interface{}{ - "key": "phone_number", - "value": msg.Phone, - }) - if err != nil { - return err - } - if gimUser == nil { - if db.DBs[msg.MasterId] == nil { - return nil - } - fmt.Println("===========================", msg.Phone) - user, err := db.UserFindByMobile(db.DBs[msg.MasterId], strconv.FormatInt(msg.Phone, 10)) - if err != nil { - return err - } - if user == nil { - return nil - } - userProfile, err := db.UserProfileFindByID(db.DBs[msg.MasterId], user.Uid) - if err != nil { - return err - } - - gimUserId, err := db2.UserInsert(db.ImDb, &model2.User{ - PhoneNumber: strconv.FormatInt(msg.Phone, 10), - Nickname: user.Nickname, - AvatarUrl: userProfile.AvatarUrl, - Sex: userProfile.Gender, - CreateTime: time.Now().Format("2006-01-02 15:04:05"), - UpdateTime: time.Now().Format("2006-01-02 15:04:05"), - MasterId: utils2.StrToInt64(msg.MasterId), - IsAutoAddedFriends: 0, - }) - if err != nil { - return errors.New("用户暂未注册im系统") - } - gimUser, err = db2.UserGetOneByParams(db.ImDb, msg.MasterId, map[string]interface{}{ - "key": "id", - "value": gimUserId, - }) - if gimUser == nil { - return errors.New("用户暂未注册im系统") - } - } - - //2、查找是否有群 - //officialGroup, err := db.DouShenImGroupGetOneByParamsForOfficial(db.Db, 1) - var officialGroup model.DouShenImGroup - officialGroups, err := db.DouShenImGroupFindByParams(db.Db, map[string]interface{}{ - "key": "kind", - "value": 1, - }) - if err != nil { - return err - } - for _, group := range *officialGroups { - if officialGroup.GroupId != 0 { - continue - } - //统计当前群有多少人 - userGroups, _ := db2.GroupUserFindByParams(db.ImDb, map[string]interface{}{ - "key": "group_id", - "value": group.GroupId, - }) - if len(*userGroups) < 500 { - officialGroup = group - } - } - - if officialGroup.GroupId == 0 { - groupName := "官方【" + utils2.AnyToString(len(*officialGroups)+1) + "】群" - //3、创建群 - resp, err := utils.GetLogicExtClient(cfg.ImLogicRpc.URL, cfg.ImLogicRpc.PORT).CreateGroup(utils.GetCtx("", strconv.FormatInt(gimUser.Id, 10), "0", msg.MasterId), &pb.CreateGroupReq{ - Name: groupName, - AvatarUrl: "", - //Introduction: "官方群", - Introduction: "", - Extra: "", - MemberIds: []int64{}, - }) - if err != nil { - return err - } - - //插入 dou_shen_im_group 记录 - now := time.Now() - _, err = db.DouShenImGroupInsert(db.Db, &model.DouShenImGroup{ - Kind: 1, - Uid: int(msg.Uid), - GroupId: int(resp.GroupId), - IsFull: 0, - Name: groupName, - CreateTime: now, - UpdateTime: now, - }) - if err != nil { - return err - } - } else { - userGroup, err2 := db2.GroupUserGetOneByParams(db.ImDb, 1, map[string]interface{}{ - "key": "group_id", - "value": officialGroup.GroupId, - }) - if err2 != nil { - return err2 - } - if userGroup == nil { - return errors.New("当前官方群暂未设置群主,请联系管理员!!!") - } - - //加入群 - _, err = utils.GetLogicExtClient(cfg.ImLogicRpc.URL, cfg.ImLogicRpc.PORT).AddGroupMembers( - utils.GetCtx("", strconv.FormatInt(userGroup.UserId, 10), "", msg.MasterId), - &pb.AddGroupMembersReq{ - GroupId: int64(officialGroup.GroupId), - UserIds: []int64{gimUser.Id}, - }) - } - return nil -} diff --git a/consume/dou_shen_user_register_for_operation_center.go b/consume/dou_shen_user_register_for_operation_center.go deleted file mode 100644 index f529596..0000000 --- a/consume/dou_shen_user_register_for_operation_center.go +++ /dev/null @@ -1,289 +0,0 @@ -package consume - -import ( - "applet/app/cfg" - "applet/app/db" - db2 "applet/app/db/gim" - "applet/app/db/gim/model" - model2 "applet/app/db/model" - "applet/app/svc" - utils2 "applet/app/utils" - "applet/app/utils/logx" - utils "applet/app/utils/rpc" - "applet/consume/md" - "applet/pkg/pb" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "strconv" - "time" -) - -func DouShenUserRegisterConsumeForOperationCenter(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>DouShenUserRegisterConsumeForOperationCenter>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") - err = handleDouShenUserRegisterConsumeForOperationCenter(res.Body) - if err != nil { - fmt.Println("!!!!!!!err!!!!!!!", err) - _ = res.Reject(false) - - utils2.FilePutContents("douShenUserRegisterConsumeForOperationCenter_err", "[err]:"+err.Error()) - if err.Error() == "用户暂未注册im系统" { - //TODO::重新推回队列末尾,避免造成队列堵塞 - var msg *md.DouShenUserRegisterMessageStructForOperationCenter - json.Unmarshal(res.Body, &msg) - ch.Publish(queue.ExchangeName, msg, queue.RoutKey) - } - } else { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleDouShenUserRegisterConsumeForOperationCenter(msgData []byte) error { - time.Sleep(time.Duration(30) * time.Second) - //1、解析mq中queue的数据结构体 - var msg *md.DouShenUserRegisterMessageStructForOperationCenter - err := json.Unmarshal(msgData, &msg) - if err != nil { - return err - } - //2、查找用户对应im系统中的数据 - gimUser, err := db2.UserGetOneByParams(db.ImDb, msg.MasterId, map[string]interface{}{ - "key": "phone_number", - "value": msg.Phone, - }) - if err != nil { - return err - } - - if gimUser == nil { - if db.DBs[msg.MasterId] == nil { - return nil - } - user, err := db.UserFindByMobile(db.DBs[msg.MasterId], strconv.FormatInt(msg.Phone, 10)) - if err != nil { - return err - } - if user == nil { - return nil - } - userProfile, err := db.UserProfileFindByID(db.DBs[msg.MasterId], user.Uid) - if err != nil { - return err - } - if userProfile == nil { - return nil - } - gimUserId, err := db2.UserInsert(db.ImDb, &model.User{ - PhoneNumber: strconv.FormatInt(msg.Phone, 10), - Nickname: user.Nickname, - AvatarUrl: userProfile.AvatarUrl, - Sex: userProfile.Gender, - CreateTime: time.Now().Format("2006-01-02 15:04:05"), - UpdateTime: time.Now().Format("2006-01-02 15:04:05"), - MasterId: utils2.StrToInt64(msg.MasterId), - IsAutoAddedFriends: 0, - }) - if err != nil { - return errors.New("用户暂未注册im系统") - } - gimUser, err = db2.UserGetOneByParams(db.ImDb, msg.MasterId, map[string]interface{}{ - "key": "id", - "value": gimUserId, - }) - if gimUser == nil { - return errors.New("用户暂未注册im系统") - } - } - - //2、查找是否有群 - //OperationGroup, err := db.DouShenImGroupGetOneByParamsForFans(db.Db, 2, msg.OperationCenterUid) - var OperationGroup model2.DouShenImGroup - operationGroups, err := db.DouShenImGroupFindByParamsByKind(db.Db, 2, map[string]interface{}{ - "key": "uid", - "value": msg.OperationCenterUid, - }) - if err != nil { - return err - } - for _, group := range *operationGroups { - //统计当前群有多少人 - userGroups, err := db2.GroupUserFindByParams(db.ImDb, map[string]interface{}{ - "key": "group_id", - "value": group.GroupId, - }) - if err != nil { - return err - } - if len(*userGroups) < 500 { - OperationGroup = group - } - } - - if OperationGroup.GroupId == 0 { - //创建运营中心群 - operationCenterUser, err := db.UserFindByID(db.DBs[msg.MasterId], msg.OperationCenterUid) - if err != nil { - return err - } - operationCenterGimUser, err := db2.UserGetOneByParams(db.ImDb, msg.MasterId, map[string]interface{}{ - "key": "phone_number", - "value": operationCenterUser.Phone, - }) - if operationCenterGimUser == nil { - return errors.New("运营中心用户暂未注册im系统") - } - var m model2.RegionalAgentUser - _, err = db.DBs[msg.MasterId].Where("uid =?", msg.OperationCenterUid).Get(&m) - if err != nil { - panic(err) - } - regionalAgentRegion, err := db.RegionalAgentRegionGetOneByParams(db.DBs[msg.MasterId], map[string]interface{}{ - "key": "id", - "value": m.RegionId, - }) - if err != nil { - panic(err) - } - - groupName := "抖省" + regionalAgentRegion.Name + "运营中心【" + utils2.AnyToString(len(*operationGroups)) + "】群" - - resp, err := utils.GetLogicExtClient(cfg.ImLogicRpc.URL, cfg.ImLogicRpc.PORT).CreateGroup(utils.GetCtx("", utils2.Int64ToStr(operationCenterGimUser.Id), "", msg.MasterId), &pb.CreateGroupReq{ - Name: groupName, - AvatarUrl: "", - //Introduction: gimUser.Nickname + "的粉丝群", - Introduction: "", - Extra: "", - MemberIds: nil, - }) - if err != nil { - return err - } - //插入 dou_shen_im_group 记录 - now := time.Now() - _, err = db.DouShenImGroupInsert(db.Db, &model2.DouShenImGroup{ - Kind: 2, - Uid: int(msg.OperationCenterUid), - GroupId: int(resp.GroupId), - IsFull: 0, - Name: groupName, - CreateTime: now, - UpdateTime: now, - }) - if err != nil { - return err - } - tmpOperationGroup, err := db.DouShenImGroupGetOneByParams(db.Db, 2, map[string]interface{}{ - "group_id": resp.GroupId, - }) - if err != nil { - return err - } - OperationGroup = *tmpOperationGroup - } - userGroup, err2 := db2.GroupUserGetOneByParams(db.ImDb, 1, map[string]interface{}{ - "key": "group_id", - "value": OperationGroup.GroupId, - }) - if err2 != nil { - return err2 - } - if userGroup == nil { - return errors.New("当前运营中心群暂未设置群主,请联系管理员!!!") - } - - //加入群 - _, err = utils.GetLogicExtClient(cfg.ImLogicRpc.URL, cfg.ImLogicRpc.PORT).AddGroupMembers(utils.GetCtx("", strconv.FormatInt(userGroup.UserId, 10), "", msg.MasterId), &pb.AddGroupMembersReq{ - GroupId: int64(OperationGroup.GroupId), - UserIds: []int64{gimUser.Id}, - }) - - //发送专属红包 - gimSendSpeciallyRedPackageUser, err := db2.DbSysCfg.SysCfgGetOne("send_specially_red_package_user", msg.MasterId) - if err != nil { - return err - } - if gimSendSpeciallyRedPackageUser == nil { - return errors.New("暂未设置专属红包发送用户") - } - sendSpeciallyRedPackageUser, err := db.SysCfgGetOne(db.DBs[msg.MasterId], "send_specially_red_package_user") - if err != nil { - return err - } - amount, err := getSendAmount(msg.MasterId) - if err != nil { - return err - } - args := md.SendRedPackageReq{ - UserId: gimSendSpeciallyRedPackageUser.Val, - DeviceId: "", - Token: "", - Amount: amount, - RedPacketType: 5, - RedPacketNums: 1, - RedPacketContent: "抖省赚钱,大吉大利", - RedPacketSmallContent: gimUser.Nickname + "的专属红包", - ReceiverType: 2, - ReceiverId: int64(OperationGroup.GroupId), - SendTime: utils2.UnixMilliTime(time.Now()), - ToUserIds: []int64{gimUser.Id}, - RedPackageCover: "", - } - err, _ = svc.CurlSendRedPackage(args, msg.MasterId, sendSpeciallyRedPackageUser.Val) - if err != nil { - return err - } - return nil -} - -func getSendAmount(masterId string) (string, error) { - speciallyRedPackageAmountRadio, err := db.SysCfgGetOne(db.DBs[masterId], "specially_red_package_amount_radio") - if err != nil { - return "", err - } - var speciallyRedPackageAmountRadioData []*md.SpeciallyRedPackageAmountRadio - err = json.Unmarshal([]byte(speciallyRedPackageAmountRadio.Val), &speciallyRedPackageAmountRadioData) - if err != nil { - return "", err - } - - var tempSpeciallyRedPackageAmountRadioData []*md.SpeciallyRedPackageAmountRadio - for _, v := range speciallyRedPackageAmountRadioData { - for i := 0; i < utils2.StrToInt(v.Value); i++ { - tempSpeciallyRedPackageAmountRadioData = append(tempSpeciallyRedPackageAmountRadioData, v) - } - } - if len(tempSpeciallyRedPackageAmountRadioData) < 100 { - return "", errors.New("红包金额比例设置有误!") - } - - randInt := utils2.RandInt(99) - min := tempSpeciallyRedPackageAmountRadioData[randInt].From - max := tempSpeciallyRedPackageAmountRadioData[randInt].To - amount := utils2.AnyToString(utils2.RandFloats(utils2.AnyToFloat64(min), utils2.AnyToFloat64(max))) - return amount, nil -} diff --git a/consume/dou_shen_user_register_for_user_register_up_lv.go b/consume/dou_shen_user_register_for_user_register_up_lv.go deleted file mode 100644 index b9f4666..0000000 --- a/consume/dou_shen_user_register_for_user_register_up_lv.go +++ /dev/null @@ -1,68 +0,0 @@ -package consume - -import ( - "applet/app/db" - utils2 "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "strconv" - "time" -) - -func DouShenUserRegisterConsumeForUserRegisterUpLv(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>DouShenUserRegisterConsumeForUserRegisterUpLv>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") - err = handleDouShenUserRegisterConsumeForUserRegisterUpLv(res.Body) - if err != nil { - fmt.Println("!!!!!!!err!!!!!!!", err) - utils2.FilePutContents("douShenUserRegisterConsumeForUserRegisterUpLv_err", "[err]:"+err.Error()) - _ = res.Reject(false) - } else { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleDouShenUserRegisterConsumeForUserRegisterUpLv(msgData []byte) error { - time.Sleep(time.Duration(10) * time.Second) - //1、解析mq中queue的数据结构体 - var msg *md.DouShenUserRegisterMessageStructForUserRegisterUpLv - err := json.Unmarshal(msgData, &msg) - if err != nil { - return err - } - if db.DBs[msg.MasterId] == nil { - return nil - } - eg := db.DBs[msg.MasterId] - levelList, _ := db.UserLevlEgAll(eg) - FindUser(eg, strconv.FormatInt(msg.Uid, 10), msg.MasterId, levelList) - return nil -} diff --git a/consume/init.go b/consume/init.go index a4ad4af..69a91d8 100644 --- a/consume/init.go +++ b/consume/init.go @@ -17,90 +17,10 @@ func Init() { // 增加消费任务队列 func initConsumes() { - //jobs[consumeMd.ZhiosGuideStoreOrderFunName] = ZhiosGuideStoreOrder - //jobs[consumeMd.ZhiosIntegralProxyRechargeFunName] = ZhiosIntegralProxyRecharge - //jobs[consumeMd.ZhiosUserUpLvFunName] = ZhiosUserUpLv - //jobs[consumeMd.CanalGuideOrderByUserUpLvConsume] = CanalGuideOrderByUserUpLvConsume - //jobs[consumeMd.ZhiosOrderFreeFunName] = ZhiosOrderFree - //jobs[consumeMd.ZhiosOrderTotalFunName] = ZhiosOrderTotal - //jobs[consumeMd.ZhiosOrderTotalSecondFunName] = ZhiosOrderTotalSecond - //// - //jobs[consumeMd.ZhiosOrderSettleTotalFunName] = ZhiosSettleTotal - //jobs[consumeMd.ZhiosOrderHjyFunName] = ZhiosOrderHjy - //jobs[consumeMd.ZhiosOrderBuckleFunName] = ZhiosOrderBuckle - //// - //jobs[consumeMd.ZhiosSupplierAfterOrderFunName] = ZhiosSupplierAfterOrder - // - //jobs[consumeMd.ZhiosAppreciationFunName] = ZhiosAppreciation - //jobs[consumeMd.ZhiosValidUserFunName] = ZhiosValidUser - // - //jobs[consumeMd.ZhiosAcquisitionConditionFunName] = ZhiosAcquisitionCondition - // - //jobs[consumeMd.DouShenUserRegisterConsumeForOfficialFunName] = DouShenUserRegisterConsumeForOfficial - //jobs[consumeMd.DouShenUserRegisterConsumeForOperationCenterFunName] = DouShenUserRegisterConsumeForOperationCenter - //jobs[consumeMd.DouShenUserRegisterConsumeForMyRecommenderFunName] = DouShenUserRegisterConsumeForMyRecommender - //jobs[consumeMd.DouShenUserRegisterConsumeForMyFansFunName] = DouShenUserRegisterConsumeForMyFans - //jobs[consumeMd.DouShenUserRegisterConsumeForUserRegisterUpLvFunName] = DouShenUserRegisterConsumeForUserRegisterUpLv - // - //jobs[consumeMd.ZhiosFastReturnOrderPayFunName] = ZhiosFastReturnOrderPay - //jobs[consumeMd.ZhiosFastReturnOrderSuccessFunName] = ZhiosFastReturnOrderSuccess - //jobs[consumeMd.ZhiosFastReturnOrderRefundFunName] = ZhiosFastReturnOrderRefund - //jobs[consumeMd.ZhiosFastReturnOrderRefundSecondFunName] = ZhiosFastReturnOrderRefundSecond - // - //jobs[consumeMd.YoumishangExchangeStoreFunName] = YoumishangExchangeStore - // - //jobs[consumeMd.ZhiosRechargeOrderFailFunName] = ZhiosRechargeOrderFail - // - //jobs[consumeMd.CloudIssuanceAsyncMLoginFunName] = CloudIssuanceAsyncMLoginConsume - //jobs[consumeMd.ZhiosTikTokUpdateFunName] = ZhiosTikTokUpdate - //jobs[consumeMd.ZhiosTikTokAllUpdateFunName] = ZhiosTikTokAllUpdate - // - //jobs[consumeMd.ZhiosCapitalPoolOrderTotalFunName] = ZhiosCapitalPoolOrderTotal - //jobs[consumeMd.ZhiosExpressOrderFail] = ZhiosExpressOrderFail - //jobs[consumeMd.ZhiosWithdrawReward] = ZhiosWithdrawReward - //jobs[consumeMd.ZhiosTaskTotal] = ZhiosTaskTotal - - // - - ////////////////////////////////////// V1 ///////////////////////////////////////////////////// - //jobs[consumeMd.CloudIssuanceMsgCallBackFunName] = CloudIssuanceMsgCallBackConsume - - //////////////////////////////////////// V2 ///////////////////////////////////////////////////// - //jobs[consumeMd.SupplyCloudChainFenxiaoNewChangeFunName] = SupplyCloudChainFenxiaoNewChangeConsume - - //////////////////////////////////////// V3 ///////////////////////////////////////////////////// - //jobs[consumeMd.MallAddSupplyGoodsFunName] = MallAddSupplyGoodsConsume - - //////////////////////////////////////// bigData ///////////////////////////////////////////////////// - //jobs[consumeMd.CanalOrderConsumeFunName] = CanalOrderConsume - //jobs[consumeMd.CanalGuideOrderConsumeFunName] = CanalGuideOrderConsume - //jobs[consumeMd.ZhiOsUserVisitIpAddressConsumeFunName] = ZhiOsUserVisitIpAddressConsume - //jobs[consumeMd.CanalUserVirtualCcoinFlowFunName] = CanalUserVirtualCoinFlowConsume - - //////////////////////////////////////// oneCircles ///////////////////////////////////////////////////// - - //jobs[consumeMd.OneCirclesSignInGreenEnergyFunName] = OneCirclesSignInGreenEnergyConsume - //jobs[consumeMd.OneCirclesStartLevelDividendFunName] = OneCirclesStartLevelDividendConsume - //jobs[consumeMd.OneCirclesActivityCoinAutoExchangeGreenEnergyFunName] = OneCirclesActivityCoinAutoExchangeGreenEnergyConsume - //jobs[consumeMd.OneCirclesActivityCoinAutoExchangeGreenEnergyForTeamFunName] = OneCirclesActivityCoinAutoExchangeGreenEnergyForTeamConsume - //jobs[consumeMd.OneCirclesSettlementPublicGiveActivityCoinFunName] = OneCirclesSettlementPublicGiveActivityCoinConsume - //jobs[consumeMd.OneCirclesSignInCopyGreenEnergyFunName] = OneCirclesSignInCopyGreenEnergyConsume - - //////////////////////////////////////// withdraw ///////////////////////////////////////////////////// - //jobs[consumeMd.WithdrawConsumeFunName] = WithdrawConsume - //jobs[consumeMd.FlexibleEmploymentWithdrawForGongMaoConsumeFunName] = FlexibleEmploymentWithdrawForGongMaoConsume - //jobs[consumeMd.FlexibleEmploymentWithdrawForPupiaoConsumeFunName] = FlexibleEmploymentWithdrawForPupiaoConsume - - //jobs[consumeMd.ZhiosMallGreenCoinConsumeFunName] = ZhiosMallGreenCoinConsume //绿色双链积分 - //jobs[consumeMd.ZhiosOneCirclesCoinConsumeFunName] = ZhiosOneCirclesCoinConsume //一个圈圈虚拟币变化 - - //////////////////////////////////////// autoRepaid ///////////////////////////////////////////////////// - //jobs[consumeMd.InstallmentPaymentAutoRepaidConsumeFunName] = InstallmentPaymentAutoRepaidConsume //分期付 - 自动扣款 - - ////////////////////////////////////// SuperCloudIssuance ///////////////////////////////////////////////////// - //jobs[consumeMd.SuperCloudIssuanceMsgCallBackFunName] = SuperCloudIssuanceMsgCallBackConsume - //jobs[consumeMd.SuperCloudIssuanceAsyncMLoginFunName] = SuperCloudIssuanceAsyncMLoginConsume + ////////////////////////////////////// order_statistics ///////////////////////////////////////////////////// + jobs[consumeMd.CanalGuideOrderForStatistics] = CanalGuideOrderForStatistics + jobs[consumeMd.CanalFinWithdrawApplyForStatistics] = CanalFinWithdrawApplyForStatistics } func Run() { diff --git a/consume/mall_add_supply_goods.go b/consume/mall_add_supply_goods.go deleted file mode 100644 index 9325ff2..0000000 --- a/consume/mall_add_supply_goods.go +++ /dev/null @@ -1,91 +0,0 @@ -package consume - -import ( - svc2 "applet/app/svc" - "applet/app/utils/logx" - "applet/consume/md" - md3 "applet/mall/md" - "applet/mall/svc" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/gin-gonic/gin" - "github.com/jinzhu/copier" - "github.com/streadway/amqp" - "strings" -) - -func MallAddSupplyGoodsConsume(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - fmt.Println(">>>>>>>>>>>>>>>>MallAddSupplyGoodsConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleMallAddSupplyGoodsConsume(res.Body) - if err != nil { - fmt.Println("*****************err*************************", err) - } - _ = res.Ack(true) - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleMallAddSupplyGoodsConsume(msgData []byte) error { - //解析mq中queue的数据结构体 - var pushStuct struct { - Args struct { - GoodsInfo []*md3.OfficialGoods `json:"goods_info"` - md3.OfficialGoodsConditions - } `json:"args"` - Mid string `json:"mid"` - } - err := json.Unmarshal(msgData, &pushStuct) - if err != nil { - panic(err) - } - //设置masterId - var c = &gin.Context{} - if pushStuct.Mid == "123456" { - return nil - } - c.Set("mid", pushStuct.Mid) - var t struct { - GoodsInfo []*md3.OfficialGoods `json:"goods_info"` - md3.OfficialGoodsConditions - } - t = pushStuct.Args - var conditions md3.OfficialGoodsConditions - conditions.CategoryId = t.CategoryId - conditions.AddPriceBase = t.AddPriceBase - conditions.AddPriceNum = t.AddPriceNum - conditions.AddPriceType = t.AddPriceType - conditions.NumType = t.NumType - engine := svc2.MasterDb(c) - for _, goods := range t.GoodsInfo { - var b2cGoods md3.OfficialGoods - copier.Copy(&b2cGoods, goods) - ex := strings.Split(b2cGoods.Price, "-") - b2cGoods.Price = ex[0] - err1 := svc.AddOfficialGoods(c, engine, &b2cGoods, &conditions) - if err1 != nil { - return err1 - } - } - return nil -} diff --git a/consume/md/consume_key.go b/consume/md/consume_key.go index a5473a5..c9ac63c 100644 --- a/consume/md/consume_key.go +++ b/consume/md/consume_key.go @@ -11,578 +11,27 @@ type MqQueue struct { } var RabbitMqQueueKeyList = []*MqQueue{ - { - ExchangeName: "", - Name: "cloud_issuance_async_mlogin", - Type: SimpleQueueType, - IsPersistent: false, - RoutKey: "", - BindKey: "", - ConsumeFunName: "CloudIssuanceAsyncMLoginConsume", - }, - { - ExchangeName: "", - Name: "super_cloud_issuance_async_mlogin", - Type: SimpleQueueType, - IsPersistent: false, - RoutKey: "", - BindKey: "", - ConsumeFunName: "SuperCloudIssuanceAsyncMLoginConsume", - }, - { - ExchangeName: "zhios.cloud.issuance.msg.callback.exchange", - Name: "cloud_issuance_msg_call_back", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "", - BindKey: "", - ConsumeFunName: "CloudIssuanceMsgCallBackConsume", - }, - { - ExchangeName: "zhios.super.cloud.issuance.msg.callback.exchange", - Name: "super_cloud_issuance_msg_call_back", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "", - BindKey: "", - ConsumeFunName: "SuperCloudIssuanceMsgCallBackConsume", - }, - { - ExchangeName: "zhios.cloud_chain.fenxiao.newChange.exchange", - Name: "cloud_chain_fenxiao_newChange", - Type: FanOutQueueType, - IsPersistent: false, - RoutKey: "", - BindKey: "", - ConsumeFunName: "SupplyCloudChainFenxiaoNewChangeConsume", - }, - { - ExchangeName: "zhios.addSupplyGoods.exchange", - Name: "mall_add_supply_goods", - Type: FanOutQueueType, - IsPersistent: false, - RoutKey: "", - BindKey: "", - ConsumeFunName: "MallAddSupplyGoodsConsume", - }, { ExchangeName: "canal.topic", - Name: "canal_order", - Type: TopicQueueType, - IsPersistent: false, - RoutKey: "canal_mall_order", - BindKey: "", - ConsumeFunName: "CanalOrderConsume", - }, - { - ExchangeName: "canal.topic", - Name: "canal_guide_order", - Type: TopicQueueType, - IsPersistent: false, - RoutKey: "canal_order_list", - BindKey: "", - ConsumeFunName: "CanalGuideOrderConsume", - }, - { - ExchangeName: "canal.topic", - Name: "canal_guide_order_by_user_up_lv", + Name: "canal_guide_order_for_statistics", Type: TopicQueueType, IsPersistent: false, RoutKey: "canal_order_list", BindKey: "", - ConsumeFunName: "CanalGuideOrderByUserUpLvConsume", - }, - { - ExchangeName: "zhios.app.user.visit.ip.address.exchange", - Name: "zhios_user_visit_ip_address_queue", - Type: FanOutQueueType, - IsPersistent: false, - RoutKey: "queue_one", - BindKey: "", - ConsumeFunName: "ZhiOsUserVisitIpAddressConsume", - }, - { - ExchangeName: "zhios.order.fast.return.exchange", - Name: "zhios_fast_return_order_pay", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "order_pay", - BindKey: "", - ConsumeFunName: "ZhiosFastReturnOrderPay", - }, - { - ExchangeName: "zhios.order.fast.return.exchange", - Name: "zhios_fast_return_order_success", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "order_success", - BindKey: "", - ConsumeFunName: "ZhiosFastReturnOrderSuccess", - }, - { - ExchangeName: "zhios.order.fast.return.exchange", - Name: "zhios_fast_return_order_refund", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "order_refund", - BindKey: "", - ConsumeFunName: "ZhiosFastReturnOrderRefund", - }, - { - ExchangeName: "zhios.order.fast.return.exchange", - Name: "zhios_fast_return_order_refund_second", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "order_refund_second", - BindKey: "", - ConsumeFunName: "ZhiosFastReturnOrderRefundSecond", - }, - { - ExchangeName: "zhios.doushen.user.register.exchange", - Name: "zhios_doushen_user_register_my_fans", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "my_fans", - BindKey: "my_fans", - ConsumeFunName: "DouShenUserRegisterConsumeForMyFans", - }, - { - ExchangeName: "zhios.doushen.user.register.exchange", - Name: "zhios_doushen_user_register_operation_center", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "operation_center", - BindKey: "operation_center", - ConsumeFunName: "DouShenUserRegisterConsumeForOperationCenter", - }, - { - ExchangeName: "zhios.doushen.user.register.exchange", - Name: "zhios_doushen_user_register_my_recommender", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "my_recommender", - BindKey: "my_recommender", - ConsumeFunName: "DouShenUserRegisterConsumeForMyRecommender", - }, - { - ExchangeName: "zhios.doushen.user.register.exchange", - Name: "zhios_doushen_user_register_official", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "official", - BindKey: "official", - ConsumeFunName: "DouShenUserRegisterConsumeForOfficial", - }, - { - ExchangeName: "zhios.doushen.user.register.exchange", - Name: "zhios_doushen_user_register_user_comm_up_lv", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "user_register_comm_up_lv", - BindKey: "user_register_comm_up_lv", - ConsumeFunName: "DouShenUserRegisterConsumeForUserRegisterUpLv", - }, - { - ExchangeName: "canal.topic", - Name: "canal_mall_ord_for_you_mi_shang", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "canal_mall_order", - BindKey: "", - ConsumeFunName: "CanalMallOrdForYouMiShang", - }, - { - ExchangeName: "zhios.youmishang.exchange", - Name: "zhios_youmishang_exchange_store", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "store", - BindKey: "store", - ConsumeFunName: "YoumishangExchangeStore", - }, - { - ExchangeName: "zhios.recharge.order.exchange", - Name: "zhios_recharge_order_fail", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "order_fail", - BindKey: "", - ConsumeFunName: "ZhiosRechargeOrderFail", - }, - { - ExchangeName: "zhios.tikTok.exchange", - Name: "zhios_tikTok_update", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "update", - BindKey: "", - ConsumeFunName: "ZhiosTikTokUpdate", - }, - { - ExchangeName: "zhios.tikTok.exchange", - Name: "zhios_tikTok_all_update", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "all_update", - BindKey: "", - ConsumeFunName: "ZhiosTikTokAllUpdate", - }, - { - ExchangeName: "zhios.capital_pool.order_total.exchange", - Name: "zhios_capital_pool_order_total", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "order_total", - BindKey: "", - ConsumeFunName: "ZhiosCapitalPoolOrderTotal", - }, - { - ExchangeName: "zhios.acquisition.exchange", - Name: "zhios_acquisition_condition", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "condition", - BindKey: "", - ConsumeFunName: "ZhiosAcquisitionCondition", - }, - { - ExchangeName: "zhios.acquisition.exchange", - Name: "zhios_acquisition_condition_dev", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "acq_dev", - BindKey: "", - ConsumeFunName: "ZhiosAcquisitionConditionDev", - }, - { - ExchangeName: "zhios.recharge.order.exchange", - Name: "zhios_recharge_order_fail_dev", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "order_fail_dev", - BindKey: "", - ConsumeFunName: "ZhiosRechargeOrderFailDev", - }, - { - ExchangeName: "zhios.express.order.exchange", - Name: "zhios_express_order_fail", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "order_fail", - BindKey: "", - ConsumeFunName: "zhiosExpressOrderFail", - }, - { - ExchangeName: "zhios.withdraw.reward.exchange", - Name: "zhios_withdraw_reward", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "withdraw_reward", - BindKey: "", - ConsumeFunName: "zhiosWithdrawReward", - }, - { - ExchangeName: "zhios.task.exchange", - Name: "zhios_task_total", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "task_total", - BindKey: "", - ConsumeFunName: "zhiosTaskTotal", - }, - { - ExchangeName: "zhios.user_valid.exchange", - Name: "zhios_user_valid", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "user_valid", - BindKey: "", - ConsumeFunName: "ZhiosValidUser", - }, - { - ExchangeName: "zhios.appreciation.exchange", - Name: "zhios_appreciation", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "appreciation", - BindKey: "", - ConsumeFunName: "ZhiosAppreciation", - }, - { - ExchangeName: "zhios.appreciation.exchange", - Name: "zhios_appreciation_dev", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "appreciation_dev", - BindKey: "", - ConsumeFunName: "ZhiosAppreciationDev", - }, - { - ExchangeName: "zhios.guide_store.exchange", - Name: "zhios_guide_store_order", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "guide_store_order", - BindKey: "", - ConsumeFunName: "ZhiosGuideStoreOrder", - }, - { - ExchangeName: "zhios.supplier_after_order.exchange", - Name: "zhios_supplier_after_order", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "refund", - BindKey: "", - ConsumeFunName: "ZhiosSupplierAfterOrder", - }, - { - ExchangeName: "zhios.order_buckle.exchange", - Name: "zhios_order_buckle", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "order_buckle", - BindKey: "", - ConsumeFunName: "ZhiosOrderBuckle", - }, - { - ExchangeName: "zhios.order_hjy.exchange", - Name: "zhios_order_hjy", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "order_hjy", - BindKey: "", - ConsumeFunName: "ZhiosOrderHjy", - }, - { - ExchangeName: "zhios.order_settle_total.exchange", - Name: "zhios_order_settle_total", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "order_settle_total", - BindKey: "", - ConsumeFunName: "ZhiosOrderSettleTotal", - }, - { - ExchangeName: "zhios.order_total.exchange", - Name: "zhios_order_total", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "order_total", - BindKey: "", - ConsumeFunName: "ZhiosOrderTotal", - }, - { - ExchangeName: "zhios.order_total.exchange", - Name: "zhios_order_total_second", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "order_total_second", - BindKey: "", - ConsumeFunName: "ZhiosOrderTotalSecond", - }, - { - ExchangeName: "zhios.order_free.exchange", - Name: "zhios_order_free", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "order_free", - BindKey: "", - ConsumeFunName: "ZhiosOrderFree", - }, - { - ExchangeName: "zhios.user_up_lv.exchange", - Name: "zhios_user_up_lv", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "user_up_lv", - BindKey: "", - ConsumeFunName: "ZhiosUserUpLv", - }, - { - ExchangeName: "zhios.integral_proxy_recharge.exchange", - Name: "zhios_integral_proxy_recharge", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "integral_proxy_recharge", - BindKey: "", - ConsumeFunName: "ZhiosIntegralProxyRecharge", - }, - { - ExchangeName: "zhios.mall_green_coin_consume.exchange", - Name: "zhios_mall_green_coin_consume", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "mall_green_coin_consume", - BindKey: "", - ConsumeFunName: "ZhiosMallGreenCoinConsume", + ConsumeFunName: "CanalGuideOrderForStatistics", }, { ExchangeName: "canal.topic", - Name: "user_virtual_coin_flow_aggregation", + Name: "canal_fin_withdraw_apply_for_statistics", Type: TopicQueueType, IsPersistent: false, - RoutKey: "canal_user_virtual_coin_flow_aggregation", - BindKey: "", - ConsumeFunName: "ZhiosOneCirclesCoinConsume", - }, - { - ExchangeName: "canal.topic", - Name: "canal_user_virtual_coin_flow", - Type: TopicQueueType, - IsPersistent: false, - RoutKey: "canal_user_virtual_coin_flow", - BindKey: "", - ConsumeFunName: "CanalUserVirtualCoinFlowConsume", - }, - { - ExchangeName: "one.circles", - Name: "one_circles_sign_in_green_energy", - Type: TopicQueueType, - IsPersistent: false, - RoutKey: "sign_in", - BindKey: "", - ConsumeFunName: "OneCirclesSignInGreenEnergyConsume", - }, - { - ExchangeName: "one.circles", - Name: "one_circles_start_level_dividend", - Type: TopicQueueType, - IsPersistent: false, - RoutKey: "star_level_dividend", - BindKey: "", - ConsumeFunName: "OneCirclesStartLevelDividendConsume", - }, - { - ExchangeName: "one.circles", - Name: "one_circles_auto_exchange_green_energy_to_person_1", - Type: TopicQueueType, - IsPersistent: false, - RoutKey: "auto_exchange_green_energy_to_person_1", - BindKey: "", - ConsumeFunName: "OneCirclesActivityCoinAutoExchangeGreenEnergyConsume", - }, - { - ExchangeName: "one.circles", - Name: "one_circles_auto_exchange_green_energy_to_team", - Type: TopicQueueType, - IsPersistent: false, - RoutKey: "auto_exchange_green_energy_to_team", - BindKey: "", - ConsumeFunName: "OneCirclesActivityCoinAutoExchangeGreenEnergyForTeamConsume", - }, - { - ExchangeName: "one.circles", - Name: "one_circles_settlement_public_give_activity_coin", - Type: TopicQueueType, - IsPersistent: false, - RoutKey: "settlement_public_give_activity_coin", - BindKey: "", - ConsumeFunName: "OneCirclesSettlementPublicGiveActivityCoinConsume", - }, - { - ExchangeName: "one.circles", - Name: "one_circles_sign_in_green_energy_copy", - Type: TopicQueueType, - IsPersistent: false, - RoutKey: "sign_in_copy", - BindKey: "", - ConsumeFunName: "OneCirclesSignInCopyGreenEnergyConsume", - }, - { - ExchangeName: "zhios.app.user.withdraw.apply.exchange", - Name: "zhios_app_user_withdraw_apply_queue", - Type: FanOutQueueType, - IsPersistent: false, - RoutKey: "queues_one", - BindKey: "", - ConsumeFunName: "WithdrawConsume", - }, - { - ExchangeName: "zhios.app.user.withdraw.apply.flexible.employment.exchange", - Name: "zhios_app_user_withdraw_apply_gongmao_queue", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "gongmao", - BindKey: "", - ConsumeFunName: "FlexibleEmploymentWithdrawForGongMaoConsume", - }, - { - ExchangeName: "zhios.app.user.withdraw.apply.flexible.employment.exchange", - Name: "zhios_app_user_withdraw_apply_pupiao_queue", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "pupiao", - BindKey: "", - ConsumeFunName: "FlexibleEmploymentWithdrawForPupiaoConsume", - }, - { - ExchangeName: "installment.payment", - Name: "zhios_installment_payment_auto_repaid", - Type: DirectQueueType, - IsPersistent: false, - RoutKey: "auto_repaid", + RoutKey: "canal_fin_withdraw_apply", BindKey: "", - ConsumeFunName: "InstallmentPaymentAutoRepaidConsume", + ConsumeFunName: "CanalFinWithdrawApplyForStatistics", }, } const ( - ZhiosUserRelateFunName = "ZhiosUserRelate" - ZhiosIntegralProxyRechargeFunName = "ZhiosIntegralProxyRecharge" - ZhiosMallGreenCoinConsumeFunName = "ZhiosMallGreenCoinConsume" - ZhiosOneCirclesCoinConsumeFunName = "ZhiosOneCirclesCoinConsume" - ZhiosUserUpLvFunName = "ZhiosUserUpLv" - CanalGuideOrderByUserUpLvConsume = "CanalGuideOrderByUserUpLvConsume" - ZhiosOrderFreeFunName = "ZhiosOrderFree" - ZhiosOrderSettleTotalFunName = "ZhiosOrderSettleTotal" - ZhiosOrderTotalFunName = "ZhiosOrderTotal" - ZhiosOrderTotalSecondFunName = "ZhiosOrderTotalSecond" - ZhiosOrderHjyFunName = "ZhiosOrderHjy" - ZhiosOrderBuckleFunName = "ZhiosOrderBuckle" - ZhiosSupplierAfterOrderFunName = "ZhiosSupplierAfterOrder" - CanalOrderConsumeFunName = "CanalOrderConsume" - CanalGuideOrderConsumeFunName = "CanalGuideOrderConsume" - ZhiOsUserVisitIpAddressConsumeFunName = "ZhiOsUserVisitIpAddressConsume" - DouShenUserRegisterConsumeForOfficialFunName = "DouShenUserRegisterConsumeForOfficial" - DouShenUserRegisterConsumeForOperationCenterFunName = "DouShenUserRegisterConsumeForOperationCenter" - DouShenUserRegisterConsumeForMyRecommenderFunName = "DouShenUserRegisterConsumeForMyRecommender" - DouShenUserRegisterConsumeForMyFansFunName = "DouShenUserRegisterConsumeForMyFans" - DouShenUserRegisterConsumeForUserRegisterUpLvFunName = "DouShenUserRegisterConsumeForUserRegisterUpLv" - ZhiosFastReturnOrderPayFunName = "ZhiosFastReturnOrderPay" - ZhiosFastReturnOrderSuccessFunName = "ZhiosFastReturnOrderSuccess" - ZhiosFastReturnOrderRefundFunName = "ZhiosFastReturnOrderRefund" - ZhiosFastReturnOrderRefundSecondFunName = "ZhiosFastReturnOrderRefundSecond" - CanalMallOrdForYouMiShangFunName = "CanalMallOrdForYouMiShang" - YoumishangExchangeStoreFunName = "YoumishangExchangeStore" - ZhiosRechargeOrderFailFunName = "ZhiosRechargeOrderFail" - ZhiosRechargeOrderFailDevFunName = "ZhiosRechargeOrderFailDev" - ZhiosCapitalPoolOrderTotalFunName = "ZhiosCapitalPoolOrderTotal" - ZhiosExpressOrderFail = "zhiosExpressOrderFail" - ZhiosWithdrawReward = "zhiosWithdrawReward" - ZhiosTikTokUpdateFunName = "ZhiosTikTokUpdate" - ZhiosTikTokAllUpdateFunName = "ZhiosTikTokAllUpdate" - CloudIssuanceAsyncMLoginFunName = "CloudIssuanceAsyncMLoginConsume" - CloudIssuanceMsgCallBackFunName = "CloudIssuanceMsgCallBackConsume" - SuperCloudIssuanceAsyncMLoginFunName = "SuperCloudIssuanceAsyncMLoginConsume" - SuperCloudIssuanceMsgCallBackFunName = "SuperCloudIssuanceMsgCallBackConsume" - ZhiosAcquisitionConditionFunName = "ZhiosAcquisitionCondition" - ZhiosValidUserFunName = "ZhiosValidUser" - ZhiosAppreciationFunName = "ZhiosAppreciation" - ZhiosAppreciationDevFunName = "ZhiosAppreciationDev" - ZhiosGuideStoreOrderFunName = "ZhiosGuideStoreOrder" - ZhiosAcquisitionConditionDevFunName = "ZhiosAcquisitionConditionDev" - SupplyCloudChainFenxiaoNewChangeFunName = "SupplyCloudChainFenxiaoNewChangeConsume" - MallAddSupplyGoodsFunName = "MallAddSupplyGoodsConsume" - CanalUserVirtualCcoinFlowFunName = "CanalUserVirtualCoinFlowConsume" - OneCirclesSignInGreenEnergyFunName = "OneCirclesSignInGreenEnergyConsume" - OneCirclesStartLevelDividendFunName = "OneCirclesStartLevelDividendConsume" - OneCirclesSignInCopyGreenEnergyFunName = "OneCirclesSignInCopyGreenEnergyConsume" - OneCirclesActivityCoinAutoExchangeGreenEnergyFunName = "OneCirclesActivityCoinAutoExchangeGreenEnergyConsume" - OneCirclesActivityCoinAutoExchangeGreenEnergyForTeamFunName = "OneCirclesActivityCoinAutoExchangeGreenEnergyForTeamConsume" - OneCirclesSettlementPublicGiveActivityCoinFunName = "OneCirclesSettlementPublicGiveActivityCoinConsume" - WithdrawConsumeFunName = "WithdrawConsume" - FlexibleEmploymentWithdrawForGongMaoConsumeFunName = "FlexibleEmploymentWithdrawForGongMaoConsume" - FlexibleEmploymentWithdrawForPupiaoConsumeFunName = "FlexibleEmploymentWithdrawForPupiaoConsume" - ZhiosTaskTotal = "zhiosTaskTotal" - InstallmentPaymentAutoRepaidConsumeFunName = "InstallmentPaymentAutoRepaidConsume" + CanalFinWithdrawApplyForStatistics = "CanalFinWithdrawApplyForStatistics" + CanalGuideOrderForStatistics = "CanalGuideOrderForStatistics" ) diff --git a/consume/md/md_canal_fin_withdraw_apply_consume.go b/consume/md/md_canal_fin_withdraw_apply_consume.go new file mode 100644 index 0000000..5fd829e --- /dev/null +++ b/consume/md/md_canal_fin_withdraw_apply_consume.go @@ -0,0 +1,22 @@ +package md + +type CanalFinWithdrawApply struct { + Id string `json:"id"` + Amount string `json:"amount"` + State string `json:"state"` + CreateAt string `json:"create_at"` + FeeType string `json:"fee_type"` +} + +type CanalFinWithdrawApplyMessage[T any] struct { + Data []T `json:"data"` + Database string `json:"database"` + ES int64 `json:"es"` + ID int64 `json:"id"` + IsDdl bool `json:"isDdl"` + Old []T `json:"old"` + PkNames []string `json:"pkNames"` + Table string `json:"table"` + TS int64 `json:"ts"` + Type string `json:"type"` +} diff --git a/consume/md/md_canal_guide_order_consume.go b/consume/md/md_canal_guide_order_consume.go index e8e80a0..83ea83b 100644 --- a/consume/md/md_canal_guide_order_consume.go +++ b/consume/md/md_canal_guide_order_consume.go @@ -16,6 +16,11 @@ type CanalGuideOrder struct { ItemNum string `json:"item_num"` SysCommission string `json:"sys_commission"` CreateAt string `json:"create_at"` + PvdSettleAt string `json:"pvd_settle_at"` + SettleAt string `json:"settle_at"` + Pvd string `json:"pvd"` + Ext string `json:"ext"` + BenefitAll string `json:"benefit_all"` } type CanalGuideOrderMessage[T any] struct { diff --git a/consume/one_circles_activity_coin_auto_exchange_green_energy_consume.go b/consume/one_circles_activity_coin_auto_exchange_green_energy_consume.go deleted file mode 100644 index 4d5d4a9..0000000 --- a/consume/one_circles_activity_coin_auto_exchange_green_energy_consume.go +++ /dev/null @@ -1,159 +0,0 @@ -package consume - -import ( - "applet/app/cfg" - "applet/app/db" - utils2 "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "applet/mall/utils" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - db2 "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/db" - md2 "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" - "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule/one_circles" - "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule/one_circles/enum" - "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule/one_circles/svc" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "time" -) - -func OneCirclesActivityCoinAutoExchangeGreenEnergyConsume(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>OneCirclesActivityCoinAutoExchangeGreenEnergyConsume>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(40) - delivery := ch.Consume(queue.Name, false) - - one_circles.Init(cfg.RedisAddr) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - err = handleOneCirclesActivityCoinAutoExchangeGreenEnergyConsume(res.Body) - if err != nil { - fmt.Println("OneCirclesActivityCoinAutoExchangeGreenEnergyConsume_ERR:::::", err.Error()) - utils2.FilePutContents("OneCirclesActivityCoinAutoExchangeGreenEnergyConsume_ERR", utils2.SerializeStr(map[string]interface{}{ - "body": res.Body, - "err": err.Error(), - })) - } - //_ = res.Reject(false) - err = res.Ack(true) - fmt.Println("err ::: ", err) - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleOneCirclesActivityCoinAutoExchangeGreenEnergyConsume(msgData []byte) error { - time.Sleep(time.Duration(100) * time.Microsecond) //休眠0.1毫秒 - //1、解析mq中queue的数据结构体 - var msg *md2.OneCirclesStructForAutoExchangeGreenEnergy - err := json.Unmarshal(msgData, &msg) - if err != nil { - return err - } - engine := db.DBs[msg.MasterId] - //2、查找 `one_circles_green_energy_basic_setting` 基础设置 - oneCirclesGreenEnergyBasicSetting, cb, err := svc.GetPrice(engine, msg.MasterId) - if err != nil { - return err - } - if cb != nil { - defer cb() // 释放锁 - } - //oneCirclesGreenEnergyBasicSetting, err := db2.OneCirclesGreenEnergyBasicSettingGetOneByParams(engine, map[string]interface{}{ - // "key": "is_open", - // "value": 1, - //}) - //if err != nil { - // return err - //} - //if oneCirclesGreenEnergyBasicSetting == nil { - // return nil - //} - - session := engine.NewSession() - defer func() { - session.Close() - if err := recover(); err != nil { - _ = logx.Error(err) - } - }() - session.Begin() - //3.1计算涨价公式 - err1, values, _, afterPriceValue := one_circles.NewCalcPriceIncreaseFormula(msg.AutoExchangeNumsAmount, oneCirclesGreenEnergyBasicSetting) - if err1 != nil { - _ = session.Rollback() - return err1 - } - //3.2给相应的用户加上个人的绿色积分(可用数量) - err = rule.DealUserCoin(session, md2.DealUserCoinReq{ - Kind: "add", - Mid: msg.MasterId, - Title: md2.OneCirclesPersonalActiveCoinExchangeGreenEnergy, - TransferType: md2.OneCirclesPersonalActiveCoinExchangeGreenEnergyForUserVirtualCoinFlow, - OrdId: "", - CoinId: oneCirclesGreenEnergyBasicSetting.PersonGreenEnergyCoinId, - Uid: msg.Uid, - Amount: utils.StrToFloat64(values), - }) - if err != nil { - _ = session.Rollback() - fmt.Println("err:::::33333", err.Error()) - return err - } - - //4.1给相应的用户减去个人活跃积分 - err = rule.DealUserCoin(session, md2.DealUserCoinReq{ - Kind: "sub", - Mid: msg.MasterId, - Title: md2.OneCirclesPersonalActiveCoinExchangeToBeGreenEnergy, - TransferType: md2.OneCirclesPersonalActiveCoinExchangeToBeGreenEnergyForUserVirtualCoinFlow, - OrdId: "", - CoinId: msg.CoinId, - Uid: msg.Uid, - Amount: utils.StrToFloat64(msg.Amount), - }) - if err != nil { - _ = session.Rollback() - fmt.Println("err:::::33333", err.Error()) - return err - } - //4.2减少“原始数量”中的绿色能量 - err = one_circles.DealAvailableGreenEnergyCoin(session, int(enum.PersonalActivePointRedemption), utils.StrToFloat64(values), utils.StrToFloat64(msg.AutoExchangeNumsAmount), enum.PersonalActivePointRedemption.String(), oneCirclesGreenEnergyBasicSetting, afterPriceValue) - if err != nil { - _ = session.Rollback() - fmt.Println("err:::::44444", err.Error()) - return err - } - - //5、修改 one_circles_green_energy_basic_setting 的 now_price - _, err = db2.OneCirclesGreenEnergyBasicSettingUpdate(session, oneCirclesGreenEnergyBasicSetting.Id, oneCirclesGreenEnergyBasicSetting) - if err != nil { - _ = session.Rollback() - fmt.Println("err:::::77777", err.Error()) - return err - } - err = session.Commit() - if err != nil { - _ = session.Rollback() - return errors.New("事务提交失败") - } - return nil -} diff --git a/consume/one_circles_activity_coin_auto_exchange_green_energy_for_team_consume.go b/consume/one_circles_activity_coin_auto_exchange_green_energy_for_team_consume.go deleted file mode 100644 index 7301a81..0000000 --- a/consume/one_circles_activity_coin_auto_exchange_green_energy_for_team_consume.go +++ /dev/null @@ -1,160 +0,0 @@ -package consume - -import ( - "applet/app/cfg" - "applet/app/db" - utils2 "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "applet/mall/utils" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - db2 "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/db" - md2 "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" - "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule/one_circles" - "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule/one_circles/enum" - "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule/one_circles/svc" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "time" -) - -func OneCirclesActivityCoinAutoExchangeGreenEnergyForTeamConsume(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>OneCirclesActivityCoinAutoExchangeGreenEnergyForTeamConsume>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(20) - delivery := ch.Consume(queue.Name, false) - - one_circles.Init(cfg.RedisAddr) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - err = handleOneCirclesActivityCoinAutoExchangeGreenEnergyForTeamConsume(res.Body) - if err != nil { - fmt.Println("OneCirclesActivityCoinAutoExchangeGreenEnergyForTeamConsume_ERR:::::", err.Error()) - utils2.FilePutContents("OneCirclesActivityCoinAutoExchangeGreenEnergyForTeamConsume_ERR", utils2.SerializeStr(map[string]interface{}{ - "body": res.Body, - "err": err.Error(), - })) - } - //_ = res.Reject(false) - err = res.Ack(true) - fmt.Println("err ::: ", err) - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleOneCirclesActivityCoinAutoExchangeGreenEnergyForTeamConsume(msgData []byte) error { - time.Sleep(time.Duration(200) * time.Microsecond) //休眠0.2毫秒 - //1、解析mq中queue的数据结构体 - var msg *md2.OneCirclesStructForAutoExchangeGreenEnergy - err := json.Unmarshal(msgData, &msg) - if err != nil { - return err - } - engine := db.DBs[msg.MasterId] - //2、查找 `one_circles_green_energy_basic_setting` 基础设置 - oneCirclesGreenEnergyBasicSetting, cb, err := svc.GetPrice(engine, msg.MasterId) - if err != nil { - return err - } - if cb != nil { - defer cb() // 释放锁 - } - // - //oneCirclesGreenEnergyBasicSetting, err := db2.OneCirclesGreenEnergyBasicSettingGetOneByParams(engine, map[string]interface{}{ - // "key": "is_open", - // "value": 1, - //}) - //if err != nil { - // return err - //} - //if oneCirclesGreenEnergyBasicSetting == nil { - // return nil - //} - - session := engine.NewSession() - defer func() { - session.Close() - if err := recover(); err != nil { - _ = logx.Error(err) - } - }() - session.Begin() - //3.1计算涨价公式 - err1, values, _, afterPriceValue := one_circles.NewCalcPriceIncreaseFormula(msg.AutoExchangeNumsAmount, oneCirclesGreenEnergyBasicSetting) - if err1 != nil { - _ = session.Rollback() - return err1 - } - //3.2给相应的用户加上个人的绿色积分(结算数量) - err = rule.DealUserCoin(session, md2.DealUserCoinReq{ - Kind: "add", - Mid: msg.MasterId, - Title: md2.OneCirclesTeamActiveCoinExchangeGreenEnergy, - TransferType: md2.OneCirclesTeamActiveCoinExchangeGreenEnergyForUserVirtualCoinFlow, - OrdId: "", - CoinId: oneCirclesGreenEnergyBasicSetting.TeamGreenEnergyCoinId, - Uid: msg.Uid, - Amount: utils.StrToFloat64(values), - }) - if err != nil { - _ = session.Rollback() - fmt.Println("err:::::33333", err.Error()) - return err - } - - //4.1给相应的用户减去团队活跃积分 - err = rule.DealUserCoin(session, md2.DealUserCoinReq{ - Kind: "sub", - Mid: msg.MasterId, - Title: md2.OneCirclesTeamActiveCoinExchangeToBeGreenEnergy, - TransferType: md2.OneCirclesTeamActiveCoinExchangeToBeGreenEnergyForUserVirtualCoinFlow, - OrdId: "", - CoinId: msg.CoinId, - Uid: msg.Uid, - Amount: utils.StrToFloat64(msg.Amount), - }) - if err != nil { - _ = session.Rollback() - fmt.Println("err:::::33333", err.Error()) - return err - } - //4.2减少“原始数量”中的绿色能量 - err = one_circles.DealAvailableGreenEnergyCoin(session, int(enum.TeamActivePointRedemption), utils.StrToFloat64(values), utils.StrToFloat64(msg.AutoExchangeNumsAmount), enum.TeamActivePointRedemption.String(), oneCirclesGreenEnergyBasicSetting, afterPriceValue) - if err != nil { - _ = session.Rollback() - fmt.Println("err:::::44444", err.Error()) - return err - } - - //5、修改 one_circles_green_energy_basic_setting 的 now_price - _, err = db2.OneCirclesGreenEnergyBasicSettingUpdate(session, oneCirclesGreenEnergyBasicSetting.Id, oneCirclesGreenEnergyBasicSetting) - if err != nil { - _ = session.Rollback() - fmt.Println("err:::::77777", err.Error()) - return err - } - err = session.Commit() - if err != nil { - _ = session.Rollback() - return errors.New("事务提交失败") - } - return nil -} diff --git a/consume/one_circles_settlement_public_activity_coin_consume.go b/consume/one_circles_settlement_public_activity_coin_consume.go deleted file mode 100644 index 7cf7403..0000000 --- a/consume/one_circles_settlement_public_activity_coin_consume.go +++ /dev/null @@ -1,100 +0,0 @@ -package consume - -import ( - "applet/app/cfg" - "applet/app/db" - utils2 "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - md2 "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" - "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule/one_circles" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "time" -) - -func OneCirclesSettlementPublicGiveActivityCoinConsume(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>OneCirclesSettlementPublicGiveActivityCoinConsume>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - one_circles.Init(cfg.RedisAddr) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - err = handleOneCirclesSettlementPublicGiveActivityCoinConsume(res.Body) - if err != nil { - fmt.Println("OneCirclesSettlementPublicGiveActivityCoinConsume_ERR:::::", err.Error()) - utils2.FilePutContents("OneCirclesSettlementPublicGiveActivityCoinConsume_ERR", utils2.SerializeStr(map[string]interface{}{ - "body": res.Body, - "err": err.Error(), - })) - } - //_ = res.Reject(false) - err = res.Ack(true) - fmt.Println("err ::: ", err) - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleOneCirclesSettlementPublicGiveActivityCoinConsume(msgData []byte) error { - time.Sleep(time.Duration(2) * time.Millisecond) //休眠2毫秒 - //1、解析mq中queue的数据结构体 - var msg *md2.DealUserCoinReq - err := json.Unmarshal(msgData, &msg) - if err != nil { - return err - } - engine := db.DBs[msg.Mid] - - session := engine.NewSession() - defer func() { - session.Close() - if err := recover(); err != nil { - _ = logx.Error(err) - } - }() - session.Begin() - - err = rule.DealUserCoin(session, md2.DealUserCoinReq{ - Kind: "add", - Mid: msg.Mid, - Title: msg.Title, - TransferType: msg.TransferType, - OrdId: "", - CoinId: msg.CoinId, - Uid: msg.Uid, - Amount: msg.Amount, - }) - if err != nil { - _ = session.Rollback() - fmt.Println("err:::::2222", err) - return err - } - - err = session.Commit() - if err != nil { - _ = session.Rollback() - return errors.New("事务提交失败") - } - return nil -} diff --git a/consume/one_circles_sign_in_consume.go b/consume/one_circles_sign_in_consume.go deleted file mode 100644 index 83f12ae..0000000 --- a/consume/one_circles_sign_in_consume.go +++ /dev/null @@ -1,66 +0,0 @@ -package consume - -import ( - "applet/app/cfg" - "applet/app/db" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule/one_circles" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" -) - -func OneCirclesSignInGreenEnergyConsume(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>OneCirclesSignInGreenEnergyConsume>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - one_circles.Init(cfg.RedisAddr) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - err = handleOneCirclesSignInGreenEnergy(res.Body) - if err != nil { - fmt.Println("OneCirclesSignInGreenEnergyConsume_ERR:::::", err.Error()) - } - //_ = res.Reject(false) - err = res.Ack(true) - fmt.Println("err ::: ", err) - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleOneCirclesSignInGreenEnergy(msgData []byte) error { - //1、解析mq中queue的数据结构体 - var msg *md.OneCirclesStructForSignIn - err := json.Unmarshal(msgData, &msg) - if err != nil { - return err - } - - engine := db.DBs[msg.MasterId] - err = one_circles.HandleSettlementSignInGreenEnergy(engine, msg.MasterId, msg.Id, msg.Uid, msg.EndTime) - fmt.Println("err::::", err) - if err != nil { - return err - } - return nil -} diff --git a/consume/one_circles_sign_in_copy_consume.go b/consume/one_circles_sign_in_copy_consume.go deleted file mode 100644 index e837841..0000000 --- a/consume/one_circles_sign_in_copy_consume.go +++ /dev/null @@ -1,66 +0,0 @@ -package consume - -import ( - "applet/app/cfg" - "applet/app/db" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule/one_circles" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" -) - -func OneCirclesSignInCopyGreenEnergyConsume(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>OneCirclesSignInCopyGreenEnergyConsume>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - one_circles.Init(cfg.RedisAddr) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - err = handleOneCirclesSignInCopyGreenEnergy(res.Body) - if err != nil { - fmt.Println("OneCirclesSignInCopyGreenEnergyConsume_ERR:::::", err.Error()) - } - //_ = res.Reject(false) - err = res.Ack(true) - fmt.Println("err ::: ", err) - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleOneCirclesSignInCopyGreenEnergy(msgData []byte) error { - //1、解析mq中queue的数据结构体 - var msg *md.OneCirclesStructForSignIn - err := json.Unmarshal(msgData, &msg) - if err != nil { - return err - } - - engine := db.DBs[msg.MasterId] - err = one_circles.HandleSettlementSignInGreenEnergy(engine, msg.MasterId, msg.Id, msg.Uid, msg.EndTime) - fmt.Println("err::::", err) - if err != nil { - return err - } - return nil -} diff --git a/consume/one_circles_start_level_dividend_consume.go b/consume/one_circles_start_level_dividend_consume.go deleted file mode 100644 index c9410f9..0000000 --- a/consume/one_circles_start_level_dividend_consume.go +++ /dev/null @@ -1,97 +0,0 @@ -package consume - -import ( - "applet/app/cfg" - "applet/app/db" - utils2 "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - db2 "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/db" - md2 "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" - "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule/one_circles" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "time" -) - -func OneCirclesStartLevelDividendConsume(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>OneCirclesStartLevelDividendConsume>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - one_circles.Init(cfg.RedisAddr) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - err = handleOneCirclesStartLevelDividendConsume(res.Body) - if err != nil { - fmt.Println("OneCirclesStartLevelDividendConsume_ERR:::::", err.Error()) - utils2.FilePutContents("OneCirclesStartLevelDividendConsume_ERR", utils2.SerializeStr(map[string]interface{}{ - "body": res.Body, - "err": err.Error(), - })) - } - //_ = res.Reject(false) - err = res.Ack(true) - fmt.Println("err ::: ", err) - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleOneCirclesStartLevelDividendConsume(msgData []byte) error { - time.Sleep(time.Duration(100) * time.Millisecond) //休眠100毫秒 - //1、解析mq中queue的数据结构体 - var msg *md.OneCirclesStructForStarLevelDividends - err := json.Unmarshal(msgData, &msg) - if err != nil { - return err - } - engine := db.DBs[msg.MasterId] - //2、查找 `one_circles_green_energy_basic_setting` 基础设置 - oneCirclesGreenEnergyBasicSetting, err := db2.OneCirclesGreenEnergyBasicSettingGetOneByParams(engine, map[string]interface{}{ - "key": "is_open", - "value": 1, - }) - if err != nil { - return err - } - if oneCirclesGreenEnergyBasicSetting == nil { - return nil - } - - //3、给相应的用户加上个人的绿色积分(结算数量) - session := engine.NewSession() - err = rule.DealUserCoin(session, md2.DealUserCoinReq{ - Kind: "add", - Mid: msg.MasterId, - Title: md2.OneCirclesSettlementStarLevelDividends, - TransferType: md2.OneCirclesSettlementStarLevelDividendsForUserVirtualCoinFlow, - OrdId: "", - CoinId: oneCirclesGreenEnergyBasicSetting.TeamGreenEnergyCoinId, - Uid: msg.Uid, - Amount: msg.SignDividend, - }) - if err != nil { - return err - } - return nil -} diff --git a/consume/super_cloud_issuance_async_mlogin.go b/consume/super_cloud_issuance_async_mlogin.go deleted file mode 100644 index a6360e5..0000000 --- a/consume/super_cloud_issuance_async_mlogin.go +++ /dev/null @@ -1,125 +0,0 @@ -package consume - -import ( - "applet/app/cfg" - "applet/app/db" - "applet/app/utils" - "applet/app/utils/cache" - tool "applet/app/utils/cloud_issuance" - "applet/app/utils/logx" - md2 "applet/cloud_issuance/md" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "code.fnuoos.com/go_rely_warehouse/zyos_model.git/src/implement" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "strconv" - "time" -) - -func SuperCloudIssuanceAsyncMLoginConsume(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - fmt.Println(">>>>>>>>>>>>>>>>SuperCloudIssuanceAsyncMLoginConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - //解析mq中queue的数据结构体 - var msg *md2.CloudIssuanceAsyncMLogin - err = json.Unmarshal(res.Body, &msg) - if err != nil { - panic(err) - } - go func() { - err := handleSuperAsyncMLogin(msg.WId, msg.MasterId, msg.UserId, msg.RobotId) - if err != nil { - fmt.Println("<<<<<<<<<<<< handleSuperAsyncMLogin err>>>>>>>>", err.Error()) - } - }() - _ = res.Ack(true) - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleSuperAsyncMLogin(wId, masterId, userId string, robotId int) error { - var timeTotal = 0 - for { - err, resp := robotSuperAsyncMacLogin(md2.RobotAsyncMacLoginRequest{ - WId: wId, - RobotId: robotId, - }) - if err == nil { - fmt.Println("success <<<<<<<", resp) - if cfg.Prd { - engine := db.DBs[masterId] - cloudIssuanceUserRobotDb := implement.NewSuperCloudIssuanceUserRobotDb(engine, utils.StrToInt(userId), masterId) - robot, err := cloudIssuanceUserRobotDb.GetSuperCloudIssuanceUserRobot() - if err != nil { - return err - } - if robot == nil { - return errors.New("未查询到机器人记录") - } - robot.WcId = resp.WcId - robot.WcNickname = resp.NickName - robot.WcHeadUrl = resp.HeadUrl - robot.LoginStatus = 1 - _, err = cloudIssuanceUserRobotDb.SaveSuperCloudIssuanceUserRobot(robot.Id, robot, "wc_id", "wc_nickname", "wc_head_url", "login_status") - if err != nil { - return err - } - } else { - //TODO::测试环境, 简化操作 通过redis 桥接 - cache.SetEx(fmt.Sprintf("super_cloud_issuance_async_login_success:%s:%s", masterId, userId), utils.SerializeStr(resp), 60*5) - } - return nil - } - - fmt.Println("err>>>>>>>>", err.Error()) - if err != nil && err.Error() != "未登录" { - return err - } - //TODO::休眠5s - time.Sleep(time.Duration(5) * time.Second) - timeTotal += 5 - if timeTotal >= 240 { - return errors.New("超时未登录") - } - } -} - -func robotSuperAsyncMacLogin(args md2.RobotAsyncMacLoginRequest) (err error, result md2.RobotAsyncMacLoginResponse) { // 同步登录状态 - url := tool.HttpBuild("itaoke.robot.async.mlogin", "127.0.0.1", map[string]string{ - "robot_id": strconv.Itoa(args.RobotId), - "wId": args.WId, - }) - data, err := tool.SendPost(url, args) - if err != nil { - return - } - resByte, err := json.Marshal(data.Data) - if err != nil { - return - } - err = json.Unmarshal(resByte, &result) - if err != nil { - return - } - return -} diff --git a/consume/super_cloud_issuance_msg_callback.go b/consume/super_cloud_issuance_msg_callback.go deleted file mode 100644 index fef7196..0000000 --- a/consume/super_cloud_issuance_msg_callback.go +++ /dev/null @@ -1,72 +0,0 @@ -package consume - -import ( - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - db "applet/super_cloud_issuance/db/official" - md2 "applet/super_cloud_issuance/md" - "applet/super_cloud_issuance/svc" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/gin-gonic/gin" - "github.com/streadway/amqp" - "time" -) - -func SuperCloudIssuanceMsgCallBackConsume(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //2、取出数据进行消费 - ch.Qos(10) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - fmt.Println(">>>>>>>>>>>>>>>>CloudIssuanceMsgCallBackConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - //解析mq中queue的数据结构体 - var msg *md2.CallbackRequest - err = json.Unmarshal(res.Body, &msg) - if err != nil { - panic(err) - } - randInt := utils.RandIntRand(100, 200) - time.Sleep(time.Millisecond * time.Duration(randInt)) // 等待100 ~ 200毫秒 - go func() { - //设置masterId - cloudIssuanceRobotRecords, err := db.SuperCloudIssuanceRobotRecordsGetOneByParams(map[string]interface{}{ - "key": "robot_id", - "value": msg.RobotId, - }) - if err != nil { - fmt.Println("CallBackErr:::::", err.Error()) - return - } - if cloudIssuanceRobotRecords == nil { - //TODO::未查询到机器人,不需要处理 - utils.FilePutContents("cloud_issuance_call_back_not_found", utils.SerializeStr(msg)) - return - } - var c = &gin.Context{} - c.Set("mid", cloudIssuanceRobotRecords.MasterId) - dealCloudIssuanceCallBackService := svc.DealSuperCloudIssuanceCallBackService{} - dealCloudIssuanceCallBackService.Set(c) - dealCloudIssuanceCallBackService.DealCallBack(c, *msg) - }() - _ = res.Ack(true) - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} diff --git a/consume/supply_cloud_chain_fenxiao_new_change.go b/consume/supply_cloud_chain_fenxiao_new_change.go deleted file mode 100644 index 4eac55b..0000000 --- a/consume/supply_cloud_chain_fenxiao_new_change.go +++ /dev/null @@ -1,227 +0,0 @@ -package consume - -import ( - svc2 "applet/app/svc" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - utils1688 "applet/supply/1688/utils" - "applet/supply/db" - "applet/supply/db/model" - "applet/supply/enum" - md2 "applet/supply/md" - "applet/supply/svc" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/gin-gonic/gin" - "github.com/streadway/amqp" - "strings" - "time" -) - -func SupplyCloudChainFenxiaoNewChangeConsume(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - fmt.Println(">>>>>>>>>>>>>>>>SupplyCloudChainFenxiaoNewChangeConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleSupplyCloudChainFenxiaoNewChangeConsume(res.Body) - if err != nil { - fmt.Println("*****************err*************************", err) - } - _ = res.Ack(true) - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func RemoveRepeatedElement(arr []string) (newArr []string) { - newArr = make([]string, 0) - for i := 0; i < len(arr); i++ { - repeat := false - for j := i + 1; j < len(arr); j++ { - if arr[i] == arr[j] { - repeat = true - break - } - } - if !repeat { - newArr = append(newArr, arr[i]) - } - } - return -} - -func handleSupplyCloudChainFenxiaoNewChangeConsume(msgData []byte) error { - //解析mq中queue的数据结构体 - var pushStuct struct { - Args struct { - md2.GoodsAddPriceConditions - } `json:"args"` - Mid string `json:"mid"` - } - err := json.Unmarshal(msgData, &pushStuct) - if err != nil { - panic(err) - } - - //设置masterId - var c = &gin.Context{} - c.Set("mid", pushStuct.Mid) - var t struct { - md2.GoodsAddPriceConditions - } - t = pushStuct.Args - var idsMap = map[string]string{} - for _, v := range t.Ids { - idsMap[v] = v - } - var idsArray []string - for _, v := range idsMap { - idsArray = append(idsArray, v) - } - t.Ids = idsArray - - basicSetting, _ := svc.GetSupplyBasicSetting(c) - if basicSetting == nil { - return errors.New("!!!!!功能开发中") - } - if basicSetting.AliCloudChainFenXiaoAppkey == "" || basicSetting.AliCloudChainFenXiaoAppsecret == "" || basicSetting.AliCloudChainFenXiaoAccesstoken == "" { - return errors.New("!!!!!必要参数没有填写,功能已暂停") - } - get, systemMerchant, err1 := db.GetSystemMerchant(svc2.MasterDb(c)) - if err1 != nil { - return err1 - } - if !get { - return errors.New("!!!!!请先去设置官方商家信息") - } - ids := RemoveRepeatedElement(t.Ids) - var tmpIds []string - var resultList []interface{} - for _, v := range ids { - tmpIds = append(tmpIds, v) - if len(tmpIds) >= 20 { - goodsFrom1688s, err := utils1688.GetFenXiaoProductInfoFrom1688(basicSetting.AliCloudChainFenXiaoAppkey, basicSetting.AliCloudChainFenXiaoAppsecret, basicSetting.AliCloudChainFenXiaoAccesstoken, tmpIds) - if err != nil { - return err - } - result, ok := goodsFrom1688s["result"].(map[string]interface{}) - if !ok { - return errors.New("!!!!!错误的数据") - } - if message, ok := result["message"]; ok { - fmt.Println("!!!!!!!!!!!!", message, "!!!!!!!!!!") - return errors.New("message 反射失败1") - } - tmpResultList, ok := result["result"].([]interface{}) - if !ok { - return errors.New("!!!!!!错误的数据2") - } - if len(tmpResultList) == 0 { - return errors.New("!!!!!!错误的数据3") - } - for _, vv := range tmpResultList { - resultList = append(resultList, vv) - } - tmpIds = []string{} - } - } - - if len(tmpIds) >= 0 { - goodsFrom1688s, err := utils1688.GetFenXiaoProductInfoFrom1688(basicSetting.AliCloudChainFenXiaoAppkey, basicSetting.AliCloudChainFenXiaoAppsecret, basicSetting.AliCloudChainFenXiaoAccesstoken, tmpIds) - if err != nil { - return err - } - result, ok := goodsFrom1688s["result"].(map[string]interface{}) - if !ok { - return errors.New("!!!!!!错误的数据4") - } - if message, ok := result["message"]; ok { - fmt.Println("!!!!!", message) - return errors.New("message 反射失败2") - } - tmpResultList, ok := result["result"].([]interface{}) - if !ok { - return errors.New("!!!!!!错误的数据4") - } - if len(tmpResultList) == 0 { - return errors.New("!!!!!!错误的数据5") - } - for _, vv := range tmpResultList { - resultList = append(resultList, vv) - } - } - - var cloudChainGoods = map[string]map[string]interface{}{} - for _, v := range resultList { - tmp, ok1 := v.(map[string]interface{}) - if !ok1 { - return errors.New("!!!!!!错误的数据6") - } - productInfo, ok1 := tmp["productInfo"].(map[string]interface{}) - if !ok1 { - return errors.New("!!!!!!错误的数据7") - } - var productId = utils.AnyToString(productInfo["productID"]) - for strings.HasSuffix(productId, "0") { - productId = strings.TrimSuffix(productId, "0") - } - if strings.HasSuffix(productId, ".") { - productId = strings.TrimSuffix(productId, ".") - } - cloudChainGoods[productId] = tmp - } - - utils.FilePutContents("cloudChainGoods", utils.SerializeStr(cloudChainGoods)) - for _, id := range ids { - if cloudChainGoods[id] == nil { - continue - } - var goods model.MallGoods - goods.CloudChainGoodsId = id - goods.MerchantId = systemMerchant.Id - getV2, err11 := goods.GetV2(svc2.MasterDb(c)) - if err11 != nil { - fmt.Println("!!!!!!", err11.Error()) - continue - } - if getV2 { - continue - } - var req md2.AddGoodsReq - req.Base.GoodsType = 1 - req.Base.CloudChainGoodsId = id - req.Base.SaleState = enum.MallGoodsSaleStateOnShelf - req.Base.CategoryId = utils.StrToInt(t.CategoryId) - req.Base.MerchantId = systemMerchant.Id - - err := svc.CloudChainFenXiaoGoodsChangeMallGoods(c, cloudChainGoods[id], &req) - if err != nil { - return err - } - - err111 := svc.AddMallGoods(c, &req) - if err111 != nil { - return err111 - } - time.Sleep(12 * time.Millisecond) - } - return nil -} diff --git a/consume/withdraw_consume.go b/consume/withdraw_consume.go deleted file mode 100644 index 5df8c79..0000000 --- a/consume/withdraw_consume.go +++ /dev/null @@ -1,100 +0,0 @@ -package consume - -import ( - "applet/app/cfg" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule/one_circles" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "time" -) - -func WithdrawConsume(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>WithdrawConsume>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - one_circles.Init(cfg.RedisAddr) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - err = handleWithdrawConsume(res.Body) - fmt.Println("err ::: ", err) - if err != nil { - fmt.Println("WithdrawConsume_ERR:::::", err.Error()) - //_ = res.Reject(true) - _ = res.Reject(false) - var msg interface{} - json.Unmarshal(res.Body, &msg) - if err.Error() == "Connection timed out" { - //TODO::重新推回队列末尾,避免造成队列堵塞 - ch.Publish(queue.ExchangeName, msg, queue.RoutKey) - } else { - //TODO::推入新的队列中备份 - utils.FilePutContents("WithdrawConsume_ERR", utils.SerializeStr(err.Error())) - ch.Publish("zhios.app.user.withdraw.apply.exception.exchange", msg, "queues_one") - } - } else { - err = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleWithdrawConsume(msgData []byte) error { - time.Sleep(time.Microsecond * 200) // 等待200毫秒 - //1、解析mq中queue的数据结构体 - var msg interface{} - err := json.Unmarshal(msgData, &msg) - if err != nil { - return err - } - fmt.Println("message:::::::::::>>>>>>>>>") - fmt.Println(msg) - var url = "http://admin.99813608.zhiyingos.com/index/transfer" - if cfg.Prd { - url = "http://zhios-admin/index/transfer" - } - post, err := utils.CurlPost(url, msg, nil) - if err != nil { - return err - } - fmt.Println("transfer:::::::::::<<<<<<<<<") - fmt.Println(string(post), "\n========================================\n\n") - var postResult struct { - Code int `json:"code"` - Msg string `json:"msg"` - Data struct { - IsOk bool `json:"isOk"` - Msg string `json:"msg"` - } `json:"data"` - } - err = json.Unmarshal(post, &postResult) - if err != nil { - return err - } - if !postResult.Data.IsOk { - return errors.New(postResult.Data.Msg) - } - return nil -} diff --git a/consume/withdraw_consume_gongmao.go b/consume/withdraw_consume_gongmao.go deleted file mode 100644 index 19b97c4..0000000 --- a/consume/withdraw_consume_gongmao.go +++ /dev/null @@ -1,165 +0,0 @@ -package consume - -import ( - "applet/app/cfg" - "applet/app/db" - db2 "applet/app/flexible_employment/db" - "applet/app/flexible_employment/enum" - "applet/app/flexible_employment/svc" - "applet/app/lib/flexible_employment" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule/one_circles" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "time" -) - -func FlexibleEmploymentWithdrawForGongMaoConsume(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>FlexibleEmploymentWithdrawForGongMaoConsume>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - one_circles.Init(cfg.RedisAddr) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - err = handleFlexibleEmploymentWithdrawForGongMaoConsume(res.Body) - fmt.Println("err ::: ", err) - if err != nil { - fmt.Println("FlexibleEmploymentWithdrawForGongMaoConsume_ERR:::::", err.Error()) - _ = res.Reject(true) //TODO::拒绝 Ack - //_ = res.Reject(false) - var msg interface{} - json.Unmarshal(res.Body, &msg) - if err.Error() == "Connection timed out" { - //TODO::重新推回队列末尾,避免造成队列堵塞 - ch.Publish(queue.ExchangeName, msg, queue.RoutKey) - } else { - //TODO::推入新的队列中备份 - utils.FilePutContents("FlexibleEmploymentWithdrawForGongMaoConsume_ERR", utils.SerializeStr(err.Error())) - ch.Publish("zhios.app.user.withdraw.apply.exception.exchange", msg, "gongmao") - } - } else { - err = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleFlexibleEmploymentWithdrawForGongMaoConsume(msgData []byte) error { - var ms string - err := json.Unmarshal(msgData, &ms) - if err != nil { - return err - } - time.Sleep(time.Microsecond * 200) // 等待200毫秒 - //1、解析mq中queue的数据结构体 - var msg struct { - Uid string `json:"uid"` - Nickname string `json:"nickname"` - MasterId string `json:"master_id"` - AppName string `json:"app_name"` - ApplyOrder string `json:"apply_order"` - ActualAmount string `json:"actual_amount"` - MobCfg interface{} `json:"mob_cfg"` - } - err = json.Unmarshal([]byte(ms), &msg) - if err != nil { - return err - } - fmt.Println("gongmao_message:::::::::::>>>>>>>>>") - fmt.Println(msg) - if db.DBs[msg.MasterId] == nil { - return nil - } - engine := db.DBs[msg.MasterId] - - //1、查找对应记录 - flexibleEmploymentOrdDb := db2.FlexibleEmploymentOrdDb{} - flexibleEmploymentOrdDb.Set(msg.MasterId) - flexibleEmploymentOrd, err := flexibleEmploymentOrdDb.Get(msg.ApplyOrder) - if err != nil { - return err - } - if flexibleEmploymentOrd == nil { - return errors.New("未查询到对应订单记录") - } - - flexibleEmploymentBasicDb := db2.FlexibleEmploymentBasicDb{} - flexibleEmploymentBasicDb.Set() - basic, err := flexibleEmploymentBasicDb.Get(msg.MasterId) - if err != nil { - return err - } - gongMao := flexible_employment.New(basic.AppKey, basic.AppSecret, basic.SecretId) - result, err := gongMao.Curl(enum.MerchantDoSinglePayment, map[string]interface{}{ - "requestId": flexibleEmploymentOrd.RequestId, - "mobile": flexibleEmploymentOrd.Mobile, - "name": flexibleEmploymentOrd.Name, - "amount": flexibleEmploymentOrd.Amount, - "identity": flexibleEmploymentOrd.Identity, - "bankAccount": flexibleEmploymentOrd.BankAccount, - "dateTime": time.Now().Format("20060102150405"), - "salaryType": flexibleEmploymentOrd.SettleType, - }) - if err != nil { - return err - } - var response struct { - Success bool `json:"success"` - ErrorCode string `json:"errorCode"` - ErrorMsg string `json:"errorMsg"` - Data struct { - RequestId string `json:"requestId"` - AppmentTime string `json:"appmentTime"` - } `json:"data"` - } - if err = json.Unmarshal(utils.Serialize(result), &response); err != nil { - return err - } - if !response.Success { - //TODO::发起提现失败,将处理提现失败状态 - finWithdrawApply, err := db.UserWithDrawApplyByUIDById(engine, flexibleEmploymentOrd.RequestId) - if err != nil { - return err - } - session := engine.NewSession() - defer session.Close() - session.Begin() - err = svc.DealFailResult(session, finWithdrawApply, msg.MasterId, response.ErrorMsg) - if err != nil { - _ = session.Rollback() - return err - } - return session.Commit() - } - flexibleEmploymentOrd.State = 1 - updateAck, err := flexibleEmploymentOrdDb.Update(flexibleEmploymentOrd.Id, flexibleEmploymentOrd, "state") - if err != nil { - return err - } - if updateAck <= 0 { - return errors.New("更新 flexible_employment_ord 状态失败") - } - return nil -} diff --git a/consume/withdraw_consume_pupiao.go b/consume/withdraw_consume_pupiao.go deleted file mode 100644 index 280adda..0000000 --- a/consume/withdraw_consume_pupiao.go +++ /dev/null @@ -1,185 +0,0 @@ -package consume - -import ( - "applet/app/cfg" - "applet/app/db" - db2 "applet/app/flexible_employment/db" - "applet/app/flexible_employment/enum" - "applet/app/flexible_employment/svc" - "applet/app/flexible_employment/utils/aes" - "applet/app/lib/flexible_employment" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule/one_circles" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "time" -) - -func FlexibleEmploymentWithdrawForPupiaoConsume(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>FlexibleEmploymentWithdrawForPupiaoConsume>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - one_circles.Init(cfg.RedisAddr) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - err = handleFlexibleEmploymentWithdrawForPupiaoConsume(res.Body) - fmt.Println("err ::: ", err) - if err != nil { - fmt.Println("FlexibleEmploymentWithdrawForPupiaoConsume_ERR:::::", err.Error()) - //_ = res.Reject(true) - _ = res.Reject(false) - var msg interface{} - json.Unmarshal(res.Body, &msg) - if err.Error() == "Connection timed out" { - //TODO::重新推回队列末尾,避免造成队列堵塞 - ch.Publish(queue.ExchangeName, msg, queue.RoutKey) - } else { - //TODO::推入新的队列中备份 - utils.FilePutContents("FlexibleEmploymentWithdrawForPupiaoConsume_ERR", utils.SerializeStr(err.Error())) - ch.Publish("zhios.app.user.withdraw.apply.exception.exchange", msg, "pupiao") - } - } else { - err = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleFlexibleEmploymentWithdrawForPupiaoConsume(msgData []byte) error { - var ms string - err := json.Unmarshal(msgData, &ms) - if err != nil { - return err - } - time.Sleep(time.Microsecond * 200) // 等待200毫秒 - //1、解析mq中queue的数据结构体 - var msg struct { - Uid string `json:"uid"` - Nickname string `json:"nickname"` - MasterId string `json:"master_id"` - AppName string `json:"app_name"` - ApplyOrder string `json:"apply_order"` - ActualAmount string `json:"actual_amount"` - Oid string `json:"oid"` - MobCfg interface{} `json:"mob_cfg"` - } - err = json.Unmarshal([]byte(ms), &msg) - if err != nil { - return err - } - fmt.Println("pupiao_message:::::::::::>>>>>>>>>") - fmt.Println(msg) - if db.DBs[msg.MasterId] == nil { - return nil - } - engine := db.DBs[msg.MasterId] - - //1、查找对应记录 - flexibleEmploymentPupiaoOrdDb := db2.FlexibleEmploymentPupiaoOrdDb{} - flexibleEmploymentPupiaoOrdDb.Set(msg.MasterId) - flexibleEmploymentPupiaoOrd, err := flexibleEmploymentPupiaoOrdDb.Get(msg.Oid) - if err != nil { - return err - } - if flexibleEmploymentPupiaoOrd == nil { - return errors.New("未查询到对应订单记录") - } - - flexibleEmploymentPuiaoBasicDb := db2.FlexibleEmploymentPuiaoBasicDb{} - flexibleEmploymentPuiaoBasicDb.Set() - basic, err := flexibleEmploymentPuiaoBasicDb.GetBasic(msg.MasterId) - if err != nil { - return err - } - - //2、发起制单 - puPiao := flexible_employment.NewPuPiao(basic.AppId, basic.AppSecret) - var userAESData = []map[string]string{ - { - "outTradeNo": "o_" + utils.Int64ToStr(flexibleEmploymentPupiaoOrd.WithdrawApplyId), - "settleType": flexibleEmploymentPupiaoOrd.SettleType, - "payeeName": flexibleEmploymentPupiaoOrd.PayeeName, - "payeeIdCard": flexibleEmploymentPupiaoOrd.PayeeIdCard, - "payeePhone": flexibleEmploymentPupiaoOrd.PayeePhone, - "payeeNo": flexibleEmploymentPupiaoOrd.PayeeNo, - "orderAmount": flexibleEmploymentPupiaoOrd.TotalAmount, - }, - } - str, _ := json.Marshal(userAESData) - itemAESContent, _ := aes.AesEncryptByECB([]byte(basic.AppSecret), string(str)) - settleAccountId := basic.SettleAccountId - if flexibleEmploymentPupiaoOrd.SettleType == "ALIPAY" { - settleAccountId = basic.SettleAccountIdForAli - } - result, err := puPiao.Curl(enum.OpenApiPaymentReceiveOrder, map[string]interface{}{ - "outBatchNo": flexibleEmploymentPupiaoOrd.OutBatchNo, - "hrcompanyId": basic.HrCompanyId, - "settleAccountId": settleAccountId, - "totalCount": "1", - "totalAmount": flexibleEmploymentPupiaoOrd.TotalAmount, - "itemAESContent": itemAESContent, - }) - if err != nil { - return err - } - var response struct { - IsSuccess string `json:"isSuccess"` - Charset string `json:"charset"` - ErrorCode string `json:"errorCode"` - ErrorMsg string `json:"errorMsg"` - Data struct { - PlatformBatchNo string `json:"platformBatchNo"` - OutBatchNo string `json:"outBatchNo"` - } `json:"data"` - } - if err = json.Unmarshal(utils.Serialize(result), &response); err != nil { - return err - } - if response.IsSuccess == "F" { - flexibleEmploymentPupiaoOrd.BatchStatus = 1 - updateAck, err := flexibleEmploymentPupiaoOrdDb.Update(flexibleEmploymentPupiaoOrd.Id, flexibleEmploymentPupiaoOrd, "batch_status") - if err != nil { - return err - } - if updateAck <= 0 { - return errors.New("更新 flexible_employment_pupiao_ord 状态失败") - } - //TODO::制单失败,将处理提现失败状态 - finWithdrawApply, err := db.UserWithDrawApplyByUIDById(engine, utils.Int64ToStr(flexibleEmploymentPupiaoOrd.WithdrawApplyId)) - if err != nil { - return err - } - session := engine.NewSession() - defer session.Close() - session.Begin() - err = svc.DealFailResultForPuPiao(session, finWithdrawApply, msg.MasterId, response.ErrorMsg) - if err != nil { - _ = session.Rollback() - return err - } - return session.Commit() - } - return nil -} diff --git a/consume/zhios_acquisition_condition.go b/consume/zhios_acquisition_condition.go deleted file mode 100644 index 27f90ca..0000000 --- a/consume/zhios_acquisition_condition.go +++ /dev/null @@ -1,679 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/db/model" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "strings" - "time" - "xorm.io/xorm" -) - -func ZhiosAcquisitionCondition(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(300) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>ZhiosAcquisitionCondition<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleZhiosAcquisition(res.Body) - //_ = res.Reject(false) - fmt.Println(err) - if err == nil { - _ = res.Ack(true) - } else { - - var canalMsg *md.ZhiosAcquisition - var tmpString string - err := json.Unmarshal(res.Body, &tmpString) - if err == nil { - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err == nil { - ch.Publish(queue.ExchangeName, utils.SerializeStr(canalMsg), queue.RoutKey) - } - } - - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} -func handleZhiosAcquisition(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.ZhiosAcquisition - fmt.Println(string(msg)) - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println(err.Error()) - return err - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err != nil { - return err - } - mid := canalMsg.Mid - eg := db.DBs[mid] - if eg == nil { - return nil - } - if canalMsg.Uid == "" { - return nil - } - userInfo, _ := db.UserFindByID(eg, canalMsg.Uid) - if userInfo == nil { - return nil - } - userProfile, _ := db.UserProfileFindByID(eg, canalMsg.Uid) - if userProfile == nil { - return nil - } - cfg := db.GetAcquisitionCfg(eg, canalMsg.Id, userInfo.CreateAt) - if cfg == nil { - return nil - } - nextUserProfile, _ := db.UserProfileFindByID(eg, userProfile.ParentUid) - var user = &md.User{Info: userInfo, Profile: userProfile} - - bools, str := checkAllCompleteTmp(eg, user, cfg) - isFull := 0 - fullTime := 0 - toRewardTime := 0 - if bools { - isFull = 1 - fullTime = int(time.Now().Unix()) - toRewardTime = int(time.Now().Unix()) + utils.StrToInt(cfg.RewardAccountDay)*86400 - } - //写入奖励记录 - - //新的设置 读第一个新注册的奖励 - lv := 0 - if len(cfg.RewardRule.LvRewardList) > 0 { - isEnd := 0 - for k, v := range cfg.RewardRule.LvRewardList { - if isEnd == 1 { - continue - } - if utils.StrToInt(v.Id) == user.Info.Level { - isEnd = 1 - } - lv = utils.StrToInt(v.Id) - if cfg.RewardRule.NewRewardCoinId != "" { - ex := strings.Split(cfg.RewardRule.NewRewardCoinId, ",") - for _, v1 := range v.CoinList { - if utils.InArr(v1.CoinId, ex) { - InvitedReward := v1.InvitedReward - if cfg.RewardRule.RewardType == "1" { - InvitedReward = Rands(v1.InvitedReward, v1.InvitedRewardMax) - } - //直推 - DirectSuccess := v1.DirectSuccess - if cfg.RewardRule.RewardType == "1" { - DirectSuccess = Rands(v1.DirectSuccess, v1.DirectSuccessMax) - } - //间推 - IndirectSuccess := v1.IndirectSuccess - if cfg.RewardRule.RewardType == "1" { - IndirectSuccess = Rands(v1.IndirectSuccess, v1.IndirectSuccessMax) - } - InvitedSource := 0 - DirectSource := 1 - IndirectSource := 2 - InvitedSourceStr := "注册奖励" - DirectSourceStr := "直推好友" - IndirectSourceStr := "间推好友" - if k > 0 { - InvitedSource = 3 - DirectSource = 4 - IndirectSource = 5 - InvitedSourceStr = "升级" + v.Name + "奖励" - DirectSourceStr = "直推好友升级" + v.Name + "奖励" - IndirectSourceStr = "间推好友升级" + v.Name + "奖励" - } - if utils.StrToFloat64(InvitedReward) > 0 { - ownRewardLog, ownhas, _ := db.GetNewAcquisitionRewardLogWhereCoinId(eg, userProfile.Uid, user.Profile.Uid, lv, utils.StrToInt(v1.CoinId)) - if !ownhas { - ownRewardLog = &model.NewAcquisitionRewardLog{ - Uid: user.Profile.Uid, - ToUid: user.Profile.Uid, - Title: user.Info.Nickname, - Source: InvitedSource, - SourceText: InvitedSourceStr, - Money: InvitedReward, - CreatedAt: int(time.Now().Unix()), - State: 0, - CoinId: utils.StrToInt(v1.CoinId), - RewardType: utils.StrToInt(cfg.RewardRule.RewardType), - InviteTime: int(userInfo.CreateAt.Unix()), - Lv: lv, - } - - db.InsertNewRewardLog(eg, ownRewardLog) - } - if ownRewardLog.GivenAt == 0 { - - ownRewardLog.CompleteCon = str - ownRewardLog.IsFull = isFull - if ownRewardLog.FullTime == 0 { - ownRewardLog.FullTime = fullTime - } - if ownRewardLog.ToRewardTime == 0 { - ownRewardLog.ToRewardTime = toRewardTime - } - eg.Where("id=?", ownRewardLog.Id).Update(ownRewardLog) - } - } - if utils.StrToFloat64(DirectSuccess) > 0 { - if userProfile.ParentUid > 0 { - //写入奖励记录 - extendRewardLog, extendHas, _ := db.GetNewAcquisitionRewardLogWhereCoinId(eg, userProfile.ParentUid, userProfile.Uid, lv, utils.StrToInt(v1.CoinId)) - if !extendHas { - extendRewardLog = &model.NewAcquisitionRewardLog{ - Uid: user.Profile.ParentUid, - ToUid: user.Profile.Uid, - Title: user.Info.Nickname, - Source: DirectSource, - SourceText: DirectSourceStr, - Money: DirectSuccess, - CreatedAt: int(time.Now().Unix()), - State: 0, - CoinId: utils.StrToInt(v1.CoinId), - RewardType: utils.StrToInt(cfg.RewardRule.RewardType), - InviteTime: int(userInfo.CreateAt.Unix()), - Lv: lv, - } - db.InsertNewRewardLog(eg, extendRewardLog) - } - if extendRewardLog.GivenAt == 0 { - - extendRewardLog.CompleteCon = str - extendRewardLog.IsFull = isFull - if extendRewardLog.FullTime == 0 { - extendRewardLog.FullTime = fullTime - } - if extendRewardLog.ToRewardTime == 0 { - extendRewardLog.ToRewardTime = toRewardTime - } - eg.Where("id=?", extendRewardLog.Id).Update(extendRewardLog) - } - } - } - if utils.StrToFloat64(IndirectSuccess) > 0 { - if nextUserProfile != nil && nextUserProfile.ParentUid > 0 { - IndirectRewardLog, IndirectHas, _ := db.GetNewAcquisitionRewardLogWhereCoinId(eg, nextUserProfile.ParentUid, userProfile.Uid, lv, utils.StrToInt(v1.CoinId)) - if !IndirectHas { - IndirectRewardLog = &model.NewAcquisitionRewardLog{ - Uid: nextUserProfile.ParentUid, - ToUid: user.Profile.Uid, - Title: user.Info.Nickname, - Source: IndirectSource, - SourceText: IndirectSourceStr, - Money: IndirectSuccess, - CreatedAt: int(time.Now().Unix()), - State: 0, - CoinId: utils.StrToInt(v1.CoinId), - RewardType: utils.StrToInt(cfg.RewardRule.RewardType), - InviteTime: int(userInfo.CreateAt.Unix()), - Lv: lv, - } - db.InsertNewRewardLog(eg, IndirectRewardLog) - } - if IndirectRewardLog.GivenAt == 0 { - IndirectRewardLog.CompleteCon = str - IndirectRewardLog.IsFull = isFull - if IndirectRewardLog.FullTime == 0 { - IndirectRewardLog.FullTime = fullTime - } - if IndirectRewardLog.ToRewardTime == 0 { - IndirectRewardLog.ToRewardTime = toRewardTime - } - eg.Where("id=?", IndirectRewardLog.Id).Update(IndirectRewardLog) - } - } - } - } - } - - } else { - InvitedReward := v.InvitedReward - if cfg.RewardRule.RewardType == "1" { - InvitedReward = Rands(v.InvitedReward, v.InvitedRewardMax) - } - //直推 - DirectSuccess := v.DirectSuccess - if cfg.RewardRule.RewardType == "1" { - DirectSuccess = Rands(v.DirectSuccess, v.DirectSuccessMax) - } - //间推 - IndirectSuccess := v.IndirectSuccess - if cfg.RewardRule.RewardType == "1" { - IndirectSuccess = Rands(v.IndirectSuccess, v.IndirectSuccessMax) - } - InvitedSource := 0 - DirectSource := 1 - IndirectSource := 2 - InvitedSourceStr := "注册奖励" - DirectSourceStr := "直推好友" - IndirectSourceStr := "间推好友" - if k > 0 { - InvitedSource = 3 - DirectSource = 4 - IndirectSource = 5 - InvitedSourceStr = "升级" + v.Name + "奖励" - DirectSourceStr = "直推好友升级" + v.Name + "奖励" - IndirectSourceStr = "间推好友升级" + v.Name + "奖励" - } - if utils.StrToFloat64(InvitedReward) > 0 { - ownRewardLog, ownhas, _ := db.GetNewAcquisitionRewardLogWhere(eg, userProfile.Uid, user.Profile.Uid, lv) - if !ownhas { - ownRewardLog = &model.NewAcquisitionRewardLog{ - Uid: user.Profile.Uid, - ToUid: user.Profile.Uid, - Title: user.Info.Nickname, - Source: InvitedSource, - SourceText: InvitedSourceStr, - Money: InvitedReward, - CreatedAt: int(time.Now().Unix()), - State: 0, - CoinId: utils.StrToInt(cfg.RewardRule.RewardCoinId), - RewardType: utils.StrToInt(cfg.RewardRule.RewardType), - InviteTime: int(userInfo.CreateAt.Unix()), - Lv: lv, - } - - db.InsertNewRewardLog(eg, ownRewardLog) - } - if ownRewardLog.GivenAt == 0 { - - ownRewardLog.CompleteCon = str - ownRewardLog.IsFull = isFull - if ownRewardLog.FullTime == 0 { - ownRewardLog.FullTime = fullTime - } - if ownRewardLog.ToRewardTime == 0 { - ownRewardLog.ToRewardTime = toRewardTime - } - eg.Where("id=?", ownRewardLog.Id).Update(ownRewardLog) - } - } - if utils.StrToFloat64(DirectSuccess) > 0 { - if userProfile.ParentUid > 0 { - //写入奖励记录 - extendRewardLog, extendHas, _ := db.GetNewAcquisitionRewardLogWhere(eg, userProfile.ParentUid, userProfile.Uid, lv) - if !extendHas { - extendRewardLog = &model.NewAcquisitionRewardLog{ - Uid: user.Profile.ParentUid, - ToUid: user.Profile.Uid, - Title: user.Info.Nickname, - Source: DirectSource, - SourceText: DirectSourceStr, - Money: DirectSuccess, - CreatedAt: int(time.Now().Unix()), - State: 0, - CoinId: utils.StrToInt(cfg.RewardRule.RewardCoinId), - RewardType: utils.StrToInt(cfg.RewardRule.RewardType), - InviteTime: int(userInfo.CreateAt.Unix()), - Lv: lv, - } - db.InsertNewRewardLog(eg, extendRewardLog) - } - if extendRewardLog.GivenAt == 0 { - - extendRewardLog.CompleteCon = str - extendRewardLog.IsFull = isFull - if extendRewardLog.FullTime == 0 { - extendRewardLog.FullTime = fullTime - } - if extendRewardLog.ToRewardTime == 0 { - extendRewardLog.ToRewardTime = toRewardTime - } - eg.Where("id=?", extendRewardLog.Id).Update(extendRewardLog) - } - } - } - if utils.StrToFloat64(IndirectSuccess) > 0 { - if nextUserProfile != nil && nextUserProfile.ParentUid > 0 { - IndirectRewardLog, IndirectHas, _ := db.GetNewAcquisitionRewardLogWhere(eg, nextUserProfile.ParentUid, userProfile.Uid, lv) - if !IndirectHas { - IndirectRewardLog = &model.NewAcquisitionRewardLog{ - Uid: nextUserProfile.ParentUid, - ToUid: user.Profile.Uid, - Title: user.Info.Nickname, - Source: IndirectSource, - SourceText: IndirectSourceStr, - Money: IndirectSuccess, - CreatedAt: int(time.Now().Unix()), - State: 0, - CoinId: utils.StrToInt(cfg.RewardRule.RewardCoinId), - RewardType: utils.StrToInt(cfg.RewardRule.RewardType), - InviteTime: int(userInfo.CreateAt.Unix()), - Lv: lv, - } - db.InsertNewRewardLog(eg, IndirectRewardLog) - } - if IndirectRewardLog.GivenAt == 0 { - IndirectRewardLog.CompleteCon = str - IndirectRewardLog.IsFull = isFull - if IndirectRewardLog.FullTime == 0 { - IndirectRewardLog.FullTime = fullTime - } - if IndirectRewardLog.ToRewardTime == 0 { - IndirectRewardLog.ToRewardTime = toRewardTime - } - eg.Where("id=?", IndirectRewardLog.Id).Update(IndirectRewardLog) - } - } - } - } - - } - } else { - InvitedReward := cfg.RewardRule.InvitedReward - if cfg.RewardRule.RewardType == "1" { - InvitedReward = Rands(cfg.RewardRule.InvitedReward, cfg.RewardRule.InvitedRewardMax) - } - //直推 - DirectSuccess := cfg.RewardRule.DirectSuccess - if cfg.RewardRule.RewardType == "1" { - DirectSuccess = Rands(cfg.RewardRule.DirectSuccess, cfg.RewardRule.DirectSuccessMax) - } - //间推 - IndirectSuccess := cfg.RewardRule.IndirectSuccess - if cfg.RewardRule.RewardType == "1" { - IndirectSuccess = Rands(cfg.RewardRule.IndirectSuccess, cfg.RewardRule.IndirectSuccessMax) - } - if utils.StrToFloat64(InvitedReward) > 0 { - ownRewardLog, ownhas, _ := db.GetNewAcquisitionRewardLog(eg, &model.NewAcquisitionRewardLog{ - Uid: user.Profile.Uid, - ToUid: user.Profile.Uid, - }) - if !ownhas { - ownRewardLog = &model.NewAcquisitionRewardLog{ - Uid: user.Profile.Uid, - ToUid: user.Profile.Uid, - Title: user.Info.Nickname, - Source: 0, - SourceText: "注册奖励", - Money: InvitedReward, - CreatedAt: int(time.Now().Unix()), - State: 0, - CoinId: utils.StrToInt(cfg.RewardRule.RewardCoinId), - RewardType: utils.StrToInt(cfg.RewardRule.RewardType), - InviteTime: int(userInfo.CreateAt.Unix()), - Lv: lv, - } - - db.InsertNewRewardLog(eg, ownRewardLog) - } - if ownRewardLog.GivenAt == 0 { - ownRewardLog.CompleteCon = str - ownRewardLog.IsFull = isFull - if ownRewardLog.FullTime == 0 { - ownRewardLog.FullTime = fullTime - } - if ownRewardLog.ToRewardTime == 0 { - ownRewardLog.ToRewardTime = toRewardTime - } - eg.Where("id=?", ownRewardLog.Id).Update(ownRewardLog) - } - } - if utils.StrToFloat64(DirectSuccess) > 0 { - if userProfile.ParentUid > 0 { - //写入奖励记录 - extendRewardLog, extendHas, _ := db.GetNewAcquisitionRewardLog(eg, &model.NewAcquisitionRewardLog{ - Uid: userProfile.ParentUid, - ToUid: userProfile.Uid, - }) - if !extendHas { - extendRewardLog = &model.NewAcquisitionRewardLog{ - Uid: user.Profile.ParentUid, - ToUid: user.Profile.Uid, - Title: user.Info.Nickname, - Source: 1, - SourceText: "直推好友", - Money: DirectSuccess, - CreatedAt: int(time.Now().Unix()), - State: 0, - CoinId: utils.StrToInt(cfg.RewardRule.RewardCoinId), - RewardType: utils.StrToInt(cfg.RewardRule.RewardType), - InviteTime: int(userInfo.CreateAt.Unix()), - Lv: lv, - } - db.InsertNewRewardLog(eg, extendRewardLog) - } - if extendRewardLog.GivenAt == 0 { - extendRewardLog.CompleteCon = str - extendRewardLog.IsFull = isFull - if extendRewardLog.FullTime == 0 { - extendRewardLog.FullTime = fullTime - } - if extendRewardLog.ToRewardTime == 0 { - extendRewardLog.ToRewardTime = toRewardTime - } - eg.Where("id=?", extendRewardLog.Id).Update(extendRewardLog) - } - } - } - if utils.StrToFloat64(IndirectSuccess) > 0 { - if nextUserProfile != nil && nextUserProfile.ParentUid > 0 { - IndirectRewardLog, IndirectHas, _ := db.GetNewAcquisitionRewardLog(eg, &model.NewAcquisitionRewardLog{ - Uid: nextUserProfile.ParentUid, - ToUid: userProfile.Uid, - }) - if !IndirectHas { - IndirectRewardLog = &model.NewAcquisitionRewardLog{ - Uid: nextUserProfile.ParentUid, - ToUid: user.Profile.Uid, - Title: user.Info.Nickname, - Source: 2, - SourceText: "间推好友", - Money: IndirectSuccess, - CreatedAt: int(time.Now().Unix()), - State: 0, - CoinId: utils.StrToInt(cfg.RewardRule.RewardCoinId), - RewardType: utils.StrToInt(cfg.RewardRule.RewardType), - InviteTime: int(userInfo.CreateAt.Unix()), - Lv: lv, - } - db.InsertNewRewardLog(eg, IndirectRewardLog) - } - if IndirectRewardLog.GivenAt == 0 { - IndirectRewardLog.CompleteCon = str - IndirectRewardLog.IsFull = isFull - if IndirectRewardLog.FullTime == 0 { - IndirectRewardLog.FullTime = fullTime - } - if IndirectRewardLog.ToRewardTime == 0 { - IndirectRewardLog.ToRewardTime = toRewardTime - } - eg.Where("id=?", IndirectRewardLog.Id).Update(IndirectRewardLog) - } - } - } - } - - return nil -} -func Rands(minVal, maxVal string) string { - min := int(utils.StrToFloat64(minVal) * 100) - max := int(utils.StrToFloat64(maxVal) * 100) - return utils.Float64ToStrByPrec(float64(utils.RandIntRand(min, max))/100, 3) -} - -//判断是否符合条件 -func checkAllCompleteTmp(eg *xorm.Engine, user *md.User, acqCfg *md.AcquisitionCfg) (bool, string) { - res := true - str := "" - if acqCfg.SuccessConditions.Register.Open == "1" { - res = res && AcqRegisterTmp(user, acqCfg) - if res { - str += ",Register" - } - } - if acqCfg.SuccessConditions.TaobaoAuthorization.Open == "1" { - res = res && AcqTaoBaoAuthTmp(user, acqCfg) - if res { - str += ",TaobaoAuthorization" - } - } - if acqCfg.SuccessConditions.FirstOrder.Open == "1" { - res = res && AcqFirstOrder(eg, user, acqCfg) - if res { - str += ",FirstOrder" - } - } - if acqCfg.SuccessConditions.SelfOrder.Open == "1" { - res = res && AcqSelfOrder(eg, user, acqCfg) - if res { - str += ",SelfOrder" - } - } - if acqCfg.SuccessConditions.OrderPay.Open == "1" { - //AcqOrderPay(eg, user, acqCfg) - res = res && AcqOrderPay(eg, user, acqCfg) - if res { - str += ",OrderPay" - } - } - if len(str) > 0 { - str = str[1:] - } - return res, str -} -func AcqRegisterTmp(user *md.User, acqCfg *md.AcquisitionCfg) bool { - var startTime = utils.TimeStdParseUnix(acqCfg.StartTime) - var endTime = utils.TimeStdParseUnix(acqCfg.EndTime) - if startTime == 0 || endTime == 0 { - return false - } - //时间不在活动范围之内返回false - if user.Info.CreateAt.Unix() < startTime { - return false - } - if user.Info.CreateAt.Unix() > endTime { - return false - } - return true -} - -func AcqTaoBaoAuthTmp(user *md.User, acqCfg *md.AcquisitionCfg) bool { - if user.Profile.AccTaobaoAuthTime > 0 { - return true - } - return false -} - -func AcqFirstOrder(eg *xorm.Engine, user *md.User, acqCfg *md.AcquisitionCfg) bool { - endTime := int(user.Info.CreateAt.Unix()) + utils.StrToInt(acqCfg.SuccessConditions.FirstOrder.Day)*86400 - return commAmount(eg, utils.IntToStr(user.Info.Uid), endTime, 0, acqCfg) -} -func AcqSelfOrder(eg *xorm.Engine, user *md.User, acqCfg *md.AcquisitionCfg) bool { - return commAmount(eg, utils.IntToStr(user.Info.Uid), 0, 2, acqCfg) -} -func AcqOrderPay(eg *xorm.Engine, user *md.User, acqCfg *md.AcquisitionCfg) bool { - return commAmount(eg, utils.IntToStr(user.Info.Uid), 0, 1, acqCfg) -} -func sqlSelect(eg *xorm.Engine, uid string, endTime, types int, acqCfg *md.AcquisitionCfg, arr []string) int { - sql := `SELECT COUNT(*) as count FROM %s ol - LEFT JOIN %s olr on olr.oid=%s and olr.uid=%s - WHERE ol.uid=? %s %s -` - str := "" - if endTime > 0 { - str += " AND olr.create_at<=" + utils.IntToStr(endTime) - } - if types == 2 { - str += " AND olr.amount>=" + acqCfg.SuccessConditions.SelfOrder.Money - } - if types == 1 { - str += " AND %s>=" + acqCfg.SuccessConditions.OrderPay.Money - str = fmt.Sprintf(str, arr[0]) - } - sqlOrd := fmt.Sprintf(sql, arr[1], arr[2], arr[3], arr[4], str, arr[5]) - ordResult, err := db.QueryNativeString(eg, sqlOrd, uid) - fmt.Println(sqlOrd) - fmt.Println(err) - count := 0 - for _, v := range ordResult { - count = utils.StrToInt(v["count"]) - } - return count -} -func commAmount(eg *xorm.Engine, uid string, endTime, types int, acqCfg *md.AcquisitionCfg) bool { - state := "0,1,2,3,5" - psoState := "'订单付款','订单结算'" - mallState := "1,2,3" - o2oState := "1,2,3,4" - b2cState := "1,2,3,4" - if acqCfg.SuccessConditions.FirstOrder.Status == "1" { - state = "1,2,3,5" - mallState = "2,3" - o2oState = "2,3,4" - b2cState = "2,3,4" - } - if acqCfg.SuccessConditions.FirstOrder.Status == "2" { - state = "2,3,5" - mallState = "2,3" - o2oState = "2,3,4" - b2cState = "2,3,4" - } - if acqCfg.SuccessConditions.FirstOrder.Status == "3" { - state = "3,5" - mallState = "3" - o2oState = "3,4" - b2cState = "3,4" - psoState = "'订单结算'" - } - - arr := []string{"ol.paid_price", "ord_list", "ord_list_relate", "ol.ord_id", "ol.uid", " and ol.state in(" + state + ")"} - count := sqlSelect(eg, uid, endTime, types, acqCfg, arr) - arr = []string{"ol.paid_price", "privilege_card_ord", "ord_list_relate", "ol.ord_id", "ol.uid", " and ol.state=1"} - count += sqlSelect(eg, uid, endTime, types, acqCfg, arr) - arr = []string{"ol.money", "express_order", "ord_list_relate", "ol.oid", "ol.uid", " and ol.status in('待取件','运输中','已完成')"} - count += sqlSelect(eg, uid, endTime, types, acqCfg, arr) - arr = []string{"ol.commission", "duoyou_ord_list", "ord_list_relate", "ol.oid", "ol.uid", " and ol.id>0"} - count += sqlSelect(eg, uid, endTime, types, acqCfg, arr) - arr = []string{"ol.amount", "recharge_order", "ord_list_relate", "ol.oid", "ol.uid", " and ol.status<>'已退款'"} - count += sqlSelect(eg, uid, endTime, types, acqCfg, arr) - arr = []string{"ol.amount", "playlet_sale_order", "ord_list_relate", "ol.custom_oid", "ol.uid", " and ol.status in(" + psoState + ")"} - count += sqlSelect(eg, uid, endTime, types, acqCfg, arr) - - arr = []string{"ol.cost_price", "mall_ord", "mall_ord_list_relate", "ol.ord_id", "ol.uid", " and ol.state in(" + mallState + ")"} - count += sqlSelect(eg, uid, endTime, types, acqCfg, arr) - - arr = []string{"ol.cost_price", "o2o_ord", "o2o_ord_list_relate", "ol.ord_id", "ol.uid", " and ol.state in(" + o2oState + ")"} - count += sqlSelect(eg, uid, endTime, types, acqCfg, arr) - arr = []string{"ol.actual_pay_amount", "o2o_pay_to_merchant", "o2o_ord_list_relate", "ol.pay_id", "ol.uid", " and ol.state >=1"} - count += sqlSelect(eg, uid, endTime, types, acqCfg, arr) - arr = []string{"ol.cost_price", "b2c_ord", "b2c_ord_list_relate", "ol.ord_id", "ol.uid", " and ol.state in(" + b2cState + ")"} - count += sqlSelect(eg, uid, endTime, types, acqCfg, arr) - if count > 0 { - return true - } - return false -} diff --git a/consume/zhios_acquisition_condition_dev.go b/consume/zhios_acquisition_condition_dev.go deleted file mode 100644 index a87841e..0000000 --- a/consume/zhios_acquisition_condition_dev.go +++ /dev/null @@ -1,59 +0,0 @@ -package consume - -import ( - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" -) - -func ZhiosAcquisitionConditionDev(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(300) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>ZhiosAcquisitionCondition<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleZhiosAcquisition(res.Body) - //_ = res.Reject(false) - fmt.Println(err) - if err == nil { - _ = res.Ack(true) - } else { - - var canalMsg *md.ZhiosAcquisition - var tmpString string - err := json.Unmarshal(res.Body, &tmpString) - if err == nil { - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err == nil { - ch.Publish(queue.ExchangeName, utils.SerializeStr(canalMsg), queue.RoutKey) - } - } - - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} diff --git a/consume/zhios_appreciation.go b/consume/zhios_appreciation.go deleted file mode 100644 index c3201b5..0000000 --- a/consume/zhios_appreciation.go +++ /dev/null @@ -1,326 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/db/model" - "applet/app/svc" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - md2 "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" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "xorm.io/xorm" -) - -func ZhiosAppreciation(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleZhiosAppreciation(res.Body) - //_ = res.Reject(false) - if err == nil { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleZhiosAppreciation(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.ZhiosAppreciation - fmt.Println(string(msg)) - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println("===with", err.Error()) - return err - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err != nil { - fmt.Println("===with", err.Error()) - return err - } - mid := canalMsg.Mid - eg := db.DBs[mid] - if eg == nil { - return nil - } - - //类型 转入 exchange - if canalMsg.Type == "exchange" { - err := exchange(eg, canalMsg) - if err != nil { - return err - } - } - //类型 提现 withdraw 到余额 - if canalMsg.Type == "withdraw" { - err := withdraw(eg, canalMsg) - if err != nil { - return err - } - } - //类型 购物销毁 - if canalMsg.Type == "destroy" { - err := destroy(eg, canalMsg) - if err != nil { - return err - } - } - //类型 购物退回 - if canalMsg.Type == "buy_refund" { - err := buyRefund(eg, canalMsg) - if err != nil { - return err - } - } - - return nil -} - -//转入 操作加入资金池和加入积分 -func exchange(eg *xorm.Engine, msg *md.ZhiosAppreciation) error { - - sess := eg.NewSession() - defer sess.Close() - sess.Begin() - //计算出当前的价值 - args := make(map[string]string) - json.Unmarshal([]byte(msg.Ext), &args) - biliMap := caleBili(eg, sess, msg.Mid, args) - ordId := utils.OrderUUID(utils.StrToInt(msg.Uid)) - coinMapInUse, _ := db.VirtualCoinMapInUse(eg, msg.Mid, "") - //积分加入 - title := coinMapInUse[args["id"]].Name + "-转入" - appreciationCoinId := db.SysCfgGetWithDb(eg, msg.Mid, "appreciation_coin_id") - _, err := svc.ExchangeUserVirFinValidAndInterFlowWithSession(sess, - utils.StrToFloat64(biliMap["in_coin"]), title, "0", 1, 109, utils.StrToInt(msg.Uid), utils.StrToInt(appreciationCoinId), 0, utils.StrToInt64(ordId), "", 0, 0) - if err != nil { - sess.Rollback() - return err - } - base := db.GetAppreciationBase(sess) - beforeValue := "0" - beforeFlowValue := "0" - if base != nil { - beforeValue = base.Sum - beforeFlowValue = base.FlowSum - } - err = db.InsertAppreciation(sess, appreciationCoinId, msg.Uid, "0", "0", msg.Oid, biliMap["coin"], biliMap["in_coin"], beforeValue, beforeFlowValue) - if err != nil { - sess.Rollback() - return err - } - //加入资金池 - sql := `UPDATE appreciation_base SET sum=sum+?,flow_sum=flow_sum+? WHERE is_use=1;` - _, err = sess.Exec(sql, utils.StrToFloat64(biliMap["coin"]), utils.StrToFloat64(biliMap["in_coin"])) - if err != nil { - sess.Rollback() - return err - } - sess.Commit() - return nil -} - -//提现 -func withdraw(eg *xorm.Engine, msg *md.ZhiosAppreciation) error { - sess := eg.NewSession() - defer sess.Close() - sess.Begin() - args := make(map[string]string) - json.Unmarshal([]byte(msg.Ext), &args) - //资产价值 - price := "" - appreciationWithdrawFee := db.SysCfgGetWithDb(eg, msg.Mid, "appreciation_withdraw_fee") - appreciationWithdrawBack := db.SysCfgGetWithDb(eg, msg.Mid, "appreciation_withdraw_back") - feeMap := md2.DealWithdrawalFeeResp{ - WithdrawalCommissionFee: utils.StrToFloat64(appreciationWithdrawFee) / 100, - WithdrawalDestroyFee: (utils.StrToFloat64(appreciationWithdrawFee) - utils.StrToFloat64(appreciationWithdrawBack)) / 100, - WithdrawalRefluxFee: utils.StrToFloat64(appreciationWithdrawBack) / 100, - } - _, resp := rule.DealWithdrawalAndDestroy(sess, feeMap, utils.StrToFloat64(args["amount"])) - //这是到手的 - newAmount := utils.GetPrec(utils.Float64ToStrByPrec(resp.TransferOutValue-resp.AmountOut, 5), "4") - //扣的 - coinSum := utils.GetPrec(utils.Float64ToStrByPrec(resp.TransferOutValue-resp.RefluxValue, 20), "4") - price = utils.GetPrec(utils.Float64ToStrByPrec(resp.Price, 20), "4") - err := svc.UpdateUserFinValidAndInterFlowSess(sess, - newAmount, args["amount"]+"个数字资产转余额,价值"+price+"/个", "appreciation", 0, 56, utils.StrToInt(msg.Uid), utils.StrToInt(msg.Oid), utils.StrToInt64(msg.Oid), utils.StrToInt64(msg.Oid)) - if err != nil { - sess.Rollback() - return err - } - base := db.GetAppreciationBase(sess) - beforeValue := "0" - beforeFlowValue := "0" - if base != nil { - beforeValue = base.Sum - beforeFlowValue = base.FlowSum - } - appreciationCoinId := db.SysCfgGetWithDb(eg, msg.Mid, "appreciation_coin_id") - //转出 - err = db.InsertAppreciation(sess, appreciationCoinId, msg.Uid, "1", "1", msg.Oid, args["amount"], args["amount"], beforeValue, beforeFlowValue) - if err != nil { - sess.Rollback() - return err - } - ////销毁的 - beforeValue = utils.GetPrec(utils.Float64ToStrByPrec(utils.StrToFloat64(beforeValue)-resp.TransferOutValue, 5), "4") - beforeFlowValue = utils.GetPrec(utils.Float64ToStrByPrec(utils.StrToFloat64(beforeFlowValue)-utils.StrToFloat64(args["amount"]), 5), "4") - //DestroyValue := utils.GetPrec(utils.Float64ToStrByPrec(resp.DestroyValue, 5), "4") - //err = db.InsertAppreciation(sess, appreciationCoinId, args["uid"], "2", "1", DestroyValue, "0", beforeValue, beforeFlowValue) - //if err != nil { - // sess.Rollback() - // return err - //} - //回流的 - RefluxValue := utils.GetPrec(utils.Float64ToStrByPrec(resp.RefluxValue, 5), "4") - err = db.InsertAppreciation(sess, appreciationCoinId, msg.Uid, "3", "0", msg.Oid, RefluxValue, "0", beforeValue, beforeFlowValue) - if err != nil { - sess.Rollback() - return err - } - sql := `UPDATE appreciation_base SET sum=sum-?,flow_sum=flow_sum-? WHERE is_use=1;` - _, err = eg.Exec(sql, utils.StrToFloat64(coinSum), utils.StrToFloat64(args["amount"])) - if err != nil { - sess.Rollback() - return err - } - sess.Where("ord_id=?", msg.Oid).Cols("price").Update(&model.UserVirtualCoinFlow{Price: price}) - sess.Commit() - return nil -} - -//购物销毁 -func destroy(eg *xorm.Engine, msg *md.ZhiosAppreciation) error { - args := make(map[string]string) - json.Unmarshal([]byte(msg.Ext), &args) - sess := eg.NewSession() - defer sess.Close() - sess.Begin() - base := db.GetAppreciationBase(sess) - beforeValue := "0" - beforeFlowValue := "0" - if base != nil { - beforeValue = base.Sum - beforeFlowValue = base.FlowSum - } - appreciationCoinId := db.SysCfgGetWithDb(eg, msg.Mid, "appreciation_coin_id") - //转出 - err := db.InsertAppreciation(sess, appreciationCoinId, msg.Uid, "4", "1", msg.Oid, args["coinPrice"], args["amount"], beforeValue, beforeFlowValue) - if err != nil { - sess.Rollback() - return err - } - - sql := `UPDATE appreciation_base SET sum=sum-?,flow_sum=flow_sum-? WHERE is_use=1;` - _, err = eg.Exec(sql, utils.StrToFloat64(args["coinPrice"]), utils.StrToFloat64(args["amount"])) - if err != nil { - sess.Rollback() - return err - } - sess.Commit() - return nil -} - -//购物退回 -func buyRefund(eg *xorm.Engine, msg *md.ZhiosAppreciation) error { - args := make(map[string]string) - json.Unmarshal([]byte(msg.Ext), &args) - sess := eg.NewSession() - defer sess.Close() - sess.Begin() - base := db.GetAppreciationBase(sess) - beforeValue := "0" - beforeFlowValue := "0" - if base != nil { - beforeValue = base.Sum - beforeFlowValue = base.FlowSum - } - appreciationCoinId := db.SysCfgGetWithDb(eg, msg.Mid, "appreciation_coin_id") - //转出 - err := db.InsertAppreciation(sess, appreciationCoinId, msg.Uid, "5", "0", msg.Oid, args["coinPrice"], args["amount"], beforeValue, beforeFlowValue) - if err != nil { - sess.Rollback() - return err - } - - sql := `UPDATE appreciation_base SET sum=sum+?,flow_sum=flow_sum+? WHERE is_use=1;` - _, err = eg.Exec(sql, utils.StrToFloat64(args["coinPrice"]), utils.StrToFloat64(args["amount"])) - if err != nil { - sess.Rollback() - return err - } - sess.Commit() - return nil -} -func caleBili(eg *xorm.Engine, sess *xorm.Session, dbName string, args map[string]string) map[string]string { - appreciationCoinId := db.SysCfgGetWithDb(eg, dbName, "appreciation_coin_id") - bCoinStr := "" - bcoin := "" - if args["id"] == "cny" { - bCoinStr = args["amount"] - } else { - ids := []string{args["id"], appreciationCoinId} - coin := db.VirtualCoinByIds(eg, ids) - aCoinBili := coin[args["id"]].ExchangeRatio - //1:5=X:money X= 1:5*money - amoney := (1 / utils.StrToFloat64(aCoinBili)) * utils.StrToFloat64(args["amount"]) - bcoin = utils.GetPrec(utils.Float64ToStrByPrec(amoney, 5), "4") - //这是只返70% - appreciationCoinFee := db.SysCfgGetWithDb(eg, dbName, "appreciation_coin_fee") - bCoins := amoney * (utils.StrToFloat64(appreciationCoinFee) / 100) - //除以当前的资产价值 - _, value := rule.DealTransferIn(sess, bCoins) - bCoins = value - bCoinStr = utils.GetPrec(utils.Float64ToStrByPrec(bCoins, 20), "4") - } - res := map[string]string{ - "in_coin": bCoinStr, - "coin": bcoin, - } - return res -} -func coinPriceEg(eg *xorm.Engine) map[string]string { - base := db.GetAppreciationBaseEg(eg) - sum := "0" - flowSum := "0" - price := "1" - if base != nil { - sum = base.Sum - flowSum = base.FlowSum - } - price = utils.GetPrec(utils.Float64ToStrByPrec(utils.StrToFloat64(sum)/utils.StrToFloat64(flowSum), 5), "4") - res := map[string]string{ - "price": price, - "sum": sum, - "flow_sum": flowSum, - } - return res -} diff --git a/consume/zhios_capital_pool_order_total.go b/consume/zhios_capital_pool_order_total.go deleted file mode 100644 index 3eb73fd..0000000 --- a/consume/zhios_capital_pool_order_total.go +++ /dev/null @@ -1,168 +0,0 @@ -package consume - -import ( - "applet/app/db" - model2 "applet/app/db/model" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "github.com/syyongx/php2go" - "time" - "xorm.io/xorm" -) - -func ZhiosCapitalPoolOrderTotal(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(20) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleZhiosCapitalPoolOrderTotal(res.Body) - //_ = res.Reject(false) - if err == nil { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleZhiosCapitalPoolOrderTotal(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.ZhiosCapitalPoolOrderTotal - fmt.Println(string(msg)) - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println(err.Error()) - return err - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err != nil { - return err - } - mid := canalMsg.Mid - eg := db.DBs[mid] - err = AddUserOrdTotal(eg, canalMsg.Mid, canalMsg.Uid, canalMsg.Runtime, canalMsg.TotalTime, canalMsg.BonusLevelType, canalMsg.Level) - if err != nil { - fmt.Println(err) - return err - } - return nil -} -func AddUserOrdTotal(eg *xorm.Engine, dbName string, uids []string, runtime, totalTime int64, leveType int, level string) error { - if len(uids) == 0 { - return nil - } - m := GetUserOrdTotal(eg, uids, totalTime) - var data []model2.CapitalPoolOrderTotal - err := eg.In("uid", uids).And("create_time=? and level_type=? and level=?", time.Unix(runtime, 0).Format("2006-01-02"), leveType, level).Find(&data) - var userData = make(map[string]model2.CapitalPoolOrderTotal) - if err == nil { - for _, v := range data { - userData[utils.IntToStr(v.Uid)] = v - } - } - for k, v := range m { - user, ok := userData[k] - if ok { - user.Sum = utils.Float64ToStrByPrec(v, 2) - user.UpdateTime = time.Now() - eg.Where("id=?", user.Id).Cols("sum,update_time").Update(&user) - } else { - fmt.Println(time.Unix(runtime, 0).Format("2006-01-02")) - var userDatas = &model2.CapitalPoolOrderTotal{ - Uid: utils.StrToInt(k), - Sum: utils.Float64ToStrByPrec(v, 2), - CreateTime: time.Unix(runtime, 0).Format("2006-01-02"), - UpdateTime: time.Now(), - LevelType: leveType, - Level: utils.StrToInt(level), - } - fmt.Println(userDatas) - _, err := eg.InsertOne(userDatas) - if err != nil { - utils.FilePutContents(dbName+"capital", utils.SerializeStr(userDatas)) - utils.FilePutContents(dbName+"capital", err.Error()) - return err - } - } - } - sum, _ := eg.Where("create_time=? and level_type=? and level=?", time.Unix(runtime, 0).Format("2006-01-02"), leveType, level).Sum(&model2.CapitalPoolOrderTotal{}, "sum") - fmt.Println(sum) - - sql := `UPDATE capital_pool_order_total SET all_sum=%f WHERE create_time='%s' and level_type=%d and level=%s;` - sql = fmt.Sprintf(sql, sum, time.Unix(runtime, 0).Format("2006-01-02"), leveType, level) - db.QueryNativeString(eg, sql) - return nil -} - -func GetUserOrdTotal(eg *xorm.Engine, uids []string, totalTime int64) map[string]float64 { - totalTimeStr := time.Unix(totalTime, 0) - var userMap = make(map[string]float64, 0) - if len(uids) == 0 { - return userMap - } - uidStr := php2go.Implode(",", uids) - guideSql := `SELECT SUM(paid_price) AS amount,uid FROM ord_list WHERE uid IN (%s) AND state IN(%s) AND confirm_at>=%d GROUP BY uid;` - guideSql = fmt.Sprintf(guideSql, uidStr, "1,2,3,5", totalTime) - guide, err := db.QueryNativeString(eg, guideSql) - fmt.Println(err) - if len(guide) > 0 { - for _, v := range guide { - userMap[v["uid"]] += utils.StrToFloat64(v["amount"]) - } - } - mallSql := `SELECT SUM(cost_price) AS amount,uid FROM mall_ord WHERE uid IN (%s) AND state IN(%s) AND confirm_time>='%s' GROUP BY uid;` - mallSql = fmt.Sprintf(mallSql, uidStr, "3", totalTimeStr) - mall, err := db.QueryNativeString(eg, mallSql) - fmt.Println(err) - - if len(mall) > 0 { - for _, v := range mall { - userMap[v["uid"]] += utils.StrToFloat64(v["amount"]) - } - } - cardSql := `SELECT SUM(paid_price) AS amount,uid FROM privilege_card_ord WHERE uid IN (%s) AND state IN(%s) AND created_at>=%d GROUP BY uid;` - cardSql = fmt.Sprintf(cardSql, uidStr, "1", totalTime) - card, err := db.QueryNativeString(eg, cardSql) - fmt.Println(err) - if len(card) > 0 { - for _, v := range card { - userMap[v["uid"]] += utils.StrToFloat64(v["amount"]) - } - } - rechargeSql := `SELECT SUM(amount) AS amount,uid FROM recharge_order WHERE uid IN (%s) AND status='已付款' AND create_time>='%s' GROUP BY uid;` - rechargeSql = fmt.Sprintf(rechargeSql, uidStr, time.Unix(totalTime, 0).Format("2006-01-02 15:04:05")) - recharge, err := db.QueryNativeString(eg, rechargeSql) - fmt.Println(err) - if len(recharge) > 0 { - for _, v := range recharge { - userMap[v["uid"]] += utils.StrToFloat64(v["amount"]) - } - } - return userMap -} diff --git a/consume/zhios_express_order_fail.go b/consume/zhios_express_order_fail.go deleted file mode 100644 index 3c5822d..0000000 --- a/consume/zhios_express_order_fail.go +++ /dev/null @@ -1,263 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/db/offical" - "applet/app/db/offical/model" - "applet/app/e" - "applet/app/svc" - "applet/app/utils" - "applet/app/utils/cache" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "code.fnuoos.com/go_rely_warehouse/zyos_go_third_party_api.git/express" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "github.com/tidwall/gjson" - "time" -) - -func ZhiosExpressOrderFail(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleZhiosExpressOrderFail(res.Body) - //_ = res.Reject(false) - if err == nil { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleZhiosExpressOrderFail(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.ZhiosExpressOrderFails - fmt.Println(string(msg)) - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println(err.Error()) - return err - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err != nil { - return err - } - mid := canalMsg.Mid - eg := db.DBs[mid] - if eg == nil { - return nil - } - //判断订单是否订单失败 - ord := db.GetExpressWithOid(eg, canalMsg.Oid) - officialOrd := offical.GetExpressWithOid(canalMsg.Oid) - if ord.Status == "已退回" { - return nil - } - ordExpressPlatform := utils.IntToStr(ord.ExpressPlatform) - base := CommBase(mid, ordExpressPlatform) - if canalMsg.IsFail != "1" { //查下订单详情 - param := map[string]interface{}{ - "clientOrderNo": canalMsg.Oid, - } - order, _ := express.ShowOrder(base, param) - if gjson.Get(order, "code").Int() == 500 || gjson.Get(order, "code").String() != "00" || gjson.Get(order, "data.status").String() == "CANCELED" { - ord.Status = "订单失败" - } - } - if ord.Status == "订单失败" || ord.Status == "已取消" { - ord.Status = "已退回" - ord.IsRefund = 1 - ord.RefundTime = time.Now() - if ord.Own != 1 { - officialOrd.Status = "已退回" - officialOrd.IsRefund = 1 - officialOrd.RefundTime = time.Now() - db.Db.Where("oid=?", officialOrd.Oid).Update(officialOrd) - } - eg.Where("oid=?", ord.Oid).Update(ord) - svc.DealMoneyWithEg(eg, ord.Uid, ord.Money, 56, utils.StrToInt64(ord.Oid), 0, 0, "快递退款", "express", 0) - if ord.AgentPay == 1 { - agentDeduct(ord.Oid, base, ord.AgentPrice) - } - if ord.StationPay == 1 { - stationDeduct(mid, ord.Oid, base, ord.StationPrice) - } - } - return nil -} - -//站长预存款扣除 -func stationDeduct(dbName, oid string, base map[string]string, price string) (error, int) { - eg := db.Db - var user model.ExpressUserMoney - get, err := eg.Where("uid=? and agent_uid=?", dbName, base["puid"]).Get(&user) - if get == false || err != nil { - return e.NewErr(400, "站点预存款不足!"), 0 - } - user.Money = utils.Float64ToStr(utils.StrToFloat64(user.Money) + utils.StrToFloat64(price)) - _, err = eg.Where("id=?", user.Id).Update(&user) - if err != nil { - return e.NewErr(400, "站点预存款扣除失败!"), 0 - } - var flow = &model.ExpressUserMoneyFlow{ - Uid: user.Uid, - Type: 0, - Time: time.Now(), - Amount: price, - AfterAmount: user.Money, - Oid: oid, - Title: "快递退款", - } - _, err = eg.Insert(flow) - if err != nil { - return e.NewErr(400, "站点预存款扣除失败!"), 0 - } - return nil, 1 -} -func agentDeduct(oid string, base map[string]string, price string) (error, int) { - eg := db.Db - var user model.ExpressAgentMoney - get, err := eg.Where("uid=?", base["puid"]).Get(&user) - if get == false || err != nil { - return e.NewErr(400, "平台预存款不足!"), 0 - } - user.Money = utils.Float64ToStr(utils.StrToFloat64(user.Money) + utils.StrToFloat64(price)) - _, err = eg.Where("id=?", user.Id).Update(&user) - if err != nil { - return e.NewErr(400, "平台预存款扣除失败!"), 0 - } - var flow = &model.ExpressAgentMoneyFlow{ - Puid: utils.StrToInt(base["puid"]), - Uid: user.Uid, - Type: 0, - Time: time.Now(), - Amount: price, - AfterAmount: user.Money, - Oid: oid, - Title: "快递退款", - } - _, err = eg.Insert(flow) - if err != nil { - return e.NewErr(400, "平台预存款扣除失败!"), 0 - } - return nil, 1 -} - -func AppUserListPuid(mid string) string { - appList := offical.GetUserAppList(mid) - uid := "0" - if appList != nil && appList.Puid > 0 { - uid = utils.IntToStr(appList.Puid) - } - - return uid -} -func AppUserListPuidNew(mid string, ordExpressPlatform string) string { - appList := offical.GetUserAppList(mid) - uid := "0" - if appList != nil && appList.Puid > 0 { - uid = utils.IntToStr(appList.Puid) - } - expressPlatform := offical.MasterListCfgGetOneData(uid, "express_platform_type") - if expressPlatform == "1" || ordExpressPlatform == "1" { //如果是1 走智莺官方 - uid = "0" - } - return uid -} - -func CommBase(mid, ordExpressPlatform string) map[string]string { - puid := AppUserListPuidNew(mid, ordExpressPlatform) - key := puid + "_official_express_info" - stringStr, err := cache.GetString(key) - stringMap := make(map[string]string) - json.Unmarshal([]byte(stringStr), &stringMap) - if len(stringMap) == 0 || err != nil { - expressType := offical.MasterListCfgGetOneData(puid, "express_type") - expressUrl := offical.MasterListCfgGetOneData(puid, "express_url") - expressClientId := offical.MasterListCfgGetOneData(puid, "express_client_id") - expressKey := offical.MasterListCfgGetOneData(puid, "express_key") - expressMinSendMoney := offical.MasterListCfgGetOneData(puid, "express_min_send_money") //最低预存款 - expressFeeSendMoney := offical.MasterListCfgGetOneData(puid, "express_fee_send_money") //充值预存款手续费 - expressFirstPayBili := offical.MasterListCfgGetOneData(puid, "express_first_pay_bili") //首重加价 - expressSecondPayBili := offical.MasterListCfgGetOneData(puid, "express_second_pay_bili") //续重加价 - stringMap = map[string]string{ - "puid": puid, - "express_type": expressType, - "express_url": expressUrl, - "express_key": expressKey, - "express_client_id": expressClientId, - "express_min_send_money": "", - "express_fee_send_money": "", - "express_first_pay_bili": "", - "express_second_pay_bili": "", - "official_express_min_send_money": expressMinSendMoney, - "official_express_fee_send_money": expressFeeSendMoney, - "official_express_first_pay_bili": expressFirstPayBili, - "official_express_second_pay_bili": expressSecondPayBili, - } - //如果是官方 不是代理就没有代理的设置 - //如果是代理 就有代理的设置 - if utils.StrToInt(puid) > 0 { - stringMap["express_min_send_money"] = expressMinSendMoney - stringMap["express_fee_send_money"] = expressFeeSendMoney - stringMap["express_first_pay_bili"] = expressFirstPayBili - stringMap["express_second_pay_bili"] = expressSecondPayBili - if stringMap["express_type"] == "1" { //代理自有渠道,智莺的加价不用了 - stringMap["official_express_min_send_money"] = "" - stringMap["official_express_fee_send_money"] = "" - stringMap["official_express_first_pay_bili"] = "" - stringMap["official_express_second_pay_bili"] = "" - } - } - cache.SetEx(key, utils.SerializeStr(stringMap), 300) - - } - if utils.StrToInt(puid) > 0 && stringMap["express_type"] != "1" { //跟随官方 - key1 := "0_official_express_info" - stringStr1, err1 := cache.GetString(key1) - stringMap1 := make(map[string]string) - json.Unmarshal([]byte(stringStr1), &stringMap1) - if len(stringMap1) == 0 || err1 != nil { //如果是代理 但只有官方设置 - stringMap1 = make(map[string]string) - - stringMap1["express_url"] = offical.MasterListCfgGetOneData("0", "express_url") - stringMap1["express_client_id"] = offical.MasterListCfgGetOneData("0", "express_client_id") - stringMap1["express_key"] = offical.MasterListCfgGetOneData("0", "express_key") - stringMap1["official_express_min_send_money"] = offical.MasterListCfgGetOneData("0", "express_min_send_money") //最低预存款 - stringMap1["official_express_fee_send_money"] = offical.MasterListCfgGetOneData("0", "express_fee_send_money") //充值预存款手续费 - stringMap1["official_express_first_pay_bili"] = offical.MasterListCfgGetOneData("0", "express_first_pay_bili") //首重加价 - stringMap1["official_express_second_pay_bili"] = offical.MasterListCfgGetOneData("0", "express_second_pay_bili") //续重加价 - cache.SetEx(key1, utils.SerializeStr(stringMap1), 300) - } - for k, v := range stringMap1 { - stringMap[k] = v - } - } - return stringMap -} diff --git a/consume/zhios_fast_return_order_pay.go b/consume/zhios_fast_return_order_pay.go deleted file mode 100644 index 2a027f6..0000000 --- a/consume/zhios_fast_return_order_pay.go +++ /dev/null @@ -1,217 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/db/model" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "code.fnuoos.com/go_rely_warehouse/zyos_go_pay.git/pay" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "github.com/tidwall/gjson" - "time" - "xorm.io/xorm" -) - -func ZhiosFastReturnOrderPay(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(10) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleZhiosFastReturnOrderPay(res.Body) - //_ = res.Reject(false) - fmt.Println(err) - if err == nil { - _ = res.Ack(true) - } else { - //var canalMsg *md.ZhiosFatReturnOrderPay - //var tmpString string - //err := json.Unmarshal(res.Body, &tmpString) - //if err == nil { - // fmt.Println(tmpString) - // err = json.Unmarshal([]byte(tmpString), &canalMsg) - // if err == nil { - // ch.Publish(queue.ExchangeName, utils.SerializeStr(canalMsg), queue.RoutKey) - // } - //} - - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleZhiosFastReturnOrderPay(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.ZhiosFatReturnOrderPay - fmt.Println(string(msg)) - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println(err.Error()) - return err - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err != nil { - return err - } - mid := canalMsg.Mid - eg := db.DBs[mid] - uid := utils.StrToInt(canalMsg.Uid) - oid := canalMsg.Oid - isFastReturn, info := CommCheckFastReturn(eg, uid, mid) - if isFastReturn == 0 { - return nil - } - var orderData model.OrdList - b, err2 := eg.Where("ord_id=?", oid).Get(&orderData) - if b == false || err2 != nil { - return errors.New("err") - } - if (orderData.IsFastSign == 1 && orderData.IsTransfer == 1) || orderData.State == 4 || orderData.IsWaitReduce > 0 { - return nil - } - var data1 model.OrdListRelate - get, err := eg.Where("uid=? and oid=? and level=?", uid, oid, 0).Get(&data1) - if get == false || err != nil { - return errors.New("err") - } - amount := int(data1.Amount * 100) - if amount <= 0 { - return nil - } - money := utils.Float64ToStr(float64(amount) / 100) - fmt.Println(money) - fastReturnMoney := db.SysCfgFindWithDb(eg, mid, "fast_return_money") - if utils.StrToFloat64(info.Money)+utils.StrToFloat64(money) > utils.StrToFloat64(fastReturnMoney["fast_return_money"]) { - return nil - } - if orderData.IsFastSign == 0 { - args := map[string]string{ - "out_order_no": oid, - "credit_agreement_id": info.CreditAgreementId, - "category_id": "pay_for_rebate_0001", - "order_amount": money, - "amount_type": "ORDER_AMOUNT", - "subject": canalMsg.Name + oid, - } - args = CommInfo(eg, mid, args) - fmt.Println(args) - order, err := pay.CreditagreementOrder(args) - if err != nil { - utils.FilePutContents(mid+"CreditagreementOrder_err", err.Error()) - } - utils.FilePutContents(mid+"CreditagreementOrder", utils.SerializeStr(args)) - utils.FilePutContents(mid+"CreditagreementOrder", utils.SerializeStr(order)) - if err != nil || order == nil { - return nil - } - if order.ZhimaCreditPayafteruseCreditbizorderOrderResponse.Code != "10000" { - return nil - } - orderData.IsFastSign = 1 - orderData.FastSignId = order.ZhimaCreditPayafteruseCreditbizorderOrderResponse.CreditBizOrderId - eg.Where("ord_id=?", oid).Cols("is_fast_sign,fast_sign_id").Update(&orderData) - sql := "UPDATE user_alipay_info SET money=money+? WHERE uid=?" - db.QueryNativeString(eg, sql, money, orderData.Uid) - } - if info.AlipayId != "" && orderData.IsTransfer != 1 { - //转账 - args1 := map[string]string{ - "out_biz_no": utils.Int64ToStr(orderData.OrdId), - "trans_amount": money, - "identity": info.AlipayId, - "identity_type": "ALIPAY_USER_ID", - "product_code": "TRANS_ACCOUNT_NO_PWD", - "biz_scene": "DIRECT_TRANSFER", - "order_title": canalMsg.Name + "秒返", - } - args1 = CommInfo(eg, mid, args1) - fmt.Println(utils.SerializeStr(args1)) - sign, err := pay.AlipayFundTransUniTransfer(args1) - if err != nil { - utils.FilePutContents(mid+"transfer_err", err.Error()) - } - fmt.Println(sign) - utils.FilePutContents(mid+"transfer", utils.SerializeStr(args1)) - utils.FilePutContents(mid+"transfer", utils.SerializeStr(sign)) - if sign != nil && sign.AlipayFundTransUniTransferResponse.Code == "10000" { - orderData.TransferSignId = sign.AlipayFundTransUniTransferResponse.OrderId - if sign.AlipayFundTransUniTransferResponse.Status == "SUCCESS" { - orderData.IsTransfer = 1 - var flow = &model.FinUserFlow{ - Type: 0, - Uid: orderData.Uid, - Amount: "", - PaymentType: 3, - BeforeAmount: "0", - AfterAmount: "0", - OrdType: "fast_return", - OrdId: utils.AnyToString(orderData.OrdId), - OrdAction: 103, - OrdTitle: "佣金到账" + money + "元(已到支付宝)", - State: 2, - OtherId: 0, - OrdTime: int(time.Now().Unix()), - CreateAt: time.Now(), - } - eg.Insert(flow) - } else { - orderData.IsTransfer = 2 - } - eg.Where("ord_id=?", oid).Cols("is_transfer,transfer_sign_id").Update(&orderData) - - } else { - fmt.Println(sign) - return errors.New("失败") - } - } - - return nil -} -func CommCheckFastReturn(eg *xorm.Engine, uid int, mid string) (int, *model.UserAlipayInfo) { - fastReturnOnoff := db.SysCfgFindWithDb(eg, mid, "fast_return_onoff") - info := db.GetUserAlipayInfo(eg, uid) - if info.IsSign == 0 || info.IsOpen == 0 || info.CreditAgreementId == "" || fastReturnOnoff["fast_return_onoff"] != "1" { - return 0, nil - } - return 1, info -} -func CommInfo(eg *xorm.Engine, mid string, args map[string]string) map[string]string { - fastReturnAlipay := db.SysCfgFindWithDb(eg, mid, "fast_return_alipay") - fastReturnAlipayInfo := fastReturnAlipay["fast_return_alipay"] - args["pay_app_cert_sn"] = gjson.Get(fastReturnAlipayInfo, "pay_app_cert_sn").String() - args["pay_alipayrsa_public_key"] = gjson.Get(fastReturnAlipayInfo, "pay_alipayrsa_public_key").String() - args["pay_ali_use_type"] = gjson.Get(fastReturnAlipayInfo, "pay_ali_use_type").String() - args["private_key"] = gjson.Get(fastReturnAlipayInfo, "private_key").String() - args["app_id"] = gjson.Get(fastReturnAlipayInfo, "app_id").String() - //args["pay_app_cert_sn"] = "25024da974663c98d943ec355e561863" - //args["pay_alipayrsa_public_key"] = "549086292366017b7710dcc74b7969c8" - //args["pay_ali_use_type"] = "1" - //args["private_key"] = "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCunVhChSZGSjiuxNrvyd2a06XAT3J7NLH1fjWiy4HfdhH769xejqFdYFGvRrWCyXRNm/ionWmplzHBopnfTP/tbdoqM7HjZegORCDV3mnB4VVqFgXbrJHlh2lum75zysFbj/7pskGG/tzc8CdjbuTkqt3Z7EXBn8RyUvBi+42XAV51dg1k8DsucoSXuKBW6H2iR27HdDYsmsZmGMIa3NaOIq69i1vMq19bu+UsoBVFHA4DBzwwAHWZEiR+hFg99vhEDyby972kgnBCPnQL2Y8xiXufKpvKFzDCJ/aDNzoWhLfr7QAUKL3vleH8z53sQDy4hTYPLYPT2Y+gGAB6LPMpAgMBAAECggEAB3iL8iyoOpGqYy/g/ilw5dLwYI4Fo+fZRVulB9YVNG5kzpaE0zbfCJO6avlngrUD2N43gV9ayfrCEjrWwosU2B+/GdckYUpW52Va0ku10qnFcciHb6Kui1eD10uqlmGybCx5B56s1w3IfVt5E/QGrxHwdAZ75ZDkYs/RoSqKIE/IkfE3FpUYwBrj8vfvCsrzvThqTSXxq3KgyH8wzcSOca9UuO41po0n3my/4PdceBufMgm0sZS0IawOwuciXljXaCsRQ0Z9q2Wun5aYE5mGkUcVyZYbYl3of/VBBueq+egauvRq5n23JQ7UBCMpwZYgKrlHUTW2Szl8iibkVmMn0QKBgQDdzxeB/I0dg/UYs5lTjk9eQnyaEZhg+wulHnnhPkwPMAChUotzFa/r22ND+4Q/gLj9Q/6SzwOm8eFi20lX7teWJyEmy1/BWrRrhL/G7GMMg2zf4XWt4+TW7oSx4aHxCu2jbleUYqJ3f+eN4BfYSOKAwh1bxtAJmTxlhY7JwlLuOwKBgQDJh+U04CdJA6E0k8pkRa1XmR0K+zkQl8ksrj37zF91XCUejuLSu9a2ATPma/lgOT2DoV72f+a9Raqw7wR4r/iDQNucPkIUN/gyRfc4bRpIuUgm0W/RvHJc8WxmNuIrUigA2yaZE7SBWCDmphrueKY/WrOgWuVf2X4lBiMZBVGZ6wKBgQDExh+4tXALKzGYhFwVgD5xBNK9a7ae8pfWGD9Pz5ByOMeWVkBYDHlQ6AQcH1mnbG6wYE3Lt9Mpm5Ozu45JcB3Zm0URwYJlai584/uuYa9NPpqr0rwvU+mDs34MwHqF+IfxYMZZYVd4ZAPsHU2KFr66M3sQHEQa/9JQzjdqTfZ8WQKBgQCF6PmhT8xq1LGaORXD2RScX04QDOxXHTR8ru7a0GshlW/IxVLsignaeCQfWOGkUYSRYXmzOzt7yr3nwXpsIylzNXZ3dFr+Ck6uQRVLdht/9TV/La0qZRhsr7LCnHdeJ8ITB4u3LYPEamW6POcqTBrTgBZZV+yP6vnJ6jEKICGfrwKBgQDBpw0jV8/DO/8TXG6OuzdE+8HmF1umoQSo2NhmCAT1Khi0kuIZKoDdg0R/Y2Ccom5H8ROJIoHnviaDBM6IIDaBM//ifl/XgezVaB/oMa/OyXRs5xB/VW31RGyXRSO9maM5R/szXndzQ8rApodbKWxfn6uamDRJHYEWnAcFXTPkTA==" - //args["app_id"] = "2021003156691664" - return args -} diff --git a/consume/zhios_fast_return_order_refund.go b/consume/zhios_fast_return_order_refund.go deleted file mode 100644 index 4f35769..0000000 --- a/consume/zhios_fast_return_order_refund.go +++ /dev/null @@ -1,168 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/db/model" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "code.fnuoos.com/go_rely_warehouse/zyos_go_pay.git/pay" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "time" -) - -func ZhiosFastReturnOrderRefund(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleZhiosFastReturnOrderRefund(res.Body) - //_ = res.Reject(false) - if err == nil { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleZhiosFastReturnOrderRefund(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.ZhiosFatReturnOrderPay - fmt.Println(string(msg)) - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println(err.Error()) - return err - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err != nil { - return err - } - mid := canalMsg.Mid - eg := db.DBs[mid] - uid := utils.StrToInt(canalMsg.Uid) - oid := canalMsg.Oid - var orderData model.OrdList - b, err2 := eg.Where("ord_id=?", oid).Get(&orderData) - if b == false || err2 != nil { - return errors.New("err") - } - if orderData.State != 4 || orderData.IsWaitReduce > 0 || orderData.FastSignId == "" { - return nil - } - var data1 model.OrdListRelate - get, err := eg.Where("uid=? and oid=? and level=?", uid, oid, 0).Get(&data1) - if get == false || err != nil { - return errors.New("err") - } - amount := int(data1.Amount * 100) - if amount <= 0 { - return nil - } - if orderData.IsTransfer == 0 { - args := map[string]string{ - "out_request_no": utils.Int64ToStr(orderData.OrdId), - "is_fulfilled": "true", - "credit_biz_order_id": orderData.FastSignId, - "remark": "", - } - args = CommInfo(eg, mid, args) - finish, err := pay.CreditagreementOrderFinish(args) - fmt.Println(finish) - if err != nil { - fmt.Println(err) - } - if err != nil || finish == nil { - return errors.New("err") - } - if finish.ZhimaCreditPayafteruseCreditbizorderFinishResponse.Code != "10000" { - return errors.New("err") - } - orderData.IsWaitReduce = 3 - eg.Where("ord_id=?", oid).Cols("is_wait_reduce").Update(&orderData) - return nil - } - money := utils.Float64ToStr(float64(amount) / 100) - args := map[string]string{ - "out_trade_no": utils.Int64ToStr(orderData.OrdId), - "creditTradeScene": "CREDIT_PAY_UNCERTAIN_FEE", - "is_async_pay": "true", - "total_amount": money, - "auth_code": orderData.FastSignId, - "scene": "ZHIMA_CREDIT_CODE", - "subject": canalMsg.Name + "订单取消", - "product_code": "GENERAL_WITHHOLDING", - "notify_url": "", - } - if canalMsg.Prd == "true" { - args["notify_url"] = "http://api.zhiyingos.com/api/v1/alipay/reduce/callback?master_id=" + mid - } else { - args["notify_url"] = "http://inapi.izhyin.cn/api/v1/alipay/reduce/callback?master_id=" + mid - } - args = CommInfo(eg, mid, args) - fmt.Println(args) - tradePay, _ := pay.AlipayTradePay(args) - orderData.IsWaitReduce = 1 - if tradePay != nil && tradePay.AlipayTradePayResponse.Code == "10000" { - orderData.IsWaitReduce = 2 - } - sql := "UPDATE user_alipay_info SET money=money-? WHERE uid=?" - db.QueryNativeString(eg, sql, money, orderData.Uid) - eg.Where("ord_id=?", oid).Cols("is_wait_reduce").Update(&orderData) - if orderData.IsWaitReduce == 2 { - args1 := map[string]string{ - "out_request_no": utils.Int64ToStr(orderData.OrdId), - "is_fulfilled": "false", - "credit_biz_order_id": orderData.FastSignId, - "remark": "", - } - if orderData.State != 4 { - args1["is_fulfilled"] = "true" - } - args1 = CommInfo(eg, mid, args1) - pay.CreditagreementOrderFinish(args1) - } - var flow = &model.FinUserFlow{ - Type: 1, - Uid: orderData.Uid, - Amount: "", - PaymentType: 3, - BeforeAmount: "0", - AfterAmount: "0", - OrdType: "fast_return", - OrdId: utils.AnyToString(orderData.OrdId), - OrdAction: 103, - OrdTitle: "秒返订单退款扣除" + money + "元(支付宝)", - State: 2, - OtherId: 0, - OrdTime: int(time.Now().Unix()), - CreateAt: time.Now(), - } - eg.Insert(flow) - return nil -} diff --git a/consume/zhios_fast_return_order_refund_second.go b/consume/zhios_fast_return_order_refund_second.go deleted file mode 100644 index 2716b03..0000000 --- a/consume/zhios_fast_return_order_refund_second.go +++ /dev/null @@ -1,163 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/db/model" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "code.fnuoos.com/go_rely_warehouse/zyos_go_pay.git/pay" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "time" -) - -func ZhiosFastReturnOrderRefundSecond(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleZhiosFastReturnOrderRefundSecond(res.Body) - //_ = res.Reject(false) - if err == nil { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleZhiosFastReturnOrderRefundSecond(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.ZhiosFatReturnOrderPay - fmt.Println(string(msg)) - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println(err.Error()) - return err - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err != nil { - return err - } - mid := canalMsg.Mid - eg := db.DBs[mid] - oid := canalMsg.Oid - var orderData model.OrdList - b, err2 := eg.Where("ord_id=?", oid).Get(&orderData) - if b == false || err2 != nil { - return errors.New("err") - } - if orderData.IsWaitReduce > 0 || orderData.FastSignId == "" { - return nil - } - amount := canalMsg.Amount - if amount <= 0 { - return nil - } - if orderData.IsTransfer == 0 { - args := map[string]string{ - "out_request_no": utils.Int64ToStr(orderData.OrdId), - "is_fulfilled": "true", - "credit_biz_order_id": orderData.FastSignId, - "remark": "", - } - args = CommInfo(eg, mid, args) - finish, err := pay.CreditagreementOrderFinish(args) - fmt.Println(finish) - if err != nil { - fmt.Println(err) - } - if err != nil || finish == nil { - return errors.New("err") - } - if finish.ZhimaCreditPayafteruseCreditbizorderFinishResponse.Code != "10000" { - return errors.New("err") - } - orderData.IsWaitReduce = 3 - eg.Where("ord_id=?", oid).Cols("is_wait_reduce").Update(&orderData) - return nil - } - money := utils.Float64ToStr(float64(amount) / 100) - args := map[string]string{ - "out_trade_no": utils.Int64ToStr(orderData.OrdId), - "creditTradeScene": "CREDIT_PAY_UNCERTAIN_FEE", - "is_async_pay": "true", - "total_amount": money, - "auth_code": orderData.FastSignId, - "scene": "ZHIMA_CREDIT_CODE", - "subject": canalMsg.Name + "订单取消", - "product_code": "GENERAL_WITHHOLDING", - "notify_url": "", - } - if canalMsg.Prd == "true" { - args["notify_url"] = "http://api.zhiyingos.com/api/v1/alipay/reduce/callback?master_id=" + mid - } else { - args["notify_url"] = "http://inapi.izhyin.cn/api/v1/alipay/reduce/callback?master_id=" + mid - } - args = CommInfo(eg, mid, args) - fmt.Println(args) - tradePay, _ := pay.AlipayTradePay(args) - orderData.IsWaitReduce = 1 - if tradePay != nil && tradePay.AlipayTradePayResponse.Code == "10000" { - orderData.IsWaitReduce = 2 - } - orderData.IsFastSign = 0 - sql := "UPDATE user_alipay_info SET money=money-? WHERE uid=?" - db.QueryNativeString(eg, sql, money, orderData.Uid) - eg.Where("ord_id=?", oid).Cols("is_fast_sign,is_wait_reduce").Update(&orderData) - if orderData.IsWaitReduce == 2 { - args1 := map[string]string{ - "out_request_no": utils.Int64ToStr(orderData.OrdId), - "is_fulfilled": "false", - "credit_biz_order_id": orderData.FastSignId, - "remark": "", - } - if orderData.State != 4 { - args1["is_fulfilled"] = "true" - } - args1 = CommInfo(eg, mid, args1) - pay.CreditagreementOrderFinish(args1) - } - var flow = &model.FinUserFlow{ - Type: 1, - Uid: orderData.Uid, - Amount: "", - PaymentType: 3, - BeforeAmount: "0", - AfterAmount: "0", - OrdType: "fast_return", - OrdId: utils.AnyToString(orderData.OrdId), - OrdAction: 103, - OrdTitle: "秒返订单退款扣除" + money + "元(支付宝)", - State: 2, - OtherId: 0, - OrdTime: int(time.Now().Unix()), - CreateAt: time.Now(), - } - eg.Insert(flow) - return nil -} diff --git a/consume/zhios_fast_return_order_success.go b/consume/zhios_fast_return_order_success.go deleted file mode 100644 index 90aa97d..0000000 --- a/consume/zhios_fast_return_order_success.go +++ /dev/null @@ -1,100 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/db/model" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "code.fnuoos.com/go_rely_warehouse/zyos_go_pay.git/pay" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" -) - -func ZhiosFastReturnOrderSuccess(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleZhiosFastReturnOrderSuccess(res.Body) - //_ = res.Reject(false) - if err == nil { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleZhiosFastReturnOrderSuccess(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.ZhiosFatReturnOrderPay - fmt.Println(string(msg)) - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println(err.Error()) - return err - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err != nil { - return err - } - mid := canalMsg.Mid - eg := db.DBs[mid] - oid := canalMsg.Oid - var orderData model.OrdList - b, err2 := eg.Where("ord_id=?", oid).Get(&orderData) - if b == false || err2 != nil { - return errors.New("err") - } - if orderData.FastSignId == "" { - return errors.New("err") - } - args := map[string]string{ - "out_request_no": utils.Int64ToStr(orderData.OrdId), - "is_fulfilled": "false", - "credit_biz_order_id": orderData.FastSignId, - "remark": "", - } - if orderData.State != 4 { - args["is_fulfilled"] = "true" - } - args = CommInfo(eg, mid, args) - finish, err := pay.CreditagreementOrderFinish(args) - fmt.Println(finish) - if err != nil { - fmt.Println(err) - } - if err != nil || finish == nil { - return errors.New("err") - } - if finish.ZhimaCreditPayafteruseCreditbizorderFinishResponse.Code != "10000" { - return errors.New("err") - } - orderData.FastSuccess = 1 - eg.Where("ord_id=?", orderData.OrdId).Cols("fast_success").Update(&orderData) - return nil -} diff --git a/consume/zhios_guide_store_order_success.go b/consume/zhios_guide_store_order_success.go deleted file mode 100644 index a0fe1f6..0000000 --- a/consume/zhios_guide_store_order_success.go +++ /dev/null @@ -1,315 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/db/model" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "time" - "xorm.io/xorm" -) - -func ZhiosGuideStoreOrder(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleZhiosGuideStoreOrderSuccess(res.Body) - //_ = res.Reject(false) - if err == nil { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleZhiosGuideStoreOrderSuccess(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.ZhiosGuideStoreOrder - fmt.Println(string(msg)) - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println("===with", err.Error()) - return err - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err != nil { - fmt.Println("===with", err.Error()) - return err - } - mid := canalMsg.Mid - eg := db.DBs[mid] - if eg == nil { - return nil - } - if canalMsg.Type == "success" { - err := success(eg, canalMsg) - if err != nil { - return err - } - } - if canalMsg.Type == "fail" { - err := fail(eg, canalMsg) - if err != nil { - return err - } - } - if canalMsg.Type == "down" { - err := down(eg, canalMsg) - if err != nil { - return err - } - } - return nil -} - -func down(eg *xorm.Engine, canalMsg *md.ZhiosGuideStoreOrder) error { - sess := eg.NewSession() - defer sess.Close() - sess.Begin() - //退积分 - sum := canalMsg.DeductPrice - //退积分 - // 111商家发布商品扣除 112商家商品审核失败退回 113 商家删除商品退回 114商品退款退回 115商家商品下架退回 - err := UpdateUserFinValidAndInterFlowFreezeSess(sess, - utils.AnyToString(sum), "商品("+canalMsg.ItemId+")删除"+canalMsg.Stock+"个退回", "0", 1, utils.StrToInt(canalMsg.Uid), utils.StrToInt(canalMsg.CoinId), 113, utils.StrToInt64(utils.OrderUUID(utils.StrToInt(canalMsg.Uid)))) - if err != nil { - sess.Rollback() - return err - } - sess.Commit() - return nil -} -func success(eg *xorm.Engine, canalMsg *md.ZhiosGuideStoreOrder) error { - sess := eg.NewSession() - defer sess.Close() - sess.Begin() - var data model.GuideStoreOrder - get, _ := sess.Where("pvd_oid=?", canalMsg.Oid).Get(&data) - var newOrd model.OrdList - sess.Where("pvd_oid=?", canalMsg.Oid).Get(&newOrd) - if get == false { - deductPrice := canalMsg.DeductPrice - var storeOrder = model.GuideStoreOrder{ - Uid: newOrd.Uid, - Time: time.Unix(int64(newOrd.CreateAt), 0), - StoreId: utils.StrToInt(canalMsg.StoreId), - Gid: newOrd.ItemId, - State: newOrd.State, - Title: canalMsg.ItemTitle, - Pvd: canalMsg.Pvd, - SubsidyPrice: canalMsg.SubsidyPrice, - Fee: canalMsg.Fee, - DeductPrice: deductPrice, - OldDeductPrice: deductPrice, - Price: utils.Float64ToStr(newOrd.PaidPrice), - Oid: utils.Int64ToStr(newOrd.OrdId), - PvdOid: newOrd.PvdOid, - DeductState: 1, - DeductAt: time.Now(), - } - if utils.StrToInt(canalMsg.State) == 4 { - storeOrder.DeductState = 0 - } - _, err := sess.Insert(&storeOrder) - if err == nil && storeOrder.DeductState == 1 { - coinId := db.SysCfgGetWithDb(eg, canalMsg.Mid, "guide_store_coin_id") - err := UpdateUserFinValidAndInterFlowFreeze(sess, - utils.AnyToString(deductPrice), "商品("+newOrd.ItemId+")下单扣除冻结积分", "0", 2, utils.StrToInt(canalMsg.StoreId), utils.StrToInt(coinId), 117, newOrd.OrdId) - if err != nil { - sess.Rollback() - return err - } - } - newOrd.OrderFormType = -2 - sess.Where("ord_id=?", newOrd.OrdId).Cols("order_form_type").Update(&newOrd) - } - sess.Commit() - return nil -} - -func fail(eg *xorm.Engine, canalMsg *md.ZhiosGuideStoreOrder) error { - sess := eg.NewSession() - defer sess.Close() - sess.Begin() - //m, _ := db.FreeProductByID(eg, canalMsg.ItemId, canalMsg.Pvd) - //直接退回账号了 定制 - storeOrder := db.GuideStoreOrderSess(sess, utils.StrToInt64(canalMsg.Oid)) - //if m != nil { - if storeOrder != nil && utils.StrToFloat64(storeOrder.DeductPrice) > 0 && storeOrder.DeductState == 1 { - coinId := db.SysCfgGetWithDb(eg, canalMsg.Mid, "guide_store_coin_id") - err := UpdateUserVirtualCoinFinValidAndInterFlow(sess, - utils.AnyToString(storeOrder.DeductPrice), "商品("+storeOrder.Gid+")退款退回", "0", 1, storeOrder.StoreId, utils.StrToInt(coinId), 114, utils.StrToInt64(canalMsg.Oid)) - if err != nil { - sess.Rollback() - return err - } - storeOrder.DeductPrice = "0" - storeOrder.DeductState = 2 - storeOrder.State = 4 - _, err = sess.Where("id=?", storeOrder.Id).Update(storeOrder) - if err != nil { - sess.Rollback() - return err - } - } - //} - sess.Commit() - return nil -} -func UpdateUserFinValidAndInterFlowFreezeSess(session *xorm.Session, money, Title, fee string, types, uid, coinId, transferType int, ordId int64) error { - UserVirtualAmount, err := db.UserVirtualAmountFindByIdWithSession(session, uid, coinId) - if err != nil || UserVirtualAmount == nil { - if err == nil { - err = errors.New("获取用户余额信息失败") - } - return err - } - beforeAmount := UserVirtualAmount.Amount - freezeBeforeAmount := UserVirtualAmount.FreezeAmount - - if types == 1 { - UserVirtualAmount.Amount = utils.AnyToString(utils.AnyToFloat64(UserVirtualAmount.Amount) + utils.StrToFloat64(money)) - UserVirtualAmount.FreezeAmount = utils.AnyToString(utils.AnyToFloat64(UserVirtualAmount.FreezeAmount) - utils.StrToFloat64(money)) - } else if types == 2 { - UserVirtualAmount.Amount = utils.AnyToString(utils.AnyToFloat64(UserVirtualAmount.Amount) - utils.StrToFloat64(money)) - UserVirtualAmount.FreezeAmount = utils.AnyToString(utils.AnyToFloat64(UserVirtualAmount.FreezeAmount) + utils.StrToFloat64(money)) - if utils.StrToFloat64(UserVirtualAmount.Amount) < 0 { - return errors.New("额度不足") - } - } - afterAmount := UserVirtualAmount.Amount - freezeAfterAmount := UserVirtualAmount.FreezeAmount - - affected, err := db.UserVirtualAmountUpdateWithSession(session, uid, coinId, UserVirtualAmount, "amount,freeze_amount") - if err != nil || affected == 0 { - if err == nil { - err = errors.New("更新用户余额信息失败") - } - return err - } - err = virtualCoinFlowInsert(session, uid, coinId, money, fee, ordId, Title, types, transferType, beforeAmount, afterAmount, freezeBeforeAmount, freezeAfterAmount) - if err != nil { - return err - } - return nil -} - -func UpdateUserVirtualCoinFinValidAndInterFlow(sess *xorm.Session, money, Title, fee string, types, uid, coinId, transferType int, ordId int64) error { - UserVirtualAmount, err := db.UserVirtualAmountFindById(sess, uid, coinId) - if err != nil || UserVirtualAmount == nil { - if err == nil { - err = errors.New("获取用户余额信息失败") - } - return err - } - beforeAmount := UserVirtualAmount.Amount - freezeBeforeAmount := UserVirtualAmount.FreezeAmount - if types == 2 { - UserVirtualAmount.Amount = utils.AnyToString(utils.AnyToFloat64(UserVirtualAmount.Amount) - utils.StrToFloat64(money)) - UserVirtualAmount.UseAmount = utils.AnyToString(utils.AnyToFloat64(UserVirtualAmount.UseAmount) + utils.StrToFloat64(money)) - } else if types == 1 { - UserVirtualAmount.Amount = utils.AnyToString(utils.AnyToFloat64(UserVirtualAmount.Amount) + utils.StrToFloat64(money)) - UserVirtualAmount.UseAmount = utils.AnyToString(utils.AnyToFloat64(UserVirtualAmount.UseAmount) - utils.StrToFloat64(money)) - } - afterAmount := UserVirtualAmount.Amount - freezeAfterAmount := UserVirtualAmount.FreezeAmount - - affected, err := db.UserVirtualAmountUpdate(sess, uid, coinId, UserVirtualAmount, "amount") - if err != nil || affected == 0 { - if err == nil { - err = errors.New("更新用户余额信息失败") - } - return err - } - err = virtualCoinFlowInsert(sess, uid, coinId, money, fee, ordId, Title, types, transferType, beforeAmount, afterAmount, freezeBeforeAmount, freezeAfterAmount) - if err != nil { - return err - } - return nil -} - -func UpdateUserFinValidAndInterFlowFreeze(sess *xorm.Session, money, Title, fee string, types, uid, coinId, transferType int, ordId int64) error { - UserVirtualAmount, err := db.UserVirtualAmountFindById(sess, uid, coinId) - if err != nil || UserVirtualAmount == nil { - if err == nil { - err = errors.New("获取用户余额信息失败") - } - return err - } - beforeAmount := UserVirtualAmount.Amount - freezeBeforeAmount := UserVirtualAmount.FreezeAmount - - if types == 2 { - UserVirtualAmount.FreezeAmount = utils.AnyToString(utils.AnyToFloat64(UserVirtualAmount.FreezeAmount) - utils.StrToFloat64(money)) - UserVirtualAmount.UseAmount = utils.AnyToString(utils.AnyToFloat64(UserVirtualAmount.UseAmount) + utils.StrToFloat64(money)) - } else if types == 1 { - UserVirtualAmount.FreezeAmount = utils.AnyToString(utils.AnyToFloat64(UserVirtualAmount.FreezeAmount) + utils.StrToFloat64(money)) - UserVirtualAmount.UseAmount = utils.AnyToString(utils.AnyToFloat64(UserVirtualAmount.UseAmount) - utils.StrToFloat64(money)) - } - afterAmount := UserVirtualAmount.Amount - freezeAfterAmount := UserVirtualAmount.FreezeAmount - affected, err := db.UserVirtualAmountUpdate(sess, uid, coinId, UserVirtualAmount, "freeze_amount,use_amount") - if err != nil || affected == 0 { - if err == nil { - err = errors.New("更新用户余额信息失败") - } - return err - } - err = virtualCoinFlowInsert(sess, uid, coinId, money, fee, ordId, Title, types, transferType, beforeAmount, afterAmount, freezeBeforeAmount, freezeAfterAmount) - if err != nil { - return err - } - return nil -} -func virtualCoinFlowInsert(sess *xorm.Session, uid, coinId int, money, SysFee string, ordId int64, ItemTitle string, types, transferType int, beforeAmount string, afterAmount string, freezeBeforeAmount string, freezeAfterAmount string) error { - now := time.Now() - if err := db.UserVirtualCoinFlowInsertOne( - sess, - &model.UserVirtualCoinFlow{ - Uid: uid, - OrdId: utils.Int64ToStr(ordId), - CoinId: coinId, - Direction: types, - Title: ItemTitle, - Amout: money, - FreezeBeforeAmout: freezeBeforeAmount, - FreezeAfterAmout: freezeAfterAmount, - BeforeAmout: beforeAmount, - AfterAmout: afterAmount, - SysFee: SysFee, - CreateTime: now, - TransferType: transferType, - }); err != nil { - _ = logx.Warn(err) - return err - } - return nil -} diff --git a/consume/zhios_installment_payment_auto_repaid_consume.go b/consume/zhios_installment_payment_auto_repaid_consume.go deleted file mode 100644 index eb60389..0000000 --- a/consume/zhios_installment_payment_auto_repaid_consume.go +++ /dev/null @@ -1,67 +0,0 @@ -package consume - -import ( - "applet/app/cfg" - "applet/app/db" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule/installment_payment" - md2 "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule/installment_payment/md" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "time" -) - -func InstallmentPaymentAutoRepaidConsume(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>InstallmentPaymentAutoRepaidConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleInstallmentPaymentAutoRepaidConsume(ch, res.Body) - if err != nil { - fmt.Println("handleInstallmentPaymentAutoRepaidConsumeERR:::::", err.Error()) - } - //_ = res.Reject(false) - err = res.Ack(true) - fmt.Println("err ::: ", err) - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleInstallmentPaymentAutoRepaidConsume(ch *rabbit.Channel, msgData []byte) error { - time.Sleep(time.Duration(1) * time.Millisecond) //休眠1毫秒 - - //1、解析mq中queue的数据结构体 - var msg *md2.InstallmentPaymentStructForAutoRepaid - err := json.Unmarshal(msgData, &msg) - if err != nil { - return err - } - engine := db.DBs[msg.MasterId] - installment_payment.Init(cfg.RedisAddr) - //2、调用 `DealInstallmentPaymentAutoRepaid` 制度方法进行扣款 - err = installment_payment.DealInstallmentPaymentAutoRepaid(engine, ch, *msg, msg.MasterId) - return nil -} diff --git a/consume/zhios_integral_proxy_recharge.go b/consume/zhios_integral_proxy_recharge.go deleted file mode 100644 index f3c59cb..0000000 --- a/consume/zhios_integral_proxy_recharge.go +++ /dev/null @@ -1,138 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "time" - "xorm.io/xorm" -) - -func ZhiosIntegralProxyRecharge(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleZhiosIntegralProxyRecharge(res.Body) - //_ = res.Reject(false) - if err == nil { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleZhiosIntegralProxyRecharge(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.ZhiosAppreciation - fmt.Println(string(msg)) - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println("===with", err.Error()) - return err - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err != nil { - fmt.Println("===with", err.Error()) - return err - } - mid := canalMsg.Mid - eg := db.DBs[mid] - if eg == nil { - return nil - } - sess := eg.NewSession() - defer sess.Close() - sess.Begin() - order := db.GetIntegralProxyRecord(sess, canalMsg.Oid) - now := int(time.Now().Unix()) - if order.State != 1 || order.SendTime > now { - sess.Rollback() - return nil - } - day := order.Time.Format("02") - if order.SendTime == 0 { - order.SendTime = int(utils.TimeStdParseUnix(order.PayTime.Format("2006-01-02") + " 00:00:00")) - } else if order.SendTime < int(time.Now().Unix()) { - order.SendTime = int(utils.TimeStdParseUnix(time.Now().Format("2006-01-02") + " 00:00:00")) - } - order.SendTime += 30 * 86400 - date := time.Unix(int64(order.SendTime), 0).Format("2006-01") - order.SendTime = int(utils.TimeStdParseUnix(date + "-" + day + " 00:00:00")) - - amount := "0" - title := "" - str := "代充值" - if order.Type == "gift_goods" { - str = "购买礼包奖励" - } - if order.Type == "give" { - str = "转赠" - } - if canalMsg.Type == "" || canalMsg.Type == "first" { - amount = order.Amount - title = str + "到账" - if order.RealOnAccount > 0 { - order.RealOnAccount-- - title = str + "第" + utils.IntToStr(order.OnAccount-order.RealOnAccount) + "期到账" - amount = order.EveryAmount - } - } - if canalMsg.Type == "second" { - if order.RealOnAccount <= 0 { //已经没了 - sess.Rollback() - return nil - } - order.RealOnAccount-- - title = str + "第" + utils.IntToStr(order.OnAccount-order.RealOnAccount) + "期到账" - amount = order.EveryAmount - } - err = addIntegral(sess, order.CoinId, order.Oid, amount, title, order.Uid) - if err != nil { - sess.Rollback() - return err - } - order.RunTime = utils.StrToInt(time.Now().Format("200601")) - update, err := sess.Where("id=?", order.Id).Cols("run_time,real_on_account,send_time").Update(order) - if update == 0 || err != nil { - sess.Rollback() - return err - } - sess.Commit() - return nil -} -func addIntegral(sess *xorm.Session, coinId int, oid int64, amount, title string, uid int) error { - err := UpdateUserVirtualCoinFinValidAndInterFlow(sess, - amount, title, "0", 1, uid, coinId, 125, oid) - if err != nil { - return err - } - return nil -} diff --git a/consume/zhios_mall_green_coin_consume.go b/consume/zhios_mall_green_coin_consume.go deleted file mode 100644 index 727a046..0000000 --- a/consume/zhios_mall_green_coin_consume.go +++ /dev/null @@ -1,90 +0,0 @@ -package consume - -import ( - "applet/app/cfg" - "applet/app/db" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" -) - -func ZhiosMallGreenCoinConsume(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>ZhiosMallGreenCoinConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleZhiosMallGreenCoinConsume(res.Body) - //_ = res.Reject(false) - if err != nil { - var canalMsg *md.ZhiosMallConsume - var tmpString string - err1 := json.Unmarshal(res.Body, &tmpString) - if err1 == nil { - fmt.Println(tmpString) - err1 = json.Unmarshal([]byte(tmpString), &canalMsg) - if err1 == nil { - canalMsg.Err = err.Error() - ch.Publish(md.MallGreenCoinConsume, utils.SerializeStr(canalMsg), md.MallGreenCoinConsumeKeyErr) - } - } - } - _ = res.Ack(true) - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleZhiosMallGreenCoinConsume(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.ZhiosMallConsume - fmt.Println(string(msg)) - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println("===with", err.Error()) - return err - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err != nil { - fmt.Println("===with", err.Error()) - return err - } - mid := canalMsg.Mid - eg := db.DBs[mid] - if eg == nil { - return nil - } - rule.InitForGreenCoinDoubleChainIntegral(cfg.RedisAddr) - err = rule.DealUserGreenCoinDoubleChainIntegral(eg, utils.StrToInt(canalMsg.Uid), canalMsg.Oid, canalMsg.Mid) - fmt.Println(err) - if err != nil { - return err - } - - return nil -} diff --git a/consume/zhios_one_circles_coin_consume.go b/consume/zhios_one_circles_coin_consume.go deleted file mode 100644 index e90b10f..0000000 --- a/consume/zhios_one_circles_coin_consume.go +++ /dev/null @@ -1,120 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/db/model" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/shopspring/decimal" - "github.com/streadway/amqp" - "strings" - "time" -) - -func ZhiosOneCirclesCoinConsume(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(50) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>ZhiosOneCirclesCoinConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleZhiosOneCirclesCoinConsume(res.Body) - if err != nil { - fmt.Println("handleZhiosOneCirclesCoinConsume:::::", err.Error()) - } - //_ = res.Reject(false) - err = res.Ack(true) - fmt.Println("err ::: ", err) - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleZhiosOneCirclesCoinConsume(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.CanalUserVirtualCoinFlowOrderMessage[md.CanalUserVirtualCoinFlowOrder] - err := json.Unmarshal(msg, &canalMsg) - if err != nil { - return err - } - masterId := strings.Split(canalMsg.Database, "_")[1] - if masterId != "31585332" { - return nil - } - engine := db.DBs[masterId] - now := time.Now() - - if canalMsg.Type == md.CanalMsgInsertSqlType { - ////2、查找 one_circles_green_energy_basic_setting 基础设置 - //userPublicPlatoonDoubleNetworkSetting, err := db.UserPublicPlatoonDoubleNetworkSettingGetOneByParams(engine, map[string]interface{}{ - // "key": "is_open", - // "value": 1, - //}) - //if err != nil { - // return err - //} - - if canalMsg.Data[0].CoinId == utils.IntToStr(7) { //TODO::数据量太大,减少查询直接写死 - //3、查找 user_public_platoon_double_network_user_coin_record - userVirtualCoinFlowAggregation, err1 := db.UserVirtualCoinFlowAggregationGetOneByParams(engine, map[string]interface{}{ - "key": "uid", - "value": canalMsg.Data[0].Uid, - }) - if err1 != nil { - return err1 - } - if userVirtualCoinFlowAggregation == nil { - //新增记录 - _, err3 := db.UserVirtualCoinFlowAggregationInsert(engine, &model.UserVirtualCoinFlowAggregation{ - Uid: utils.StrToInt(canalMsg.Data[0].Uid), - CoinId: utils.StrToInt(canalMsg.Data[0].CoinId), - TodayData: canalMsg.Data[0].Amout, - ThisWeekData: canalMsg.Data[0].Amout, - ThisMonthData: canalMsg.Data[0].Amout, - NowData: canalMsg.Data[0].Amout, - CreateAt: now.Format("2006-01-02 15:04:05"), - UpdateAt: now.Format("2006-01-02 15:04:05"), - }) - if err3 != nil { - return err3 - } - } else { - //更新记录 - amount, _ := decimal.NewFromString(canalMsg.Data[0].Amout) - todayData, _ := decimal.NewFromString(userVirtualCoinFlowAggregation.TodayData) - thisWeekData, _ := decimal.NewFromString(userVirtualCoinFlowAggregation.ThisWeekData) - thisMonthData, _ := decimal.NewFromString(userVirtualCoinFlowAggregation.ThisMonthData) - userVirtualCoinFlowAggregation.TodayData = todayData.Add(amount).String() - userVirtualCoinFlowAggregation.ThisWeekData = thisWeekData.Add(amount).String() - userVirtualCoinFlowAggregation.ThisMonthData = thisMonthData.Add(amount).String() - userVirtualCoinFlowAggregation.NowData = canalMsg.Data[0].AfterAmout - _, err2 := db.UserVirtualCoinFlowAggregationUpdate(engine, userVirtualCoinFlowAggregation.Id, userVirtualCoinFlowAggregation, "today_data", "this_week_data", "this_month_data", "now_data") - if err2 != nil { - return err2 - } - } - } - } - return nil -} diff --git a/consume/zhios_order_buckle.go b/consume/zhios_order_buckle.go deleted file mode 100644 index 9f07447..0000000 --- a/consume/zhios_order_buckle.go +++ /dev/null @@ -1,646 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/db/model" - md2 "applet/app/md" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/lib/comm_plan" - md3 "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" - "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/svc" - "encoding/json" - "errors" - "fmt" - "github.com/jinzhu/copier" - "github.com/streadway/amqp" - "github.com/tidwall/gjson" - "time" - "xorm.io/xorm" -) - -func ZhiosOrderBuckle(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleZhiosOrderBuckle(res.Body) - //_ = res.Reject(false) - if err != nil { - _ = res.Reject(false) - //TODO::重新推回队列末尾,避免造成队列堵塞 - var msg *md.ZhiosOrderBuckle - var tmpString string - err := json.Unmarshal(res.Body, &tmpString) - if err != nil { - return - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &msg) - if err != nil { - return - } - ch.Publish(queue.ExchangeName, utils.SerializeStr(msg), queue.RoutKey) - } else { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleZhiosOrderBuckle(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.ZhiosOrderBuckle - fmt.Println(string(msg)) - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println("===with", err.Error()) - return err - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err != nil { - fmt.Println("===with", err.Error()) - return err - } - mid := canalMsg.Mid - eg := db.DBs[mid] - if eg == nil { - return nil - } - sess := eg.NewSession() - defer sess.Close() - sess.Begin() - - ordData, err := db.OrderListByPvdOid(sess, canalMsg.Oid) - if err != nil || ordData == nil { - return nil - } - if ordData.OrderFormType < 0 || ordData.State > 3 { - sess.Commit() - - return nil - } - user, _ := db.UserFindByID(eg, ordData.Uid) - if user == nil { - sess.Commit() - - return nil - } - //判断是否符合条件 TODO - bools := checkUser(eg, canalMsg.Mid, user, utils.FloatFormat(ordData.BenefitAll, 3)) - if bools == false { - sess.Commit() - - return nil - } - - fmt.Println(ordData) - //加入分佣关系链 - opts, commissionOpts, _ := svc.GetAllPlan(eg, canalMsg.Mid) - if opts == nil { - sess.Commit() - - return nil - } - BenefitAll := ordData.BenefitAll - pvd := ordData.Pvd - if ordData.OrderFormType == 1 { //京东自营 - pvd = md3.PVD_JDOwn - } - var rmd = md3.CommissionParam{IsTikTokTeamOrder: utils.IntToStr(ordData.IsTikTokTeamOrder)} - opt, err := svc.GetPlanCfg(eg, pvd, canalMsg.Mid, opts, commissionOpts, map[int]string{}, &rmd) - if err != nil { - sess.Commit() - return nil - } - - if opt.BuckleRate == 0 { - sess.Commit() - - return nil - } - //计算出暗扣的比例 TODO - if opt.BuckleRate > 0 { - BenefitAll = utils.FloatFormat(ordData.BenefitAll*(1-opt.BuckleRate), 9) - } - var ord = md2.OrderInfo{ - PvdOid: ordData.PvdOid, - Pvd: pvd, - ItemId: ordData.ItemId, - ItemNum: ordData.ItemNum, - ItemPrice: ordData.ItemPrice, - PaidPrice: ordData.PaidPrice, - OrderType: ordData.OrderType, - Commission: BenefitAll, - State: ordData.State, - } - //调用公共的分佣 - isShare := 0 - if ord.OrderType == 1 { - isShare = 1 - } - //计算每个用户的分佣 - req := md2.CommissionFirstParam{ - CommissionParam: md2.CommissionParam{ - Commission: utils.Float64ToStr(ord.Commission), - PaidPrice: utils.Float64ToStr(ord.PaidPrice), - OldPrice: utils.Float64ToStr(ord.PaidPrice), - IsTikTokTeamOrder: utils.IntToStr(ordData.IsTikTokTeamOrder), - }, - Uid: utils.IntToStr(ordData.Uid), - IsShare: isShare, - Provider: ord.Pvd, - IsAllLevelReturn: 1, - } - if utils.InArr(ord.Pvd, []string{md3.PVD_TB, md3.PVD_TM, md3.PVD_PDD, md3.PVD_SN, md3.PVD_KL, md3.PVD_JD, md3.PVD_JDOwn, md3.PVD_VIP}) == false { - req.CommissionParam.GoodsPrice = utils.Float64ToStr(ord.PaidPrice) - } - commissionList, err := GetCommissionByCommApi(eg, canalMsg.Mid, req) - if err != nil || commissionList.LvUser == nil { - sess.Commit() - return nil - } - pvdFee := commissionList.PvdFee - sysFee := commissionList.SysFee - subsidyFee := commissionList.SubsidyFee - lvUser := commissionList.LvUser - profit := commissionList.Profit - ordData.SubsidyFee = subsidyFee - ordData.PvdCommission = pvdFee - ordData.SysCommission = sysFee - ordData.BuckleCommission = utils.Float64ToStr(BenefitAll) - if ordData.OrderFormType == 2 { - ordData.OrderFormType = -2 - } else { - ordData.OrderFormType = -1 - - } - var selfRate float64 = 0 - var subsidyRate float64 = 0 - //处理记录佣金 - if opt != nil { - profit = lvUser.Profit - //判断下这个等级有么有设置 - ordData.UserCommission = profit - ordData.SubsidyRate = subsidyRate - ordData.UserCommissionRate = selfRate - ordData.PlanCommissionId = opt.PlanCommissionId - ordData.BenefitList = SerializeLvUser(NewCalcLvUserFee(lvUser)) - } - - has, _ := db.OrderListByUpdateOrd(sess, ordData) - if has == false { - sess.Rollback() - return nil - } - - //批量写入 - if lvUser != nil { - err := OrderRelateInsert(eg, sess, ordData.OrdId, ordData.Pvd, ordData.CreateAt, lvUser, ordData, canalMsg.Mid, true, opt.Mode, "1") - if err != nil { - sess.Rollback() - return err - } - } - sess.Commit() - return nil -} - -func checkUser(eg *xorm.Engine, dbName string, user *model.User, commission float64) bool { - buckleData := db.SysCfgGetWithDb(eg, dbName, "buckle_data") - //注册时间 - lastMonthEstimateCommission := gjson.Get(buckleData, "last_month_estimate_commission").String() //用户上个月预估佣金金额大于 - monthOrderCount := gjson.Get(buckleData, "month_order_count").String() //用户每月订单笔数 - orderCommissionEnd := gjson.Get(buckleData, "order_commission_end").String() //用户订单佣金金额:结束区间 - orderCommissionStart := gjson.Get(buckleData, "order_commission_start").String() //用户订单佣金金额:开始区间 - userRegDay := gjson.Get(buckleData, "user_reg_day").String() //用户注册时间 - if (time.Now().Unix()-user.CreateAt.Unix())/86400 < utils.StrToInt64(userRegDay) && utils.StrToInt64(userRegDay) > 0 { - fmt.Println("时间=============", (time.Now().Unix()-user.CreateAt.Unix())/86400) - return false - } - if utils.StrToFloat64(lastMonthEstimateCommission) > 0 { - lastMonthRange := utils.GetTimeRange("last_month") - // 统计上月预估 (预估包含结算部分且是有效订单) - sqlTpl2 := `SELECT cast(SUM(IF(ol.state<>4 or pco.state=1 or dol.id>0 or ro.status<>'已退款' or pso.status<>'订单退款', LEFT(olr.amount,LENGTH(olr.amount)-2), 0)) as decimal(50,4)) AS amount -FROM ord_list_relate olr - LEFT JOIN ord_list ol ON olr.oid = ol.ord_id - LEFT JOIN privilege_card_ord pco ON olr.oid =pco.ord_id - LEFT JOIN duoyou_ord_list dol ON olr.oid =dol.oid -LEFT JOIN recharge_order ro ON olr.oid =ro.oid - LEFT JOIN playlet_sale_order pso ON olr.oid =pso.custom_oid -WHERE olr.uid = ? - AND olr.create_at >= ? - AND olr.create_at < ? -` - lastMonthResult, _ := db.QueryNativeString(eg, sqlTpl2, user.Uid, lastMonthRange["start"], lastMonthRange["end"]) - if len(lastMonthRange) == 0 { - return false - } - fmt.Println("上月预估佣金=============", lastMonthResult[0]["amount"]) - - if utils.StrToFloat64(lastMonthResult[0]["amount"]) < utils.StrToFloat64(lastMonthEstimateCommission) { - return false - } - } - if utils.StrToFloat64(monthOrderCount) > 0 { - currentMonth := utils.GetTimeRange("current_month") - count, _ := eg.Where("uid=? and create_at>=?", user.Uid, currentMonth["start"]).In("state", []string{"0", "1", "2", "3", "5"}).Count(&model.OrdList{}) - fmt.Println("本月订单数=============", count) - - if count < utils.StrToInt64(monthOrderCount) { - return false - } - } - if utils.StrToFloat64(orderCommissionEnd) > 0 && utils.StrToFloat64(orderCommissionStart) > 0 { - fmt.Println("订单佣金=============", commission) - if commission < utils.StrToFloat64(orderCommissionStart) { - return false - } - if commission > utils.StrToFloat64(orderCommissionEnd) { - return false - } - } - return true -} - -func OrderRelateInsert(eg *xorm.Engine, sess *xorm.Session, oid int64, pvd string, createTime int, lvUser *comm_plan.LvUser, newOrd *model.OrdList, masterId string, isDelete bool, mode string, isNew string) error { - if lvUser == nil { - return nil - } - uid := lvUser.Uid - if uid == 0 { - return nil - } - oldLvUser := lvUser - oldLevel := 0 - byOid, _ := db.OrderListByOid(sess, utils.Int64ToStr(oid)) - data := OrderRelateInsertComm(eg, oid, pvd, createTime, lvUser, newOrd, masterId, mode) - fmt.Println(data) - - if data == nil || len(data) == 0 { - return nil - } - list, _ := db.OrderRelateFindByOid(sess, oid, pvd) - listMap := make(map[int]model.OrdListRelate) - if list != nil { - for _, v := range *list { - listMap[v.Uid] = v - } - } - for k, v := range data { - tmp, ok := listMap[v.Uid] - if ok { - data[k].OldAmount = tmp.Amount - leave := utils.FloatFormat(tmp.Amount-v.Amount, 6) - if leave >= 0 { - var tmps = model.BuckleRecord{ - Date: time.Now().Format("2006-01"), - Time: time.Now(), - Uid: v.Uid, - OrdId: utils.Int64ToStr(v.Oid), - PvdOrdId: byOid.PvdOid, - Amount: utils.Float64ToStrByPrec(leave, 6), - BeforeAmount: utils.Float64ToStrByPrec(tmp.Amount, 6), - AfterAmount: utils.Float64ToStrByPrec(v.Amount, 6), - Level: v.Level, - } - _, err := sess.Insert(&tmps) - if err != nil { - return err - } - - } - } - - } - - fmt.Println(isDelete) - _, err2 := db.OrderRelateDeleteByOid(sess, oid, pvd) - if err2 != nil { - return err2 - } - _, err2 = db.VirtualCoinOrderRelateDeleteByOid(sess, oid, pvd) - if err2 != nil { - return err2 - } - //后写入 - err := db.DbInsertBatchSess(sess, data) - if err != nil { - return err - - } else if lvUser.ProfitList != nil { - // 插入虚拟币数据 - vcrData := CombineVirtualCoinRelateData(oldLvUser, oid, pvd, oldLevel, mode) - if len(vcrData) == 0 { - return nil - } - err := db.DbInsertBatchSess(sess, vcrData) - if err != nil { - return err - - } - } - if lvUser.TikTokOwnSubsidyFeeList != nil { - _, err2 := db.TikTokTeamOrderRelateDeleteByOid(sess, oid, pvd) - if err != nil { - return err2 - } - var teamData []model.TikTokTeamOrderRelate - TikTokTeamCommission := newOrd.TikTokTeamCommission - if utils.StrToFloat64(newOrd.TikTokTeamRealCommission) > 0 { - TikTokTeamCommission = newOrd.TikTokTeamRealCommission - } - for k, v := range lvUser.TikTokOwnSubsidyFeeList { - tmp := model.TikTokTeamOrderRelate{ - CoinId: utils.StrToInt(k), - Uid: uid, - Amount: utils.Float64ToStrByPrec(v, 8), - Oid: utils.Int64ToStr(oid), - Time: time.Now(), - Commission: TikTokTeamCommission, - Pvd: pvd, - } - teamData = append(teamData, tmp) - } - if len(teamData) == 0 { - return nil - } - err := db.DbInsertBatchSess(sess, &teamData) - if err != nil { - return err - - } - } - return nil -} -func OrderRelateInsertNew(eg *xorm.Engine, sess *xorm.Session, oid int64, pvd string, createTime int, lvUser *comm_plan.LvUser, newOrd *model.OrdList, masterId string, isDelete bool, mode string, isNew string) error { - if lvUser == nil { - return nil - } - uid := lvUser.Uid - if uid == 0 { - return nil - } - oldLvUser := lvUser - oldLevel := 0 - data := OrderRelateInsertComm(eg, oid, pvd, createTime, lvUser, newOrd, masterId, mode) - fmt.Println(data) - - if data == nil || len(data) == 0 { - return nil - } - list, _ := db.OrderRelateFindByOid(sess, oid, pvd) - listMap := make(map[int]model.OrdListRelate) - if list != nil { - for _, v := range *list { - listMap[v.Uid] = v - } - } - - fmt.Println(isDelete) - _, err2 := db.OrderRelateDeleteByOid(sess, oid, pvd) - if err2 != nil { - return err2 - } - _, err2 = db.VirtualCoinOrderRelateDeleteByOid(sess, oid, pvd) - if err2 != nil { - return err2 - } - //后写入 - err := db.DbInsertBatchSess(sess, data) - if err != nil { - return err - - } else if lvUser.ProfitList != nil { - // 插入虚拟币数据 - vcrData := CombineVirtualCoinRelateData(oldLvUser, oid, pvd, oldLevel, mode) - if len(vcrData) == 0 { - return nil - } - err := db.DbInsertBatchSess(sess, vcrData) - if err != nil { - return err - - } - } - if lvUser.TikTokOwnSubsidyFeeList != nil { - _, err2 := db.TikTokTeamOrderRelateDeleteByOid(sess, oid, pvd) - if err != nil { - return err2 - } - var teamData []model.TikTokTeamOrderRelate - TikTokTeamCommission := newOrd.TikTokTeamCommission - if utils.StrToFloat64(newOrd.TikTokTeamRealCommission) > 0 { - TikTokTeamCommission = newOrd.TikTokTeamRealCommission - } - for k, v := range lvUser.TikTokOwnSubsidyFeeList { - tmp := model.TikTokTeamOrderRelate{ - CoinId: utils.StrToInt(k), - Uid: uid, - Amount: utils.Float64ToStrByPrec(v, 8), - Oid: utils.Int64ToStr(oid), - Time: time.Now(), - Commission: TikTokTeamCommission, - Pvd: pvd, - } - teamData = append(teamData, tmp) - } - if len(teamData) == 0 { - return nil - } - err := db.DbInsertBatchSess(sess, &teamData) - if err != nil { - return err - - } - } - return nil -} -func CombineVirtualCoinRelateData(lvUser *comm_plan.LvUser, oid int64, pvd string, level int, mode string) []*model.VirtualCoinRelate { - var data []*model.VirtualCoinRelate - //可能没有极差返利 只有补贴 - profitList := lvUser.ProfitList - if len(profitList) == 0 { - profitList = lvUser.SubsidyFeeList - } - if profitList != nil { - var subsidyFeeList map[string]float64 - if lvUser.SubsidyFeeList != nil && len(lvUser.ProfitList) > 0 { - subsidyFeeList = convertList2Map(lvUser.SubsidyFeeList) - } - var coinList = make([]string, 0) - for _, v := range profitList { - coinList = append(coinList, v.Cid) - } - if utils.InArr(mode, []string{"lv_winery", "public_platoon"}) && lvUser.SubsidyFeeList != nil { //补贴类型 没有的要补上 - subsidyFeeList = convertList2Map(lvUser.SubsidyFeeList) - for _, v := range lvUser.SubsidyFeeList { - if utils.InArr(v.Cid, coinList) == false && v.Val > 0 { - v.Val = 0 - profitList = append(profitList, v) - } - } - } - for _, item := range profitList { - if item.Cid != "0" && item.Cid != "commission" { - //加上补贴 - subsidyFee := subsidyFeeList[item.Cid] - var ownSubsidyFee float64 = 0 - ownSubsidyFee1, ok := lvUser.OwnSubsidyFeeList[item.Cid] - if ok { - ownSubsidyFee = ownSubsidyFee1 - } - var additionalSubsidy float64 = 0 - profit := utils.Float64ToStrByPrec(item.Val+subsidyFee+ownSubsidyFee, 9) - if utils.InArr(mode, []string{"lv_winery", "public_platoon"}) { - profit = utils.Float64ToStrByPrec(item.Val+ownSubsidyFee, 9) - additionalSubsidy = subsidyFee - - } - if mode == "public_platoon" && level > 1 { - profit = "0" - } - if lvUser.Uid == 0 { - continue - } - var virtualCoinRelate = &model.VirtualCoinRelate{ - Oid: oid, - Uid: lvUser.Uid, - CoinId: utils.StrToInt(item.Cid), - Amount: profit, - Pvd: pvd, - CreateAt: int(time.Now().Unix()), - Level: level, - Mode: mode, - AdditionalSubsidy: utils.Float64ToStrByPrec(additionalSubsidy, 6), - ExtendType: lvUser.ExtendType, - } - data = append(data, virtualCoinRelate) - } - } - } - if lvUser.ParentUser != nil { - level += 1 - data = append(data, CombineVirtualCoinRelateData(lvUser.ParentUser, oid, pvd, level, mode)...) - } - return data -} -func convertList2Map(a []*comm_plan.VirtualCoinCommission) (b map[string]float64) { - b = make(map[string]float64) - for _, i := range a { - b[i.Cid] = i.Val - } - return b -} - -func OrderRelateInsertComm(eg *xorm.Engine, oid int64, pvd string, createTime int, lvUser *comm_plan.LvUser, newOrd *model.OrdList, masterId string, mode string) []*model.OrdListRelate { - var datas []*model.OrdListRelate - if lvUser == nil { - return datas - } - level := 0 - fmt.Println("关系链---"+utils.Int64ToStr(oid)+"---"+pvd+"---", utils.SerializeStr(lvUser)) - var ownSubsidyFee float64 = 0 - ownSubsidyFee1, ok := lvUser.OwnSubsidyFeeList["0"] - if ok { - ownSubsidyFee = ownSubsidyFee1 - } - profit := utils.FloatFormat(lvUser.Profit+lvUser.SubsidyFee+ownSubsidyFee, 9) - data := []*model.OrdListRelate{{Oid: oid, Uid: lvUser.Uid, Amount: profit, AdditionalSubsidy: utils.Float64ToStrByPrec(lvUser.AdditionalSubsidy, 9), Pvd: pvd, CreateAt: createTime, Level: level, Mode: mode, ExtendType: lvUser.ExtendType}} - for lvUser.ParentUser != nil { - lvUser = lvUser.ParentUser - fmt.Println(lvUser) - level = level + 1 - profit = utils.FloatFormat(lvUser.Profit+lvUser.SubsidyFee, 9) - var additionalSubsidy float64 = 0 - if utils.InArr(mode, []string{"lv_winery", "public_platoon"}) { - profit = utils.FloatFormat(lvUser.Profit, 6) - additionalSubsidy = lvUser.SubsidyFee - } - if lvUser.Uid == 0 { - continue - } - data = append(data, &model.OrdListRelate{ - Oid: oid, - Uid: lvUser.Uid, - Amount: profit, - Pvd: pvd, - CreateAt: createTime, - Level: level, - Mode: mode, - AdditionalSubsidy: utils.Float64ToStrByPrec(additionalSubsidy, 9), - ExtendType: lvUser.ExtendType, - }) - } - return data -} - -func SerializeLvUser(lvUser map[int]float64) string { - s := "" - for k, v := range lvUser { - s += "|" + utils.IntToStr(k) + ":" + utils.Float64ToStr(v) - } - return s -} - -func NewCalcLvUserFee(lvUser *comm_plan.LvUser) map[int]float64 { - fee := map[int]float64{} - if lvUser == nil { - return fee - } - if lvUser.ParentUser == nil { - fee[lvUser.Uid] = lvUser.Profit - } - for lvUser.ParentUser != nil { - fee[lvUser.Uid] = lvUser.Profit - lvUser = lvUser.ParentUser - } - return fee -} - -func SettleComm(eg *xorm.Engine, masterId string, CommissionParam md2.CommissionFirstParam) (float64, float64, float64, float64, *comm_plan.LvUser, error) { - var CommissionParam1 = md3.CommissionFirstParam{} - copier.Copy(&CommissionParam1, CommissionParam) - profit, pvdFee, sysFee, subsidyFee, lvUser, err := rule.SettleCommWithOrder(eg, masterId, CommissionParam1) - return profit, pvdFee, sysFee, subsidyFee, lvUser, err -} - -// GetCommissionByCommApi 调用公共接口获取佣金 -func GetCommissionByCommApi(eg *xorm.Engine, masterId string, req md2.CommissionFirstParam) (*comm_plan.SettleCommissionToGuide, error) { - profit, pvdFee, sysFee, subsidyFee, lvUser, err := SettleComm(eg, masterId, req) - if err != nil { - return nil, err - } - result := &comm_plan.SettleCommissionToGuide{ - Profit: profit, - PvdFee: pvdFee, - SysFee: sysFee, - SubsidyFee: subsidyFee, - LvUser: lvUser, - } - return result, nil -} diff --git a/consume/zhios_order_free.go b/consume/zhios_order_free.go deleted file mode 100644 index 77ab2ee..0000000 --- a/consume/zhios_order_free.go +++ /dev/null @@ -1,623 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/db/model" - md2 "applet/app/md" - svc2 "applet/app/svc" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - md3 "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" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "strings" - "time" - "xorm.io/xorm" -) - -func ZhiosOrderFree(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(100) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleZhiosOrderFree(res.Body) - //_ = res.Reject(false) - if err == nil { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleZhiosOrderFree(msg []byte) error { - time.Sleep(time.Microsecond * 20) // 等待500毫秒 - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.ZhiosOrderFree - fmt.Println(string(msg)) - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println("===with", err.Error()) - return err - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err != nil { - fmt.Println("===with", err.Error()) - return err - } - mid := canalMsg.Mid - eg := db.DBs[mid] - if eg == nil { - return nil - } - sess := eg.NewSession() - defer sess.Close() - sess.Begin() - ordData, err := db.OrderListByPvdOid(sess, canalMsg.Oid) - if err != nil || ordData == nil { - return nil - } - if ordData.State > 3 || ordData.PriceType > 0 || ordData.ThirdPriceType > 0 { - return nil - } - if canalMsg.OrderType == "13" { - freeNewType := db.SysCfgGetWithDb(eg, canalMsg.Mid, "more_free_new_type") - freeOrder := moreOrderFreeCheck(eg, sess, canalMsg) - if freeOrder != nil { - priceType := freeOrder.PriceType - ordData.ThirdPriceType = priceType - fee := utils.StrToFloat64(freeOrder.Fee) - allCommission := utils.StrToFloat64(freeOrder.ReturnMoney) - ordData.BenefitAll = allCommission - ownbuyReturnType := 0 - if freeOrder.OwnbuyReturnType == 0 && freeOrder.ReturnType == 1 { //自购补贴等于0为关闭 并且是淘礼金商品 - ownbuyReturnType = 1 - } - storeId := freeOrder.StoreId - bili := utils.StrToFloat64(freeOrder.Bili) - //加入分佣关系链 - opts, commissionOpts, _ := svc.GetAllPlan(eg, canalMsg.Mid) - if opts == nil { - sess.Commit() - - return nil - } - BenefitAll := ordData.BenefitAll - pvd := "moreFree_" + utils.IntToStr(priceType) - var rmd = md3.CommissionParam{IsTikTokTeamOrder: utils.IntToStr(ordData.IsTikTokTeamOrder)} - opt, err := svc.GetPlanCfg(eg, pvd, canalMsg.Mid, opts, commissionOpts, map[int]string{}, &rmd) - if err != nil { - sess.Commit() - return nil - } - var ord = md2.OrderInfo{ - PvdOid: ordData.PvdOid, - Pvd: pvd, - ItemId: ordData.ItemId, - ItemNum: ordData.ItemNum, - ItemPrice: ordData.ItemPrice, - PaidPrice: ordData.PaidPrice, - OrderType: ordData.OrderType, - Commission: BenefitAll, - State: ordData.State, - } - - //调用公共的分佣 - isShare := 0 - if ord.OrderType == 1 { - isShare = 1 - } - //计算每个用户的分佣 - req := md2.CommissionFirstParam{ - CommissionParam: md2.CommissionParam{ - Commission: utils.Float64ToStr(ord.Commission), - PaidPrice: utils.Float64ToStr(ord.PaidPrice), - OldPrice: utils.Float64ToStr(ord.PaidPrice), - IsTikTokTeamOrder: utils.IntToStr(ordData.IsTikTokTeamOrder), - }, - Uid: utils.IntToStr(ordData.Uid), - IsShare: isShare, - Provider: ord.Pvd, - IsAllLevelReturn: 1, - OwnbuyReturnType: ownbuyReturnType, - } - if utils.InArr(ord.Pvd, []string{md3.PVD_TB, md3.PVD_TM, md3.PVD_PDD, md3.PVD_SN, md3.PVD_KL, md3.PVD_JD, md3.PVD_JDOwn, md3.PVD_VIP}) == false { - req.CommissionParam.GoodsPrice = utils.Float64ToStr(ord.PaidPrice) - } - commissionList, err := GetCommissionByCommApi(eg, canalMsg.Mid, req) - if err != nil || commissionList.LvUser == nil { - sess.Commit() - return nil - } - pvdFee := commissionList.PvdFee - sysFee := commissionList.SysFee - subsidyFee := commissionList.SubsidyFee - lvUser := commissionList.LvUser - profit := commissionList.Profit - ordData.SubsidyFee = subsidyFee - ordData.PvdCommission = pvdFee - ordData.SysCommission = sysFee - var selfRate float64 = 0 - var subsidyRate float64 = 0 - //处理记录佣金 - if opt != nil { - profit = lvUser.Profit - //判断下这个等级有么有设置 - ordData.UserCommission = profit - ordData.SubsidyRate = subsidyRate - ordData.UserCommissionRate = selfRate - ordData.PlanCommissionId = opt.PlanCommissionId - ordData.BenefitList = SerializeLvUser(NewCalcLvUserFee(lvUser)) - } - if storeId > 0 { - deductPrice := (allCommission + fee) * bili - arg := md.ZhiosGuideStoreOrder{ - Uid: utils.IntToStr(ordData.Uid), - Mid: canalMsg.Mid, - Oid: ordData.PvdOid, - StoreId: utils.IntToStr(storeId), - DeductPrice: utils.Float64ToStr(deductPrice), - ItemTitle: ord.ItemTitle, - Pvd: "free", - SubsidyPrice: utils.Float64ToStr(allCommission), - Fee: utils.Float64ToStr(fee), - State: utils.IntToStr(ordData.State), - Type: "success", - } - ordData.Data = utils.SerializeStr(arg) - } - has, _ := db.OrderListByUpdateOrd(sess, ordData) - if has == false { - sess.Rollback() - return nil - } - - //批量写入 - if lvUser != nil { - if freeNewType == "1" { - lvUser.AdditionalSubsidy = ordData.BenefitAll - } - err := OrderRelateInsertNew(eg, sess, ordData.OrdId, ordData.Pvd, ordData.CreateAt, lvUser, ordData, canalMsg.Mid, true, opt.Mode, "1") - if err != nil { - sess.Rollback() - return err - } - } - } - } else { - freeNewType := db.SysCfgGetWithDb(eg, canalMsg.Mid, "free_new_type") - freeOrder := orderFreeCheck(eg, sess, canalMsg) - if freeOrder != nil { - priceType := freeOrder.PriceType - ordData.PriceType = priceType - fee := utils.StrToFloat64(freeOrder.Fee) - allCommission := utils.StrToFloat64(freeOrder.ReturnMoney) - ordData.BenefitAll = allCommission - ownbuyReturnType := 0 - if freeOrder.OwnbuyReturnType == 0 && freeOrder.ReturnType == 1 { //自购补贴等于0为关闭 并且是淘礼金商品 - ownbuyReturnType = 1 - } - storeId := freeOrder.StoreId - bili := utils.StrToFloat64(freeOrder.Bili) - //加入分佣关系链 - opts, commissionOpts, _ := svc.GetAllPlan(eg, canalMsg.Mid) - if opts == nil { - sess.Commit() - - return nil - } - if canalMsg.OrderType == "6" || canalMsg.OrderType == "7" { - ordData.OrderType = 3 //淘礼金免单 - } - BenefitAll := ordData.BenefitAll - pvd := "free" - var rmd = md3.CommissionParam{IsTikTokTeamOrder: utils.IntToStr(ordData.IsTikTokTeamOrder)} - opt, err := svc.GetPlanCfg(eg, pvd, canalMsg.Mid, opts, commissionOpts, map[int]string{}, &rmd) - if err != nil { - sess.Commit() - return nil - } - var ord = md2.OrderInfo{ - PvdOid: ordData.PvdOid, - Pvd: pvd, - ItemId: ordData.ItemId, - ItemNum: ordData.ItemNum, - ItemPrice: ordData.ItemPrice, - PaidPrice: ordData.PaidPrice, - OrderType: ordData.OrderType, - Commission: BenefitAll, - State: ordData.State, - } - - //调用公共的分佣 - isShare := 0 - if ord.OrderType == 1 { - isShare = 1 - } - //计算每个用户的分佣 - req := md2.CommissionFirstParam{ - CommissionParam: md2.CommissionParam{ - Commission: utils.Float64ToStr(ord.Commission), - PaidPrice: utils.Float64ToStr(ord.PaidPrice), - OldPrice: utils.Float64ToStr(ord.PaidPrice), - IsTikTokTeamOrder: utils.IntToStr(ordData.IsTikTokTeamOrder), - }, - Uid: utils.IntToStr(ordData.Uid), - IsShare: isShare, - Provider: ord.Pvd, - IsAllLevelReturn: 1, - OwnbuyReturnType: ownbuyReturnType, - } - if utils.InArr(ord.Pvd, []string{md3.PVD_TB, md3.PVD_TM, md3.PVD_PDD, md3.PVD_SN, md3.PVD_KL, md3.PVD_JD, md3.PVD_JDOwn, md3.PVD_VIP}) == false { - req.CommissionParam.GoodsPrice = utils.Float64ToStr(ord.PaidPrice) - } - commissionList, err := GetCommissionByCommApi(eg, canalMsg.Mid, req) - if err != nil || commissionList.LvUser == nil { - sess.Commit() - return nil - } - pvdFee := commissionList.PvdFee - sysFee := commissionList.SysFee - subsidyFee := commissionList.SubsidyFee - lvUser := commissionList.LvUser - profit := commissionList.Profit - ordData.SubsidyFee = subsidyFee - ordData.PvdCommission = pvdFee - ordData.SysCommission = sysFee - var selfRate float64 = 0 - var subsidyRate float64 = 0 - //处理记录佣金 - if opt != nil { - profit = lvUser.Profit - //判断下这个等级有么有设置 - ordData.UserCommission = profit - ordData.SubsidyRate = subsidyRate - ordData.UserCommissionRate = selfRate - ordData.PlanCommissionId = opt.PlanCommissionId - ordData.BenefitList = SerializeLvUser(NewCalcLvUserFee(lvUser)) - } - if storeId > 0 { - deductPrice := (allCommission + fee) * bili - arg := md.ZhiosGuideStoreOrder{ - Uid: utils.IntToStr(ordData.Uid), - Mid: canalMsg.Mid, - Oid: ordData.PvdOid, - StoreId: utils.IntToStr(storeId), - DeductPrice: utils.Float64ToStr(deductPrice), - ItemTitle: ord.ItemTitle, - Pvd: "free", - SubsidyPrice: utils.Float64ToStr(allCommission), - Fee: utils.Float64ToStr(fee), - State: utils.IntToStr(ordData.State), - Type: "success", - } - ordData.Data = utils.SerializeStr(arg) - } - has, _ := db.OrderListByUpdateOrd(sess, ordData) - if has == false { - sess.Rollback() - return nil - } - - //批量写入 - if lvUser != nil { - if freeNewType == "1" { - lvUser.AdditionalSubsidy = ordData.BenefitAll - } - err := OrderRelateInsertNew(eg, sess, ordData.OrdId, ordData.Pvd, ordData.CreateAt, lvUser, ordData, canalMsg.Mid, true, opt.Mode, "1") - if err != nil { - sess.Rollback() - return err - } - } - } - } - sess.Commit() - - return nil -} -func orderFreeCheck(eg *xorm.Engine, sess *xorm.Session, canalMsg *md.ZhiosOrderFree) *model.NewcomersFreeProduct { - - m, err := db.FreeProductByID(sess, canalMsg.ItemId, canalMsg.OptPvd) - stock := 0 - if m != nil && m.StoreId > 0 { //小于多少份就不能出售了 - guideStoreStock := db.SysCfgGetWithDb(eg, canalMsg.Mid, "guide_store_stock") - stock = utils.StrToInt(guideStoreStock) - } - if err != nil || m == nil || (m != nil && m.Stock <= stock) { - sess.Rollback() - return nil - } - - if strings.Contains(canalMsg.Pid, "free_") && m.ReturnType == 0 { - mt, err := db.FreePriceTypeByID(sess, m.PriceType) - if err != nil || mt == nil { - sess.Rollback() - - return nil - } - limitBuyConditions := &md.LimitBuyCondition{} - utils.Unserialize([]byte(mt.LimitBuyCondition), limitBuyConditions) - //判断条件前,先判断下有没有限购 - if mt.NeedLimitBuy == 1 { - //判断当前栏目购买商品数量 并且开启了 - if limitBuyConditions.OpenMoregoodsBuy == "1" && utils.StrToInt64(limitBuyConditions.MoregoodsBuyLimit) > 0 { - moreGoodsCount, _ := db.OrderListCountByPriceType(sess, canalMsg.Uid, mt.Id, utils.StrToInt(limitBuyConditions.MoregoodsBuyLimitDay)) - if moreGoodsCount+1 > utils.StrToInt64(limitBuyConditions.MoregoodsBuyLimit) { - sess.Rollback() - - return nil - } - } - //判断当前栏目购买商品数量 并且开启了 - if limitBuyConditions.OpenOnegoodsBuy == "1" && utils.StrToInt64(limitBuyConditions.OnegoodsBuyLimit) > 0 { - moreGoodsCount, _ := db.OrderListCountByItemId(sess, canalMsg.Uid, canalMsg.ItemId, utils.StrToInt(limitBuyConditions.OnegoodsBuyLimitDay)) - if moreGoodsCount+1 > utils.StrToInt64(limitBuyConditions.OnegoodsBuyLimit) { - sess.Rollback() - return nil - } - } - } - // 查找用户剩余的免单资格数 - profile, err := db.UserProfileFindByID(eg, canalMsg.Uid) - if err != nil || profile == nil { - logx.Warn(err) - sess.Rollback() - - return nil - } - if m.StoreId > 0 { - //商家放单 查下冻结 - coinId := db.SysCfgGetWithDb(eg, canalMsg.Uid, "guide_store_coin_id") - amount := db.GetUserVirtualCoinAmount(eg, m.StoreId, coinId) - if amount == nil { - sess.Rollback() - - return nil - } - if utils.StrToFloat64(amount.FreezeAmount) < utils.StrToFloat64(m.ReturnMoney) { - sess.Rollback() - - return nil - } - } - - //判断要不要扣免单券 - if mt.NeedUseQuan == 1 { - // 更新剩余次数 - isNeed := 1 - if mt.NeedQuan == 0 { - isNeed = 0 - } - if mt.NeedQuan > profile.FreeRemainTime { - auth, perm := svc2.CheckNewOrderAuth(eg, utils.StrToInt(canalMsg.Uid), mt) - if perm.AuthType == "all" || auth == false { - sess.Rollback() - return nil - } - if perm.AuthType != "all" && auth == true { - isNeed = 0 - } - } - if isNeed == 1 { - profile.FreeRemainTime = profile.FreeRemainTime - mt.NeedQuan - _, err = db.UserProfileUpdate(eg, profile.Uid, profile, "free_remain_time") - if err != nil { - logx.Warn(err) - sess.Rollback() - - return nil - } - // 插入日志记录 - db.FreeQualificationRecordInsertOne(eg, &model.NewcomersQualificationRecord{ - Uid: profile.Uid, - Source: 3, - SourceText: "消费扣除", - OrderId: utils.StrToInt64(canalMsg.Oid), - ChangeNum: -mt.NeedQuan, - AfterChangeNum: profile.FreeRemainTime, - CreatedAt: time.Now(), - UpdatedAt: time.Now(), - }) - } - - } - m.Stock-- - if m.Stock < 0 { - m.Stock = 0 - } - m.Sale++ - _, err = eg.Where("id=?", m.Id).Cols("stock,sale").Update(m) - if err != nil { - sess.Rollback() - return nil - } - if m.StoreId > 0 { //扣库存 - var storeGoods model.GuideStoreGoods - _, err := sess.Where("gid=? and delete_time is null and stock>?", m.GoodId, 0).Get(&storeGoods) - if err != nil { - sess.Rollback() - return nil - } - storeGoods.Stock-- - if storeGoods.Stock < 0 { - storeGoods.DownState = 3 - storeGoods.EndTime = int(time.Now().Unix()) - } - _, err = sess.Where("id=?", storeGoods.Id).Cols("down_state,end_time,stock").Update(&storeGoods) - if err != nil { - sess.Rollback() - return nil - } - } - sess.Commit() - return m - } - sess.Commit() - return m -} -func moreOrderFreeCheck(eg *xorm.Engine, sess *xorm.Session, canalMsg *md.ZhiosOrderFree) *model.MoreNewcomersFreeProduct { - - m, err := db.MoreFreeProductByID(sess, canalMsg.ItemId, canalMsg.OptPvd) - stock := 0 - if m != nil && m.StoreId > 0 { //小于多少份就不能出售了 - guideStoreStock := db.SysCfgGetWithDb(eg, canalMsg.Mid, "guide_store_stock") - stock = utils.StrToInt(guideStoreStock) - } - if err != nil || m == nil || (m != nil && m.Stock <= stock) { - sess.Rollback() - return nil - } - - if strings.Contains(canalMsg.Pid, "moreFree_") && m.ReturnType == 0 { - mt, err := db.MoreFreePriceTypeByID(sess, m.PriceType) - if err != nil || mt == nil { - sess.Rollback() - - return nil - } - limitBuyConditions := &md.LimitBuyCondition{} - utils.Unserialize([]byte(mt.LimitBuyCondition), limitBuyConditions) - //判断条件前,先判断下有没有限购 - if mt.NeedLimitBuy == 1 { - //判断当前栏目购买商品数量 并且开启了 - if limitBuyConditions.OpenMoregoodsBuy == "1" && utils.StrToInt64(limitBuyConditions.MoregoodsBuyLimit) > 0 { - moreGoodsCount, _ := db.OrderListCountByMorePriceType(sess, canalMsg.Uid, mt.Id, utils.StrToInt(limitBuyConditions.MoregoodsBuyLimitDay)) - if moreGoodsCount+1 > utils.StrToInt64(limitBuyConditions.MoregoodsBuyLimit) { - sess.Rollback() - - return nil - } - } - //判断当前栏目购买商品数量 并且开启了 - if limitBuyConditions.OpenOnegoodsBuy == "1" && utils.StrToInt64(limitBuyConditions.OnegoodsBuyLimit) > 0 { - moreGoodsCount, _ := db.OrderListCountByMoreItemId(sess, canalMsg.Uid, canalMsg.ItemId, utils.StrToInt(limitBuyConditions.OnegoodsBuyLimitDay)) - if moreGoodsCount+1 > utils.StrToInt64(limitBuyConditions.OnegoodsBuyLimit) { - sess.Rollback() - return nil - } - } - } - // 查找用户剩余的免单资格数 - profile, err := db.UserProfileFindByID(eg, canalMsg.Uid) - if err != nil || profile == nil { - logx.Warn(err) - sess.Rollback() - - return nil - } - if m.StoreId > 0 { - //商家放单 查下冻结 - coinId := db.SysCfgGetWithDb(eg, canalMsg.Uid, "guide_store_coin_id") - amount := db.GetUserVirtualCoinAmount(eg, m.StoreId, coinId) - if amount == nil { - sess.Rollback() - - return nil - } - if utils.StrToFloat64(amount.FreezeAmount) < utils.StrToFloat64(m.ReturnMoney) { - sess.Rollback() - - return nil - } - } - - //判断要不要扣免单券 - if mt.NeedUseQuan == 1 { - // 更新剩余次数 - isNeed := 1 - if mt.NeedQuan == 0 { - isNeed = 0 - } - if mt.NeedQuan > profile.ThirdFreeRemainTime { - auth, perm := svc2.MoreCheckNewOrderAuth(eg, utils.StrToInt(canalMsg.Uid), mt) - if perm.AuthType == "all" || auth == false { - sess.Rollback() - return nil - } - if perm.AuthType != "all" && auth == true { - isNeed = 0 - } - } - if isNeed == 1 { - profile.ThirdFreeRemainTime = profile.ThirdFreeRemainTime - mt.NeedQuan - _, err = db.UserProfileUpdate(eg, profile.Uid, profile, "third_free_remain_time") - if err != nil { - logx.Warn(err) - sess.Rollback() - - return nil - } - // 插入日志记录 - db.ThirdFreeQualificationRecordInsertOne(eg, &model.ThirdNewcomersQualificationRecord{ - Uid: profile.Uid, - Source: 3, - SourceText: "消费扣除", - OrderId: utils.StrToInt64(canalMsg.Oid), - ChangeNum: -mt.NeedQuan, - AfterChangeNum: profile.ThirdFreeRemainTime, - CreatedAt: time.Now(), - UpdatedAt: time.Now(), - }) - } - - } - m.Stock-- - if m.Stock < 0 { - m.Stock = 0 - } - m.Sale++ - _, err = eg.Where("id=?", m.Id).Cols("stock,sale").Update(m) - if err != nil { - sess.Rollback() - return nil - } - if m.StoreId > 0 { //扣库存 - var storeGoods model.GuideStoreGoods - _, err := sess.Where("gid=? and delete_time is null and stock>?", m.GoodId, 0).Get(&storeGoods) - if err != nil { - sess.Rollback() - return nil - } - storeGoods.Stock-- - if storeGoods.Stock < 0 { - storeGoods.DownState = 3 - storeGoods.EndTime = int(time.Now().Unix()) - } - _, err = sess.Where("id=?", storeGoods.Id).Cols("down_state,end_time,stock").Update(&storeGoods) - if err != nil { - sess.Rollback() - return nil - } - } - sess.Commit() - return m - } - sess.Commit() - return m -} diff --git a/consume/zhios_order_hjy.go b/consume/zhios_order_hjy.go deleted file mode 100644 index 17374ec..0000000 --- a/consume/zhios_order_hjy.go +++ /dev/null @@ -1,373 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/db/model" - md2 "applet/app/md" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/lib/comm_plan" - md3 "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" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "github.com/syyongx/php2go" - "sort" - "time" - "xorm.io/xorm" -) - -func ZhiosOrderHjy(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(500) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleZhiosOrderHjy(res.Body) - //_ = res.Reject(false) - if err != nil { - _ = res.Reject(false) - //TODO::重新推回队列末尾,避免造成队列堵塞 - var msg *md.ZhiosOrderBuckle - var tmpString string - err := json.Unmarshal(res.Body, &tmpString) - if err != nil { - return - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &msg) - if err != nil { - return - } - ch.Publish(queue.ExchangeName, utils.SerializeStr(msg), queue.RoutKey) - } else { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} -func GetHjyOrderCommission(eg *xorm.Engine, dbName, order_id string) (string, string) { - url := "https://app.openapi.dhcc.wang" - hjyAppkey := db.SysCfgGetWithDb(eg, dbName, "hjy_appkey") - hjyAppSecret := db.SysCfgGetWithDb(eg, dbName, "hjy_app_secret") - param := map[string]string{ - "app_key": hjyAppkey, - "time": utils.Int64ToStr(time.Now().Unix()), - "order_id": order_id, - "page": "1", - "api_name": "dhcc.oauth.order.commission", - "version": "v1", - "pagesize": "1", - } - keys := KsortToStr(param) - str := "" - for _, v := range keys { - if str == "" { - str += v + "=" + php2go.URLEncode(param[v]) - } else { - str += "&" + v + "=" + php2go.URLEncode(param[v]) - } - } - str += hjyAppSecret - param["sign"] = utils.Md5(str) - post, _ := utils.CurlPost(url, param, nil) - fmt.Println(string(post)) - var data md.HjyOrderCommisisonData - json.Unmarshal(post, &data) - if data.Code != 0 { - return "0", "0" - } - for _, v := range data.Data.List { - if v.SettlementStatus == "已结" { - return "1", v.SettlementTime - } - } - return "0", "" -} -func KsortToStr(params map[string]string) []string { - keys := make([]string, len(params)) - i := 0 - for k, _ := range params { - keys[i] = k - i++ - } - sort.Strings(keys) - return keys -} -func handleZhiosOrderHjy(msg []byte) error { - - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.ZhiosOrderBuckle - fmt.Println(string(msg)) - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println("===with", err.Error()) - return err - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err != nil { - fmt.Println("===with", err.Error()) - return err - } - mid := canalMsg.Mid - eg := db.DBs[mid] - if eg == nil { - return nil - } - sess := eg.NewSession() - defer sess.Close() - sess.Begin() - - ordData, err := db.OrderListByhjyOid(sess, canalMsg.Oid) - if err != nil || ordData == nil { - return nil - } - if ordData.OrderFormType < 0 { - sess.Commit() - - return nil - } - user, _ := db.UserFindByID(eg, ordData.Uid) - if user == nil { - fmt.Println(user) - sess.Commit() - - return nil - } - - if ordData.State == 5 { - sess.Commit() - return nil - } - //if ordData.State == 1 || ordData.State == 3 { - // if int64(ordData.ConfirmAt) >= utils.TimeStdParseUnix("2023-11-01 00:00:00") { - // isSettle, settleTime := GetHjyOrderCommission(eg, canalMsg.Mid, utils.IntToStr(ordData.HjyOid)) - // if isSettle == "1" { - // ordData.State = 5 - // ordData.SettleAt = int(utils.TimeStdParseUnix(settleTime)) - // } - // } - // - //} - var ordRelate = make([]model.OrdListRelate, 0) - sess.Where("oid=?", canalMsg.Oid).Find(&ordRelate) - if len(ordRelate) > 0 { - sess.Commit() - return nil - } - if ordData.State != 4 && int64(ordData.ConfirmAt) > 0 && int64(ordData.ConfirmAt) < utils.TimeStdParseUnix("2023-11-01 00:00:00") { - ordData.State = 5 - ordData.SettleAt = ordData.ConfirmAt - } - - fmt.Println(ordData) - //加入分佣关系链 - opts, commissionOpts, _ := svc.GetAllPlan(eg, canalMsg.Mid) - if opts == nil { - fmt.Println(opts) - - sess.Commit() - - return nil - } - BenefitAll := ordData.BenefitAll - pvd := ordData.Pvd - if ordData.OrderFormType == 1 { //京东自营 - pvd = md3.PVD_JDOwn - } - var rmd = md3.CommissionParam{IsTikTokTeamOrder: utils.IntToStr(ordData.IsTikTokTeamOrder)} - opt, err := svc.GetPlanCfg(eg, pvd, canalMsg.Mid, opts, commissionOpts, map[int]string{}, &rmd) - if err != nil { - fmt.Println(err) - - sess.Commit() - return nil - } - - var ord = md2.OrderInfo{ - PvdOid: ordData.PvdOid, - Pvd: pvd, - ItemId: ordData.ItemId, - ItemNum: ordData.ItemNum, - ItemPrice: ordData.ItemPrice, - PaidPrice: ordData.PaidPrice, - OrderType: ordData.OrderType, - Commission: BenefitAll, - State: ordData.State, - } - //调用公共的分佣 - isShare := 0 - if ord.OrderType == 1 { - isShare = 1 - } - //计算每个用户的分佣 - req := md2.CommissionFirstParam{ - CommissionParam: md2.CommissionParam{ - Commission: utils.Float64ToStr(ord.Commission), - PaidPrice: utils.Float64ToStr(ord.PaidPrice), - OldPrice: utils.Float64ToStr(ord.PaidPrice), - IsTikTokTeamOrder: utils.IntToStr(ordData.IsTikTokTeamOrder), - }, - Uid: utils.IntToStr(ordData.Uid), - IsShare: isShare, - Provider: ord.Pvd, - IsAllLevelReturn: 1, - } - if utils.InArr(ord.Pvd, []string{md3.PVD_TB, md3.PVD_TM, md3.PVD_PDD, md3.PVD_SN, md3.PVD_KL, md3.PVD_JD, md3.PVD_JDOwn, md3.PVD_VIP}) == false { - req.CommissionParam.GoodsPrice = utils.Float64ToStr(ord.PaidPrice) - } - commissionList, err := GetCommissionByCommApi(eg, canalMsg.Mid, req) - if err != nil || commissionList.LvUser == nil { - fmt.Println(err) - sess.Commit() - return nil - } - pvdFee := commissionList.PvdFee - sysFee := commissionList.SysFee - subsidyFee := commissionList.SubsidyFee - lvUser := commissionList.LvUser - profit := commissionList.Profit - ordData.SubsidyFee = subsidyFee - ordData.PvdCommission = pvdFee - ordData.SysCommission = sysFee - ordData.BuckleCommission = utils.Float64ToStr(BenefitAll) - var selfRate float64 = 0 - var subsidyRate float64 = 0 - //处理记录佣金 - if opt != nil { - profit = lvUser.Profit - //判断下这个等级有么有设置 - ordData.UserCommission = profit - ordData.SubsidyRate = subsidyRate - ordData.UserCommissionRate = selfRate - ordData.PlanCommissionId = opt.PlanCommissionId - ordData.BenefitList = SerializeLvUser(NewCalcLvUserFee(lvUser)) - } - _, err = db.OrderListByUpdateOrd(sess, ordData) - if err != nil { - fmt.Println(err) - - sess.Rollback() - return nil - } - fmt.Println(lvUser) - - //批量写入 - if lvUser != nil { - err := OrderRelateInsert1(eg, sess, ordData.OrdId, ordData.Pvd, ordData.CreateAt, lvUser, ordData, canalMsg.Mid, true, opt.Mode, "1") - fmt.Println(err) - if err != nil { - sess.Rollback() - return err - } - } - sess.Commit() - return nil -} - -func OrderRelateInsert1(eg *xorm.Engine, sess *xorm.Session, oid int64, pvd string, createTime int, lvUser *comm_plan.LvUser, newOrd *model.OrdList, masterId string, isDelete bool, mode string, isNew string) error { - if lvUser == nil { - return nil - } - uid := lvUser.Uid - if uid == 0 { - return nil - } - oldLvUser := lvUser - oldLevel := 0 - data := OrderRelateInsertComm(eg, oid, pvd, createTime, lvUser, newOrd, masterId, mode) - fmt.Println(data) - - if data == nil || len(data) == 0 { - return nil - } - list, _ := db.OrderRelateFindByOid(sess, oid, pvd) - listMap := make(map[int]model.OrdListRelate) - if list != nil { - for _, v := range *list { - listMap[v.Uid] = v - } - } - fmt.Println(isDelete) - _, err2 := db.OrderRelateDeleteByOid(sess, oid, pvd) - if err2 != nil { - return err2 - } - _, err2 = db.VirtualCoinOrderRelateDeleteByOid(sess, oid, pvd) - if err2 != nil { - return err2 - } - //后写入 - err := db.DbInsertBatchSess(sess, data) - if err != nil { - return err - - } else if lvUser.ProfitList != nil { - // 插入虚拟币数据 - vcrData := CombineVirtualCoinRelateData(oldLvUser, oid, pvd, oldLevel, mode) - if len(vcrData) == 0 { - return nil - } - err := db.DbInsertBatchSess(sess, vcrData) - if err != nil { - return err - - } - } - if lvUser.TikTokOwnSubsidyFeeList != nil { - _, err2 := db.TikTokTeamOrderRelateDeleteByOid(sess, oid, pvd) - if err != nil { - return err2 - } - var teamData []model.TikTokTeamOrderRelate - TikTokTeamCommission := newOrd.TikTokTeamCommission - if utils.StrToFloat64(newOrd.TikTokTeamRealCommission) > 0 { - TikTokTeamCommission = newOrd.TikTokTeamRealCommission - } - for k, v := range lvUser.TikTokOwnSubsidyFeeList { - tmp := model.TikTokTeamOrderRelate{ - CoinId: utils.StrToInt(k), - Uid: uid, - Amount: utils.Float64ToStrByPrec(v, 8), - Oid: utils.Int64ToStr(oid), - Time: time.Now(), - Commission: TikTokTeamCommission, - Pvd: pvd, - } - teamData = append(teamData, tmp) - } - if len(teamData) == 0 { - return nil - } - err := db.DbInsertBatchSess(sess, &teamData) - if err != nil { - return err - - } - } - return nil -} diff --git a/consume/zhios_order_settle_total.go b/consume/zhios_order_settle_total.go deleted file mode 100644 index 11ece81..0000000 --- a/consume/zhios_order_settle_total.go +++ /dev/null @@ -1,190 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/db/model" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "time" -) - -func ZhiosSettleTotal(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleZhiosOrderSettleTotal(res.Body) - //_ = res.Reject(false) - if err != nil { - fmt.Println("==================", err.Error()) - _ = res.Reject(false) - //TODO::重新推回队列末尾,避免造成队列堵塞 - var msg *md.ZhiosOrderBuckle - var tmpString string - err := json.Unmarshal(res.Body, &tmpString) - if err != nil { - return - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &msg) - if err != nil { - return - } - ch.Publish(queue.ExchangeName, utils.SerializeStr(msg), queue.RoutKey) - } else { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleZhiosOrderSettleTotal(msg []byte) error { - //time.Sleep(time.Microsecond * 20) // 等待500毫秒 - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.ZhiosOrderBuckle - fmt.Println(string(msg)) - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println("===with", err.Error()) - return err - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err != nil { - fmt.Println("===with", err.Error()) - return err - } - mid := canalMsg.Mid - eg := db.DBs[mid] - if eg == nil { - return nil - } - sess := eg.NewSession() - defer sess.Close() - sess.Begin() - times := time.Now() - fmt.Println("==================", time.Since(times)) - ordData, err := db.OrderListByPvdOid(sess, canalMsg.Oid) - if err != nil || ordData == nil { - return nil - } - fmt.Println("==================1", time.Since(times)) - - var ordRelate = make([]model.OrdListRelate, 0) - sess.Where("oid=?", canalMsg.Oid).Find(&ordRelate) - fmt.Println("==================2", time.Since(times)) - - if len(ordRelate) > 0 { - for _, v := range ordRelate { - if v.Amount == 0 && utils.StrToFloat64(v.AdditionalSubsidy) == 0 { - continue - } - - var userStatistics model.UserStatistics - sess.Where("uid=?", v.Uid).Get(&userStatistics) - if userStatistics.Id == 0 { - userStatistics = model.UserStatistics{ - ImportFinTotal: "", - FinTotal: "", - Uid: v.Uid, - } - _, err := sess.Insert(&userStatistics) - if err != nil { - sess.Rollback() - return err - } - } - userStatistics.FinTotal = utils.Float64ToStrByPrec(utils.StrToFloat64(userStatistics.FinTotal)+v.Amount+utils.StrToFloat64(v.AdditionalSubsidy), 4) - _, err := sess.Where("id=?", userStatistics.Id).Cols("fin_total").Update(&userStatistics) - if err != nil { - return err - } - fmt.Println("==================3", time.Since(times)) - - var userStatistics1 model.UserWaitAmount - sess.Where("uid=? ", v.Uid).Get(&userStatistics1) - if userStatistics1.Id == 0 { - continue - } - userStatistics1.Amount = utils.Float64ToStrByPrec(utils.StrToFloat64(userStatistics1.Amount)-v.Amount-utils.StrToFloat64(v.AdditionalSubsidy), 4) - _, err1 := sess.Where("id=?", userStatistics1.Id).Cols("amount").Update(&userStatistics1) - if err1 != nil { - sess.Rollback() - return err - } - fmt.Println("==================4", time.Since(times)) - - //if update1 == 0 { - // sess.Rollback() - // return errors.New("失败") - //} - - var userStatistics2 model.UserMonthAmount - if ordData.SettleAt == 0 { - ordData.SettleAt = int(time.Now().Unix()) - } - now := time.Unix(int64(ordData.SettleAt), 0).Format("200601") - sess.Where("uid=? and date=?", v.Uid, now).Get(&userStatistics2) - fmt.Println("==================31", time.Since(times)) - - if userStatistics2.Id == 0 { - userStatistics2 = model.UserMonthAmount{ - Date: utils.StrToInt(now), - Uid: v.Uid, - } - has, err := sess.Insert(&userStatistics2) - if err != nil { - sess.Rollback() - return err - } - if has == 0 { - sess.Rollback() - return errors.New("失败") - } - } - fmt.Println("==================41", time.Since(times)) - - userStatistics2.SettleAmount = utils.Float64ToStrByPrec(utils.StrToFloat64(userStatistics2.SettleAmount)+v.Amount+utils.StrToFloat64(v.AdditionalSubsidy), 4) - _, err2 := sess.Where("id=?", userStatistics2.Id).Cols("settle_amount").Update(&userStatistics2) - if err2 != nil { - sess.Rollback() - return err2 - } - fmt.Println("==================5", time.Since(times)) - - //if update2 == 0 { - // sess.Rollback() - // return errors.New("失败") - //} - } - } - sess.Commit() - - return nil -} diff --git a/consume/zhios_order_total.go b/consume/zhios_order_total.go deleted file mode 100644 index cbd2962..0000000 --- a/consume/zhios_order_total.go +++ /dev/null @@ -1,166 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/db/model" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "time" - "xorm.io/xorm" -) - -func ZhiosOrderTotal(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(100) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleZhiosOrderTotal(res.Body) - //_ = res.Reject(false) - if err != nil { - _ = res.Reject(false) - //TODO::重新推回队列末尾,避免造成队列堵塞 - var msg *md.ZhiosOrderBuckle - var tmpString string - err := json.Unmarshal(res.Body, &tmpString) - if err != nil { - return - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &msg) - if err != nil { - return - } - ch.Publish(queue.ExchangeName, utils.SerializeStr(msg), queue.RoutKey) - } else { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleZhiosOrderTotal(msg []byte) error { - time.Sleep(time.Microsecond * 20) // 等待500毫秒 - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.ZhiosOrderBuckle - fmt.Println(string(msg)) - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println("===with", err.Error()) - return err - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err != nil { - fmt.Println("===with", err.Error()) - return err - } - mid := canalMsg.Mid - eg := db.DBs[mid] - if eg == nil { - return nil - } - statUserOrderMoney(eg, canalMsg) - return nil -} -func statUserOrderMoney(eg *xorm.Engine, req *md.ZhiosOrderBuckle) (map[string]string, error) { - result := make(map[string]string) - thisMonthRange := utils.GetTimeRange("current_month") - lastMonthRange := utils.GetTimeRange("last_month") - var thisMonthData model.UserMonthAmount - thismonth := time.Unix(thisMonthRange["start"], 0).Format("200601") - eg.Where("uid=? and date=?", req.Uid, thismonth).Get(&thisMonthData) - if thisMonthData.Id == 0 { - thisMonthData.Uid = utils.StrToInt(req.Uid) - thisMonthData.Date = utils.StrToInt(thismonth) - eg.Insert(&thisMonthData) - } - - var lastMonthData model.UserMonthAmount - lastmonth := time.Unix(lastMonthRange["start"], 0).Format("200601") - eg.Where("uid=? and date=?", req.Uid, lastmonth).Get(&lastMonthData) - if lastMonthData.Id == 0 { - lastMonthData.Uid = utils.StrToInt(req.Uid) - lastMonthData.Date = utils.StrToInt(lastmonth) - eg.Insert(&lastMonthData) - } - types := "" - uid := req.Uid - // 获取时间范围 - - // 统计预估 (预估包含结算部分且是有效订单) - sqlTpl := `SELECT cast(SUM(LEFT(olr.amount,LENGTH(olr.amount)-2)) as decimal(50,4)) AS amount -FROM ord_list_relate olr - LEFT JOIN ord_list ol ON olr.oid = ol.ord_id - LEFT JOIN privilege_card_ord pco ON olr.oid =pco.ord_id - LEFT JOIN duoyou_ord_list dol ON olr.oid =dol.oid - LEFT JOIN recharge_order ro ON olr.oid =ro.oid - LEFT JOIN playlet_sale_order pso ON olr.oid =pso.custom_oid -WHERE olr.uid = ? %s - AND olr.create_at >= ? - AND olr.create_at < ? AND (ol.state<>4 or pco.state=1 or dol.id>0 or ro.status<>'已退款' or pso.status<>'订单退款'); -` - sqlTpl = fmt.Sprintf(sqlTpl, types) - - fmt.Println(lastMonthRange) - thisMonthResult, err := db.QueryNativeString(eg, sqlTpl, uid, thisMonthRange["start"], thisMonthRange["end"]) - if err != nil { - _ = logx.Warn(err) - result["thisMonth"] = "0" - } else { - result["thisMonth"] = thisMonthResult[0]["amount"] - } - thisMonthData.Amount = result["thisMonth"] - eg.Where("id=?", thisMonthData.Id).Update(&thisMonthData) - - // 统计上月预估 (预估包含结算部分且是有效订单) - sqlTpl2 := `SELECT cast(SUM(IF(ol.state<>4 or pco.state=1 or dol.id>0 or ro.status<>'已退款' or pso.status<>'订单退款', LEFT(olr.amount,LENGTH(olr.amount)-2), 0)) as decimal(50,4)) AS amount -FROM ord_list_relate olr - LEFT JOIN ord_list ol ON olr.oid = ol.ord_id - LEFT JOIN privilege_card_ord pco ON olr.oid =pco.ord_id - LEFT JOIN duoyou_ord_list dol ON olr.oid =dol.oid -LEFT JOIN recharge_order ro ON olr.oid =ro.oid - LEFT JOIN playlet_sale_order pso ON olr.oid =pso.custom_oid -WHERE olr.uid = ? %s - AND olr.create_at >= ? - AND olr.create_at < ? -` - sqlTpl2 = fmt.Sprintf(sqlTpl2, types) - - lastMonthResult, err := db.QueryNativeString(eg, sqlTpl2, uid, lastMonthRange["start"], lastMonthRange["end"]) - if err != nil { - _ = logx.Warn(err) - result["lastMonth"] = "0" - } else { - result["lastMonth"] = lastMonthResult[0]["amount"] - } - - lastMonthData.Amount = result["lastMonth"] - eg.Where("id=?", lastMonthData.Id).Update(&lastMonthData) - return result, nil -} diff --git a/consume/zhios_order_total_second.go b/consume/zhios_order_total_second.go deleted file mode 100644 index 060d981..0000000 --- a/consume/zhios_order_total_second.go +++ /dev/null @@ -1,313 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/db/model" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "time" -) - -func ZhiosOrderTotalSecond(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleZhiosOrderTotalSecond(res.Body) - //_ = res.Reject(false) - if err != nil { - _ = res.Reject(false) - //TODO::重新推回队列末尾,避免造成队列堵塞 - var msg *md.ZhiosOrderBuckle - var tmpString string - err := json.Unmarshal(res.Body, &tmpString) - if err != nil { - return - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &msg) - if err != nil { - return - } - ch.Publish(queue.ExchangeName, utils.SerializeStr(msg), queue.RoutKey) - } else { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleZhiosOrderTotalSecond(msg []byte) error { - time.Sleep(time.Microsecond * 20) // 等待500毫秒 - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.ZhiosOrderBuckle - fmt.Println(string(msg)) - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println("===with", err.Error()) - return err - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err != nil { - fmt.Println("===with", err.Error()) - return err - } - mid := canalMsg.Mid - eg := db.DBs[mid] - if eg == nil { - return nil - } - sess := eg.NewSession() - defer sess.Close() - sess.Begin() - - ordData, err := db.OrderListByPvdOid(sess, canalMsg.Oid) - if err != nil || ordData == nil { - sess.Rollback() - return nil - } - - now := time.Unix(int64(ordData.CreateAt), 0).Format("200601") - nowDay := time.Unix(int64(ordData.CreateAt), 0).Format("20060102") - isTotal := ordData.IsTotal - if ordData.OrderFormType >= 0 { - if ordData.IsTotal == 1 && ordData.State != 4 { - sess.Rollback() - return nil - } - if ordData.IsTotal == 2 && ordData.State == 4 { - sess.Rollback() - return nil - } - var ordRelate = make([]model.OrdListRelate, 0) - sess.Where("oid=?", canalMsg.Oid).Find(&ordRelate) - if len(ordRelate) > 0 { - for _, v := range ordRelate { - if v.Amount == 0 && utils.StrToFloat64(v.AdditionalSubsidy) == 0 { - continue - } - var userStatistics model.UserMonthAmount - sess.Where("uid=? and date=?", v.Uid, now).Get(&userStatistics) - if userStatistics.Id == 0 { - userStatistics = model.UserMonthAmount{ - Date: utils.StrToInt(now), - Uid: v.Uid, - } - has, err := sess.Insert(&userStatistics) - if err != nil { - sess.Rollback() - return err - } - if has == 0 { - sess.Rollback() - return errors.New("失败") - } - } - isupdate := 0 - if ordData.State == 4 && ordData.IsTotal == 1 { - isupdate = 1 - isTotal = 2 - userStatistics.Amount = utils.Float64ToStrByPrec(utils.StrToFloat64(userStatistics.Amount)-v.Amount-utils.StrToFloat64(v.AdditionalSubsidy), 4) - } - if ordData.State != 4 && ordData.IsTotal == 0 { - isupdate = 1 - isTotal = 1 - userStatistics.Amount = utils.Float64ToStrByPrec(utils.StrToFloat64(userStatistics.Amount)+v.Amount+utils.StrToFloat64(v.AdditionalSubsidy), 4) - } - update, err := sess.Where("id=?", userStatistics.Id).Cols("amount").Update(&userStatistics) - if err != nil { - sess.Rollback() - return err - } - if update == 0 && isupdate == 1 { - sess.Rollback() - return errors.New("失败") - } - if v.CreateAt > 1711086661 { - var userStatistics1 model.UserDayAmount - sess.Where("uid=? and date=?", v.Uid, nowDay).Get(&userStatistics1) - if userStatistics1.Id == 0 { - userStatistics1 = model.UserDayAmount{ - Date: utils.StrToInt(nowDay), - Uid: v.Uid, - } - has, err := sess.Insert(&userStatistics1) - if err != nil { - sess.Rollback() - return err - } - if has == 0 { - sess.Rollback() - return errors.New("失败") - } - } - isupdate1 := 0 - if ordData.State == 4 && ordData.IsTotal == 1 { - isupdate1 = 1 - userStatistics1.Amount = utils.Float64ToStrByPrec(utils.StrToFloat64(userStatistics1.Amount)-v.Amount-utils.StrToFloat64(v.AdditionalSubsidy), 4) - } - if ordData.State != 4 && ordData.IsTotal == 0 { - isupdate1 = 1 - userStatistics1.Amount = utils.Float64ToStrByPrec(utils.StrToFloat64(userStatistics1.Amount)+v.Amount+utils.StrToFloat64(v.AdditionalSubsidy), 4) - } - update1, err1 := sess.Where("id=?", userStatistics1.Id).Cols("amount").Update(&userStatistics1) - if err1 != nil { - sess.Rollback() - return err - } - if update1 == 0 && isupdate1 == 1 { - sess.Rollback() - return errors.New("失败") - } - } - var userStatistics1 model.UserWaitAmount - sess.Where("uid=? ", v.Uid).Get(&userStatistics1) - if userStatistics1.Id == 0 { - userStatistics1 = model.UserWaitAmount{ - Uid: v.Uid, - } - has, err := sess.Insert(&userStatistics1) - if err != nil { - sess.Rollback() - return err - } - if has == 0 { - sess.Rollback() - return errors.New("失败") - } - } - isupdate1 := 0 - if ordData.State == 4 && ordData.IsTotal == 1 { - isupdate1 = 1 - userStatistics1.Amount = utils.Float64ToStrByPrec(utils.StrToFloat64(userStatistics1.Amount)-v.Amount-utils.StrToFloat64(v.AdditionalSubsidy), 4) - } - if ordData.State != 4 && ordData.IsTotal == 0 { - isupdate1 = 1 - userStatistics1.Amount = utils.Float64ToStrByPrec(utils.StrToFloat64(userStatistics1.Amount)+v.Amount+utils.StrToFloat64(v.AdditionalSubsidy), 4) - } - update1, err1 := sess.Where("id=?", userStatistics1.Id).Cols("amount").Update(&userStatistics1) - if err1 != nil { - sess.Rollback() - return err - } - if update1 == 0 && isupdate1 == 1 { - sess.Rollback() - return errors.New("失败") - } - } - } - } else { - if ordData.IsTotal == 3 && ordData.State != 4 { - sess.Rollback() - return nil - } - if ordData.IsTotal == 2 && ordData.State == 4 { - sess.Rollback() - return nil - } - var ordRelate = make([]model.BuckleRecord, 0) - sess.Where("ord_id=?", canalMsg.Oid).Find(&ordRelate) - if len(ordRelate) > 0 { - for _, v := range ordRelate { - if utils.StrToFloat64(v.Amount) == 0 { - continue - } - var userStatistics model.UserMonthAmount - sess.Where("uid=? and date=?", v.Uid, now).Get(&userStatistics) - if userStatistics.Id == 0 { - userStatistics = model.UserMonthAmount{ - Date: utils.StrToInt(now), - Uid: v.Uid, - } - _, err := sess.Insert(&userStatistics) - if err != nil { - sess.Rollback() - return err - } - } - if ordData.State == 4 && (ordData.IsTotal == 1 || ordData.IsTotal == 3) { - isTotal = 2 - userStatistics.Amount = utils.Float64ToStrByPrec(utils.StrToFloat64(userStatistics.Amount)-utils.StrToFloat64(v.AfterAmount), 4) - } - if ordData.State != 4 && (ordData.IsTotal == 0) { - isTotal = 3 - userStatistics.Amount = utils.Float64ToStrByPrec(utils.StrToFloat64(userStatistics.Amount)+utils.StrToFloat64(v.AfterAmount), 4) - } - if ordData.State != 4 && (ordData.IsTotal == 1) { - isTotal = 3 - userStatistics.Amount = utils.Float64ToStrByPrec(utils.StrToFloat64(userStatistics.Amount)-utils.StrToFloat64(v.Amount), 4) - } - _, err := sess.Where("id=?", userStatistics.Id).Cols("amount").Update(&userStatistics) - if err != nil { - sess.Rollback() - return err - } - var userStatistics1 model.UserWaitAmount - sess.Where("uid=? ", v.Uid).Get(&userStatistics1) - if userStatistics1.Id == 0 { - userStatistics1 = model.UserWaitAmount{ - Uid: v.Uid, - } - has, err := sess.Insert(&userStatistics1) - if err != nil { - sess.Rollback() - return err - } - if has == 0 { - sess.Rollback() - return errors.New("失败") - } - } - if ordData.State == 4 && (ordData.IsTotal == 1 || ordData.IsTotal == 3) { - isTotal = 2 - userStatistics1.Amount = utils.Float64ToStrByPrec(utils.StrToFloat64(userStatistics1.Amount)-utils.StrToFloat64(v.AfterAmount), 4) - } - if ordData.State != 4 && (ordData.IsTotal == 0) { - isTotal = 3 - userStatistics1.Amount = utils.Float64ToStrByPrec(utils.StrToFloat64(userStatistics1.Amount)+utils.StrToFloat64(v.AfterAmount), 4) - } - if ordData.State != 4 && (ordData.IsTotal == 1) { - isTotal = 3 - userStatistics1.Amount = utils.Float64ToStrByPrec(utils.StrToFloat64(userStatistics1.Amount)-utils.StrToFloat64(v.Amount), 4) - } - _, err = sess.Where("id=?", userStatistics1.Id).Cols("amount").Update(&userStatistics) - if err != nil { - sess.Rollback() - return err - } - - } - } - } - ordData.IsTotal = isTotal - sess.Where("ord_id=?", ordData.OrdId).Update(ordData) - sess.Commit() - return nil -} diff --git a/consume/zhios_recharge_order_fail.go b/consume/zhios_recharge_order_fail.go deleted file mode 100644 index 487d983..0000000 --- a/consume/zhios_recharge_order_fail.go +++ /dev/null @@ -1,258 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/db/model" - "applet/app/db/offical" - model2 "applet/app/db/offical/model" - "applet/app/e" - md2 "applet/app/md" - "applet/app/svc" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "code.fnuoos.com/go_rely_warehouse/zyos_go_pay.git/pay" - "code.fnuoos.com/go_rely_warehouse/zyos_go_third_party_api.git/recharge" - "encoding/json" - "errors" - "fmt" - "github.com/shopspring/decimal" - "github.com/streadway/amqp" - "github.com/tidwall/gjson" - "strings" - "time" - "xorm.io/xorm" -) - -func ZhiosRechargeOrderFail(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleZhiosRechargeOrderFail(res.Body) - //_ = res.Reject(false) - if err == nil { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleZhiosRechargeOrderFail(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.ZhiosRechargeOrderPay - fmt.Println(string(msg)) - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println(err.Error()) - return err - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err != nil { - return err - } - mid := canalMsg.Mid - eg := db.DBs[mid] - uid := utils.StrToInt(canalMsg.Uid) - oid := canalMsg.Oid - var orderData model.RechargeOrder - b, err2 := eg.Where("oid=? and uid=?", oid, uid).Get(&orderData) - if err2 != nil { - return errors.New("err") - } - if b == false { - return nil - } - if orderData.Status != "已付款" { - return nil - } - //查询官方接口看看有没有订单 - param, aggregationRechargeApiKey := CommAggregation(eg, mid) - param["out_trade_nums"] = oid - aggregationRechargeApiUrl := GetApiUrl() - order, err := recharge.GetOrder(aggregationRechargeApiUrl, aggregationRechargeApiKey, param) - utils.FilePutContents(mid+"rech", utils.SerializeStr(param)) - utils.FilePutContents(mid+"rech", aggregationRechargeApiKey) - utils.FilePutContents(mid+"rech", utils.SerializeStr(order)) - if err != nil { - utils.FilePutContents(mid+"rech", err.Error()) - return errors.New("err") - } - if gjson.Get(order, "errno").Int() == 0 && strings.Contains(order, oid) == false { - utils.FilePutContents(mid+"rech", utils.SerializeStr(orderData)) - NSFNTheSameBack := true - if orderData.PayMethod == 3 { - wechatP12ApiclientCert := db.SysCfgGetWithDb(eg, mid, "wechat_p12_apiclient_cert") - wechatPayRefundType := db.SysCfgGetWithDb(eg, mid, "wechat_pay_refund_type") - NSFNTheSameBack = false - if wechatP12ApiclientCert == "" || orderData.TradeNo == "" || wechatPayRefundType != "1" || orderData.AppId == "" { - NSFNTheSameBack = true - } else { - params := map[string]string{ - "subject": "聚合充值" + orderData.Title + "退款", - "total_fee": wxMoneyMulHundred(orderData.Amount), - "amount": wxMoneyMulHundred(orderData.Amount), - "out_refund_no": orderData.Oid, - "p12_str": canalMsg.WxappletFilepathUrl + "/" + wechatP12ApiclientCert, - "transaction_id": orderData.TradeNo, - "pay_wx_mch_id": db.SysCfgGetWithDb(eg, mid, "pay_wx_mch_id"), - "pay_wx_api_key": db.SysCfgGetWithDb(eg, mid, "pay_wx_api_key"), - "uid": utils.IntToStr(orderData.Uid), - "notify_url": canalMsg.DomainUrl + "/api/v1/refund/callback/" + mid, - } - params["pay_wx_appid"] = orderData.AppId - r, r1, err := pay.WxAppRefund(params) - utils.FilePutContents("mall_refund", utils.SerializeStr(params)) - utils.FilePutContents("mall_refund", utils.SerializeStr(r)) - utils.FilePutContents("mall_refund", utils.SerializeStr(r1)) - if err != nil { - utils.FilePutContents("mall_refund", err.Error()) - return err - } - if r.ReturnCode != "SUCCESS" { - return errors.New(r.ReturnMsg) - } - } - } - if orderData.PayMethod == 2 { - alipayPayRefundType := db.SysCfgGetWithDb(eg, mid, "alipay_pay_refund_type") - NSFNTheSameBack = false - if orderData.TradeNo == "" || alipayPayRefundType != "1" { - NSFNTheSameBack = true - } else { - var params = &md2.AliPayPayParams{} - config, _ := svc.CommAlipayConfig(eg, mid, params) - config["trade_no"] = orderData.TradeNo - config["refund_amount"] = orderData.Amount - config["refund_reason"] = "退款" - config["out_request_no"] = utils.OrderUUID(orderData.Uid) - refund, err := pay.AlipayTradeRefund(config) - utils.FilePutContents("mall_refund", utils.SerializeStr(config)) - utils.FilePutContents("mall_refund", utils.SerializeStr(refund)) - if err != nil { - return err - } - if refund.AlipayTradeRefundResponse.Code != "10000" { - return errors.New(refund.AlipayTradeRefundResponse.SubMsg) - - } - if refund.AlipayTradeRefundResponse.FundChange != "Y" { - return errors.New("退款失败") - } - } - } - // 更改为已支付 - orderData.Status = "已退款" - orderData.RefundTime = time.Now() - // 保存ord - row, err := eg.ID(orderData.Id).Cols("status,pay_method,refund_time").Update(&orderData) - if row > 0 && err == nil { - if NSFNTheSameBack { - svc.UpdateUserFinValidAndInterFlow(eg, - orderData.Amount, "聚合充值"+orderData.Title+"退款", "aggregation_recharge", 0, 24, orderData.Uid, orderData.Id, int64(orderData.Id), utils.StrToInt64(orderData.Oid)) - } - } else { - return errors.New("err") - } - rechargeNotPayMoney := db.SysCfgGetWithDb(eg, mid, "recharge_not_pay_money") - if rechargeNotPayMoney != "1" { - ZyRechargeMoneyDeal(mid, orderData.Oid, orderData.Uid, utils.StrToFloat64(orderData.ZyAmount), 0, orderData.Title+"退款", "refund") - } - } - return nil -} - -// 微信金额乘100 -func wxMoneyMulHundred(m string) string { - amount, _ := decimal.NewFromString(m) - newM := amount.Mul(decimal.NewFromInt(100)) - return newM.String() -} -func GetApiUrl() string { - aggregationRechargeApiUrl := "" - aggregationRechargeApiUrlData := offical.SysCfgByKey("aggregation_recharge_api_url") - if aggregationRechargeApiUrlData != nil { - aggregationRechargeApiUrl = aggregationRechargeApiUrlData.V - } - return aggregationRechargeApiUrl -} -func ZyRechargeMoneyDeal(mid string, orderId string, uid int, officalAmount float64, types int, title, orderType string) error { - info := offical.GetAggregationUserInfo(mid) - if info == nil { - fmt.Println("获取价格失败") - return e.NewErr(400, "获取价格失败") - } - if types == 1 { - if utils.StrToFloat64(info.Amount)+utils.StrToFloat64(info.CreditAmount)-officalAmount < 0 { - fmt.Println("预存款不足") - return e.NewErr(400, "预存款不足") - } - info.Amount = utils.Float64ToStr(utils.StrToFloat64(info.Amount) - officalAmount) - } else { - info.Amount = utils.Float64ToStr(utils.StrToFloat64(info.Amount) + officalAmount) - } - update, err := db.Db.Where("id=?", info.Id).Cols("amount").Update(info) - if update == 0 || err != nil { - return e.NewErr(400, "预存款不足") - } - var flow = model2.AggregationUserRechargeOrd{ - OrdId: orderId, - Uid: utils.StrToInt(mid), - Amount: utils.Float64ToStr(officalAmount), - CostPrice: utils.Float64ToStr(officalAmount), - Balance: info.Amount, - PayWay: 0, - State: 1, - Memo: title, - CreateAt: time.Now(), - Type: types, - OrdType: orderType, - SubUid: uid, - } - //TODO 要不要判断失败呢 - db.Db.Insert(&flow) - return nil -} - -func CommAggregation(eg *xorm.Engine, mid string) (map[string]string, string) { - aggregationRechargeApiKey := db.SysCfgGetWithDb(eg, mid, "aggregation_recharge_api_key") - aggregationRechargeUserId := db.SysCfgGetWithDb(eg, mid, "aggregation_recharge_user_id") - if aggregationRechargeApiKey == "" { - aggregationRechargeApiKeyMap := offical.SysCfgByKey("aggregation_recharge_api_key") - if aggregationRechargeApiKeyMap != nil { - aggregationRechargeApiKey = aggregationRechargeApiKeyMap.V - } - } - if aggregationRechargeUserId == "" { - aggregationRechargeUserIdMap := offical.SysCfgByKey("aggregation_recharge_user_id") - if aggregationRechargeUserIdMap != nil { - aggregationRechargeUserId = aggregationRechargeUserIdMap.V - } - } - param := map[string]string{ - "userid": aggregationRechargeUserId, - } - return param, aggregationRechargeApiKey -} diff --git a/consume/zhios_recharge_order_fail_dev.go b/consume/zhios_recharge_order_fail_dev.go deleted file mode 100644 index 594d488..0000000 --- a/consume/zhios_recharge_order_fail_dev.go +++ /dev/null @@ -1,154 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/db/model" - "applet/app/svc" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "code.fnuoos.com/go_rely_warehouse/zyos_go_pay.git/pay" - "code.fnuoos.com/go_rely_warehouse/zyos_go_third_party_api.git/recharge" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "github.com/tidwall/gjson" - "strings" - "time" -) - -func ZhiosRechargeOrderFailDev(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleZhiosRechargeOrderFailDev(res.Body) - //_ = res.Reject(false) - if err == nil { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleZhiosRechargeOrderFailDev(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.ZhiosRechargeOrderPay - fmt.Println(string(msg)) - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println(err.Error()) - return err - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err != nil { - return err - } - mid := canalMsg.Mid - eg := db.DBs[mid] - uid := utils.StrToInt(canalMsg.Uid) - oid := canalMsg.Oid - var orderData model.RechargeOrder - b, err2 := eg.Where("oid=? and uid=?", oid, uid).Get(&orderData) - if err2 != nil { - return errors.New("err") - } - if b == false { - return nil - } - if orderData.Status != "已付款" { - return nil - } - //查询官方接口看看有没有订单 - param, aggregationRechargeApiKey := CommAggregation(eg, mid) - param["out_trade_nums"] = oid - aggregationRechargeApiUrl := GetApiUrl() - order, err := recharge.GetOrder(aggregationRechargeApiUrl, aggregationRechargeApiKey, param) - utils.FilePutContents(mid+"rech", utils.SerializeStr(param)) - utils.FilePutContents(mid+"rech", aggregationRechargeApiKey) - utils.FilePutContents(mid+"rech", utils.SerializeStr(order)) - if err != nil { - utils.FilePutContents(mid+"rech", err.Error()) - return errors.New("err") - } - if gjson.Get(order, "errno").Int() == 0 && strings.Contains(order, oid) == false { - utils.FilePutContents(mid+"rech", utils.SerializeStr(orderData)) - NSFNTheSameBack := true - if orderData.PayMethod == 3 { - wechatP12ApiclientCert := db.SysCfgGetWithDb(eg, mid, "wechat_p12_apiclient_cert") - wechatPayRefundType := db.SysCfgGetWithDb(eg, mid, "wechat_pay_refund_type") - NSFNTheSameBack = false - if wechatP12ApiclientCert == "" || orderData.TradeNo == "" || wechatPayRefundType != "1" || orderData.AppId == "" { - NSFNTheSameBack = true - } else { - params := map[string]string{ - "subject": "聚合充值" + orderData.Title + "退款", - "total_fee": wxMoneyMulHundred(orderData.Amount), - "amount": wxMoneyMulHundred(orderData.Amount), - "out_refund_no": orderData.Oid, - "p12_str": canalMsg.WxappletFilepathUrl + "/" + wechatP12ApiclientCert, - "transaction_id": orderData.TradeNo, - "pay_wx_mch_id": db.SysCfgGetWithDb(eg, mid, "pay_wx_mch_id"), - "pay_wx_api_key": db.SysCfgGetWithDb(eg, mid, "pay_wx_api_key"), - "uid": utils.IntToStr(orderData.Uid), - "notify_url": canalMsg.DomainUrl + "/api/v1/refund/callback/" + mid, - } - //params["p12_str"] = "D:\\Downloads\\WXCertUtil\\cert\\1534243971_20230825_cert\\" + wechatP12ApiclientCert - //params["notify_url"] = strings.ReplaceAll(params["notify_url"], "http:", "https:") - params["pay_wx_appid"] = orderData.AppId - r, r1, err := pay.WxAppRefund(params) - utils.FilePutContents("mall_refund", utils.SerializeStr(params)) - utils.FilePutContents("mall_refund", utils.SerializeStr(r)) - utils.FilePutContents("mall_refund", utils.SerializeStr(r1)) - if err != nil { - utils.FilePutContents("mall_refund", err.Error()) - return err - } - if r.ReturnCode != "SUCCESS" { - return errors.New(r.ReturnMsg) - } - } - } - // 更改为已支付 - orderData.Status = "已退款" - orderData.RefundTime = time.Now() - // 保存ord - row, err := eg.ID(orderData.Id).Cols("status,pay_method,refund_time").Update(&orderData) - if row > 0 && err == nil { - if NSFNTheSameBack { - svc.UpdateUserFinValidAndInterFlow(eg, - orderData.Amount, "聚合充值"+orderData.Title+"退款", "aggregation_recharge", 0, 24, orderData.Uid, orderData.Id, int64(orderData.Id), utils.StrToInt64(orderData.Oid)) - } - } else { - return errors.New("err") - } - rechargeNotPayMoney := db.SysCfgGetWithDb(eg, mid, "recharge_not_pay_money") - if rechargeNotPayMoney != "1" { - ZyRechargeMoneyDeal(mid, orderData.Oid, orderData.Uid, utils.StrToFloat64(orderData.ZyAmount), 0, orderData.Title+"退款", "refund") - } - } - return nil -} diff --git a/consume/zhios_supplier_after_order.go b/consume/zhios_supplier_after_order.go deleted file mode 100644 index ca40cd3..0000000 --- a/consume/zhios_supplier_after_order.go +++ /dev/null @@ -1,214 +0,0 @@ -package consume - -import ( - "applet/app/cfg" - "applet/app/db" - "applet/app/db/model" - "applet/app/e" - md2 "applet/app/md" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "code.fnuoos.com/go_rely_warehouse/zyos_go_pay.git/pay" - "encoding/json" - "errors" - "fmt" - "github.com/iGoogle-ink/gopay/alipay" - "github.com/streadway/amqp" - "xorm.io/xorm" -) - -func ZhiosSupplierAfterOrder(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleZhiosSupplierAfterOrder(res.Body) - //_ = res.Reject(false) - if err == nil { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleZhiosSupplierAfterOrder(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.ZhiosAppreciation - fmt.Println(string(msg)) - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println("===with", err.Error()) - return err - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err != nil { - fmt.Println("===with", err.Error()) - return err - } - mid := canalMsg.Mid - eg := db.DBs[mid] - if eg == nil { - return nil - } - var afterOrder model.MallOrdAfterSale - get, err := eg.Where("ord_id=?", canalMsg.Oid).Get(&afterOrder) - if get == false || err != nil { - return nil - } - - if afterOrder.IsRefund == 0 && afterOrder.State == 4 { - var order model.MallOrd - get, err = eg.Where("ord_id = ?", canalMsg.Oid).Get(&order) - if get == false || err != nil { - return nil - } - if utils.StrToFloat64(afterOrder.ActualRefundAmount) == 0 { - afterOrder.ActualRefundAmount = afterOrder.ApplyRefundMoney - } - wechatP12ApiclientCert := db.SysCfgGetWithDb(eg, canalMsg.Mid, "wechat_p12_apiclient_cert") - wechatPayRefundType := db.SysCfgGetWithDb(eg, canalMsg.Mid, "wechat_pay_refund_type") - alipayPayRefundType := db.SysCfgGetWithDb(eg, canalMsg.Mid, "alipay_pay_refund_type") - switch order.PayChannel { - case 2: // 支付宝支付 - if order.TransactionId != "" && alipayPayRefundType == "1" { - var param = &md2.AliPayPayParams1{} - config, _ := CommMasterConfig(eg, canalMsg.Mid, param) - config["trade_no"] = order.TransactionId - config["refund_amount"] = afterOrder.ActualRefundAmount - config["refund_reason"] = "自营退货" - config["out_request_no"] = utils.OrderUUID(order.Uid) - refund, err := pay.AlipayTradeRefund(config) - utils.FilePutContents("mall_refund", utils.SerializeStr(config)) - utils.FilePutContents("mall_refund", utils.SerializeStr(refund)) - if err != nil { - utils.FilePutContents("mall_refund", err.Error()) - order.ErrMsg = err.Error() - eg.Where("ord_id=?", order.OrdId).Cols("err_msg").Update(&order) - return nil - } - if refund.AlipayTradeRefundResponse.Code != "10000" { - order.ErrMsg = utils.SerializeStr(refund) - eg.Where("ord_id=?", order.OrdId).Cols("err_msg").Update(&order) - return nil - } - if refund.AlipayTradeRefundResponse.FundChange != "Y" { - order.ErrMsg = utils.SerializeStr(refund) - eg.Where("ord_id=?", order.OrdId).Cols("err_msg").Update(&order) - return nil - } - fmt.Println(refund) - fmt.Println(err) - order.MoneyInAccount = 1 - afterOrder.IsRefund = 1 - } - case 3: // 微信支付 - if wechatP12ApiclientCert == "" || order.TransactionId == "" || wechatPayRefundType != "1" || order.AppId == "" { - } else { - - params := map[string]string{ - "subject": "自营商城退款", - "total_fee": wxMoneyMulHundred(afterOrder.ActualRefundAmount), - "amount": wxMoneyMulHundred(afterOrder.ActualRefundAmount), - "out_refund_no": utils.Int64ToStr(afterOrder.OrdId), - "p12_str": cfg.WxappletFilepath.URL + "/" + wechatP12ApiclientCert, - "transaction_id": order.TransactionId, - "pay_wx_mch_id": db.SysCfgGetWithDb(eg, canalMsg.Mid, "pay_wx_mch_id"), - "pay_wx_api_key": db.SysCfgGetWithDb(eg, canalMsg.Mid, "pay_wx_api_key"), - "uid": utils.IntToStr(order.Uid), - "notify_url": "http://api.zhiyingos.com/api/v1/mall/refund/callback/" + canalMsg.Mid, - } - //params["p12_str"] = "D:\\Downloads\\WXCertUtil\\cert\\1534243971_20230825_cert\\" + wechatP12ApiclientCert - //params["notify_url"] = strings.ReplaceAll(params["notify_url"], "http:", "https:") - params["pay_wx_appid"] = order.AppId - r, r1, err := pay.WxAppRefund(params) - utils.FilePutContents("mall_refund", utils.SerializeStr(params)) - utils.FilePutContents("mall_refund", utils.SerializeStr(r)) - utils.FilePutContents("mall_refund", utils.SerializeStr(r1)) - if err != nil { - utils.FilePutContents("mall_refund", err.Error()) - order.ErrMsg = err.Error() - eg.Where("ord_id=?", order.OrdId).Cols("err_msg").Update(&order) - return nil - } - if r.ReturnCode != "SUCCESS" { - order.ErrMsg = utils.SerializeStr(r) - eg.Where("ord_id=?", order.OrdId).Cols("err_msg").Update(&order) - return nil - } - order.MoneyInAccount = 1 - afterOrder.IsRefund = 1 - } - default: - } - eg.Where("id=?", afterOrder.Id).Cols("is_refund").Update(&afterOrder) - eg.Where("ord_id=?", order.OrdId).Cols("money_in_account").Update(&order) - } - - return nil -} -func CommMasterConfig(eg *xorm.Engine, dbName string, p *md2.AliPayPayParams1) (map[string]string, error) { - //获取支付配置 - req := map[string]string{ - "pay_ali_use_type": db.SysCfgGetWithDb(eg, dbName, "pay_ali_use_type"), - "private_key": db.SysCfgGetWithDb(eg, dbName, "pay_ali_private_key"), - "app_id": db.SysCfgGetWithDb(eg, dbName, "pay_ali_app_id"), - "rsa": db.SysCfgGetWithDb(eg, dbName, "pay_ali_key_len_type"), - "pkcs": db.SysCfgGetWithDb(eg, dbName, "pay_ali_key_format_type"), - } - if req["pay_ali_use_type"] == "1" { - req["private_key"] = db.SysCfgGetWithDb(eg, dbName, "pay_ali_new_private_key") - req["app_id"] = db.SysCfgGetWithDb(eg, dbName, "pay_ali_new_app_id") - appCertSN, err := alipay.GetCertSN(cfg.WxappletFilepath.URL + "/" + db.SysCfgGetWithDb(eg, dbName, "pay_app_cert_sn")) - if err != nil { - fmt.Println(err) - return nil, err - } - if appCertSN == "" { - fmt.Println(err) - return nil, err - } - req["pay_app_cert_sn"] = appCertSN - aliPayPublicCertSN, err := alipay.GetCertSN(cfg.WxappletFilepath.URL + "/" + db.SysCfgGetWithDb(eg, dbName, "pay_alipayrsa_public_key")) - if err != nil { - fmt.Println(err) - return nil, err - } - if aliPayPublicCertSN == "" { - fmt.Println(err) - return nil, err - } - req["pay_alipayrsa_public_key"] = aliPayPublicCertSN - } - if req["private_key"] == "" || req["app_id"] == "" { - return req, e.NewErr(400, "请在后台正确配置支付宝") - } - req["ord_id"] = p.OrdId - req["amount"] = p.Amount - req["subject"] = p.Subject - req["order_type"] = p.OrderType - - return req, nil -} diff --git a/consume/zhios_task_total.go b/consume/zhios_task_total.go deleted file mode 100644 index ac714e8..0000000 --- a/consume/zhios_task_total.go +++ /dev/null @@ -1,102 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "time" -) - -func ZhiosTaskTotal(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1000) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleZhiosTaskTotal(res.Body) - //_ = res.Reject(false) - if err == nil { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleZhiosTaskTotal(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.ZhiosAcquisition - fmt.Println(string(msg)) - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println(err.Error()) - return err - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err != nil { - return err - } - mid := canalMsg.Mid - eg := db.DBs[mid] - if eg == nil { - return nil - } - sess := eg.NewSession() - defer sess.Close() - sess.Begin() - - list := db.GetTaskCenterRewardList(sess, canalMsg.Id) - if list == nil { - sess.Rollback() - return nil - } - if list.IsSend == 1 { - sess.Rollback() - return nil - } - var tmp = make(map[string]string) - json.Unmarshal([]byte(list.Reward), &tmp) - for k, v := range tmp { - if utils.StrToFloat64(v) == 0 { - continue - } - err := db.GetTaskTotal(sess, utils.IntToStr(list.Uid), time.Unix(int64(list.CreateTime), 0).Format("20060102"), time.Unix(int64(list.CreateTime), 0).Format("200601"), k, list.Type, list.TaskType, list.Title, v) - if err != nil { - sess.Rollback() - return err - } - } - list.IsSend = 1 - update, err := sess.Where("id=?", list.Id).Cols("is_send").Update(list) - if update == 0 || err != nil { - sess.Rollback() - return errors.New("失败") - } - sess.Commit() - return nil -} diff --git a/consume/zhios_tikTok_goods_update.go b/consume/zhios_tikTok_goods_update.go deleted file mode 100644 index 6e65899..0000000 --- a/consume/zhios_tikTok_goods_update.go +++ /dev/null @@ -1,160 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/db/model" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "time" -) - -func ZhiosTikTokUpdate(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, true) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleZhiosTikTokGoodsUpdate(res.Body) - //_ = res.Reject(false) - //if err == nil { - //_ = res.Ack(true) - //} - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} -func ZhiosTikTokAllUpdate(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, true) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleZhiosTikTokGoodsUpdate(res.Body) - //_ = res.Reject(false) - //if err == nil { - //_ = res.Ack(true) - //} - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleZhiosTikTokGoodsUpdate(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.TikTokExChangeRoutKeyForUpdateParam - fmt.Println(string(msg)) - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println(err.Error()) - return err - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err != nil { - return err - } - mid := canalMsg.Mid - eg := db.DBs[mid] - var v md.TikTokData - json.Unmarshal([]byte(canalMsg.Data), &v) - var tmp model.TikTokTeamGoods - //cache.HSet("tik_"+canalMsg.Mid, canalMsg.Cid+"_"+v.GoodsID, string(msg)) - get, _ := eg.Where("gid=? and activity_id=?", v.GoodsID, canalMsg.Cid).Get(&tmp) - if get { - //if tmp.IsDown == 1 { - // continue - //} - tmp.IsDown = 0 - tmp.ServiceRatio = v.ServiceRatio - tmp.Price = v.Price - tmp.TalentCommission = v.PublicCommission - tmp.PublicCommission = v.PublicCommission - tmp.Title = v.GoodsTitle - tmp.CostPrice = v.CostPrice - tmp.Commission = v.Commission - tmp.GoodsImg = v.GoodsImg - tmp.DetailUrl = v.DetailURL - tmp.EndType = "已采集" - tmp.LmType = "" - tmp.Sales = utils.StrToInt(v.GoodsSales) - tmp.ActivityId = utils.StrToInt(canalMsg.Cid) - tmp.ActivityStartTime = utils.TimeParseStd(v.ActivityStartTime + " 00:00:00") - tmp.ActivityEndTime = utils.TimeParseStd(v.ActivityEndTime + " 23:59:59") - tmp.OldActivityEndTime = utils.TimeParseStd(v.ActivityEndTime + " 23:59:59") - tmp.UpdateTime = time.Now() - tmp.Status = utils.StrToInt(canalMsg.Status) - if tmp.Status == 3 || tmp.Status == 6 { - tmp.ActivityEndTime = time.Now() - } - eg.Where("id=?", tmp.Id).AllCols().Update(&tmp) - } else { - if utils.InArr(canalMsg.Status, []string{"3", "6"}) { - return nil - } - tmp = model.TikTokTeamGoods{ - Cid: utils.StrToInt(v.Cid), - ServiceRatio: v.ServiceRatio, - Title: v.GoodsTitle, - Price: v.Price, - CostPrice: v.CostPrice, - Commission: v.Commission, - TalentCommission: v.PublicCommission, - PublicCommission: v.PublicCommission, - Gid: v.GoodsID, - Sales: utils.StrToInt(v.GoodsSales), - GoodsImg: v.GoodsImg, - DetailUrl: v.DetailURL, - ShopName: v.ShopName, - ActivityStartTime: utils.TimeParseStd(v.ActivityStartTime + " 00:00:00"), - ActivityEndTime: utils.TimeParseStd(v.ActivityEndTime + " 23:59:59"), - OldActivityEndTime: utils.TimeParseStd(v.ActivityEndTime + " 23:59:59"), - ActivityId: utils.StrToInt(canalMsg.Cid), - UpdateTime: time.Now(), - EndType: "已采集", - IsDown: 0, - } - eg.InsertOne(&tmp) - } - return nil -} diff --git a/consume/zhios_user_relate.go b/consume/zhios_user_relate.go deleted file mode 100644 index a67d13b..0000000 --- a/consume/zhios_user_relate.go +++ /dev/null @@ -1,160 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/db/model" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "strings" - "time" - "xorm.io/xorm" -) - -func ZhiosUserRelate(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleZhiosUserRelate(res.Body) - //_ = res.Reject(false) - if err != nil { - _ = res.Reject(false) - //TODO::重新推回队列末尾,避免造成队列堵塞 - var msg *md.ZhiosOrderBuckle - var tmpString string - err := json.Unmarshal(res.Body, &tmpString) - if err != nil { - return - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &msg) - if err != nil { - return - } - ch.Publish(queue.ExchangeName, utils.SerializeStr(msg), queue.RoutKey) - } else { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleZhiosUserRelate(msg []byte) error { - time.Sleep(time.Microsecond * 20) // 等待500毫秒 - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.ZhiosOrderBuckle - fmt.Println(string(msg)) - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println("===with", err.Error()) - return err - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err != nil { - fmt.Println("===with", err.Error()) - return err - } - mid := canalMsg.Mid - eg := db.DBs[mid] - if eg == nil { - return nil - } - profile, err := db.UserProfileFindByID(eg, canalMsg.Uid) - if err != nil || profile == nil { - - return nil - } - if profile.ParentUid > 0 { - ur := new(model.UserRelate) - //如果有上级要加入关系链 - initLV := 1 - ur.ParentUid = profile.ParentUid - ur.Uid = profile.Uid - ur.Level = initLV - ur.InviteTime = time.Now() - _, err = db.UserRelateInsert(eg, ur) - - if err != nil && strings.Contains(err.Error(), "Duplicate") == false { - return err - } - // 插入多级关联 - RoutineMultiRelate1(eg, ur.ParentUid, ur.Uid, initLV) - - } - return nil -} - -//RoutineMultiRelate is 多级关联 -func RoutineMultiRelate1(eg *xorm.Engine, pid int, uid int, lv int) { - - for { - if pid == 0 { - break - } - m, err := db.UserProfileFindByID(eg, pid) - if err != nil { - logx.Warn(err) - break - } - if m != nil { - if m.ParentUid == 0 { - break - } - lv++ - ur := new(model.UserRelate) - ur.ParentUid = m.ParentUid - ur.Uid = uid - ur.Level = lv - ur.InviteTime = time.Now() - _, err := db.UserRelateInsert(eg, ur) - if err != nil && strings.Contains(err.Error(), "Duplicate") == false { - logx.Warn(err) - break - } - if err != nil && strings.Contains(err.Error(), "Duplicate") { - tmp, _, _ := db.UserRelateByUIDAndPUID(eg, ur.Uid, ur.ParentUid) - if tmp != nil && tmp.Level != ur.Level { - db.UserRelateUpdate(eg, ur) - } - } - // 还要关联当前的用户的所有下级,注意关联等级 - //go RoutineInsertUserRelate(c, m.ParentUid, uid, lv) - // 下级关联上上级 - // 继续查询 - logx.Info(fmt.Sprintf("关联pid(%v) -> uid(%v),lv:%v", ur.ParentUid, ur.Uid, lv)) - logx.Info("继续查询") - pid = m.ParentUid - } - if m == nil { - logx.Info("查询结束,退出") - break - } - } -} diff --git a/consume/zhios_user_up_lv.go b/consume/zhios_user_up_lv.go deleted file mode 100644 index 5ac4441..0000000 --- a/consume/zhios_user_up_lv.go +++ /dev/null @@ -1,86 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" -) - -//自动升级 -func ZhiosUserUpLv(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1000) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleUserUpLv(res.Body) - //_ = res.Reject(false) - fmt.Println(err) - _ = res.Ack(true) - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleUserUpLv(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.ZhiosAcquisition - fmt.Println(string(msg)) - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println(err.Error()) - return err - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err != nil { - return err - } - mid := canalMsg.Mid - eg := db.DBs[mid] - if eg == nil { - return nil - } - uid := canalMsg.Uid - levelList, _ := db.UserLevlEgAll(eg) - isAuto := 0 - for _, v := range levelList { - if v.AutoUpdate == 1 { - isAuto = 1 - } - } - if isAuto == 0 { - return nil - } - FindUser(eg, uid, mid, levelList) - oneUser, _ := db.UserProfileFindByID(eg, uid) - if oneUser == nil || (oneUser != nil && oneUser.ParentUid == 0) { - return nil - } - FindUser(eg, utils.IntToStr(oneUser.ParentUid), mid, levelList) - return nil -} diff --git a/consume/zhios_user_visit_ip_address_consume.go b/consume/zhios_user_visit_ip_address_consume.go deleted file mode 100644 index dadbdd6..0000000 --- a/consume/zhios_user_visit_ip_address_consume.go +++ /dev/null @@ -1,172 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/db/model" - "applet/app/utils" - "applet/app/utils/cache" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/cc14514/go-geoip2" - geoip2db "github.com/cc14514/go-geoip2-db" - "github.com/streadway/amqp" - "net" - "strings" - "time" -) - -var data []*model.MasterAreaVisitsFlows - -func ZhiOsUserVisitIpAddressConsume(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>ZhiOsUserVisitIpAddressConsume<<<<<<<<<<<<<<<<<<<<<<<") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - geoIp2db, _ := geoip2db.NewGeoipDbByStatik() - defer geoIp2db.Close() - - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(100) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") - err = handleUserVisitIpAddress(res.Body, geoIp2db) - //_ = res.Reject(false) - _ = res.Ack(true) - if len(data) >= 100 { - db.BatchAddMasterAreaVisitsFlows(db.DataDb, data) - data = []*model.MasterAreaVisitsFlows{} - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleUserVisitIpAddress(msg []byte, geoIp2db *geoip2.DBReader) error { - now := time.Now() - today := now.Format("2006-01-02") - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println(err.Error()) - return err - } - var msgStruct md.ZhiOsUserVisitIpAddressMessage - err = json.Unmarshal([]byte(tmpString), &msgStruct) - if err != nil { - fmt.Println(err.Error()) - return err - } - - if msgStruct.MasterId == "" { - cacheKeyForUrl := fmt.Sprintf(md.ZhiOsMasterIdForUrlHashMapCacheKey) - get, _ := cache.HGetString(cacheKeyForUrl, msgStruct.Url) - if get == "" { - msgStruct.MasterId = GetWebSiteDomainMasterId(msgStruct.Url) - utils.FilePutContents("GetWebSiteDomainMasterId", utils.SerializeStr(msgStruct)) - cache.HSet(cacheKeyForUrl, msgStruct.Url, msgStruct.MasterId) - cache.Expire(cacheKeyForUrl, md.ZhiOsUserVisitIpAddressHashMapCacheTime) - } else { - msgStruct.MasterId = get - } - } - - //1、判断ip是否已统计 - //cacheKey := fmt.Sprintf(md.ZhiOsUserVisitIpAddressHashMapCacheKey, msgStruct.MasterId, today) - //get, _ := cache.HGetString(cacheKey, msgStruct.Ip) - //if get == "" { - if true { - //2、分析ip归属地 - countryName, provinceId, cityId, provinceName, cityName := getIpAddress(geoIp2db, msgStruct) - if provinceId != "" || cityId != "" || countryName != "" || provinceName != "" || cityName != "" { - //3、插入`master_area_visits_flows` 表 - if provinceName == "" { - provinceName = msgStruct.Province - } - if cityName == "" { - cityName = msgStruct.City - } - - data = append(data, &model.MasterAreaVisitsFlows{ - Ip: msgStruct.Ip, - MasterId: utils.StrToInt(msgStruct.MasterId), - Date: today, - CountryName: countryName, - ProvinceName: provinceName, - ProvinceId: provinceId, - CityName: cityName, - CityId: cityId, - Pvd: msgStruct.Pvd, - CreateAt: now, - UpdateAt: now, - }) - //db.MasterAreaVisitsFlowsInsert(db.DataDb, ) - } - //4、加入到缓存map中 - //cache.HSet(cacheKey, msgStruct.Ip, msgStruct.MasterId) - //cache.Expire(cacheKey, md.ZhiOsUserVisitIpAddressHashMapCacheTime) - } - return nil -} - -func getIpAddress(geoIp2db *geoip2.DBReader, message md.ZhiOsUserVisitIpAddressMessage) (countryName, provinceId, cityId, provinceName, cityName string) { - record, _ := geoIp2db.City(net.ParseIP(message.Ip)) - if record.Country.Names != nil && record.Subdivisions != nil && record.City.Names != nil { - message.Country = record.Country.Names["zh-CN"] - message.Province = record.Subdivisions[0].Names["zh-CN"] - message.City = record.City.Names["zh-CN"] - } - - countryName = message.Country - if countryName == "中国" && message.Province != "" { - if message.Province == "闽" { - message.Province = "福建" - } - province, err := db.ProvinceGetOneByName(message.Province) - if err != nil { - return "", "", "", "", "" - } - provinceId = province.Id - provinceName = province.Name - - if message.City != "" { - city, err := db.CityGetOneByName(message.City) - if err != nil { - return "", "", "", "", "" - } - cityId = city.Id - cityName = city.Name - } - } - return -} - -// 获取指定类型的域名对应的masterId:admin、wap、api -func GetWebSiteDomainMasterId(host string) string { - obj := new(model.UserAppDomain) - has, err := db.Db.Where("domain=?", host).Get(obj) - if err != nil || !has { - hostList := strings.Split(host, ":") - has, err = db.Db.Where("domain=?", hostList[0]).Get(obj) - if err != nil || !has { - return "" - } - } - return utils.AnyToString(obj.Uuid) -} diff --git a/consume/zhios_valid_user.go b/consume/zhios_valid_user.go deleted file mode 100644 index 2bd5b54..0000000 --- a/consume/zhios_valid_user.go +++ /dev/null @@ -1,187 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/db/model" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "xorm.io/xorm" -) - -func ZhiosValidUser(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(300) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>ZhiosAcquisitionCondition<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleValidUser(res.Body) - //_ = res.Reject(false) - fmt.Println(err) - _ = res.Ack(true) - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} -func handleValidUser(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.ZhiosAcquisition - fmt.Println(string(msg)) - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println(err.Error()) - return err - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err != nil { - return err - } - mid := canalMsg.Mid - eg := db.DBs[mid] - if eg == nil { - return nil - } - if canalMsg.Uid == "" { - return nil - } - RoutineUpdateUserComm(eg, mid, canalMsg.Uid) - return nil -} -func RoutineUpdateUserComm(eg *xorm.Engine, dbName, uid string) { - if utils.StrToInt(uid) == 0 { - return - } - user, _ := db.UserFindByID(eg, uid) - if user == nil { - return - } - userProfile, _ := db.UserProfileFindByID(eg, uid) - if userProfile == nil { - return - } - if userProfile.IsVerify == 1 { - return - } - validConditionMap := map[string]interface{}{} - checkMap := map[string]interface{}{} - todone := 0 - //有效会员 校验 - vdata := db.SysCfgGetWithDb(eg, dbName, "valid_member_condition") - if err := json.Unmarshal([]byte(vdata), &validConditionMap); err != nil { - return - logx.Warn(err) - } - for k, v := range validConditionMap { - if v != "" && utils.AnyToFloat64(v) > 0 { - todone++ - checkMap[k] = v - } - } - - for k, v := range checkMap { - switch k { - case "taskVideo": - sum, _ := eg.Where("uid=? and task_type=? and task_id>0", user.Uid, 3).Sum(&model.TaskVideoNum{}, "count") - if sum >= utils.AnyToFloat64(v) { - todone-- - } - case "realCheck": - // 检查实名认证 - one, _ := db.GetRealNameAuthByUidWithState(eg, user.Uid, 1) - if one != nil && one.Uid == user.Uid { - todone-- - } - case "bindPhone": - // 检查绑定手机号 - if user.Phone != "" { - todone-- - } - case "goodsCommission": - sqlTpl := `SELECT cast(SUM(LEFT(olr.amount,LENGTH(olr.amount)-2)) as decimal(50,4)) AS amount -FROM ord_list_relate olr - LEFT JOIN ord_list ol ON olr.oid = ol.ord_id - LEFT JOIN privilege_card_ord pco ON olr.oid =pco.ord_id - LEFT JOIN duoyou_ord_list dol ON olr.oid =dol.oid - LEFT JOIN recharge_order ro ON olr.oid =ro.oid - LEFT JOIN playlet_sale_order pso ON olr.oid =pso.custom_oid -WHERE olr.uid = ? AND (ol.state<>4 or pco.state=1 or dol.id>0 or ro.status<>'已退款' or pso.status<>'订单退款'); -` - todayResult, err := db.QueryNativeString(eg, sqlTpl, uid) - today := "0" - if err == nil { - today = todayResult[0]["amount"] - } - // 累计佣金 - if utils.StrToFloat64(today) >= utils.AnyToFloat64(v) { - todone-- - } - case "orderPay": - // 付款订单满足v元 - ms, err := db.OrderListByUIDByPaidPrice(eg, user.Uid, v, []string{"0", "1", "2", "3", "5"}) - if err != nil { - logx.Warn(err) - } - mss := *ms - if len(mss) > 0 { - todone-- - } - case "receive": - // 已收货 - ms, err := db.OrderListByUIDByState(eg, user.Uid, []string{"1", "2", "3", "5"}) - if err != nil { - logx.Warn(err) - } - mss := *ms - if len(mss) > 0 { - todone-- - } - case "tbAuth": - // 是否淘宝授权 - if userProfile.AccTaobaoAuthTime != 0 { - todone-- - } - case "withdraw": - // 提现 - sum, err := db.UserWithDrawApplySumByState(eg, user.Uid, "1", "2") - if err != nil { - logx.Warn(err) - } - if sum > 0 { - todone-- - } - } - } - // 满足条件则将改用户打为有效用户 - if todone == 0 { - userProfile.IsVerify = 1 - } - _, err := db.UserProfileUpdate(eg, userProfile.Uid, userProfile) - if err != nil { - logx.Warn(err) - } - return -} diff --git a/consume/zhios_withdraw_reward.go b/consume/zhios_withdraw_reward.go deleted file mode 100644 index 7eac75a..0000000 --- a/consume/zhios_withdraw_reward.go +++ /dev/null @@ -1,144 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/db/model" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "code.fnuoos.com/go_rely_warehouse/zyos_go_order_relate_rule.git/rule" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" - "github.com/tidwall/gjson" - "time" - "xorm.io/xorm" -) - -func ZhiosWithdrawReward(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(20) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleZhiosWithdrawReward(res.Body) - //_ = res.Reject(false) - if err == nil { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleZhiosWithdrawReward(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.ZhiosWithdraw - fmt.Println(string(msg)) - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println("===with", err.Error()) - return err - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err != nil { - fmt.Println("===with", err.Error()) - return err - } - mid := canalMsg.Mid - eg := db.DBs[mid] - if eg == nil { - return nil - } - //判断用户是什么等级 - var apply model.FinWithdrawApply - get, err := eg.Where("id=?", canalMsg.Id).Get(&apply) - if get == false || err != nil { - return nil - } - if apply.Uid == 0 { - return nil - } - // - withdrawSetting := db.SysCfgGetWithDb(eg, mid, "withdraw_setting") - withdrawFirstBili := gjson.Get(withdrawSetting, "withdrawFirstBili").String() - publicWithdrawTeamBili := db.SysCfgGetWithDb(eg, mid, "public_withdraw_team_bili") - publicWithdrawTeamCount := db.SysCfgGetWithDb(eg, mid, "public_withdraw_team_count") - if utils.StrToFloat64(withdrawFirstBili) > 0 { - level := 0 - all, _ := db.UserLevlEgAll(eg) - for k, v := range all { - if k == 0 { - level = v.Id - } - } - //分给粉丝 - levelUser := db.UserFindByLevel(eg, level) - if len(levelUser) == 0 { - return nil - } - ids := make([]int64, 0) - for _, v := range levelUser { - ids = append(ids, int64(v.Uid)) - } - money := utils.FloatFormat(utils.StrToFloat64(apply.Amount)*(utils.StrToFloat64(withdrawFirstBili)/100)/float64(len(levelUser)), 6) - comm(eg, canalMsg.Id, ids, money, "全网提现分红", "withdraw_reward", "92") - } - if utils.StrToFloat64(publicWithdrawTeamBili) > 0 && utils.StrToFloat64(publicWithdrawTeamCount) > 0 { - //分给粉丝 - user, _ := rule.FindRandUser(eg, utils.StrToInt(publicWithdrawTeamCount)) - fmt.Println("=zhe", utils.SerializeStr(user)) - money := utils.FloatFormat(utils.StrToFloat64(apply.Amount)*(utils.StrToFloat64(publicWithdrawTeamBili)/100)/float64(len(user)), 6) - comm(eg, canalMsg.Id, user, money, "公排团队提现分红", "withdraw_team_reward", "93") - } - return nil -} -func comm(eg *xorm.Engine, id string, levelUser []int64, money float64, title, types, ordAction string) { - for _, v := range levelUser { - profile, err := db.UserProfileFindByID(eg, v) - if err != nil || profile == nil { - continue - } - oldAmount := profile.FinValid - profile.FinValid = utils.Float64ToStrByPrec(utils.StrToFloat64(profile.FinValid)+money, 6) - eg.Where("uid=?", profile.Uid).Update(profile) - var flow = model.FinUserFlow{ - Uid: int(v), - Type: 0, - Amount: utils.Float64ToStrByPrec(money, 6), - BeforeAmount: oldAmount, - AfterAmount: profile.FinValid, - OrdType: types, - OrdId: id, - OrdTitle: title, - OrdAction: utils.StrToInt(ordAction), - OrdTime: int(time.Now().Unix()), - State: 2, - CreateAt: time.Now(), - UpdateAt: time.Now(), - } - eg.Insert(&flow) - } - -} diff --git a/consume/zhios_youmishang_exchange_store.go b/consume/zhios_youmishang_exchange_store.go deleted file mode 100644 index 4c97a31..0000000 --- a/consume/zhios_youmishang_exchange_store.go +++ /dev/null @@ -1,75 +0,0 @@ -package consume - -import ( - "applet/app/db" - "applet/app/utils" - "applet/app/utils/logx" - "applet/consume/md" - "code.fnuoos.com/go_rely_warehouse/zyos_go_mq.git/rabbit" - "encoding/json" - "errors" - "fmt" - "github.com/streadway/amqp" -) - -func YoumishangExchangeStore(queue md.MqQueue) { - fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>") - ch, err := rabbit.Cfg.Pool.GetChannel() - if err != nil { - logx.Error(err) - return - } - defer ch.Release() - //1、将自己绑定到交换机上 - ch.Bind(queue.Name, queue.ExchangeName, queue.RoutKey) - //2、取出数据进行消费 - ch.Qos(1) - delivery := ch.Consume(queue.Name, false) - - var res amqp.Delivery - var ok bool - for { - res, ok = <-delivery - if ok == true { - //fmt.Println(string(res.Body)) - fmt.Println(">>>>>>>>>>>>>>>>CanalOrderConsume<<<<<<<<<<<<<<<<<<<<<<<<<") - err = handleYoumishangExchangeStore(res.Body) - //_ = res.Reject(false) - fmt.Println(err) - if err == nil { - _ = res.Ack(true) - } - } else { - panic(errors.New("error getting message")) - } - } - fmt.Println("get msg done") -} - -func handleYoumishangExchangeStore(msg []byte) error { - //1、解析canal采集至mq中queue的数据结构体 - var canalMsg *md.YouMiShangExchangeStoreStruct - fmt.Println(string(msg)) - var tmpString string - err := json.Unmarshal(msg, &tmpString) - if err != nil { - fmt.Println(err.Error()) - return err - } - fmt.Println(tmpString) - err = json.Unmarshal([]byte(tmpString), &canalMsg) - if err != nil { - return err - } - mid := canalMsg.MasterId - eg := db.DBs[mid] - uid := canalMsg.Uid - levelList, _ := db.UserLevlEgAll(eg) - FindUser(eg, utils.Int64ToStr(uid), mid, levelList) - oneUser, _ := db.UserProfileFindByID(eg, uid) - if oneUser == nil || (oneUser != nil && oneUser.ParentUid == 0) { - return nil - } - FindUser(eg, utils.IntToStr(oneUser.ParentUid), mid, levelList) - return nil -}