123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505 |
- package user_merchant
- import (
- "context"
- "gd_management/apis"
- "gd_management/errors"
- "gd_management/impl/order"
- "gd_management/impl/pubsub"
- "encoding/json"
- "fmt"
- "time"
- "gd_management/common.in/id"
- "gd_management/common.in/jsonrpc2"
- "gd_management/common.in/storage"
- "gd_management/common.in/utils"
- "github.com/astaxie/beego/orm"
- "go.uber.org/zap"
- )
- func ManagementSetMerchantDataApiQuota(ctx context.Context, req *apis.ManagementSetMerchantDataApiQuotaReq, reply *apis.ManagementSetMerchantDataApiQuotaReply) (err error) {
- task := func(o orm.Ormer) error {
- now := time.Now()
- nowString := now.Format("2006-01-02 15:04:05")
- nowSecond := now.Unix()
- mdaTab := apis.TGdMerchantDataApi{}
- if err := pubsub.PublishMerchantApiNotify(req.MerchantDataApiId, 0, 0, 0); err != nil {
- return err
- }
- err := o.QueryTable("t_gd_merchant_data_api").Filter("id", req.MerchantDataApiId).One(&mdaTab)
- if err != nil {
- if err == orm.ErrNoRows {
- return errors.DataBaseNoRecord
- }
- return errors.DataBaseError
- }
- //按次数
- state := 0
- if mdaTab.ComboType == 0 {
- if mdaTab.EndTime == 0 {
- mdaTab.ComboType = 1
- } else {
- mdaTab.ComboType = 2
- }
- }
- if mdaTab.ComboType == 1 {
- if req.Count < 0 {
- return errors.ArgsError
- }
- if req.Count == 0 {
- state = 1
- }
- sql := "update t_gd_merchant_data_api set count=?, state=?, update_time=? where id=?"
- _, err := o.Raw(sql, req.Count, state, nowString, req.MerchantDataApiId).Exec()
- if err != nil {
- l.Error("mysql",
- zap.String("sql", sql),
- zap.String("fields", fmt.Sprintf("id:%d", req.MerchantDataApiId)),
- zap.String("error", err.Error()))
- return errors.DataBaseError
- }
- return nil
- }
- if mdaTab.ComboType == 2 {
- if req.DayNumber < 0 || req.DayCount < 0 {
- return errors.ArgsError
- }
- if req.DayNumber == 0 {
- state = 1
- }
- var start_time int64
- var end_time int64
- err = o.Raw("select start_time,end_time from t_gd_merchant_data_api where id = ?", req.MerchantDataApiId).QueryRow(&start_time, &end_time)
- if err != nil {
- l.Error("mysql",
- zap.String("sql", "select start_time from t_gd_merchant_data_api where id = ?"),
- zap.String("fields", fmt.Sprintf("id:%d", req.MerchantDataApiId)),
- zap.String("error", err.Error()))
- return errors.DataBaseError
- }
- if end_time < nowSecond {
- start_time = nowSecond
- end_time = start_time + int64(req.DayNumber*24*3600)
- } else {
- end_time = nowSecond + int64(req.DayNumber*24*3600) - (nowSecond-start_time)%(3600*24)
- }
- sql := "update t_gd_merchant_data_api set count_per_day=?, state=?, start_time=?, end_time=?, update_time=? where id=?"
- _, err = o.Raw(sql, req.DayCount, state, start_time, end_time, nowString, req.MerchantDataApiId).Exec()
- if err != nil {
- l.Error("mysql",
- zap.String("sql", sql),
- zap.String("fields", fmt.Sprintf("id:%d", req.MerchantDataApiId)),
- zap.String("error", err.Error()))
- return errors.DataBaseError
- }
- }
- return nil
- }
- tasks := []storage.DbaTasker{}
- tasks = append(tasks, storage.GenerateDbaTask(task))
- storage.ExecTrans(tasks...)
- l.Debug(utils.MarshalJsonString(req, reply))
- return nil
- }
- func GetMerchantDataApiQuota(ctx context.Context, req *apis.GetMerchantDataApiQuotaReq, reply *apis.GetMerchantDataApiQuotaReply) error {
- if req.Id <= 0 {
- return errors.ArgsError
- }
- p := apis.TGdMerchantDataApi{}
- sql := "SELECT * FROM t_gd_merchant_data_api WHERE id = ?"
- err := orm.NewOrm().Raw(sql, req.Id).QueryRow(&p)
- if err != nil {
- l.Error("mysql",
- zap.String("sql", sql),
- zap.String("fields", fmt.Sprintf("id:%d", req.Id)),
- zap.String("error", err.Error()))
- return errors.DataBaseError
- }
- reply.MerchantId = p.MerchantId
- reply.QueryTypeId = p.QueryTypeId
- reply.Count = p.Count
- reply.CountPerDay = p.CountPerDay
- reply.StartTime = p.StartTime
- reply.EndTime = p.EndTime
- reply.ComboType = p.ComboType
- reply.State = p.State
- return nil
- }
- const (
- H5Order = "10"
- DataApiOrder = "20"
- )
- func generateDataApiOrderID(o orm.Ormer) (string, error) {
- count := 0
- for {
- count++
- dsId, err := id.GetDistributedUniqueID()
- if count > 5 {
- return "", errors.ApiOrderGenrateFail
- }
- if err != nil {
- continue
- }
- orderId := fmt.Sprintf("%s%d", DataApiOrder, dsId)
- exist := o.QueryTable("t_gd_data_api_order").Filter("order_no", orderId).Exist()
- if exist {
- continue
- } else {
- return orderId, nil
- }
- }
- }
- func getUsedCount(o orm.Ormer, merchantDataApiId int64) (int, error) {
- ret := 0
- sql := fmt.Sprintf("select count from t_gd_api_access_count where merchant_data_api_id=%d and create_time='0000-00-00'", merchantDataApiId)
- err := o.Raw(sql).QueryRow(&ret)
- if err != nil && err != orm.ErrNoRows {
- return 0, errors.DataBaseError
- }
- return ret, nil
- }
- func updateThreshold(req *apis.UpdateMerchantDataApiReq, p apis.TGdMerchantDataApi, o orm.Ormer) error {
- _, err := o.Raw("update t_gd_merchant_data_api set count_per_day=?, count_thresholds=?, day_thresholds=?, day_total_count=?, ip_whitelist=?, ip_whitelist_enable=?, count_thresholds_enable=?, update_time=? where id=?",
- req.TotalComboDayCount, req.CountThresholds, req.DayThresholds, req.DayTotalCount, req.IpWhitelist, req.IpWhitelistEnable, req.CountThresholdsEnable, time.Now().Format("2006-01-02 15:04:05"), req.MerchantDataApiId).Exec()
- if err != nil {
- return errors.DataBaseError
- }
- return nil
- }
- func getTargetComb(o orm.Ormer, comboId int64) (*apis.TGdDataApiCombo, error) {
- ret := apis.TGdDataApiCombo{}
- err := o.Raw("select * from t_gd_data_api_combo where id=?", comboId).QueryRow(&ret)
- if err != nil {
- if err != orm.ErrNoRows {
- return nil, errors.DataBaseError
- }
- return nil, errors.DataBaseNoRecord
- }
- return &ret, nil
- }
- func changeCombo(o orm.Ormer, req *apis.UpdateMerchantDataApiReq, target *apis.TGdDataApiCombo, p *apis.TGdMerchantDataApi) error {
- newOrderId, err := generateDataApiOrderID(o)
- if err != nil {
- return err
- }
- newOrder := apis.TGdDataApiOrder{}
- newOrder.Status = order.OrderComplete
- newOrder.OrderNo = newOrderId
- newOrder.ComboId = target.Id
- newOrder.BuyAccount = "GD后台管理员"
- newOrder.PayType = 1
- newOrder.Count = 1
- newOrder.MerchantId = p.MerchantId
- newOrder.QueryTypeId = p.QueryTypeId
- newOrder.GoodsPrice = target.Price
- newOrder.CreateTime = time.Now().Format("2006-01-02 15:04:05")
- if target.Type == 1 {
- if target.Count+req.Count < 0 {
- return errors.ArgsError
- }
- sql := fmt.Sprintf("update t_gd_merchant_data_api set combo_type=1, state=0, count_after_increase=0, used_before_increase=0, count_per_day=0, start_time=0, end_time=0, count=%d where id=%d", target.Count+req.Count, req.MerchantDataApiId)
- _, err := o.Raw(sql).Exec()
- if err != nil {
- return errors.DataBaseError
- }
- days := int((p.EndTime - p.StartTime) / (24 * 3600))
- newOrder.ComboDesc = fmt.Sprintf("%d次每天/%d天-%d次", p.CountPerDay, days, target.Count+req.Count)
- } else if target.Type == 2 {
- now := time.Now()
- if target.Count+req.DayCount < 0 ||
- target.TotalDay+req.DayNumber < 0 {
- return errors.ArgsError
- }
- start := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location()).Unix()
- end := start + int64((target.TotalDay+req.DayNumber)*24*3600)
- sql := fmt.Sprintf("update t_gd_merchant_data_api set combo_type=2, state = 0, count_after_increase=0, used_before_increase=0, count_per_day=%d, start_time=%d, end_time=%d, count=0 where id=%d", target.Count+req.DayCount, start, end, req.MerchantDataApiId)
- _, err := o.Raw(sql).Exec()
- if err != nil {
- return errors.DataBaseError
- }
- newOrder.ComboDesc = fmt.Sprintf("%d次-%d次每天/%d天", p.Count, target.Count+req.DayCount, target.TotalDay+req.DayNumber)
- } else {
- return errors.FreeQueryTypeCanNotSetQuota
- }
- _, err = o.Raw("delete from t_gd_api_access_count where merchant_data_api_id=?", req.MerchantDataApiId).Exec()
- if err != nil {
- return errors.DataBaseError
- }
- _, err = o.Insert(&newOrder)
- if err != nil {
- return errors.DataBaseError
- }
- return nil
- }
- // Update 修改商户数据API
- func Update(ctx context.Context, req *apis.UpdateMerchantDataApiReq, reply *apis.UpdateMerchantDataApiReply) (err error) {
- // 捕获各个task中的异常并返回给调用者
- defer func() {
- if r := recover(); r != nil {
- err = fmt.Errorf("%+v", r)
- e := &jsonrpc2.Error{}
- if er := json.Unmarshal([]byte(err.Error()), e); er != nil {
- l.Error("err",
- zap.String("system_err", err.Error()),
- zap.Stack("stacktrace"))
- }
- }
- }()
- // 参数检查
- if req.MerchantDataApiId <= 0 {
- l.Error("argument",
- zap.String("call", "check"),
- zap.String("fields", utils.MarshalJsonString(req)))
- return errors.ArgsError
- }
- var (
- p = apis.TGdMerchantDataApi{}
- )
- // 发布redis订阅
- redisPublishTask := func(db orm.Ormer) error {
- if err := pubsub.PublishMerchantApiNotify(req.MerchantDataApiId, 0, 0, 0); err != nil {
- return err
- }
- if err := pubsub.PublishApiExportInfoNotify(); err != nil {
- return err
- }
- return nil
- }
- // 查询数据api类型
- getDataApiInfoTask := func(db orm.Ormer) error {
- err := db.Raw("SELECT * FROM t_gd_merchant_data_api where id = ?", req.MerchantDataApiId).QueryRow(&p)
- if err != nil {
- l.Error("mysql",
- zap.String("sql", "SELECT * FROM t_gd_merchant_data_api where id = ?"),
- zap.String("fields", utils.MarshalJsonString(req.MerchantDataApiId)),
- zap.String("error", err.Error()))
- if err == orm.ErrNoRows {
- return errors.DataBaseNoRecord
- }
- return errors.DataBaseError
- }
- var is_free int
- db.Raw("select is_free from t_gd_data_api_query_type where id = ?", p.QueryTypeId).QueryRow(&is_free)
- if is_free == 1 {
- return errors.FreeQueryTypeCanNotSetQuota
- }
- return nil
- }
- // 更新数据api配额
- updateDataApiTask := func(db orm.Ormer) error {
- if err := updateThreshold(req, p, db); err != nil {
- return err
- }
- if p.ComboType == 0 {
- if p.EndTime == 0 {
- p.ComboType = 1
- } else {
- p.ComboType = 2
- }
- }
- targetCombo, err := getTargetComb(db, req.ComboId)
- if err != nil {
- return err
- }
- if targetCombo.Type != p.ComboType {
- return changeCombo(db, req, targetCombo, &p)
- }
- used, err := getUsedCount(db, req.MerchantDataApiId)
- if err != nil {
- return err
- }
- if p.ComboType == 1 {
- // 按次数
- if req.Count == 0 {
- return nil
- }
- if p.Count+req.Count < 0 {
- return errors.ArgsError
- }
- state := 0
- if p.Count+req.Count == 0 {
- state = 1
- }
- dataOrder := apis.TGdDataApiOrder{}
- dataOrder.Status = order.OrderComplete
- dataOrder.BuyAccount = "GD后台管理员"
- dataOrder.PayType = 1
- dataOrder.Count = 1
- dataOrder.MerchantId = p.MerchantId
- dataOrder.QueryTypeId = p.QueryTypeId
- dataOrder.CreateTime = time.Now().Format("2006-01-02 15:04:05")
- orderId, err := generateDataApiOrderID(db)
- if err != nil {
- return errors.ApiOrderGenrateFail
- }
- dataOrder.OrderNo = orderId
- if err != nil {
- return errors.DataBaseError
- }
- countAfterIncrease := 0
- usedBeforeIncrease := 0
- countAfterIncrease = req.Count + p.Count - used
- usedBeforeIncrease = used
- if countAfterIncrease < 0 {
- countAfterIncrease = 0
- usedBeforeIncrease = 0
- }
- if req.Count > 0 {
- dataOrder.ComboDesc = fmt.Sprintf("+%d次", req.Count)
- } else {
- dataOrder.ComboDesc = fmt.Sprintf("%d次", req.Count)
- }
- _, err = db.Insert(&dataOrder)
- sql := fmt.Sprintf("UPDATE t_gd_merchant_data_api SET count = %d, update_time = '%s', state = %d WHERE id = %d",
- p.Count+req.Count, time.Now().Format("2006-01-02 15:04:05"), state, req.MerchantDataApiId)
- if countAfterIncrease > 0 {
- sql = fmt.Sprintf("UPDATE t_gd_merchant_data_api SET count = %d, update_time = '%s', state = %d, count_after_increase=%d, used_before_increase=%d WHERE id = %d",
- p.Count+req.Count, time.Now().Format("2006-01-02 15:04:05"), state, countAfterIncrease, usedBeforeIncrease, req.MerchantDataApiId)
- }
- if _, err = db.Raw(sql).Exec(); err != nil {
- l.Error("mysql",
- zap.String("sql", sql),
- zap.String("error", err.Error()))
- return errors.DataBaseError
- }
- } else if p.ComboType == 2 {
- // 按时间
- if p.CountPerDay+req.DayCount < 0 {
- return errors.ArgsError
- }
- state := 0
- if p.CountPerDay+req.DayCount == 0 {
- state = 1
- }
- dataOrder := apis.TGdDataApiOrder{}
- dataOrder.Status = order.OrderComplete
- dataOrder.BuyAccount = "GD后台管理员"
- dataOrder.PayType = 1
- dataOrder.Count = 1
- dataOrder.MerchantId = p.MerchantId
- dataOrder.QueryTypeId = p.QueryTypeId
- dataOrder.CreateTime = time.Now().Format("2006-01-02 15:04:05")
- orderId, err := generateDataApiOrderID(db)
- if err != nil {
- return errors.ApiOrderGenrateFail
- }
- dataOrder.OrderNo = orderId
- if req.DayCount != 0 {
- if req.DayCount > 0 {
- dataOrder.ComboDesc = fmt.Sprintf("+%d次/天", req.DayCount)
- } else {
- dataOrder.ComboDesc = fmt.Sprintf("%d次/天", req.DayCount)
- }
- }
- if req.DayNumber != 0 {
- if dataOrder.ComboDesc != "" {
- dataOrder.ComboDesc = dataOrder.ComboDesc + ","
- }
- if req.DayNumber > 0 {
- dataOrder.ComboDesc = fmt.Sprintf(dataOrder.ComboDesc+"+%d天", req.DayNumber)
- } else {
- dataOrder.ComboDesc = fmt.Sprintf(dataOrder.ComboDesc+"%d天", req.DayNumber)
- }
- }
- _, err = db.Insert(&dataOrder)
- if err != nil {
- return errors.DataBaseError
- }
- // values
- var start, end int64
- if req.DayNumber == 0 {
- start = p.StartTime
- end = p.EndTime
- } else {
- now := time.Now()
- ts := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location()).Unix()
- if p.EndTime < ts {
- start = ts
- end = start + int64(req.DayNumber*24*3600)
- } else {
- start = p.StartTime
- end = p.EndTime + int64(req.DayNumber*24*3600)
- //end = ts + int64(req.DayNumber*24*3600) - (ts-p.StartTime)%(3600*24)
- }
- if end <= start {
- state = 1
- }
- }
- if _, err := db.Raw("UPDATE t_gd_merchant_data_api SET count_per_day=?, state=?, start_time=?, end_time=?, update_time=? WHERE id = ?",
- p.CountPerDay+req.DayCount, state, start, end, time.Now().Format("2006-01-02 15:04:05"), req.MerchantDataApiId).Exec(); err != nil {
- l.Error("mysql",
- zap.String("sql", "UPDATE t_gd_merchant_data_api SET count_per_day=?, state=?, start_time=?, end_time=?, update_time=? WHERE id = ?"),
- zap.String("fields", utils.MarshalJsonString(p.CountPerDay+req.DayCount, state, start, end, time.Now().Format("2006-01-02 15:04:05"), req.MerchantDataApiId)),
- zap.String("error", err.Error()))
- return errors.DataBaseError
- }
- }
- return nil
- }
- tasks := []storage.DbaTasker{}
- tasks = append(tasks, storage.GenerateDbaTask(getDataApiInfoTask))
- tasks = append(tasks, storage.GenerateDbaTask(updateDataApiTask))
- tasks = append(tasks, storage.GenerateDbaTask(redisPublishTask))
- storage.ExecTrans(tasks...)
- return nil
- }
|