Create & Init Project...

This commit is contained in:
2019-04-22 18:49:16 +08:00
commit fc4fa37393
25440 changed files with 4054998 additions and 0 deletions

View File

@@ -0,0 +1,29 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
"go_test",
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [
":package-srcs",
"//app/admin/main/esports/cmd:all-srcs",
"//app/admin/main/esports/conf:all-srcs",
"//app/admin/main/esports/dao:all-srcs",
"//app/admin/main/esports/http:all-srcs",
"//app/admin/main/esports/model:all-srcs",
"//app/admin/main/esports/service:all-srcs",
],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

View File

@@ -0,0 +1,43 @@
# 电竞管理后台
#### Version 1.3.2
##### Features
> 1.赛事活动数据页
#### Version 1.3.1
##### Features
> 1.赛事活动页H5增加字段
#### Version 1.3.0
##### Features
> 1.添加赛事活动页相关接口
#### Version 1.2.0
##### Features
> 1.添加是否在app展示功能
> 2.添加特殊赛程后台配置功能
#### Version 1.1.3
##### Features
> 1.修改remoteip方法
#### Version 1.1.2
##### Features
> 1.添加排序字段并实现排序
#### Version 1.1.1
##### Bug Fixes
>1.csv 去除errgroup
>2.fix搜稿件标题问题
#### Version 1.1.0
##### Bug Fixes
1.import arcs fix
#### Version 1.0.1
##### Bug Fixes
1.import bug fix
#### Version 1.0.0
##### Features
1.项目init

View File

@@ -0,0 +1,13 @@
# Owner
liweijia
renwei
# Author
wuhao02
guanyanliang
liweijia
# Reviewer
guanyanliang
liweijia
zhapuyu

View File

@@ -0,0 +1,18 @@
# See the OWNERS docs at https://go.k8s.io/owners
approvers:
- guanyanliang
- liweijia
- renwei
- wuhao02
labels:
- admin
- admin/main/esports
- main
options:
no_parent_owners: true
reviewers:
- guanyanliang
- liweijia
- wuhao02
- zhapuyu

View File

@@ -0,0 +1 @@
### 电竞管理后台

View File

@@ -0,0 +1,45 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_binary",
"go_library",
)
go_binary(
name = "cmd",
embed = [":go_default_library"],
tags = ["automanaged"],
)
go_library(
name = "go_default_library",
srcs = ["main.go"],
data = ["esports-admin-test.toml"],
importpath = "go-common/app/admin/main/esports/cmd",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/admin/main/esports/conf:go_default_library",
"//app/admin/main/esports/http:go_default_library",
"//app/admin/main/esports/service:go_default_library",
"//library/log:go_default_library",
"//library/net/trace:go_default_library",
"//library/os/signal:go_default_library",
"//library/syscall:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

View File

@@ -0,0 +1,73 @@
version = "1.0.0"
user = "nobody"
dir = "./"
family = "esports-admin"
trace = false
debug = false
env = "qa"
[log]
dir = "/data/log/esports-admin/"
[orm]
dsn = "test:test@tcp(172.16.33.205:3308)/bilibili_esports?timeout=5s&readTimeout=5s&writeTimeout=5s&parseTime=true&loc=Local&charset=utf8,utf8mb4"
active = 5
idle = 5
idleTimeout = "4h"
[permit]
managerHost = "http://uat-manager.bilibili.co"
dashboardHost = "http://uat-dashboard-mng.bilibili.co"
dashboardCaller = "manager-go"
[permit.DsHTTPClient]
key = "manager-go"
secret = "949bbb2dd3178252638c2407578bc7ad"
dial = "1s"
timeout = "1s"
keepAlive = "60s"
[permit.MaHTTPClient]
key = "f6433799dbd88751"
secret = "36f8ddb1806207fe07013ab6a77a3935"
dial = "1s"
timeout = "1s"
keepAlive = "60s"
[permit.MaHTTPClient.breaker]
window = "3s"
sleep = "100ms"
bucket = 10
ratio = 0.5
request = 100
[permit.session]
sessionIDLength = 32
cookieLifeTime = 1800
cookieName = "mng-go"
domain = ".bilibili.co"
[permit.session.Memcache]
name = "go-business/auth"
proto = "tcp"
addr = "172.16.33.54:11211"
active = 10
idle = 5
dialTimeout = "1s"
readTimeout = "1s"
writeTimeout = "1s"
idleTimeout = "80s"
[rule]
maxCSVRows = 1000
maxBatchArcLimit = 10
maxTreeContests = 32
[httpReply]
key = "96923574ed650ef9"
secret = "35113863f243e6a84b8bbdafa2ba76cd"
dial = "3s"
timeout = "10s"
keepAlive = "60s"
[[gameTypes]]
id = 1
name= "LOL"
[[gameTypes]]
id = 2
name= "DOTA2"

View File

@@ -0,0 +1,49 @@
package main
import (
"flag"
"os"
"time"
"go-common/app/admin/main/esports/conf"
"go-common/app/admin/main/esports/http"
"go-common/app/admin/main/esports/service"
"go-common/library/log"
"go-common/library/net/trace"
"go-common/library/os/signal"
"go-common/library/syscall"
)
var (
s *service.Service
)
func main() {
flag.Parse()
if err := conf.Init(); err != nil {
log.Error("conf.Init() error(%v)", err)
panic(err)
}
log.Init(conf.Conf.Log)
defer log.Close()
trace.Init(conf.Conf.Tracer)
defer trace.Close()
// service init
s = service.New(conf.Conf)
http.Init(conf.Conf, s)
log.Info("esports-admin start")
ch := make(chan os.Signal, 1)
signal.Notify(ch, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT, syscall.SIGSTOP)
for {
si := <-ch
switch si {
case syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGSTOP, syscall.SIGINT:
log.Info("get a signal %s, stop the esports-admin process", si.String())
time.Sleep(time.Second)
return
case syscall.SIGHUP:
default:
return
}
}
}

View File

@@ -0,0 +1,38 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = ["conf.go"],
importpath = "go-common/app/admin/main/esports/conf",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//library/conf:go_default_library",
"//library/database/orm:go_default_library",
"//library/log:go_default_library",
"//library/net/http/blademaster:go_default_library",
"//library/net/http/blademaster/middleware/permit:go_default_library",
"//library/net/rpc/warden:go_default_library",
"//library/net/trace:go_default_library",
"//vendor/github.com/BurntSushi/toml:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

View File

@@ -0,0 +1,110 @@
package conf
import (
"errors"
"flag"
"go-common/library/conf"
"go-common/library/database/orm"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
"go-common/library/net/http/blademaster/middleware/permit"
"go-common/library/net/rpc/warden"
"go-common/library/net/trace"
"github.com/BurntSushi/toml"
)
var (
confPath string
client *conf.Client
// Conf of config
Conf = &Config{}
)
// Config def.
type Config struct {
// base
// http
BM *bm.ServerConfig
// auth
Permit *permit.Config
// db
ORM *orm.Config
// log
Log *log.Config
// tracer
Tracer *trace.Config
// rule
Rule *Rule
// client
HTTPReply *bm.ClientConfig
// Warden Client
ArcClient *warden.ClientConfig
AccClient *warden.ClientConfig
// GameTypes game types.
GameTypes []*types
}
// Rule .
type Rule struct {
MaxCSVRows int
MaxBatchArcLimit int
MaxTreeContests int
}
type types struct {
ID int64
Name string
}
func local() (err error) {
_, err = toml.DecodeFile(confPath, &Conf)
return
}
func remote() (err error) {
if client, err = conf.New(); err != nil {
return
}
if err = load(); err != nil {
return
}
go func() {
for range client.Event() {
log.Info("config reload")
if load() != nil {
log.Error("config reload error (%v)", err)
}
}
}()
return
}
func load() (err error) {
var (
s string
ok bool
tmpConf *Config
)
if s, ok = client.Value("esports-admin.toml"); !ok {
return errors.New("load config center error")
}
if _, err = toml.Decode(s, &tmpConf); err != nil {
return errors.New("could not decode config")
}
*Conf = *tmpConf
return
}
func init() {
flag.StringVar(&confPath, "conf", "", "default config path")
}
// Init int config
func Init() error {
if confPath != "" {
return local()
}
return remote()
}

View File

@@ -0,0 +1,60 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
"go_test",
)
go_library(
name = "go_default_library",
srcs = [
"dao.go",
"reply.go",
"search.go",
],
importpath = "go-common/app/admin/main/esports/dao",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/admin/main/esports/conf:go_default_library",
"//app/admin/main/esports/model:go_default_library",
"//library/database/elastic:go_default_library",
"//library/database/orm:go_default_library",
"//library/ecode:go_default_library",
"//library/log:go_default_library",
"//library/net/http/blademaster:go_default_library",
"//vendor/github.com/jinzhu/gorm:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)
go_test(
name = "go_default_test",
srcs = [
"dao_test.go",
"reply_test.go",
"search_test.go",
],
embed = [":go_default_library"],
rundir = ".",
tags = ["automanaged"],
deps = [
"//app/admin/main/esports/conf:go_default_library",
"//app/admin/main/esports/model:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
],
)

View File

@@ -0,0 +1,42 @@
package dao
import (
"context"
"go-common/app/admin/main/esports/conf"
"go-common/library/database/elastic"
"go-common/library/database/orm"
bm "go-common/library/net/http/blademaster"
"github.com/jinzhu/gorm"
)
const _esports = "esports"
// Dao .
type Dao struct {
c *conf.Config
DB *gorm.DB
Elastic *elastic.Elastic
// client
replyClient *bm.Client
}
// New .
func New(c *conf.Config) (d *Dao) {
d = &Dao{
// conf
c: c,
// db
DB: orm.NewMySQL(c.ORM),
// elastic
Elastic: elastic.NewElastic(nil),
replyClient: bm.NewClient(c.HTTPReply),
}
return
}
// Ping .
func (d *Dao) Ping(c context.Context) error {
return d.DB.DB().PingContext(c)
}

View File

@@ -0,0 +1,36 @@
package dao
import (
"flag"
"os"
"testing"
"go-common/app/admin/main/esports/conf"
)
var (
d *Dao
)
func TestMain(m *testing.M) {
if os.Getenv("DEPLOY_ENV") != "" {
flag.Set("app_id", "main.manager.esports-admin")
flag.Set("conf_token", "8664d908294b47ec512d22c7d2ed9d0f")
flag.Set("tree_id", "38071")
flag.Set("conf_version", "docker-1")
flag.Set("deploy_env", "uat")
flag.Set("conf_host", "config.bilibili.co")
flag.Set("conf_path", "/tmp")
flag.Set("region", "sh")
flag.Set("zone", "sh001")
} else {
flag.Set("conf", "../cmd/esports-admin-test.toml")
}
flag.Parse()
if err := conf.Init(); err != nil {
panic(err)
}
d = New(conf.Conf)
m.Run()
os.Exit(0)
}

View File

@@ -0,0 +1,38 @@
package dao
import (
"context"
"net/url"
"strconv"
"go-common/library/ecode"
"go-common/library/log"
)
const (
_replyState = "0" // 0: open, 1: close
_replyURL = "http://api.bilibili.co/x/internal/v2/reply/subject/regist"
_gameOfficial = 32708316
)
// RegReply opens eports's reply.
func (d *Dao) RegReply(c context.Context, maid, adid int64, replyType string) (err error) {
params := url.Values{}
params.Set("adid", strconv.FormatInt(adid, 10))
params.Set("mid", strconv.FormatInt(_gameOfficial, 10))
params.Set("oid", strconv.FormatInt(maid, 10))
params.Set("type", replyType)
params.Set("state", _replyState)
var res struct {
Code int `json:"code"`
}
if err = d.replyClient.Post(c, _replyURL, "", params, &res); err != nil {
log.Error("d.replyClient.Post(%s) error(%v)", _replyURL+"?"+params.Encode(), err)
return
}
if res.Code != ecode.OK.Code() {
log.Error("d.replyClient.Post(%s) error(%v)", _replyURL+"?"+params.Encode(), err)
err = ecode.Int(res.Code)
}
return
}

View File

@@ -0,0 +1,22 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoRegReply(t *testing.T) {
var (
c = context.Background()
maid = int64(11)
adid = int64(123)
)
convey.Convey("RegReply", t, func(ctx convey.C) {
err := d.RegReply(c, maid, adid, "25")
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}

View File

@@ -0,0 +1,46 @@
package dao
import (
"context"
"go-common/app/admin/main/esports/model"
"go-common/library/database/elastic"
"go-common/library/log"
)
// SearchArc search archive.
func (d *Dao) SearchArc(c context.Context, p *model.ArcListParam) (rs []*model.SearchArc, total int, err error) {
req := d.Elastic.NewRequest(_esports).Index(_esports).Pn(p.Pn).Ps(p.Ps)
req.Fields("aid", "typeid", "title", "state", "mid", "gid", "tags", "teams", "matchs", "year")
if p.Title != "" {
req.WhereLike([]string{"title"}, []string{p.Title}, true, elastic.LikeLevelLow)
}
if p.Aid > 0 {
req.WhereEq("aid", p.Aid)
}
if p.TypeID > 0 {
req.WhereEq("type_id", p.TypeID)
}
if p.Copyright > 0 {
req.WhereEq("copyright", p.Copyright)
}
if p.State != "" {
req.WhereEq("state", p.State)
}
req.WhereEq("is_deleted", 0)
res := new(struct {
Page struct {
Num int `json:"num"`
Size int `json:"size"`
Total int `json:"total"`
} `json:"page"`
Result []*model.SearchArc `json:"result"`
})
if err = req.Scan(c, &res); err != nil || res == nil {
log.Error("SearchArc req.Scan error(%v)", err)
return
}
total = res.Page.Total
rs = res.Result
return
}

View File

@@ -0,0 +1,25 @@
package dao
import (
"context"
"testing"
"go-common/app/admin/main/esports/model"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoSearchArc(t *testing.T) {
var (
c = context.Background()
p = &model.ArcListParam{Pn: 1, Ps: 1, Title: "dota"}
)
convey.Convey("SearchArc", t, func(ctx convey.C) {
rs, total, err := d.SearchArc(c, p)
ctx.Convey("Then err should be nil.rs,total should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(total, convey.ShouldNotBeNil)
ctx.So(rs, convey.ShouldNotBeNil)
})
})
}

View File

@@ -0,0 +1,50 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = [
"archive.go",
"contest.go",
"game.go",
"http.go",
"match.go",
"match_active.go",
"match_detail.go",
"season.go",
"tag.go",
"team.go",
"tree.go",
],
importpath = "go-common/app/admin/main/esports/http",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/admin/main/esports/conf:go_default_library",
"//app/admin/main/esports/model:go_default_library",
"//app/admin/main/esports/service:go_default_library",
"//library/ecode:go_default_library",
"//library/log:go_default_library",
"//library/net/http/blademaster:go_default_library",
"//library/net/http/blademaster/middleware/permit:go_default_library",
"//library/xstr:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

View File

@@ -0,0 +1,191 @@
package http
import (
"encoding/csv"
"io/ioutil"
"strings"
"go-common/app/admin/main/esports/conf"
"go-common/app/admin/main/esports/model"
"go-common/library/ecode"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
"go-common/library/xstr"
"strconv"
)
func arcList(c *bm.Context) {
var (
list []*model.ArcResult
cnt int
err error
)
v := new(model.ArcListParam)
if err = c.Bind(v); err != nil {
return
}
if v.Pn == 0 {
v.Pn = 1
}
if v.Ps == 0 {
v.Ps = 20
}
if list, cnt, err = esSvc.ArcList(c, v); err != nil {
c.JSON(nil, err)
return
}
data := make(map[string]interface{}, 2)
page := map[string]int{
"num": v.Pn,
"size": v.Ps,
"total": cnt,
}
data["page"] = page
data["list"] = list
c.JSON(data, nil)
}
func batchAddArc(c *bm.Context) {
v := new(model.ArcAddParam)
if err := c.Bind(v); err != nil {
return
}
if len(v.Aids) > conf.Conf.Rule.MaxBatchArcLimit {
c.JSON(nil, ecode.RequestErr)
return
}
c.JSON(nil, esSvc.BatchAddArc(c, v))
}
func batchEditArc(c *bm.Context) {
v := new(model.ArcAddParam)
if err := c.Bind(v); err != nil {
return
}
if len(v.Aids) > conf.Conf.Rule.MaxBatchArcLimit {
c.JSON(nil, ecode.RequestErr)
return
}
c.JSON(nil, esSvc.BatchEditArc(c, v))
}
func editArc(c *bm.Context) {
v := new(model.ArcImportParam)
if err := c.Bind(v); err != nil {
return
}
c.JSON(nil, esSvc.EditArc(c, v))
}
func arcImportCSV(c *bm.Context) {
var (
err error
data []byte
)
file, _, err := c.Request.FormFile("file")
if err != nil {
log.Error("arcImportCSV upload err(%v)", err)
c.JSON(nil, ecode.RequestErr)
return
}
defer file.Close()
data, err = ioutil.ReadAll(file)
if err != nil {
log.Error("arcImportCSV ioutil.ReadAll err(%v)", err)
c.JSON(nil, ecode.RequestErr)
return
}
r := csv.NewReader(strings.NewReader(string(data)))
records, err := r.ReadAll()
if err != nil {
log.Error("r.ReadAll() err(%v)", err)
c.JSON(nil, ecode.RequestErr)
return
}
if l := len(records); l > conf.Conf.Rule.MaxCSVRows || l <= 1 {
c.JSON(nil, ecode.RequestErr)
return
}
var arcs []*model.ArcImportParam
aidMap := make(map[int64]int64, len(arcs))
for _, v := range records {
arc := new(model.ArcImportParam)
// aid
if aid, err := strconv.ParseInt(v[0], 10, 64); err != nil || aid <= 0 {
log.Warn("arcImportCSV strconv.ParseInt(%s) error(%v)", v[0], err)
continue
} else {
if _, ok := aidMap[aid]; ok {
continue
}
arc.Aid = aid
aidMap[aid] = aid
}
// gids
if gids, err := xstr.SplitInts(v[1]); err != nil {
log.Warn("arcImportCSV gids xstr.SplitInts(%s) aid(%d) error(%v)", v[1], arc.Aid, err)
} else {
for _, id := range gids {
if id > 0 {
arc.Gids = append(arc.Gids, id)
}
}
}
// match ids
if matchIDs, err := xstr.SplitInts(v[2]); err != nil {
log.Warn("arcImportCSV match xstr.SplitInts(%s) aid(%d) error(%v)", v[2], arc.Aid, err)
} else {
for _, id := range matchIDs {
if id > 0 {
arc.MatchIDs = append(arc.MatchIDs, id)
}
}
}
// team ids
if teamIDs, err := xstr.SplitInts(v[3]); err != nil {
log.Warn("arcImportCSV team xstr.SplitInts(%s) aid(%d) error(%v)", v[3], arc.Aid, err)
} else {
for _, id := range teamIDs {
if id > 0 {
arc.TeamIDs = append(arc.TeamIDs, id)
}
}
}
// tag ids
if tagIDs, err := xstr.SplitInts(v[4]); err != nil {
log.Warn("arcImportCSV tag xstr.SplitInts(%s) aid(%d) error(%v)", v[4], arc.Aid, err)
} else {
for _, id := range tagIDs {
if id > 0 {
arc.TagIDs = append(arc.TagIDs, id)
}
}
}
// years
if years, err := xstr.SplitInts(v[5]); err != nil {
log.Warn("arcImportCSV year xstr.SplitInts(%s) aid(%d) error(%v)", v[5], arc.Aid, err)
} else {
for _, id := range years {
if id > 0 {
arc.Years = append(arc.Years, id)
}
}
}
arcs = append(arcs, arc)
}
if len(arcs) == 0 {
c.JSON(nil, ecode.RequestErr)
return
}
c.JSON(nil, esSvc.ArcImportCSV(c, arcs))
}
func batchDelArc(c *bm.Context) {
v := new(struct {
Aids []int64 `form:"aids,split" validate:"dive,gt=1,required"`
})
if err := c.Bind(v); err != nil {
return
}
c.JSON(nil, esSvc.BatchDelArc(c, v.Aids))
}

View File

@@ -0,0 +1,148 @@
package http
import (
"go-common/app/admin/main/esports/model"
"go-common/library/ecode"
bm "go-common/library/net/http/blademaster"
"go-common/library/xstr"
)
const _special = 1
func contestInfo(c *bm.Context) {
v := new(struct {
ID int64 `form:"id" validate:"min=1"`
})
if err := c.Bind(v); err != nil {
return
}
c.JSON(esSvc.ContestInfo(c, v.ID))
}
func contestList(c *bm.Context) {
var (
list []*model.ContestInfo
cnt int64
err error
)
v := new(struct {
Pn int64 `form:"pn" validate:"min=0"`
Ps int64 `form:"ps" validate:"min=0,max=50"`
Mid int64 `form:"mid"`
Sid int64 `form:"sid"`
Sort int64 `form:"sort"`
})
if err = c.Bind(v); err != nil {
return
}
if v.Pn == 0 {
v.Pn = 1
}
if v.Ps == 0 {
v.Ps = 20
}
if list, cnt, err = esSvc.ContestList(c, v.Mid, v.Sid, v.Pn, v.Ps, v.Sort); err != nil {
c.JSON(nil, err)
return
}
data := make(map[string]interface{}, 2)
page := map[string]int64{
"num": v.Pn,
"size": v.Ps,
"total": cnt,
}
data["page"] = page
data["list"] = list
c.JSON(data, nil)
}
func addContest(c *bm.Context) {
var (
err error
tmpGids, gids []int64
)
v := new(model.Contest)
if err = c.Bind(v); err != nil {
return
}
if v.Special == _special && v.SpecialName == "" {
c.JSON(nil, ecode.RequestErr)
return
}
gidStr := c.Request.Form.Get("gids")
if gidStr == "" {
c.JSON(nil, ecode.RequestErr)
return
}
if tmpGids, err = xstr.SplitInts(gidStr); err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
for _, v := range tmpGids {
if v > 0 {
gids = append(gids, v)
}
}
if len(gids) == 0 {
c.JSON(nil, ecode.RequestErr)
return
}
if v.DataType > 0 && v.MatchID == 0 {
c.JSON(nil, ecode.RequestErr)
return
}
c.JSON(nil, esSvc.AddContest(c, v, gids))
}
func editContest(c *bm.Context) {
var (
err error
tmpGids, gids []int64
)
v := new(model.Contest)
if err = c.Bind(v); err != nil {
return
}
if v.ID <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
if v.Special == _special && v.SpecialName == "" {
c.JSON(nil, ecode.RequestErr)
return
}
gidStr := c.Request.Form.Get("gids")
if gidStr == "" {
c.JSON(nil, ecode.RequestErr)
return
}
if tmpGids, err = xstr.SplitInts(gidStr); err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
for _, v := range tmpGids {
if v > 0 {
gids = append(gids, v)
}
}
if len(gids) == 0 {
c.JSON(nil, ecode.RequestErr)
return
}
if v.DataType > 0 && v.MatchID == 0 {
c.JSON(nil, ecode.RequestErr)
return
}
c.JSON(nil, esSvc.EditContest(c, v, gids))
}
func forbidContest(c *bm.Context) {
v := new(struct {
ID int64 `form:"id" validate:"min=1"`
State int `form:"state" validate:"min=0,max=1"`
})
if err := c.Bind(v); err != nil {
return
}
c.JSON(nil, esSvc.ForbidContest(c, v.ID, v.State))
}

View File

@@ -0,0 +1,112 @@
package http
import (
"go-common/app/admin/main/esports/model"
"go-common/library/ecode"
bm "go-common/library/net/http/blademaster"
)
func gameInfo(c *bm.Context) {
v := new(struct {
ID int64 `form:"id" validate:"min=1"`
})
if err := c.Bind(v); err != nil {
return
}
c.JSON(esSvc.GameInfo(c, v.ID))
}
func gameList(c *bm.Context) {
var (
list []*model.Game
cnt int64
err error
)
v := new(struct {
Pn int64 `form:"pn" validate:"min=0"`
Ps int64 `form:"ps" validate:"min=0,max=30"`
Name string `form:"name"`
State int64 `form:"state"`
})
if err = c.Bind(v); err != nil {
return
}
if v.Pn == 0 {
v.Pn = 1
}
if v.Ps == 0 {
v.Ps = 20
}
if list, cnt, err = esSvc.GameList(c, v.Pn, v.Ps, v.Name); err != nil {
c.JSON(nil, err)
return
}
data := make(map[string]interface{}, 2)
page := map[string]int64{
"num": v.Pn,
"size": v.Ps,
"total": cnt,
}
data["page"] = page
data["list"] = list
c.JSON(data, nil)
}
func addGame(c *bm.Context) {
v := new(model.Game)
if err := c.Bind(v); err != nil {
return
}
if v.Plat != 0 {
if _, ok := model.PlatMap[v.Plat]; !ok {
c.JSON(nil, ecode.RequestErr)
return
}
}
if v.Type != 0 {
if _, ok := model.TypeMap[v.Type]; !ok {
c.JSON(nil, ecode.RequestErr)
return
}
}
c.JSON(nil, esSvc.AddGame(c, v))
}
func editGame(c *bm.Context) {
v := new(model.Game)
if err := c.Bind(v); err != nil {
return
}
if v.ID <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
if v.Plat != 0 {
if _, ok := model.PlatMap[v.Plat]; !ok {
c.JSON(nil, ecode.RequestErr)
return
}
}
if v.Type != 0 {
if _, ok := model.TypeMap[v.Type]; !ok {
c.JSON(nil, ecode.RequestErr)
return
}
}
c.JSON(nil, esSvc.EditGame(c, v))
}
func forbidGame(c *bm.Context) {
v := new(struct {
ID int64 `form:"id" validate:"min=1"`
State int `form:"state" validate:"min=0,max=1"`
})
if err := c.Bind(v); err != nil {
return
}
c.JSON(nil, esSvc.ForbidGame(c, v.ID, v.State))
}
func types(c *bm.Context) {
c.JSON(esSvc.Types(c))
}

View File

@@ -0,0 +1,124 @@
package http
import (
"net/http"
"go-common/app/admin/main/esports/conf"
"go-common/app/admin/main/esports/service"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
"go-common/library/net/http/blademaster/middleware/permit"
)
var (
esSvc *service.Service
//idfSvc *identify.Identify
permitSvc *permit.Permit
)
// Init init http sever instance.
func Init(c *conf.Config, s *service.Service) {
esSvc = s
permitSvc = permit.New(c.Permit)
engine := bm.DefaultServer(c.BM)
authRouter(engine)
// init internal server
if err := engine.Start(); err != nil {
log.Error("engine.Start error(%v)", err)
panic(err)
}
}
func authRouter(e *bm.Engine) {
e.Ping(ping)
group := e.Group("/x/admin/esports", permitSvc.Permit("ESPORTS_ADMIN"))
{
matchGroup := group.Group("/matchs")
{
matchGroup.GET("/info", matchInfo)
matchGroup.GET("/list", matchList)
matchGroup.POST("/add", addMatch)
matchGroup.POST("/save", editMatch)
matchGroup.POST("/forbid", forbidMatch)
}
seasonGroup := group.Group("/seasons")
{
seasonGroup.GET("/info", seasonInfo)
seasonGroup.GET("/list", seasonList)
seasonGroup.POST("/add", addSeason)
seasonGroup.POST("/save", editSeason)
seasonGroup.POST("/forbid", forbidSeason)
}
contestGroup := group.Group("/contest")
{
contestGroup.GET("/info", contestInfo)
contestGroup.GET("/list", contestList)
contestGroup.POST("/add", addContest)
contestGroup.POST("/save", editContest)
contestGroup.POST("/forbid", forbidContest)
}
gameGroup := group.Group("/games")
{
gameGroup.GET("/info", gameInfo)
gameGroup.GET("/list", gameList)
gameGroup.POST("/add", addGame)
gameGroup.POST("/save", editGame)
gameGroup.POST("/forbid", forbidGame)
gameGroup.GET("/types", types)
}
teamGroup := group.Group("/teams")
{
teamGroup.GET("/info", teamInfo)
teamGroup.GET("/list", teamList)
teamGroup.POST("/add", addTeam)
teamGroup.POST("/save", editTeam)
teamGroup.POST("/forbid", forbidTeam)
}
tagGroup := group.Group("/tags")
{
tagGroup.GET("/info", tagInfo)
tagGroup.GET("/list", tagList)
tagGroup.POST("/add", addTag)
tagGroup.POST("/save", editTag)
tagGroup.POST("/forbid", forbidTag)
}
arcGroup := group.Group("/arcs")
{
arcGroup.GET("/list", arcList)
arcGroup.POST("/edit", editArc)
arcGroup.POST("/batch/add", batchAddArc)
arcGroup.POST("/batch/edit", batchEditArc)
arcGroup.POST("/batch/del", batchDelArc)
arcGroup.POST("/import/csv", arcImportCSV)
}
actGroup := group.Group("/active")
{
actGroup.GET("", listAct)
actGroup.POST("/add", addAct)
actGroup.POST("/edit", editAct)
actGroup.POST("/forbid", forbidAct)
dGroup := actGroup.Group("/detail")
{
dGroup.GET("/list", listDetail)
dGroup.POST("/add", addDetail)
dGroup.POST("/edit", editDetail)
dGroup.POST("/forbid", forbidDetail)
dGroup.POST("/online", onLine)
}
tGroup := actGroup.Group("/tree")
{
tGroup.GET("/list", listTree)
tGroup.POST("/add", addTree)
tGroup.POST("/edit", editTree)
tGroup.POST("/del", delTree)
}
}
}
}
func ping(c *bm.Context) {
if err := esSvc.Ping(c); err != nil {
log.Error("esport-admin ping error")
c.AbortWithStatus(http.StatusServiceUnavailable)
}
}

View File

@@ -0,0 +1,128 @@
package http
import (
"go-common/app/admin/main/esports/model"
"go-common/library/ecode"
bm "go-common/library/net/http/blademaster"
"go-common/library/xstr"
)
func matchInfo(c *bm.Context) {
v := new(struct {
ID int64 `form:"id" validate:"min=1"`
})
if err := c.Bind(v); err != nil {
return
}
c.JSON(esSvc.MatchInfo(c, v.ID))
}
func matchList(c *bm.Context) {
var (
list []*model.MatchInfo
cnt int64
err error
)
v := new(struct {
Pn int64 `form:"pn" validate:"min=0"`
Ps int64 `form:"ps" validate:"min=0,max=50"`
Title string `form:"title"`
})
if err = c.Bind(v); err != nil {
return
}
if v.Pn == 0 {
v.Pn = 1
}
if v.Ps == 0 {
v.Ps = 20
}
if list, cnt, err = esSvc.MatchList(c, v.Pn, v.Ps, v.Title); err != nil {
c.JSON(nil, err)
return
}
data := make(map[string]interface{}, 2)
page := map[string]int64{
"num": v.Pn,
"size": v.Ps,
"total": cnt,
}
data["page"] = page
data["list"] = list
c.JSON(data, nil)
}
func addMatch(c *bm.Context) {
var (
err error
tmpGids, gids []int64
)
v := new(model.Match)
if err = c.Bind(v); err != nil {
return
}
gidStr := c.Request.Form.Get("gids")
if gidStr == "" {
c.JSON(nil, ecode.RequestErr)
return
}
if tmpGids, err = xstr.SplitInts(gidStr); err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
for _, v := range tmpGids {
if v > 0 {
gids = append(gids, v)
}
}
if len(gids) == 0 {
c.JSON(nil, ecode.RequestErr)
return
}
c.JSON(nil, esSvc.AddMatch(c, v, gids))
}
func editMatch(c *bm.Context) {
var (
err error
tmpGids, gids []int64
)
v := new(model.Match)
if err = c.Bind(v); err != nil {
return
}
if v.ID <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
gidStr := c.Request.Form.Get("gids")
if gidStr == "" {
c.JSON(nil, ecode.RequestErr)
return
}
if tmpGids, err = xstr.SplitInts(gidStr); err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
for _, v := range tmpGids {
if v > 0 {
gids = append(gids, v)
}
}
if len(gids) == 0 {
c.JSON(nil, ecode.RequestErr)
return
}
c.JSON(nil, esSvc.EditMatch(c, v, gids))
}
func forbidMatch(c *bm.Context) {
v := new(struct {
ID int64 `form:"id" validate:"min=1"`
State int `form:"state" validate:"min=0,max=1"`
})
if err := c.Bind(v); err != nil {
return
}
c.JSON(nil, esSvc.ForbidMatch(c, v.ID, v.State))
}

View File

@@ -0,0 +1,62 @@
package http
import (
"go-common/app/admin/main/esports/model"
bm "go-common/library/net/http/blademaster"
)
func addAct(c *bm.Context) {
v := new(model.ParamMA)
if err := c.Bind(v); err != nil {
return
}
c.JSON(esSvc.AddAct(c, v))
}
func editAct(c *bm.Context) {
v := new(model.ParamMA)
if err := c.Bind(v); err != nil {
return
}
c.JSON(esSvc.EditAct(c, v))
}
func forbidAct(c *bm.Context) {
v := new(struct {
ID int64 `form:"id" validate:"required"`
State int `form:"state" validate:"min=0,max=1"`
})
if err := c.Bind(v); err != nil {
return
}
c.JSON(nil, esSvc.ForbidAct(c, v.ID, v.State))
}
func listAct(c *bm.Context) {
var (
list []*model.MatchModule
cnt int64
err error
)
v := new(struct {
Mid int64 `form:"mid"`
Pn int64 `form:"pn" validate:"min=0" default:"1"`
Ps int64 `form:"ps" validate:"min=0,max=30" default:"20"`
})
if err = c.Bind(v); err != nil {
return
}
if list, cnt, err = esSvc.ListAct(c, v.Mid, v.Pn, v.Ps); err != nil {
c.JSON(nil, err)
return
}
data := make(map[string]interface{}, 2)
page := map[string]int64{
"num": v.Pn,
"size": v.Ps,
"count": cnt,
}
data["page"] = page
data["list"] = list
c.JSON(data, nil)
}

View File

@@ -0,0 +1,73 @@
package http
import (
"go-common/app/admin/main/esports/model"
bm "go-common/library/net/http/blademaster"
)
func addDetail(c *bm.Context) {
v := new(model.MatchDetail)
if err := c.Bind(v); err != nil {
return
}
c.JSON(nil, esSvc.AddDetail(c, v))
}
func editDetail(c *bm.Context) {
v := new(model.MatchDetail)
if err := c.Bind(v); err != nil {
return
}
c.JSON(nil, esSvc.EditDetail(c, v))
}
func forbidDetail(c *bm.Context) {
v := new(struct {
ID int64 `form:"id" validate:"required"`
State int `form:"state" validate:"min=0,max=1"`
})
if err := c.Bind(v); err != nil {
return
}
c.JSON(nil, esSvc.ForbidDetail(c, v.ID, v.State))
}
func onLine(c *bm.Context) {
v := new(struct {
ID int64 `form:"id" validate:"required"`
State int64 `form:"state" validate:"min=0,max=1"`
})
if err := c.Bind(v); err != nil {
return
}
c.JSON(nil, esSvc.UpOnline(c, v.ID, v.State))
}
func listDetail(c *bm.Context) {
var (
list []*model.MatchDetail
cnt int64
err error
)
v := new(struct {
MaID int64 `json:"ma_id,omitempty" form:"ma_id" validate:"required"`
Pn int64 `form:"pn" validate:"min=0" default:"1"`
Ps int64 `form:"ps" validate:"min=0,max=30" default:"20"`
})
if err = c.Bind(v); err != nil {
return
}
if list, cnt, err = esSvc.ListDetail(c, v.MaID, v.Pn, v.Ps); err != nil {
c.JSON(nil, err)
return
}
data := make(map[string]interface{}, 2)
page := map[string]int64{
"num": v.Pn,
"size": v.Ps,
"count": cnt,
}
data["page"] = page
data["list"] = list
c.JSON(data, nil)
}

View File

@@ -0,0 +1,128 @@
package http
import (
"go-common/app/admin/main/esports/model"
"go-common/library/ecode"
bm "go-common/library/net/http/blademaster"
"go-common/library/xstr"
)
func seasonInfo(c *bm.Context) {
v := new(struct {
ID int64 `form:"id" validate:"min=1"`
})
if err := c.Bind(v); err != nil {
return
}
c.JSON(esSvc.SeasonInfo(c, v.ID))
}
func seasonList(c *bm.Context) {
var (
list []*model.SeasonInfo
cnt int64
err error
)
v := new(struct {
Mid int64 `form:"mid"`
Pn int64 `form:"pn" validate:"min=0"`
Ps int64 `form:"ps" validate:"min=0,max=30"`
})
if err = c.Bind(v); err != nil {
return
}
if v.Pn == 0 {
v.Pn = 1
}
if v.Ps == 0 {
v.Ps = 20
}
if list, cnt, err = esSvc.SeasonList(c, v.Mid, v.Pn, v.Ps); err != nil {
c.JSON(nil, err)
return
}
data := make(map[string]interface{}, 2)
page := map[string]int64{
"num": v.Pn,
"size": v.Ps,
"count": cnt,
}
data["page"] = page
data["list"] = list
c.JSON(data, nil)
}
func addSeason(c *bm.Context) {
var (
err error
tmpGids, gids []int64
)
v := new(model.Season)
if err = c.Bind(v); err != nil {
return
}
gidStr := c.Request.Form.Get("gids")
if gidStr == "" {
c.JSON(nil, ecode.RequestErr)
return
}
if tmpGids, err = xstr.SplitInts(gidStr); err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
for _, v := range tmpGids {
if v > 0 {
gids = append(gids, v)
}
}
if len(gids) == 0 {
c.JSON(nil, ecode.RequestErr)
return
}
c.JSON(nil, esSvc.AddSeason(c, v, gids))
}
func editSeason(c *bm.Context) {
var (
err error
tmpGids, gids []int64
)
v := new(model.Season)
if err = c.Bind(v); err != nil {
return
}
if v.ID <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
gidStr := c.Request.Form.Get("gids")
if gidStr == "" {
c.JSON(nil, ecode.RequestErr)
return
}
if tmpGids, err = xstr.SplitInts(gidStr); err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
for _, v := range tmpGids {
if v > 0 {
gids = append(gids, v)
}
}
if len(gids) == 0 {
c.JSON(nil, ecode.RequestErr)
return
}
c.JSON(nil, esSvc.EditSeason(c, v, gids))
}
func forbidSeason(c *bm.Context) {
v := new(struct {
ID int64 `form:"id" validate:"min=1"`
State int `form:"state" validate:"min=0,max=1"`
})
if err := c.Bind(v); err != nil {
return
}
c.JSON(nil, esSvc.ForbidSeason(c, v.ID, v.State))
}

View File

@@ -0,0 +1,82 @@
package http
import (
"go-common/app/admin/main/esports/model"
"go-common/library/ecode"
bm "go-common/library/net/http/blademaster"
)
func tagInfo(c *bm.Context) {
v := new(struct {
ID int64 `form:"id" validate:"min=1"`
})
if err := c.Bind(v); err != nil {
return
}
c.JSON(esSvc.TagInfo(c, v.ID))
}
func tagList(c *bm.Context) {
var (
list []*model.Tag
cnt int64
err error
)
v := new(struct {
Pn int64 `form:"pn" validate:"min=0"`
Ps int64 `form:"ps" validate:"min=0,max=30"`
})
if err = c.Bind(v); err != nil {
return
}
if v.Pn == 0 {
v.Pn = 1
}
if v.Ps == 0 {
v.Ps = 20
}
if list, cnt, err = esSvc.TagList(c, v.Pn, v.Ps); err != nil {
c.JSON(nil, err)
return
}
data := make(map[string]interface{}, 2)
page := map[string]int64{
"num": v.Pn,
"size": v.Ps,
"count": cnt,
}
data["page"] = page
data["list"] = list
c.JSON(data, nil)
}
func addTag(c *bm.Context) {
v := new(model.Tag)
if err := c.Bind(v); err != nil {
return
}
c.JSON(nil, esSvc.AddTag(c, v))
}
func editTag(c *bm.Context) {
v := new(model.Tag)
if err := c.Bind(v); err != nil {
return
}
if v.ID <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
c.JSON(nil, esSvc.EditTag(c, v))
}
func forbidTag(c *bm.Context) {
v := new(struct {
ID int64 `form:"id" validate:"min=1"`
State int `form:"state" validate:"min=0,max=1"`
})
if err := c.Bind(v); err != nil {
return
}
c.JSON(nil, esSvc.ForbidTag(c, v.ID, v.State))
}

View File

@@ -0,0 +1,129 @@
package http
import (
"go-common/app/admin/main/esports/model"
"go-common/library/ecode"
bm "go-common/library/net/http/blademaster"
"go-common/library/xstr"
)
func teamInfo(c *bm.Context) {
v := new(struct {
ID int64 `form:"id" validate:"min=1"`
})
if err := c.Bind(v); err != nil {
return
}
c.JSON(esSvc.TeamInfo(c, v.ID))
}
func teamList(c *bm.Context) {
var (
list []*model.TeamInfo
cnt int64
err error
)
v := new(struct {
Pn int64 `form:"pn" validate:"min=0"`
Ps int64 `form:"ps" validate:"min=0,max=30"`
Title string `form:"title"`
Status int `form:"status"`
})
if err = c.Bind(v); err != nil {
return
}
if v.Pn == 0 {
v.Pn = 1
}
if v.Ps == 0 {
v.Ps = 20
}
if list, cnt, err = esSvc.TeamList(c, v.Pn, v.Ps, v.Title, v.Status); err != nil {
c.JSON(nil, err)
return
}
data := make(map[string]interface{}, 2)
page := map[string]int64{
"num": v.Pn,
"size": v.Ps,
"count": cnt,
}
data["page"] = page
data["list"] = list
c.JSON(data, nil)
}
func addTeam(c *bm.Context) {
var (
err error
gids, tmpGids []int64
)
v := new(model.Team)
if err = c.Bind(v); err != nil {
return
}
gidStr := c.Request.Form.Get("gids")
if gidStr == "" {
c.JSON(nil, ecode.RequestErr)
return
}
if tmpGids, err = xstr.SplitInts(gidStr); err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
for _, v := range tmpGids {
if v > 0 {
gids = append(gids, v)
}
}
if len(gids) == 0 {
c.JSON(nil, ecode.RequestErr)
return
}
c.JSON(nil, esSvc.AddTeam(c, v, gids))
}
func editTeam(c *bm.Context) {
var (
err error
gids, tmpGids []int64
)
v := new(model.Team)
if err = c.Bind(v); err != nil {
return
}
if v.ID <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
gidStr := c.Request.Form.Get("gids")
if gidStr == "" {
c.JSON(nil, ecode.RequestErr)
return
}
if tmpGids, err = xstr.SplitInts(gidStr); err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
for _, v := range tmpGids {
if v > 0 {
gids = append(gids, v)
}
}
if len(gids) == 0 {
c.JSON(nil, ecode.RequestErr)
return
}
c.JSON(nil, esSvc.EditTeam(c, v, gids))
}
func forbidTeam(c *bm.Context) {
v := new(struct {
ID int64 `form:"id" validate:"min=1"`
State int `form:"state" validate:"min=0,max=1"`
})
if err := c.Bind(v); err != nil {
return
}
c.JSON(nil, esSvc.ForbidTeam(c, v.ID, v.State))
}

View File

@@ -0,0 +1,43 @@
package http
import (
"go-common/app/admin/main/esports/model"
"go-common/library/ecode"
bm "go-common/library/net/http/blademaster"
)
func addTree(c *bm.Context) {
v := new(model.Tree)
if err := c.Bind(v); err != nil {
return
}
if v.Pid > 0 && v.RootID == 0 {
c.JSON(nil, ecode.RequestErr)
return
}
c.JSON(esSvc.AddTree(c, v))
}
func editTree(c *bm.Context) {
v := new(model.TreeEditParam)
if err := c.Bind(v); err != nil {
return
}
c.JSON(nil, esSvc.EditTree(c, v))
}
func delTree(c *bm.Context) {
v := new(model.TreeDelParam)
if err := c.Bind(v); err != nil {
return
}
c.JSON(nil, esSvc.DelTree(c, v))
}
func listTree(c *bm.Context) {
v := new(model.TreeListParam)
if err := c.Bind(v); err != nil {
return
}
c.JSON(esSvc.TreeList(c, v))
}

View File

@@ -0,0 +1,46 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = [
"archive.go",
"contest.go",
"contest_data.go",
"game.go",
"gid_map.go",
"match.go",
"match_active.go",
"match_detail.go",
"match_map.go",
"season.go",
"tag.go",
"tag_map.go",
"team.go",
"team_map.go",
"tree.go",
"year_map.go",
],
importpath = "go-common/app/admin/main/esports/model",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = ["//library/xstr:go_default_library"],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

View File

@@ -0,0 +1,111 @@
package model
import (
"fmt"
"strings"
)
const _arcBatchAddSQL = "INSERT INTO es_archives(`aid`) VALUES %s"
// Arc .
type Arc struct {
ID int64 `json:"id"`
Aid int64 `json:"aid"`
IsDeleted int `json:"is_deleted"`
}
// ArcAddParam .
type ArcAddParam struct {
Aids []int64 `form:"aids,split" validate:"dive,gt=1"`
Gids []int64 `form:"gids,split"`
MatchIDs []int64 `form:"match_ids,split"`
TeamIDs []int64 `form:"team_ids,split"`
TagIDs []int64 `form:"tag_ids,split"`
Years []int64 `form:"years,split"`
}
// ArcImportParam .
type ArcImportParam struct {
Aid int64 `form:"aid" validate:"min=1"`
Gids []int64 `form:"gids,split"`
MatchIDs []int64 `form:"match_ids,split"`
TeamIDs []int64 `form:"team_ids,split"`
TagIDs []int64 `form:"tag_ids,split"`
Years []int64 `form:"years,split"`
}
// ArcListParam .
type ArcListParam struct {
Title string `form:"title"`
Aid int64 `form:"aid"`
TypeID int64 `form:"type_id"`
Copyright int `form:"copyright"`
State string `form:"state"`
Pn int `form:"pn"`
Ps int `form:"ps"`
}
// SearchArc .
type SearchArc struct {
Aid int64 `json:"aid"`
TypeID int64 `json:"typeid"`
Title string `json:"title"`
State int64 `json:"state"`
Mid int64 `json:"mid"`
Gid []int64 `json:"gid"`
Tags []int64 `json:"tags"`
Matchs []int64 `json:"matchs"`
Teams []int64 `json:"teams"`
Year []int64 `json:"year"`
}
// ArcResult .
type ArcResult struct {
Aid int64 `json:"aid"`
TypeID int64 `json:"type_id"`
Title string `json:"title"`
State int64 `json:"state"`
Mid int64 `json:"mid"`
Uname string `json:"uname"`
Games []*Game `json:"games"`
Tags []*Tag `json:"tags"`
Matchs []*Match `json:"matchs"`
Teams []*Team `json:"teams"`
Years []int64 `json:"years"`
}
// ArcRelation .
type ArcRelation struct {
AddGids []*GIDMap
UpAddGids []int64
UpDelGids []int64
AddMatchs []*MatchMap
UpAddMatchs []int64
UpDelMatchs []int64
AddTags []*TagMap
UpAddTags []int64
UpDelTags []int64
AddTeams []*TeamMap
UpAddTeams []int64
UpDelTeams []int64
AddYears []*YearMap
UpAddYears []int64
UpDelYears []int64
}
// TableName .
func (a Arc) TableName() string {
return "es_archives"
}
// ArcBatchAddSQL .
func ArcBatchAddSQL(aids []int64) string {
if len(aids) == 0 {
return ""
}
var rowStrings []string
for _, aid := range aids {
rowStrings = append(rowStrings, fmt.Sprintf("(%d)", aid))
}
return fmt.Sprintf(_arcBatchAddSQL, strings.Join(rowStrings, ","))
}

View File

@@ -0,0 +1,48 @@
package model
// Contest .
type Contest struct {
ID int64 `json:"id" form:"id"`
GameStage string `json:"game_stage" form:"game_stage" validate:"required"`
Stime int64 `json:"stime" form:"stime"`
Etime int64 `json:"etime" form:"etime"`
HomeID int64 `json:"home_id" form:"home_id"`
AwayID int64 `json:"away_id" form:"away_id"`
HomeScore int64 `json:"home_score" form:"home_score"`
AwayScore int64 `json:"away_score" form:"away_score"`
LiveRoom int64 `json:"live_room" form:"live_room"`
Aid int64 `json:"aid" form:"aid"`
Collection int64 `json:"collection" form:"collection"`
GameState int `json:"game_state" form:"game_state"`
Dic string `json:"dic" form:"dic"`
Status int `json:"status" form:"status"`
Sid int64 `json:"sid" form:"sid" validate:"required"`
Mid int64 `json:"mid" form:"mid" validate:"required"`
Special int `json:"special" form:"special"`
SuccessTeam int64 `json:"success_team" form:"success_team"`
SpecialName string `json:"special_name" form:"special_name"`
SpecialTips string `json:"special_tips" form:"special_tips"`
SpecialImage string `json:"special_image" form:"special_image"`
Playback string `json:"playback" form:"playback"`
CollectionURL string `json:"collection_url" form:"collection_url"`
LiveURL string `json:"live_url" form:"live_url"`
DataType int64 `json:"data_type" form:"data_type"`
Data string `json:"-" form:"data" gorm:"-"`
Adid int64 `json:"-" form:"adid" gorm:"-" validate:"required"`
MatchID int64 `json:"match_id" form:"match_id"`
}
// ContestInfo .
type ContestInfo struct {
*Contest
Games []*Game `json:"games"`
HomeName string `json:"home_name"`
AwayName string `json:"away_name"`
SuccessName string `json:"success_name" form:"success_name"`
Data []*ContestData `json:"data"`
}
// TableName es_contests
func (c Contest) TableName() string {
return "es_contests"
}

View File

@@ -0,0 +1,56 @@
package model
import (
"fmt"
"strings"
"go-common/library/xstr"
)
const (
_cDataInsertSQL = "INSERT INTO es_contests_data(cid,url,point_data) VALUES %s"
_cDataEditSQL = "UPDATE es_contests_data SET url = CASE %s END,point_data = CASE %s END WHERE id IN (%s)"
)
// ContestData .
type ContestData struct {
ID int64 `json:"id"`
CID int64 `json:"cid" gorm:"column:cid"`
URL string `json:"url"`
PointData int `json:"point_data"`
IsDeleted int `json:"is_deleted"`
}
// TableName es_contests_data.
func (t ContestData) TableName() string {
return "es_contests_data"
}
// BatchAddCDataSQL .
func BatchAddCDataSQL(cID int64, data []*ContestData) string {
if len(data) == 0 {
return ""
}
var rowStrings []string
for _, v := range data {
rowStrings = append(rowStrings, fmt.Sprintf("(%d,'%s',%d)", cID, v.URL, v.PointData))
}
return fmt.Sprintf(_cDataInsertSQL, strings.Join(rowStrings, ","))
}
// BatchEditCDataSQL .
func BatchEditCDataSQL(cDatas []*ContestData) string {
if len(cDatas) == 0 {
return ""
}
var (
urlStr, pDataStr string
ids []int64
)
for _, module := range cDatas {
urlStr = fmt.Sprintf("%s WHEN id = %d THEN '%s'", urlStr, module.ID, module.URL)
pDataStr = fmt.Sprintf("%s WHEN id = %d THEN '%d'", pDataStr, module.ID, module.PointData)
ids = append(ids, module.ID)
}
return fmt.Sprintf(_cDataEditSQL, urlStr, pDataStr, xstr.JoinInts(ids))
}

View File

@@ -0,0 +1,50 @@
package model
// game play and type
const (
PlatPc = 1
PlatMobile = 2
TypeMOBA = 1
TypeACT = 2
TypeFPS = 3
TypeFTG = 4
TypeRTS = 5
TypeRPG = 6
)
// game plat map and type map
var (
PlatMap = map[int]int{
PlatPc: PlatPc,
PlatMobile: PlatMobile,
}
TypeMap = map[int]int{
TypeMOBA: TypeMOBA,
TypeACT: TypeACT,
TypeFPS: TypeFPS,
TypeFTG: TypeFTG,
TypeRTS: TypeRTS,
TypeRPG: TypeRPG,
}
)
// Game .
type Game struct {
ID int64 `json:"id" form:"id"`
Title string `json:"title" form:"title" validate:"required"`
SubTitle string `json:"sub_title" form:"sub_title"`
ETitle string `json:"e_title" form:"e_title"`
Plat int `json:"plat" form:"plat"`
Type int `json:"type" form:"type"`
Logo string `json:"logo" form:"logo" validate:"required"`
Publisher string `json:"publisher" form:"publisher"`
Operations string `json:"operations" form:"operations"`
PbTime int64 `json:"pb_time" form:"pb_time"`
Dic string `json:"dic" form:"dic"`
Status int `json:"status" form:"status"`
}
// TableName es_game
func (g Game) TableName() string {
return "es_games"
}

View File

@@ -0,0 +1,42 @@
package model
import (
"fmt"
"strings"
)
// gid map
const (
TypeMatch = 1
TypeSeason = 2
TypeContest = 3
TypeTeam = 4
TypeArc = 5
_gidMapInsertSQL = "INSERT INTO es_gid_map(`type`,`oid`,`gid`) VALUES %s"
)
// GIDMap .
type GIDMap struct {
ID int64 `json:"id"`
Type int `json:"type"`
Oid int64 `json:"oid"`
Gid int64 `json:"gid"`
IsDeleted int `json:"is_deleted"`
}
// TableName .
func (g GIDMap) TableName() string {
return "es_gid_map"
}
// GidBatchAddSQL .
func GidBatchAddSQL(gidMap []*GIDMap) string {
if len(gidMap) == 0 {
return ""
}
var rowStrings []string
for _, v := range gidMap {
rowStrings = append(rowStrings, fmt.Sprintf("(%d,%d,%d)", v.Type, v.Oid, v.Gid))
}
return fmt.Sprintf(_gidMapInsertSQL, strings.Join(rowStrings, ","))
}

View File

@@ -0,0 +1,25 @@
package model
// Match .
type Match struct {
ID int64 `json:"id" form:"id"`
Title string `json:"title" form:"title"`
SubTitle string `json:"sub_title" form:"sub_title"`
CYear int `json:"c_year" form:"c_year"`
Sponsor string `json:"sponsor" form:"sponsor"`
Logo string `json:"logo" form:"logo" validate:"required"`
Dic string `json:"dic" form:"dic"`
Status int `json:"status" form:"status"`
Rank int `json:"rank" form:"rank" validate:"min=0,max=99"`
}
// MatchInfo .
type MatchInfo struct {
*Match
Games []*Game `json:"games"`
}
// TableName .
func (m Match) TableName() string {
return "es_matchs"
}

View File

@@ -0,0 +1,100 @@
package model
import (
"fmt"
"strings"
"go-common/library/xstr"
)
const (
_moduleInsertSQL = "INSERT INTO es_matchs_module(ma_id,name,oids) VALUES %s"
_moduleEditSQL = "UPDATE es_matchs_module SET name = CASE %s END,oids = CASE %s END WHERE id IN (%s)"
)
// ParamMA .
type ParamMA struct {
MatchActive
Modules string `json:"-" form:"modules"`
Adid int64 `json:"-" form:"adid" validate:"required"`
}
// MatchActive .
type MatchActive struct {
ID int64 `json:"id" form:"id"`
Sid int64 `json:"sid" form:"sid" validate:"required"`
Mid int64 `json:"mid" form:"mid" validate:"required"`
Background string `json:"background" form:"background"`
BackColor string `json:"back_color" form:"back_color"`
ColorStep string `json:"color_step" form:"color_step"`
LiveID int64 `json:"live_id" form:"live_id" validate:"required"`
Intr string `json:"intr" form:"intr"`
Focus string `json:"focus" form:"focus"`
URL string `json:"url" form:"url"`
Status int `json:"status" form:"status"`
H5Background string `json:"h5_background" form:"h5_background"`
H5BackColor string `json:"h5_back_color" form:"h5_back_color"`
H5Focus string `json:"h5_focus" form:"h5_focus"`
H5URL string `json:"h5_url" form:"h5_url"`
IntrLogo string `json:"intr_logo" form:"intr_logo"`
IntrTitle string `json:"intr_title" form:"intr_title"`
IntrText string `json:"intr_text" form:"intr_text"`
}
// Module .
type Module struct {
ID int64 `json:"id"`
MaID int64 `json:"ma_id"`
Name string `json:"name"`
Oids string `json:"oids"`
Status int `json:"-" form:"status"`
}
// MatchModule .
type MatchModule struct {
*MatchActive
Modules []*Module `json:"modules"`
MatchTitle string `json:"match_title"`
MatchSubTitle string `json:"match_sub_title"`
SeasonTitle string `json:"season_title"`
SeasonSubTitle string `json:"season_sub_title"`
}
// TableName es_matchs_module.
func (t Module) TableName() string {
return "es_matchs_module"
}
// TableName es_matchs_active.
func (t MatchActive) TableName() string {
return "es_matchs_active"
}
// BatchAddModuleSQL .
func BatchAddModuleSQL(maID int64, data []*Module) string {
if len(data) == 0 {
return ""
}
var rowStrings []string
for _, v := range data {
rowStrings = append(rowStrings, fmt.Sprintf("(%d,'%s','%s')", maID, v.Name, v.Oids))
}
return fmt.Sprintf(_moduleInsertSQL, strings.Join(rowStrings, ","))
}
// BatchEditModuleSQL .
func BatchEditModuleSQL(mapModuel []*Module) string {
if len(mapModuel) == 0 {
return ""
}
var (
nameStr, oidsStr string
ids []int64
)
for _, module := range mapModuel {
nameStr = fmt.Sprintf("%s WHEN id = %d THEN '%s'", nameStr, module.ID, module.Name)
oidsStr = fmt.Sprintf("%s WHEN id = %d THEN '%s'", oidsStr, module.ID, module.Oids)
ids = append(ids, module.ID)
}
return fmt.Sprintf(_moduleEditSQL, nameStr, oidsStr, xstr.JoinInts(ids))
}

View File

@@ -0,0 +1,21 @@
package model
// MatchDetail .
type MatchDetail struct {
ID int64 `json:"id" form:"id"`
MaID int64 `json:"ma_id" form:"ma_id" validate:"required"`
GameType int64 `json:"game_type" form:"game_type" validate:"required"`
Stime int64 `json:"stime" form:"stime" validate:"required"`
Etime int64 `json:"etime" form:"etime" validate:"required"`
GameStage string `json:"game_stage" form:"game_stage" validate:"required"`
KnockoutType int64 `json:"knockout_type" form:"knockout_type"`
WinnerType int64 `json:"winner_type" form:"winner_type"`
ScoreID int64 `json:"score_id" form:"score_id"`
Status int `json:"status" form:"status"`
Online int `json:"online" form:"online"`
}
// TableName .
func (t MatchDetail) TableName() string {
return "es_matchs_detail"
}

View File

@@ -0,0 +1,33 @@
package model
import (
"fmt"
"strings"
)
const _matchMapInsertSQL = "INSERT INTO es_matchs_map(mid,aid) VALUES %s"
// MatchMap .
type MatchMap struct {
ID int64 `json:"id"`
Mid int64 `json:"mid"`
Aid int64 `json:"aid"`
IsDeleted int `json:"is_deleted"`
}
// TableName es_year_map.
func (m MatchMap) TableName() string {
return "es_matchs_map"
}
// BatchAddMachMapSQL .
func BatchAddMachMapSQL(data []*MatchMap) string {
if len(data) == 0 {
return ""
}
var rowStrings []string
for _, v := range data {
rowStrings = append(rowStrings, fmt.Sprintf("(%d,%d)", v.Mid, v.Aid))
}
return fmt.Sprintf(_matchMapInsertSQL, strings.Join(rowStrings, ","))
}

View File

@@ -0,0 +1,31 @@
package model
// Season .
type Season struct {
ID int64 `json:"id" form:"id"`
Mid int64 `json:"mid" form:"mid" validate:"required"`
Title string `json:"title" form:"title" validate:"required"`
SubTitle string `json:"sub_title" form:"sub_title"`
Stime int64 `json:"stime" form:"stime"`
Etime int64 `json:"etime" form:"etime"`
Sponsor string `json:"sponsor" form:"sponsor"`
Logo string `json:"logo" form:"logo" validate:"required"`
Dic string `json:"dic" form:"dic"`
Status int `json:"status" form:"is_deleted"`
IsApp int `json:"is_app" form:"is_app"`
Rank int `json:"rank" form:"rank" validate:"min=0,max=10"`
URL string `json:"url" form:"url"`
DataFocus string `json:"data_focus" form:"data_focus"`
FocusURL string `json:"focus_url" form:"focus_url"`
}
// SeasonInfo .
type SeasonInfo struct {
*Season
Games []*Game `json:"games"`
}
// TableName .
func (s Season) TableName() string {
return "es_seasons"
}

View File

@@ -0,0 +1,13 @@
package model
// Tag .
type Tag struct {
ID int64 `json:"id" form:"id"`
Name string `json:"name" form:"name" validate:"required"`
Status int `json:"status" form:"status"`
}
// TableName .
func (t Tag) TableName() string {
return "es_tags"
}

View File

@@ -0,0 +1,33 @@
package model
import (
"fmt"
"strings"
)
const _tagMapInsertSQL = "INSERT INTO es_tags_map(tid,aid) VALUES %s"
// TagMap .
type TagMap struct {
ID int64 `json:"id"`
Tid int64 `json:"tid"`
Aid int64 `json:"aid"`
IsDeleted int `json:"is_deleted"`
}
// TableName es_year_map.
func (t TagMap) TableName() string {
return "es_tags_map"
}
// BatchAddTagMapSQL .
func BatchAddTagMapSQL(data []*TagMap) string {
if len(data) == 0 {
return ""
}
var rowStrings []string
for _, v := range data {
rowStrings = append(rowStrings, fmt.Sprintf("(%d,%d)", v.Tid, v.Aid))
}
return fmt.Sprintf(_tagMapInsertSQL, strings.Join(rowStrings, ","))
}

View File

@@ -0,0 +1,27 @@
package model
// Team .
type Team struct {
ID int64 `json:"id" form:"id"`
Title string `json:"title" form:"title" validate:"required"`
SubTitle string `json:"sub_title" form:"sub_title"`
ETitle string `json:"e_title" form:"e_title"`
CreateTime int64 `json:"create_time" form:"create_time"`
Area string `json:"area" form:"area"`
Logo string `json:"logo" form:"logo" validate:"required"`
UID int64 `json:"uid" form:"uid" gorm:"column:uid"`
Members string `json:"members" form:"members"`
Dic string `json:"dic" form:"dic"`
IsDeleted int `json:"is_deleted" form:"is_deleted"`
}
// TeamInfo .
type TeamInfo struct {
*Team
Games []*Game `json:"games"`
}
// TableName .
func (t Team) TableName() string {
return "es_teams"
}

View File

@@ -0,0 +1,33 @@
package model
import (
"fmt"
"strings"
)
const _teamMapInsertSQL = "INSERT INTO es_teams_map(tid,aid) VALUES %s"
// TeamMap .
type TeamMap struct {
ID int64 `json:"id"`
Tid int64 `json:"tid"`
Aid int64 `json:"aid"`
IsDeleted int `json:"is_deleted"`
}
// TableName es_teams_map.
func (t TeamMap) TableName() string {
return "es_teams_map"
}
// BatchAddTeamMapSQL .
func BatchAddTeamMapSQL(data []*TeamMap) string {
if len(data) == 0 {
return ""
}
var rowStrings []string
for _, v := range data {
rowStrings = append(rowStrings, fmt.Sprintf("(%d,%d)", v.Tid, v.Aid))
}
return fmt.Sprintf(_teamMapInsertSQL, strings.Join(rowStrings, ","))
}

View File

@@ -0,0 +1,71 @@
package model
import (
"fmt"
"go-common/library/xstr"
)
const _treeEditSQL = "UPDATE es_matchs_tree SET mid = CASE %s END WHERE id IN (%s)"
// TreeListParam .
type TreeListParam struct {
MadID int64 `form:"mad_id" validate:"required"`
}
// TreeEditParam .
type TreeEditParam struct {
MadID int64 `form:"mad_id" validate:"required"`
Nodes string `form:"nodes" validate:"required"`
}
// TreeDelParam .
type TreeDelParam struct {
MadID int64 `form:"mad_id" validate:"required"`
IDs string `form:"ids" validate:"required"`
}
// Tree .
type Tree struct {
ID int64 `json:"id" form:"id"`
MaID int64 `json:"ma_id,omitempty" form:"ma_id" validate:"required"`
MadID int64 `json:"mad_id,omitempty" form:"mad_id" validate:"required"`
Pid int64 `json:"pid" form:"pid"`
RootID int64 `json:"root_id" form:"root_id"`
GameRank int64 `json:"game_rank,omitempty" form:"game_rank" validate:"required"`
Mid int64 `json:"mid" form:"mid"`
IsDeleted int `json:"is_deleted,omitempty" form:"is_deleted"`
}
// TreeList .
type TreeList struct {
*Tree
*ContestInfo
}
// TreeDetailList .
type TreeDetailList struct {
Detail *MatchDetail `json:"detail"`
Tree [][]*TreeList `json:"tree"`
}
// TableName .
func (t Tree) TableName() string {
return "es_matchs_tree"
}
// BatchEditTreeSQL .
func BatchEditTreeSQL(nodes map[int64]int64) string {
if len(nodes) == 0 {
return ""
}
var (
caseStr string
ids []int64
)
for id, mid := range nodes {
caseStr = fmt.Sprintf("%s WHEN id = %d THEN %d", caseStr, id, mid)
ids = append(ids, id)
}
return fmt.Sprintf(_treeEditSQL, caseStr, xstr.JoinInts(ids))
}

View File

@@ -0,0 +1,33 @@
package model
import (
"fmt"
"strings"
)
const _yearMapInsertSQL = "INSERT INTO es_year_map(year,aid) VALUES %s"
// YearMap .
type YearMap struct {
ID int64 `json:"id"`
Year int64 `json:"year"`
Aid int64 `json:"aid"`
IsDeleted int `json:"is_deleted"`
}
// TableName es_year_map.
func (y YearMap) TableName() string {
return "es_year_map"
}
// BatchAddYearMapSQL .
func BatchAddYearMapSQL(data []*YearMap) string {
if len(data) == 0 {
return ""
}
var rowStrings []string
for _, v := range data {
rowStrings = append(rowStrings, fmt.Sprintf("(%d,%d)", v.Year, v.Aid))
}
return fmt.Sprintf(_yearMapInsertSQL, strings.Join(rowStrings, ","))
}

View File

@@ -0,0 +1,74 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
"go_test",
)
go_library(
name = "go_default_library",
srcs = [
"archive.go",
"contest.go",
"game.go",
"match.go",
"match_active.go",
"match_detail.go",
"season.go",
"service.go",
"tag.go",
"team.go",
"tree.go",
],
importpath = "go-common/app/admin/main/esports/service",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/admin/main/esports/conf:go_default_library",
"//app/admin/main/esports/dao:go_default_library",
"//app/admin/main/esports/model:go_default_library",
"//app/service/main/account/api:go_default_library",
"//app/service/main/archive/api:go_default_library",
"//library/ecode:go_default_library",
"//library/log:go_default_library",
"//library/net/metadata:go_default_library",
"//library/sync/errgroup:go_default_library",
"//library/xstr:go_default_library",
"//vendor/github.com/jinzhu/gorm:go_default_library",
"//vendor/github.com/pkg/errors:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)
go_test(
name = "go_default_test",
srcs = [
"archive_test.go",
"game_test.go",
"match_test.go",
"service_test.go",
"team_test.go",
],
embed = [":go_default_library"],
rundir = ".",
tags = ["automanaged"],
deps = [
"//app/admin/main/esports/conf:go_default_library",
"//app/admin/main/esports/model:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
],
)

View File

@@ -0,0 +1,826 @@
package service
import (
"context"
"go-common/app/admin/main/esports/model"
accwarden "go-common/app/service/main/account/api"
"go-common/library/ecode"
"go-common/library/log"
"go-common/library/net/metadata"
"github.com/jinzhu/gorm"
)
const (
_typeAdd = "add"
_typeEdit = "edit"
)
var _emptyArcList = make([]*model.ArcResult, 0)
// ArcList archive list.
func (s *Service) ArcList(c context.Context, arg *model.ArcListParam) (arcs []*model.ArcResult, total int, err error) {
var (
list []*model.SearchArc
gids, tids, matchIDs, teamIDs, mids []int64
games []*model.Game
tags []*model.Tag
matchs []*model.Match
teams []*model.Team
gameMap map[int64]*model.Game
tagMap map[int64]*model.Tag
matchMap map[int64]*model.Match
teamMap map[int64]*model.Team
infosReply *accwarden.InfosReply
ip = metadata.String(c, metadata.RemoteIP)
)
if list, total, err = s.dao.SearchArc(c, arg); err != nil {
return
}
if len(list) == 0 {
arcs = _emptyArcList
return
}
for _, arc := range list {
if len(arc.Gid) > 0 {
gids = append(gids, arc.Gid...)
}
if len(arc.Tags) > 0 {
tids = append(tids, arc.Tags...)
}
if len(arc.Matchs) > 0 {
matchIDs = append(matchIDs, arc.Matchs...)
}
if len(arc.Teams) > 0 {
teamIDs = append(teamIDs, arc.Teams...)
}
if arc.Mid > 0 {
mids = append(mids, arc.Mid)
}
}
if len(gids) > 0 {
if err = s.dao.DB.Model(&model.Game{}).Where("id IN (?)", unique(gids)).Find(&games).Error; err != nil {
log.Error("ArcList Game gids(%+v) error(%v)", gids, err)
return
}
if gl := len(games); gl > 0 {
gameMap = make(map[int64]*model.Game, gl)
for _, v := range games {
gameMap[v.ID] = v
}
}
}
if len(tids) > 0 {
if err = s.dao.DB.Model(&model.Tag{}).Where("id IN (?)", unique(tids)).Find(&tags).Error; err != nil {
log.Error("ArcList Tag tids(%+v) error(%v)", tids, err)
return
}
if tl := len(tags); tl > 0 {
tagMap = make(map[int64]*model.Tag, tl)
for _, v := range tags {
tagMap[v.ID] = v
}
}
}
if len(matchIDs) > 0 {
if err = s.dao.DB.Model(&model.Match{}).Where("id IN (?)", unique(matchIDs)).Find(&matchs).Error; err != nil {
log.Error("ArcList Match ids(%+v) error(%v)", tids, err)
return
}
if tl := len(matchs); tl > 0 {
matchMap = make(map[int64]*model.Match, tl)
for _, v := range matchs {
matchMap[v.ID] = v
}
}
}
if len(teamIDs) > 0 {
if err = s.dao.DB.Model(&model.Team{}).Where("id IN (?)", unique(teamIDs)).Find(&teams).Error; err != nil {
log.Error("ArcList Team ids(%+v) error(%v)", tids, err)
return
}
if tl := len(teams); tl > 0 {
teamMap = make(map[int64]*model.Team, tl)
for _, v := range teams {
teamMap[v.ID] = v
}
}
}
if len(mids) > 0 {
if infosReply, err = s.accClient.Infos3(c, &accwarden.MidsReq{Mids: unique(mids), RealIp: ip}); err != nil {
log.Error("账号Infos3:grpc错误", "s.accClient.Infos3 error(%v)", err)
return
}
}
for _, v := range list {
arcRes := &model.ArcResult{
Aid: v.Aid,
TypeID: v.TypeID,
Title: v.Title,
State: v.State,
Mid: v.Mid,
Years: v.Year,
}
if infosReply != nil && len(infosReply.Infos) > 0 {
if info, ok := infosReply.Infos[v.Mid]; ok && info != nil {
arcRes.Uname = info.Name
}
}
if len(gameMap) > 0 {
for _, gid := range v.Gid {
if game, ok := gameMap[gid]; ok {
arcRes.Games = append(arcRes.Games, game)
}
}
}
if len(tagMap) > 0 {
for _, tid := range v.Tags {
if tag, ok := tagMap[tid]; ok {
arcRes.Tags = append(arcRes.Tags, tag)
}
}
}
if len(matchMap) > 0 {
for _, tid := range v.Matchs {
if match, ok := matchMap[tid]; ok {
arcRes.Matchs = append(arcRes.Matchs, match)
}
}
}
if len(teamMap) > 0 {
for _, tid := range v.Teams {
if team, ok := teamMap[tid]; ok {
arcRes.Teams = append(arcRes.Teams, team)
}
}
}
if len(arcRes.Games) == 0 {
arcRes.Games = _emptyGameList
}
if len(arcRes.Tags) == 0 {
arcRes.Tags = _emptyTagList
}
if len(arcRes.Matchs) == 0 {
arcRes.Matchs = _emptyMatchList
}
if len(arcRes.Teams) == 0 {
arcRes.Teams = _emptyTeamList
}
arcs = append(arcs, arcRes)
}
return
}
// EditArc edit archive.
func (s *Service) EditArc(c context.Context, arg *model.ArcImportParam) (err error) {
var preArc *model.Arc
if err = s.dao.DB.Model(&model.Arc{}).Where("aid = ?", arg.Aid).Where("is_deleted=?", _notDeleted).First(&preArc).Error; err != nil {
log.Error("EditArc check aid Error (%v)", err)
return
}
var data *model.ArcRelation
if data, err = s.arcRelationChanges(c, arg, _typeEdit); err != nil {
return
}
tx := s.dao.DB.Begin()
if err = tx.Error; err != nil {
log.Error("s.dao.DB.Begin error(%v)", err)
return
}
if err = upArcRelation(tx, data); err != nil {
err = tx.Rollback().Error
return
}
err = tx.Commit().Error
return
}
// BatchAddArc batch add archive.
func (s *Service) BatchAddArc(c context.Context, param *model.ArcAddParam) (err error) {
var (
arcs []*model.Arc
upAddAids, addAids, changeAids []int64
)
if err = s.dao.DB.Model(&model.Arc{}).Where("aid IN (?)", param.Aids).Find(&arcs).Error; err != nil {
log.Error("BatchAddArc check aids Error (%v)", err)
return
}
if len(arcs) > 0 {
arcMap := make(map[int64]*model.Arc, len(param.Aids))
for _, v := range arcs {
arcMap[v.Aid] = v
}
for _, aid := range param.Aids {
if arc, ok := arcMap[aid]; ok {
if arc.IsDeleted == _deleted {
upAddAids = append(upAddAids, arc.ID)
changeAids = append(changeAids, arc.Aid)
}
} else {
addAids = append(addAids, aid)
changeAids = append(changeAids, aid)
}
}
} else {
addAids = param.Aids
changeAids = param.Aids
}
tx := s.dao.DB.Begin()
if err = tx.Error; err != nil {
log.Error("s.dao.DB.Begin error(%v)", err)
return
}
if len(addAids) > 0 {
if err = tx.Model(&model.Arc{}).Exec(model.ArcBatchAddSQL(addAids)).Error; err != nil {
log.Error("BatchAddArc Arc tx.Model Exec(%+v) error(%v)", addAids, err)
err = tx.Rollback().Error
return
}
}
if len(changeAids) > 0 {
arcRelation := new(model.ArcRelation)
for _, aid := range changeAids {
var data *model.ArcRelation
arg := &model.ArcImportParam{
Aid: aid,
Gids: param.Gids,
MatchIDs: param.MatchIDs,
TagIDs: param.TagIDs,
TeamIDs: param.TeamIDs,
Years: param.Years,
}
if data, err = s.arcRelationChanges(c, arg, _typeAdd); err != nil {
return
}
arcRelation.UpAddGids = append(arcRelation.UpAddGids, data.UpAddGids...)
arcRelation.UpDelGids = append(arcRelation.UpDelGids, data.UpDelGids...)
arcRelation.AddGids = append(arcRelation.AddGids, data.AddGids...)
arcRelation.UpAddMatchs = append(arcRelation.UpAddMatchs, data.UpAddMatchs...)
arcRelation.UpDelMatchs = append(arcRelation.UpDelMatchs, data.UpDelMatchs...)
arcRelation.AddMatchs = append(arcRelation.AddMatchs, data.AddMatchs...)
arcRelation.UpAddTags = append(arcRelation.UpAddTags, data.UpAddTags...)
arcRelation.UpDelTags = append(arcRelation.UpDelTags, data.UpDelTags...)
arcRelation.AddTags = append(arcRelation.AddTags, data.AddTags...)
arcRelation.UpAddTeams = append(arcRelation.UpAddTeams, data.UpAddTeams...)
arcRelation.UpDelTeams = append(arcRelation.UpDelTeams, data.UpDelTeams...)
arcRelation.AddTeams = append(arcRelation.AddTeams, data.AddTeams...)
arcRelation.UpAddYears = append(arcRelation.UpAddYears, data.UpAddYears...)
arcRelation.UpDelYears = append(arcRelation.UpDelYears, data.UpDelYears...)
arcRelation.AddYears = append(arcRelation.AddYears, data.AddYears...)
}
if err = upArcRelation(tx, arcRelation); err != nil {
err = tx.Rollback().Error
return
}
}
if len(upAddAids) > 0 {
if err = tx.Model(&model.Arc{}).Where("id IN (?)", upAddAids).Updates(map[string]interface{}{"is_deleted": _notDeleted}).Error; err != nil {
log.Error("BatchAddArc Save(%+v) error(%v)", upAddAids, err)
err = tx.Rollback().Error
return
}
}
err = tx.Commit().Error
return
}
// BatchEditArc batch add arc.
func (s *Service) BatchEditArc(c context.Context, param *model.ArcAddParam) (err error) {
var (
arcs []*model.Arc
changeAids []int64
)
if err = s.dao.DB.Model(&model.Arc{}).Where("aid IN (?)", param.Aids).Find(&arcs).Error; err != nil {
log.Error("BatchEditArc check aids Error (%v)", err)
return
}
if len(arcs) > 0 {
arcMap := make(map[int64]*model.Arc, len(param.Aids))
for _, v := range arcs {
arcMap[v.Aid] = v
}
for _, aid := range param.Aids {
if arc, ok := arcMap[aid]; ok {
if arc.IsDeleted == _notDeleted {
changeAids = append(changeAids, arc.Aid)
}
}
}
}
if len(changeAids) == 0 {
err = ecode.RequestErr
return
}
arcRelation := new(model.ArcRelation)
tx := s.dao.DB.Begin()
if err = tx.Error; err != nil {
log.Error("s.dao.DB.Begin error(%v)", err)
return
}
for _, aid := range changeAids {
var data *model.ArcRelation
arg := &model.ArcImportParam{
Aid: aid,
Gids: param.Gids,
MatchIDs: param.MatchIDs,
TagIDs: param.TagIDs,
TeamIDs: param.TeamIDs,
Years: param.Years,
}
if data, err = s.arcRelationChanges(c, arg, _typeEdit); err != nil {
return
}
arcRelation.UpAddGids = append(arcRelation.UpAddGids, data.UpAddGids...)
arcRelation.UpDelGids = append(arcRelation.UpDelGids, data.UpDelGids...)
arcRelation.AddGids = append(arcRelation.AddGids, data.AddGids...)
arcRelation.UpAddMatchs = append(arcRelation.UpAddMatchs, data.UpAddMatchs...)
arcRelation.UpDelMatchs = append(arcRelation.UpDelMatchs, data.UpDelMatchs...)
arcRelation.AddMatchs = append(arcRelation.AddMatchs, data.AddMatchs...)
arcRelation.UpAddTags = append(arcRelation.UpAddTags, data.UpAddTags...)
arcRelation.UpDelTags = append(arcRelation.UpDelTags, data.UpDelTags...)
arcRelation.AddTags = append(arcRelation.AddTags, data.AddTags...)
arcRelation.UpAddTeams = append(arcRelation.UpAddTeams, data.UpAddTeams...)
arcRelation.UpDelTeams = append(arcRelation.UpDelTeams, data.UpDelTeams...)
arcRelation.AddTeams = append(arcRelation.AddTeams, data.AddTeams...)
arcRelation.UpAddYears = append(arcRelation.UpAddYears, data.UpAddYears...)
arcRelation.UpDelYears = append(arcRelation.UpDelYears, data.UpDelYears...)
arcRelation.AddYears = append(arcRelation.AddYears, data.AddYears...)
}
if err = upArcRelation(tx, arcRelation); err != nil {
err = tx.Rollback().Error
return
}
err = tx.Commit().Error
return
}
// ArcImportCSV archive import.
func (s *Service) ArcImportCSV(c context.Context, list []*model.ArcImportParam) (err error) {
var (
aids, addAids, changeAids, saveAids []int64
arcs []*model.Arc
)
listMap := make(map[int64]*model.ArcImportParam, len(aids))
for _, v := range list {
aids = append(aids, v.Aid)
listMap[v.Aid] = v
}
if err = s.dao.DB.Model(&model.Arc{}).Where("aid IN (?)", aids).Find(&arcs).Error; err != nil {
log.Error("arcImport check aids Error (%v)", err)
return
}
if len(arcs) > 0 {
arcMap := make(map[int64]*model.Arc, len(aids))
for _, v := range arcs {
arcMap[v.Aid] = v
}
for _, aid := range aids {
if arc, ok := arcMap[aid]; ok {
if arc.IsDeleted == _deleted {
saveAids = append(saveAids, arc.ID)
changeAids = append(changeAids, arc.Aid)
}
} else {
addAids = append(addAids, aid)
changeAids = append(changeAids, aid)
}
}
} else {
addAids = aids
changeAids = aids
}
tx := s.dao.DB.Begin()
if err = tx.Error; err != nil {
log.Error("s.dao.DB.Begin error(%v)", err)
return
}
if len(addAids) > 0 {
if err = tx.Model(&model.Arc{}).Exec(model.ArcBatchAddSQL(addAids)).Error; err != nil {
log.Error("arcImport Arc tx.Model Exec(%+v) error(%v)", addAids, err)
err = tx.Rollback().Error
return
}
}
if len(saveAids) > 0 {
if err = tx.Model(&model.Arc{}).Where("id IN (?)", saveAids).Updates(map[string]interface{}{"is_deleted": _notDeleted}).Error; err != nil {
log.Error("arcImport Save(%+v) error(%v)", saveAids, err)
err = tx.Rollback().Error
return
}
}
if len(changeAids) > 0 {
arcRelation := new(model.ArcRelation)
for _, aid := range changeAids {
if arc, ok := listMap[aid]; ok {
var data *model.ArcRelation
arg := &model.ArcImportParam{
Aid: aid,
Gids: arc.Gids,
MatchIDs: arc.MatchIDs,
TagIDs: arc.TagIDs,
TeamIDs: arc.TeamIDs,
Years: arc.Years,
}
if data, err = s.arcRelationChanges(c, arg, _typeAdd); err != nil {
return
}
arcRelation.UpAddGids = append(arcRelation.UpAddGids, data.UpAddGids...)
arcRelation.UpDelGids = append(arcRelation.UpDelGids, data.UpDelGids...)
arcRelation.AddGids = append(arcRelation.AddGids, data.AddGids...)
arcRelation.UpAddMatchs = append(arcRelation.UpAddMatchs, data.UpAddMatchs...)
arcRelation.UpDelMatchs = append(arcRelation.UpDelMatchs, data.UpDelMatchs...)
arcRelation.AddMatchs = append(arcRelation.AddMatchs, data.AddMatchs...)
arcRelation.UpAddTags = append(arcRelation.UpAddTags, data.UpAddTags...)
arcRelation.UpDelTags = append(arcRelation.UpDelTags, data.UpDelTags...)
arcRelation.AddTags = append(arcRelation.AddTags, data.AddTags...)
arcRelation.UpAddTeams = append(arcRelation.UpAddTeams, data.UpAddTeams...)
arcRelation.UpDelTeams = append(arcRelation.UpDelTeams, data.UpDelTeams...)
arcRelation.AddTeams = append(arcRelation.AddTeams, data.AddTeams...)
arcRelation.UpAddYears = append(arcRelation.UpAddYears, data.UpAddYears...)
arcRelation.UpDelYears = append(arcRelation.UpDelYears, data.UpDelYears...)
arcRelation.AddYears = append(arcRelation.AddYears, data.AddYears...)
}
}
if err = upArcRelation(tx, arcRelation); err != nil {
err = tx.Rollback().Error
return
}
}
err = tx.Commit().Error
return
}
func (s *Service) arcRelationChanges(c context.Context, arg *model.ArcImportParam, typ string) (data *model.ArcRelation, err error) {
data = new(model.ArcRelation)
// add game map
if len(arg.Gids) > 0 {
var gidMaps []*model.GIDMap
if err = s.dao.DB.Model(&model.GIDMap{}).Where("oid=?", arg.Aid).Where("gid IN (?)", arg.Gids).Where("type=?", model.TypeArc).Find(&gidMaps).Error; err != nil {
log.Error("arcRelationChanges GIDMap s.dao.DB.Model MatchMap(%+v) error(%v)", arg.Gids, err)
return
}
if len(gidMaps) > 0 {
gidMap := make(map[int64]*model.GIDMap, len(gidMaps))
for _, v := range gidMaps {
gidMap[v.Gid] = v
}
for _, gid := range arg.Gids {
if gidItem, ok := gidMap[gid]; ok {
if gidItem.IsDeleted == _deleted {
data.UpAddGids = append(data.UpAddGids, gidItem.ID)
}
} else {
data.AddGids = append(data.AddGids, &model.GIDMap{Type: model.TypeArc, Gid: gid, Oid: arg.Aid})
}
}
} else {
for _, gid := range arg.Gids {
data.AddGids = append(data.AddGids, &model.GIDMap{Type: model.TypeArc, Gid: gid, Oid: arg.Aid})
}
}
}
// add match map
if len(arg.MatchIDs) > 0 {
var matchs []*model.MatchMap
if err = s.dao.DB.Model(&model.MatchMap{}).Where("aid=?", arg.Aid).Where("mid IN (?)", arg.MatchIDs).Find(&matchs).Error; err != nil {
log.Error("arcRelationChanges Arc s.dao.DB.Model MatchMap(%+v) error(%v)", arg.MatchIDs, err)
return
}
if len(matchs) > 0 {
matchMap := make(map[int64]*model.MatchMap, len(matchs))
for _, v := range matchs {
matchMap[v.Mid] = v
}
for _, mid := range arg.MatchIDs {
if match, ok := matchMap[mid]; ok {
if match.IsDeleted == _deleted {
data.UpAddMatchs = append(data.UpAddMatchs, match.ID)
}
} else {
data.AddMatchs = append(data.AddMatchs, &model.MatchMap{Mid: mid, Aid: arg.Aid})
}
}
} else {
for _, mid := range arg.MatchIDs {
data.AddMatchs = append(data.AddMatchs, &model.MatchMap{Mid: mid, Aid: arg.Aid})
}
}
}
// add tags map
if len(arg.TagIDs) > 0 {
var tags []*model.TagMap
if err = s.dao.DB.Model(&model.TagMap{}).Where("aid=?", arg.Aid).Where("tid IN (?)", arg.TagIDs).Find(&tags).Error; err != nil {
log.Error("arcRelationChanges Arc s.dao.DB.Model TagMap(%+v) error(%v)", arg.TagIDs, err)
return
}
if len(tags) > 0 {
tagMap := make(map[int64]*model.TagMap, len(tags))
for _, v := range tags {
tagMap[v.Tid] = v
}
for _, tid := range arg.TagIDs {
if tag, ok := tagMap[tid]; ok {
if tag.IsDeleted == _deleted {
data.UpAddTags = append(data.UpAddTags, tag.ID)
}
} else {
data.AddTags = append(data.AddTags, &model.TagMap{Tid: tid, Aid: arg.Aid})
}
}
} else {
for _, tid := range arg.TagIDs {
data.AddTags = append(data.AddTags, &model.TagMap{Tid: tid, Aid: arg.Aid})
}
}
}
// add teams map
if len(arg.TeamIDs) > 0 {
var teams []*model.TeamMap
if err = s.dao.DB.Model(&model.TeamMap{}).Where("aid=?", arg.Aid).Where("tid IN (?)", arg.TeamIDs).Find(&teams).Error; err != nil {
log.Error("arcRelationChanges Arc s.dao.DB.Model TeamMap(%+v) error(%v)", arg.TeamIDs, err)
return
}
if len(teams) > 0 {
teamMap := make(map[int64]*model.TeamMap, len(teams))
for _, v := range teams {
teamMap[v.Tid] = v
}
for _, teamID := range arg.TeamIDs {
if team, ok := teamMap[teamID]; ok {
if team.IsDeleted == _deleted {
data.UpAddTeams = append(data.UpAddTeams, team.ID)
}
} else {
data.AddTeams = append(data.AddTeams, &model.TeamMap{Tid: teamID, Aid: arg.Aid})
}
}
} else {
for _, teamID := range arg.TeamIDs {
data.AddTeams = append(data.AddTeams, &model.TeamMap{Tid: teamID, Aid: arg.Aid})
}
}
}
// add year map
if len(arg.Years) > 0 {
var yearMaps []*model.YearMap
if err = s.dao.DB.Model(&model.YearMap{}).Where("aid=?", arg.Aid).Where("year IN (?)", arg.Years).Find(&yearMaps).Error; err != nil {
log.Error("arcRelationChanges Arc s.dao.DB.Model YearMap(%+v) error(%v)", arg.Years, err)
return
}
if len(yearMaps) > 0 {
yearMap := make(map[int64]*model.YearMap, len(yearMaps))
for _, v := range yearMaps {
yearMap[v.Year] = v
}
for _, yearID := range arg.Years {
if year, ok := yearMap[yearID]; ok {
if year.IsDeleted == _deleted {
data.UpAddYears = append(data.UpAddYears, year.ID)
}
} else {
data.AddYears = append(data.AddYears, &model.YearMap{Year: yearID, Aid: arg.Aid})
}
}
} else {
for _, yearID := range arg.Years {
data.AddYears = append(data.AddYears, &model.YearMap{Year: yearID, Aid: arg.Aid})
}
}
}
if typ == _typeEdit {
var (
gidMaps []*model.GIDMap
matchs []*model.MatchMap
tags []*model.TagMap
teams []*model.TeamMap
years []*model.YearMap
)
// gid map
if err = s.dao.DB.Model(&model.GIDMap{}).Where("oid=?", arg.Aid).Where("type=?", model.TypeArc).Where("is_deleted=?", _notDeleted).Find(&gidMaps).Error; err != nil {
log.Error("arcRelationChanges GIDMap s.dao.DB.Model MatchMap(%+v) error(%v)", arg.Gids, err)
return
}
if len(gidMaps) > 0 {
if len(arg.Gids) > 0 {
gidMap := make(map[int64]int64, len(arg.Gids))
for _, gid := range arg.Gids {
gidMap[gid] = gid
}
for _, v := range gidMaps {
if _, ok := gidMap[v.Gid]; !ok {
data.UpDelGids = append(data.UpDelGids, v.ID)
}
}
} else {
for _, v := range gidMaps {
data.UpDelGids = append(data.UpDelGids, v.ID)
}
}
}
// match
if err = s.dao.DB.Model(&model.MatchMap{}).Where("aid=?", arg.Aid).Where("is_deleted=?", _notDeleted).Find(&matchs).Error; err != nil {
log.Error("arcRelationChanges Arc s.dao.DB.Model MatchMap(%+v) error(%v)", arg.MatchIDs, err)
return
}
if len(matchs) > 0 {
if len(arg.MatchIDs) > 0 {
matchIDMap := make(map[int64]int64, len(arg.MatchIDs))
for _, id := range arg.MatchIDs {
matchIDMap[id] = id
}
for _, v := range matchs {
if _, ok := matchIDMap[v.Mid]; !ok {
data.UpDelMatchs = append(data.UpDelMatchs, v.ID)
}
}
} else {
for _, v := range matchs {
data.UpDelMatchs = append(data.UpDelMatchs, v.ID)
}
}
}
// tag
if err = s.dao.DB.Model(&model.TagMap{}).Where("aid=?", arg.Aid).Where("is_deleted=?", _notDeleted).Find(&tags).Error; err != nil {
log.Error("arcRelationChanges Arc s.dao.DB.Model TagMap(%+v) error(%v)", arg.TagIDs, err)
return
}
if len(tags) > 0 {
if len(arg.TagIDs) > 0 {
tagIDMap := make(map[int64]int64, len(arg.TagIDs))
for _, id := range arg.TagIDs {
tagIDMap[id] = id
}
for _, v := range tags {
if _, ok := tagIDMap[v.Tid]; !ok {
data.UpDelTags = append(data.UpDelTags, v.ID)
}
}
} else {
for _, v := range tags {
data.UpDelTags = append(data.UpDelTags, v.ID)
}
}
}
// team
if err = s.dao.DB.Model(&model.TeamMap{}).Where("aid=?", arg.Aid).Where("is_deleted=?", _notDeleted).Find(&teams).Error; err != nil {
log.Error("arcRelationChanges Arc s.dao.DB.Model MatchMap(%+v) error(%v)", arg.MatchIDs, err)
return
}
if len(teams) > 0 {
if len(arg.TeamIDs) > 0 {
teamIDMap := make(map[int64]int64, len(arg.TeamIDs))
for _, id := range arg.TeamIDs {
teamIDMap[id] = id
}
for _, v := range teams {
if _, ok := teamIDMap[v.Tid]; !ok {
data.UpDelTeams = append(data.UpDelTeams, v.ID)
}
}
} else {
for _, v := range teams {
data.UpDelTeams = append(data.UpDelTeams, v.ID)
}
}
}
// year
if err = s.dao.DB.Model(&model.YearMap{}).Where("aid=?", arg.Aid).Where("is_deleted=?", _notDeleted).Find(&years).Error; err != nil {
log.Error("arcRelationChanges Arc s.dao.DB.Model MatchMap(%+v) error(%v)", arg.MatchIDs, err)
return
}
if len(years) > 0 {
if len(arg.Years) > 0 {
yearMap := make(map[int64]int64, len(arg.Years))
for _, id := range arg.Years {
yearMap[id] = id
}
for _, v := range years {
if _, ok := yearMap[v.Year]; !ok {
data.UpDelYears = append(data.UpDelYears, v.ID)
}
}
} else {
for _, v := range years {
data.UpDelYears = append(data.UpDelYears, v.ID)
}
}
}
}
return
}
// BatchDelArc batch del archive.
func (s *Service) BatchDelArc(c context.Context, aids []int64) (err error) {
tx := s.dao.DB.Begin()
if err = tx.Error; err != nil {
log.Error("s.dao.DB.Begin error(%v)", err)
return
}
if err = tx.Model(&model.Arc{}).Where("aid IN (?)", aids).Update(map[string]int{"is_deleted": _deleted}).Error; err != nil {
log.Error("BatchDelArc Arc s.dao.DB.Model Update(%+v) error(%v)", aids, err)
err = tx.Rollback().Error
return
}
if err = tx.Model(&model.GIDMap{}).Where("oid IN (?)", aids).Update(map[string]int{"is_deleted": _deleted}).Error; err != nil {
log.Error("BatchDelArc GIDMap s.dao.DB.Model Update(%+v) error(%v)", aids, err)
err = tx.Rollback().Error
return
}
err = tx.Commit().Error
return
}
func upArcRelation(tx *gorm.DB, data *model.ArcRelation) (err error) {
if len(data.AddGids) > 0 {
if err = tx.Model(&model.GIDMap{}).Exec(model.GidBatchAddSQL(data.AddGids)).Error; err != nil {
log.Error("upArcRelation GIDMap tx.Model Exec(%+v) error(%v)", data.AddGids, err)
return
}
}
if len(data.UpAddGids) > 0 {
if err = tx.Model(&model.GIDMap{}).Where("id IN (?)", data.UpAddGids).Updates(map[string]interface{}{"is_deleted": _notDeleted}).Error; err != nil {
log.Error("upArcRelation Tag tx.Model Updates(%+v) error(%v)", data.UpAddGids, err)
return
}
}
if len(data.UpDelGids) > 0 {
if err = tx.Model(&model.GIDMap{}).Where("id IN (?)", data.UpDelGids).Updates(map[string]interface{}{"is_deleted": _deleted}).Error; err != nil {
log.Error("upArcRelation Tag tx.Model Updates(%+v) error(%v)", data.UpDelGids, err)
return
}
}
if len(data.AddMatchs) > 0 {
if err = tx.Model(&model.MatchMap{}).Exec(model.BatchAddMachMapSQL(data.AddMatchs)).Error; err != nil {
log.Error("upArcRelation Match tx.Model Exec(%+v) error(%v)", data.AddMatchs, err)
return
}
}
if len(data.UpAddMatchs) > 0 {
if err = tx.Model(&model.MatchMap{}).Where("id IN (?)", data.UpAddMatchs).Updates(map[string]interface{}{"is_deleted": _notDeleted}).Error; err != nil {
log.Error("upArcRelation Match tx.Model Updates(%+v) error(%v)", data.UpAddMatchs, err)
return
}
}
if len(data.UpDelMatchs) > 0 {
if err = tx.Model(&model.MatchMap{}).Where("id IN (?)", data.UpDelMatchs).Updates(map[string]interface{}{"is_deleted": _deleted}).Error; err != nil {
log.Error("upArcRelation Match tx.Model Updates(%+v) error(%v)", data.UpDelMatchs, err)
return
}
}
if len(data.AddTags) > 0 {
if err = tx.Model(&model.TagMap{}).Exec(model.BatchAddTagMapSQL(data.AddTags)).Error; err != nil {
log.Error("upArcRelation Tag tx.Model Exec(%+v) error(%v)", data.AddTags, err)
return
}
}
if len(data.UpAddTags) > 0 {
if err = tx.Model(&model.TagMap{}).Where("id IN (?)", data.UpAddTags).Updates(map[string]interface{}{"is_deleted": _notDeleted}).Error; err != nil {
log.Error("upArcRelation Tag tx.Model Updates(%+v) error(%v)", data.UpAddTags, err)
return
}
}
if len(data.UpDelTags) > 0 {
if err = tx.Model(&model.TagMap{}).Where("id IN (?)", data.UpDelTags).Updates(map[string]interface{}{"is_deleted": _deleted}).Error; err != nil {
log.Error("upArcRelation Tag tx.Model Updates(%+v) error(%v)", data.UpDelTags, err)
return
}
}
if len(data.AddTeams) > 0 {
if err = tx.Model(&model.TeamMap{}).Exec(model.BatchAddTeamMapSQL(data.AddTeams)).Error; err != nil {
log.Error("upArcRelation Team tx.Model Exec(%+v) error(%v)", data.AddTeams, err)
return
}
}
if len(data.UpAddTeams) > 0 {
if err = tx.Model(&model.TeamMap{}).Where("id IN (?)", data.UpAddTeams).Updates(map[string]interface{}{"is_deleted": _notDeleted}).Error; err != nil {
log.Error("upArcRelation Team tx.Model Updates(%+v) error(%v)", data.UpAddTags, err)
return
}
}
if len(data.UpDelTeams) > 0 {
if err = tx.Model(&model.TeamMap{}).Where("id IN (?)", data.UpDelTeams).Updates(map[string]interface{}{"is_deleted": _deleted}).Error; err != nil {
log.Error("upArcRelation Team tx.Model Updates(%+v) error(%v)", data.UpDelTags, err)
return
}
}
if len(data.AddYears) > 0 {
if err = tx.Model(&model.YearMap{}).Exec(model.BatchAddYearMapSQL(data.AddYears)).Error; err != nil {
log.Error("upArcRelation Year tx.Model Exec(%+v) error(%v)", data.AddYears, err)
return
}
}
if len(data.UpAddYears) > 0 {
if err = tx.Model(&model.YearMap{}).Where("id IN (?)", data.UpAddYears).Updates(map[string]interface{}{"is_deleted": _notDeleted}).Error; err != nil {
log.Error("upArcRelation Year tx.Model Updates(%+v) error(%v)", data.UpAddTags, err)
return
}
}
if len(data.UpDelYears) > 0 {
if err = tx.Model(&model.YearMap{}).Where("id IN (?)", data.UpDelYears).Updates(map[string]interface{}{"is_deleted": _deleted}).Error; err != nil {
log.Error("upArcRelation Year tx.Model Updates(%+v) error(%v)", data.UpDelTags, err)
return
}
}
return
}

View File

@@ -0,0 +1,49 @@
package service
import (
"context"
"testing"
"go-common/app/admin/main/esports/model"
. "github.com/smartystreets/goconvey/convey"
)
func TestService_arcRelationChanges(t *testing.T) {
Convey("test arc relation", t, WithService(func(s *Service) {
arg := &model.ArcImportParam{
Aid: 2147483647,
Gids: []int64{2, 3, 5},
MatchIDs: []int64{91},
TeamIDs: []int64{2, 3, 4},
TagIDs: []int64{2, 4},
Years: []int64{1986, 2003},
}
data, err := s.arcRelationChanges(context.Background(), arg, _typeEdit)
So(err, ShouldBeNil)
for _, v := range data.AddTeams {
Printf("Add %+v \n", v)
}
for _, v := range data.UpAddTeams {
Printf("upAdd %+v \n", v)
}
for _, v := range data.UpDelTeams {
Printf("upDel %+v \n", v)
}
}))
}
func TestService_BatchAddArc(t *testing.T) {
Convey("test batch add arc", t, WithService(func(s *Service) {
arg := &model.ArcAddParam{
Aids: []int64{44444444, 55555555},
Gids: []int64{6},
MatchIDs: []int64{31},
TeamIDs: []int64{3, 2},
TagIDs: []int64{3},
Years: []int64{2017, 2018},
}
err := s.BatchAddArc(context.Background(), arg)
So(err, ShouldBeNil)
}))
}

View File

@@ -0,0 +1,452 @@
package service
import (
"context"
"encoding/json"
"go-common/app/admin/main/esports/model"
"go-common/library/ecode"
"go-common/library/log"
)
var (
_emptyContestList = make([]*model.Contest, 0)
_emptyContestData = make([]*model.ContestData, 0)
)
const (
_sortDesc = 1
_sortASC = 2
_ReplyTypeContest = "27"
)
// ContestInfo .
func (s *Service) ContestInfo(c context.Context, id int64) (data *model.ContestInfo, err error) {
var (
gameMap map[int64][]*model.Game
teamMap map[int64]*model.Team
teamIDs []int64
hasTeam bool
)
contest := new(model.Contest)
if err = s.dao.DB.Where("id=?", id).First(&contest).Error; err != nil {
log.Error("ContestInfo Error (%v)", err)
return
}
if gameMap, err = s.gameList(c, model.TypeContest, []int64{id}); err != nil {
return
}
if contest.HomeID > 0 {
teamIDs = append(teamIDs, contest.HomeID)
}
if contest.AwayID > 0 {
teamIDs = append(teamIDs, contest.AwayID)
}
if ids := unique(teamIDs); len(ids) > 0 {
var teams []*model.Team
if err = s.dao.DB.Model(&model.Team{}).Where("id IN (?)", ids).Find(&teams).Error; err != nil {
log.Error("ContestList team Error (%v)", err)
return
}
if len(teams) > 0 {
hasTeam = true
}
teamMap = make(map[int64]*model.Team, len(teams))
for _, v := range teams {
teamMap[v.ID] = v
}
}
data = &model.ContestInfo{Contest: contest}
if len(gameMap) > 0 {
if games, ok := gameMap[id]; ok {
data.Games = games
}
}
if len(data.Games) == 0 {
data.Games = _emptyGameList
}
if hasTeam {
if team, ok := teamMap[contest.HomeID]; ok {
data.HomeName = team.Title
}
if team, ok := teamMap[contest.AwayID]; ok {
data.AwayName = team.Title
}
}
var cDatas []*model.ContestData
if err = s.dao.DB.Model(&model.ContestData{}).Where(map[string]interface{}{"is_deleted": _notDeleted}).Where("cid IN (?)", []int64{id}).Find(&cDatas).Error; err != nil {
log.Error("ContestInfo Find ContestData Error (%v)", err)
return
}
data.Data = cDatas
return
}
// ContestList .
func (s *Service) ContestList(c context.Context, mid, sid, pn, ps, srt int64) (list []*model.ContestInfo, count int64, err error) {
var contests []*model.Contest
source := s.dao.DB.Model(&model.Contest{})
if srt == _sortDesc {
source = source.Order("stime DESC")
} else if srt == _sortASC {
source = source.Order("stime ASC")
}
if mid > 0 {
source = source.Where("mid=?", mid)
}
if sid > 0 {
source = source.Where("sid=?", sid)
}
source.Count(&count)
if err = source.Offset((pn - 1) * ps).Limit(ps).Find(&contests).Error; err != nil {
log.Error("ContestList Error (%v)", err)
return
}
if len(contests) == 0 {
contests = _emptyContestList
return
}
if list, err = s.contestInfos(c, contests, true); err != nil {
log.Error("s.contestInfos Error (%v)", err)
}
return
}
func (s *Service) contestInfos(c context.Context, contests []*model.Contest, useGame bool) (list []*model.ContestInfo, err error) {
var (
conIDs, teamIDs []int64
gameMap map[int64][]*model.Game
teamMap map[int64]*model.Team
cDataMap map[int64][]*model.ContestData
hasGame, hasTeam, hasCData bool
)
for _, v := range contests {
conIDs = append(conIDs, v.ID)
if v.HomeID > 0 {
teamIDs = append(teamIDs, v.HomeID)
}
if v.AwayID > 0 {
teamIDs = append(teamIDs, v.AwayID)
}
if v.SuccessTeam > 0 {
teamIDs = append(teamIDs, v.SuccessTeam)
}
}
if useGame {
if gameMap, err = s.gameList(c, model.TypeContest, conIDs); err != nil {
return
} else if len(gameMap) > 0 {
hasGame = true
}
}
if ids := unique(teamIDs); len(ids) > 0 {
var teams []*model.Team
if err = s.dao.DB.Model(&model.Team{}).Where("id IN (?)", ids).Find(&teams).Error; err != nil {
log.Error("ContestList team Error (%v)", err)
return
}
if len(teams) > 0 {
hasTeam = true
}
teamMap = make(map[int64]*model.Team, len(teams))
for _, v := range teams {
teamMap[v.ID] = v
}
}
if len(conIDs) > 0 {
var cDatas []*model.ContestData
if err = s.dao.DB.Model(&model.ContestData{}).Where(map[string]interface{}{"is_deleted": _notDeleted}).Where("cid IN (?)", conIDs).Find(&cDatas).Error; err != nil {
log.Error("ContestList Find ContestData Error (%v)", err)
return
}
if len(cDatas) > 0 {
hasCData = true
}
cDataMap = make(map[int64][]*model.ContestData, len(cDatas))
for _, v := range cDatas {
cDataMap[v.CID] = append(cDataMap[v.CID], v)
}
}
for _, v := range contests {
contest := &model.ContestInfo{Contest: v}
if hasGame {
if games, ok := gameMap[v.ID]; ok {
contest.Games = games
}
}
if len(contest.Games) == 0 {
contest.Games = _emptyGameList
}
if hasTeam {
if team, ok := teamMap[v.HomeID]; ok {
contest.HomeName = team.Title
}
if team, ok := teamMap[v.AwayID]; ok {
contest.AwayName = team.Title
}
if team, ok := teamMap[v.SuccessTeam]; ok {
contest.SuccessName = team.Title
}
}
if hasCData {
if cData, ok := cDataMap[v.ID]; ok {
contest.Data = cData
}
} else {
contest.Data = _emptyContestData
}
list = append(list, contest)
}
return
}
// AddContest .
func (s *Service) AddContest(c context.Context, param *model.Contest, gids []int64) (err error) {
// TODO check name exist
// check sid
season := new(model.Season)
if err = s.dao.DB.Where("id=?", param.Sid).Where("status=?", _statusOn).First(&season).Error; err != nil {
log.Error("AddContest s.dao.DB.Where id(%d) error(%d)", param.Sid, err)
return
}
// check mid
match := new(model.Match)
if err = s.dao.DB.Where("id=?", param.Mid).Where("status=?", _statusOn).First(&match).Error; err != nil {
log.Error("AddContest s.dao.DB.Where id(%d) error(%d)", param.Mid, err)
return
}
// check game idsEsportsCDataErr
var (
games []*model.Game
gidMaps []*model.GIDMap
contestData []*model.ContestData
)
if param.DataType == 0 {
param.Data = ""
param.MatchID = 0
}
if param.Data != "" {
if err = json.Unmarshal([]byte(param.Data), &contestData); err != nil {
err = ecode.EsportsContestDataErr
return
}
}
if err = s.dao.DB.Model(&model.Game{}).Where("status=?", _statusOn).Where("id IN (?)", gids).Find(&games).Error; err != nil {
log.Error("AddContest check game ids Error (%v)", err)
return
}
if len(games) == 0 {
log.Error("AddContest games(%v) not found", gids)
err = ecode.RequestErr
return
}
tx := s.dao.DB.Begin()
if err = tx.Model(&model.Contest{}).Create(param).Error; err != nil {
log.Error("AddContest tx.Model Create(%+v) error(%v)", param, err)
err = tx.Rollback().Error
return
}
for _, v := range games {
gidMaps = append(gidMaps, &model.GIDMap{Type: model.TypeContest, Oid: param.ID, Gid: v.ID})
}
if err = tx.Model(&model.GIDMap{}).Exec(model.GidBatchAddSQL(gidMaps)).Error; err != nil {
log.Error("AddContest tx.Model Create(%+v) error(%v)", param, err)
err = tx.Rollback().Error
return
}
if len(contestData) > 0 {
if err = tx.Model(&model.Module{}).Exec(model.BatchAddCDataSQL(param.ID, contestData)).Error; err != nil {
log.Error("AddContest Module tx.Model Create(%+v) error(%v)", param, err)
err = tx.Rollback().Error
return
}
}
if err = tx.Commit().Error; err != nil {
return
}
// register reply
if err = s.dao.RegReply(c, param.ID, param.Adid, _ReplyTypeContest); err != nil {
err = nil
}
return
}
// EditContest .
func (s *Service) EditContest(c context.Context, param *model.Contest, gids []int64) (err error) {
var (
games []*model.Game
preGidMaps, addGidMaps []*model.GIDMap
upGidMapAdd, upGidMapDel []int64
)
// TODO check name exist
// check sid
season := new(model.Season)
if err = s.dao.DB.Where("id=?", param.Sid).Where("status=?", _statusOn).First(&season).Error; err != nil {
log.Error("EditContest s.dao.DB.Where id(%d) error(%d)", param.Sid, err)
return
}
// check mid
match := new(model.Match)
if err = s.dao.DB.Where("id=?", param.Mid).Where("status=?", _statusOn).First(&match).Error; err != nil {
log.Error("EditContest s.dao.DB.Where id(%d) error(%d)", param.Mid, err)
return
}
preData := new(model.Contest)
if err = s.dao.DB.Where("id=?", param.ID).First(&preData).Error; err != nil {
log.Error("EditContest s.dao.DB.Where id(%d) error(%d)", param.ID, err)
return
}
if err = s.dao.DB.Model(&model.Game{}).Where("status=?", _statusOn).Where("id IN (?)", gids).Find(&games).Error; err != nil {
log.Error("EditContest check game ids Error (%v)", err)
return
}
if len(games) == 0 {
log.Error("EditContest games(%v) not found", gids)
err = ecode.RequestErr
return
}
if err = s.dao.DB.Model(&model.GIDMap{}).Where("oid=?", param.ID).Where("type=?", model.TypeContest).Find(&preGidMaps).Error; err != nil {
log.Error("EditContest games(%v) not found", gids)
return
}
var (
newCData []*model.ContestData
)
if param.DataType == 0 {
param.Data = ""
param.MatchID = 0
}
if param.Data != "" {
if err = json.Unmarshal([]byte(param.Data), &newCData); err != nil {
err = ecode.EsportsContestDataErr
return
}
}
gidsMap := make(map[int64]int64, len(gids))
preGidsMap := make(map[int64]int64, len(preGidMaps))
for _, v := range gids {
gidsMap[v] = v
}
for _, v := range preGidMaps {
preGidsMap[v.Gid] = v.Gid
if _, ok := gidsMap[v.Gid]; ok {
if v.IsDeleted == 1 {
upGidMapAdd = append(upGidMapAdd, v.ID)
}
} else {
upGidMapDel = append(upGidMapDel, v.ID)
}
}
for _, gid := range gids {
if _, ok := preGidsMap[gid]; !ok {
addGidMaps = append(addGidMaps, &model.GIDMap{Type: model.TypeContest, Oid: param.ID, Gid: gid})
}
}
tx := s.dao.DB.Begin()
if err = tx.Error; err != nil {
log.Error("s.dao.DB.Begin error(%v)", err)
return
}
if err = tx.Model(&model.Contest{}).Save(param).Error; err != nil {
log.Error("EditContest Update(%+v) error(%v)", param, err)
err = tx.Rollback().Error
return
}
if len(upGidMapAdd) > 0 {
if err = tx.Model(&model.GIDMap{}).Where("id IN (?)", upGidMapAdd).Updates(map[string]interface{}{"is_deleted": _notDeleted}).Error; err != nil {
log.Error("EditContest GIDMap Add(%+v) error(%v)", upGidMapAdd, err)
err = tx.Rollback().Error
return
}
}
if len(upGidMapDel) > 0 {
if err = tx.Model(&model.GIDMap{}).Where("id IN (?)", upGidMapDel).Updates(map[string]interface{}{"is_deleted": _deleted}).Error; err != nil {
log.Error("EditContest GIDMap Del(%+v) error(%v)", upGidMapDel, err)
err = tx.Rollback().Error
return
}
}
if len(addGidMaps) > 0 {
if err = tx.Model(&model.GIDMap{}).Exec(model.GidBatchAddSQL(addGidMaps)).Error; err != nil {
log.Error("EditContest GIDMap Create(%+v) error(%v)", addGidMaps, err)
err = tx.Rollback().Error
return
}
}
var (
mapOldCData, mapNewCData map[int64]*model.ContestData
upCData, addCData, oldCData []*model.ContestData
delCData []int64
)
if len(newCData) > 0 {
// check module
if err = s.dao.DB.Model(&model.ContestData{}).Where("cid=?", param.ID).Where("is_deleted=?", _notDeleted).Find(&oldCData).Error; err != nil {
log.Error("EditContest s.dao.DB.Model Find (%+v) error(%v)", param.ID, err)
return
}
mapOldCData = make(map[int64]*model.ContestData, len(oldCData))
for _, v := range oldCData {
mapOldCData[v.ID] = v
}
//新数据在老数据中 更新老数据。新的数据不在老数据 添加新数据
for _, cData := range newCData {
if _, ok := mapOldCData[cData.ID]; ok {
upCData = append(upCData, cData)
} else {
addCData = append(addCData, cData)
}
}
mapNewCData = make(map[int64]*model.ContestData, len(oldCData))
for _, v := range newCData {
mapNewCData[v.ID] = v
}
//老数据在新中 上面已经处理。老数据不在新数据中 删除老数据
for _, cData := range oldCData {
if _, ok := mapNewCData[cData.ID]; !ok {
delCData = append(delCData, cData.ID)
}
}
if len(upCData) > 0 {
if err = tx.Model(&model.ContestData{}).Exec(model.BatchEditCDataSQL(upCData)).Error; err != nil {
log.Error("EditContest s.dao.DB.Model tx.Model Exec(%+v) error(%v)", upCData, err)
err = tx.Rollback().Error
return
}
}
if len(delCData) > 0 {
if err = tx.Model(&model.ContestData{}).Where("id IN (?)", delCData).Updates(map[string]interface{}{"is_deleted": _deleted}).Error; err != nil {
log.Error("EditContest s.dao.DB.Model Updates(%+v) error(%v)", delCData, err)
err = tx.Rollback().Error
return
}
}
if len(addCData) > 0 {
if err = tx.Model(&model.ContestData{}).Exec(model.BatchAddCDataSQL(param.ID, addCData)).Error; err != nil {
log.Error("EditContest s.dao.DB.Model Create(%+v) error(%v)", addCData, err)
err = tx.Rollback().Error
return
}
}
} else {
if err = tx.Model(&model.ContestData{}).Where("cid = ?", param.ID).Updates(map[string]interface{}{"is_deleted": _deleted}).Error; err != nil {
log.Error("EditContest s.dao.DB.Model Updates(%+v) error(%v)", param.ID, err)
err = tx.Rollback().Error
return
}
}
err = tx.Commit().Error
return
}
// ForbidContest .
func (s *Service) ForbidContest(c context.Context, id int64, state int) (err error) {
preContest := new(model.Contest)
if err = s.dao.DB.Where("id=?", id).First(&preContest).Error; err != nil {
log.Error("ContestForbid s.dao.DB.Where id(%d) error(%d)", id, err)
return
}
if err = s.dao.DB.Model(&model.Contest{}).Where("id=?", id).Update(map[string]int{"status": state}).Error; err != nil {
log.Error("ContestForbid s.dao.DB.Model error(%v)", err)
}
return
}

View File

@@ -0,0 +1,129 @@
package service
import (
"context"
"fmt"
"go-common/app/admin/main/esports/model"
"go-common/library/log"
)
var _emptyGameList = make([]*model.Game, 0)
// GameInfo .
func (s *Service) GameInfo(c context.Context, id int64) (game *model.Game, err error) {
game = new(model.Game)
if err = s.dao.DB.Where("id=?", id).First(&game).Error; err != nil {
log.Error("GameInfo Error (%v)", err)
}
return
}
// GameList .
func (s *Service) GameList(c context.Context, pn, ps int64, title string) (list []*model.Game, count int64, err error) {
source := s.dao.DB.Model(&model.Game{})
if title != "" {
likeStr := fmt.Sprintf("%%%s%%", title)
source = source.Where("title like ?", likeStr)
}
source.Count(&count)
if err = source.Offset((pn - 1) * ps).Limit(ps).Find(&list).Error; err != nil {
log.Error("GameList Error (%v)", err)
}
return
}
// AddGame .
func (s *Service) AddGame(c context.Context, param *model.Game) (err error) {
// TODO check name exist
if err = s.dao.DB.Model(&model.Game{}).Create(param).Error; err != nil {
log.Error("AddGame s.dao.DB.Model Create(%+v) error(%v)", param, err)
}
return
}
// EditGame .
func (s *Service) EditGame(c context.Context, param *model.Game) (err error) {
preGame := new(model.Game)
if err = s.dao.DB.Where("id=?", param.ID).First(&preGame).Error; err != nil {
log.Error("EditGame s.dao.DB.Where id(%d) error(%d)", param.ID, err)
return
}
if err = s.dao.DB.Model(&model.Game{}).Update(param).Error; err != nil {
log.Error("EditGame s.dao.DB.Model Update(%+v) error(%v)", param, err)
}
return
}
// ForbidGame .
func (s *Service) ForbidGame(c context.Context, id int64, state int) (err error) {
preGame := new(model.Game)
if err = s.dao.DB.Where("id=?", id).First(&preGame).Error; err != nil {
log.Error("GameForbid s.dao.DB.Where id(%d) error(%d)", id, err)
return
}
if err = s.dao.DB.Model(&model.Game{}).Where("id=?", id).Update(map[string]int{"status": state}).Error; err != nil {
log.Error("GameForbid s.dao.DB.Model error(%v)", err)
}
return
}
// gameList return game info map with oid key.
func (s *Service) gameList(c context.Context, typ int, oids []int64) (list map[int64][]*model.Game, err error) {
var (
gidMaps []*model.GIDMap
gids []int64
games []*model.Game
)
if len(oids) == 0 {
return
}
if err = s.dao.DB.Model(&model.GIDMap{}).Where("is_deleted=?", _notDeleted).Where("type=?", typ).Where("oid IN(?)", oids).Find(&gidMaps).Error; err != nil {
log.Error("gameList gidMap Error (%v)", err)
return
}
if len(gidMaps) == 0 {
return
}
gidMap := make(map[int64]int64, len(gidMaps))
oidGidMap := make(map[int64][]int64, len(gidMaps))
for _, v := range gidMaps {
oidGidMap[v.Oid] = append(oidGidMap[v.Oid], v.Gid)
if _, ok := gidMap[v.Gid]; ok {
continue
}
gids = append(gids, v.Gid)
gidMap[v.Gid] = v.Gid
}
if err = s.dao.DB.Model(&model.Game{}).Where("status=?", _statusOn).Where("id IN(?)", gids).Find(&games).Error; err != nil {
log.Error("gameList games Error (%v)", err)
return
}
if len(games) == 0 {
return
}
gameMap := make(map[int64]*model.Game, len(games))
for _, v := range games {
gameMap[v.ID] = v
}
list = make(map[int64][]*model.Game, len(oids))
for _, oid := range oids {
if ids, ok := oidGidMap[oid]; ok {
for _, id := range ids {
if game, ok := gameMap[id]; ok {
list[oid] = append(list[oid], game)
}
}
}
}
return
}
// Types return data page game types.
func (s *Service) Types(c context.Context) (list map[int64]string, err error) {
list = make(map[int64]string, len(s.c.GameTypes))
for _, tp := range s.c.GameTypes {
list[tp.ID] = tp.Name
}
return
}

View File

@@ -0,0 +1,21 @@
package service
import (
"context"
"encoding/json"
"testing"
"go-common/app/admin/main/esports/model"
. "github.com/smartystreets/goconvey/convey"
)
func TestService_GameList(t *testing.T) {
Convey("test game list", t, WithService(func(s *Service) {
oids := []int64{21, 16}
data, err := s.gameList(context.Background(), model.TypeTeam, oids)
So(err, ShouldBeNil)
bs, _ := json.Marshal(data)
Printf(string(bs))
}))
}

View File

@@ -0,0 +1,198 @@
package service
import (
"context"
"fmt"
"go-common/app/admin/main/esports/model"
"go-common/library/ecode"
"go-common/library/log"
)
var _emptyMatchList = make([]*model.Match, 0)
// MatchInfo .
func (s *Service) MatchInfo(c context.Context, id int64) (data *model.MatchInfo, err error) {
var gameMap map[int64][]*model.Game
match := new(model.Match)
if err = s.dao.DB.Where("id=?", id).First(&match).Error; err != nil {
log.Error("MatchInfo Error (%v)", err)
return
}
if gameMap, err = s.gameList(c, model.TypeMatch, []int64{id}); err != nil {
return
}
if games, ok := gameMap[id]; ok {
data = &model.MatchInfo{Match: match, Games: games}
} else {
data = &model.MatchInfo{Match: match, Games: _emptyGameList}
}
return
}
// MatchList .
func (s *Service) MatchList(c context.Context, pn, ps int64, title string) (list []*model.MatchInfo, count int64, err error) {
var (
matchs []*model.Match
matchIDs []int64
gameMap map[int64][]*model.Game
)
source := s.dao.DB.Model(&model.Match{})
if title != "" {
likeStr := fmt.Sprintf("%%%s%%", title)
source = source.Where("title like ?", likeStr)
}
source.Count(&count)
if err = source.Offset((pn - 1) * ps).Order("rank DESC,id ASC").Limit(ps).Find(&matchs).Error; err != nil {
log.Error("MatchList Error (%v)", err)
return
}
if len(matchs) == 0 {
return
}
for _, v := range matchs {
matchIDs = append(matchIDs, v.ID)
}
if gameMap, err = s.gameList(c, model.TypeMatch, matchIDs); err != nil {
return
}
for _, v := range matchs {
if games, ok := gameMap[v.ID]; ok {
list = append(list, &model.MatchInfo{Match: v, Games: games})
} else {
list = append(list, &model.MatchInfo{Match: v, Games: _emptyGameList})
}
}
return
}
// AddMatch .
func (s *Service) AddMatch(c context.Context, param *model.Match, gids []int64) (err error) {
// check game ids
var (
games []*model.Game
gidMaps []*model.GIDMap
)
if err = s.dao.DB.Model(&model.Game{}).Where("status=?", _statusOn).Where("id IN (?)", gids).Find(&games).Error; err != nil {
log.Error("AddMatch check game ids Error (%v)", err)
return
}
if len(games) == 0 {
log.Error("AddMatch games(%v) not found", gids)
err = ecode.RequestErr
return
}
tx := s.dao.DB.Begin()
if err = tx.Error; err != nil {
log.Error("s.dao.DB.Begin error(%v)", err)
return
}
if err = tx.Model(&model.Match{}).Create(param).Error; err != nil {
log.Error("AddMatch s.dao.DB.Model Create(%+v) error(%v)", param, err)
err = tx.Rollback().Error
return
}
for _, v := range games {
gidMaps = append(gidMaps, &model.GIDMap{Type: model.TypeMatch, Oid: param.ID, Gid: v.ID})
}
if err = tx.Model(&model.GIDMap{}).Exec(model.GidBatchAddSQL(gidMaps)).Error; err != nil {
log.Error("AddMatch s.dao.DB.Model Create(%+v) error(%v)", param, err)
err = tx.Rollback().Error
return
}
err = tx.Commit().Error
return
}
// EditMatch .
func (s *Service) EditMatch(c context.Context, param *model.Match, gids []int64) (err error) {
var (
games []*model.Game
preGidMaps, addGidMaps []*model.GIDMap
upGidMapAdd, upGidMapDel []int64
)
preData := new(model.Match)
if err = s.dao.DB.Where("id=?", param.ID).First(&preData).Error; err != nil {
log.Error("EditMatch s.dao.DB.Where id(%d) error(%d)", param.ID, err)
return
}
if err = s.dao.DB.Model(&model.Game{}).Where("status=?", _statusOn).Where("id IN (?)", gids).Find(&games).Error; err != nil {
log.Error("AddMatch check game ids Error (%v)", err)
return
}
if len(games) == 0 {
log.Error("AddMatch games(%v) not found", gids)
err = ecode.RequestErr
return
}
if err = s.dao.DB.Model(&model.GIDMap{}).Where("oid=?", param.ID).Where("type=?", model.TypeMatch).Find(&preGidMaps).Error; err != nil {
log.Error("AddMatch games(%v) not found", gids)
return
}
gidsMap := make(map[int64]int64, len(gids))
preGidsMap := make(map[int64]int64, len(preGidMaps))
for _, v := range gids {
gidsMap[v] = v
}
for _, v := range preGidMaps {
preGidsMap[v.Gid] = v.Gid
if _, ok := gidsMap[v.Gid]; ok {
if v.IsDeleted == 1 {
upGidMapAdd = append(upGidMapAdd, v.ID)
}
} else {
upGidMapDel = append(upGidMapDel, v.ID)
}
}
for _, gid := range gids {
if _, ok := preGidsMap[gid]; !ok {
addGidMaps = append(addGidMaps, &model.GIDMap{Type: model.TypeMatch, Oid: param.ID, Gid: gid})
}
}
tx := s.dao.DB.Begin()
if err = tx.Error; err != nil {
log.Error("s.dao.DB.Begin error(%v)", err)
return
}
if err = tx.Model(&model.Match{}).Save(param).Error; err != nil {
log.Error("EditMatch Match Update(%+v) error(%v)", param, err)
err = tx.Rollback().Error
return
}
if len(upGidMapAdd) > 0 {
if err = tx.Model(&model.GIDMap{}).Where("id IN (?)", upGidMapAdd).Updates(map[string]interface{}{"is_deleted": _notDeleted}).Error; err != nil {
log.Error("EditMatch GIDMap Add(%+v) error(%v)", upGidMapAdd, err)
err = tx.Rollback().Error
return
}
}
if len(upGidMapDel) > 0 {
if err = tx.Model(&model.GIDMap{}).Where("id IN (?)", upGidMapDel).Updates(map[string]interface{}{"is_deleted": _deleted}).Error; err != nil {
log.Error("EditMatch GIDMap Del(%+v) error(%v)", upGidMapDel, err)
err = tx.Rollback().Error
return
}
}
if len(addGidMaps) > 0 {
if err = tx.Model(&model.GIDMap{}).Exec(model.GidBatchAddSQL(addGidMaps)).Error; err != nil {
log.Error("EditMatch GIDMap Create(%+v) error(%v)", addGidMaps, err)
err = tx.Rollback().Error
return
}
}
err = tx.Commit().Error
return
}
// ForbidMatch .
func (s *Service) ForbidMatch(c context.Context, id int64, state int) (err error) {
preMatch := new(model.Match)
if err = s.dao.DB.Where("id=?", id).First(&preMatch).Error; err != nil {
log.Error("MatchForbid s.dao.DB.Where id(%d) error(%d)", id, err)
return
}
if err = s.dao.DB.Model(&model.Match{}).Where("id=?", id).Update(map[string]int{"status": state}).Error; err != nil {
log.Error("MatchForbid s.dao.DB.Model error(%v)", err)
}
return
}

View File

@@ -0,0 +1,345 @@
package service
import (
"context"
"encoding/json"
"sync"
"go-common/app/admin/main/esports/model"
arcmdl "go-common/app/service/main/archive/api"
"go-common/library/ecode"
"go-common/library/log"
"go-common/library/sync/errgroup"
"go-common/library/xstr"
"github.com/pkg/errors"
)
const (
_arcsSize = 50
_ReplyTypeAct = "25"
)
var (
_emptyModules = make([]*model.Module, 0)
_emptMatchMod = make([]*model.MatchModule, 0)
_emptyActive = make([]*model.MatchModule, 0)
)
// AddAct .
func (s *Service) AddAct(c context.Context, param *model.ParamMA) (arcs map[string][]int64, err error) {
var ms []*model.Module
if param.Modules != "" {
if err = json.Unmarshal([]byte(param.Modules), &ms); err != nil {
err = ecode.EsportsActModErr
return
}
if arcs, err = s.checkArc(c, ms); err != nil {
return
}
}
tx := s.dao.DB.Begin()
if err = tx.Model(&model.MatchActive{}).Create(&param.MatchActive).Error; err != nil {
log.Error("AddAct MatchActive tx.Model Create(%+v) error(%v)", param, err)
err = tx.Rollback().Error
return
}
maID := param.ID
if len(ms) > 0 {
if err = tx.Model(&model.Module{}).Exec(model.BatchAddModuleSQL(maID, ms)).Error; err != nil {
log.Error("AddAct Module tx.Model Create(%+v) error(%v)", param, err)
err = tx.Rollback().Error
return
}
}
if err = tx.Commit().Error; err != nil {
return
}
// register reply
if err = s.dao.RegReply(c, maID, param.Adid, _ReplyTypeAct); err != nil {
err = nil
}
return
}
// EditAct .
func (s *Service) EditAct(c context.Context, param *model.ParamMA) (arcs map[string][]int64, err error) {
var (
tmpMs, upM, addM, ms []*model.Module
mapMID map[int64]int64
pMID map[int64]*model.Module
delM []int64
)
if param.Modules != "" {
if err = json.Unmarshal([]byte(param.Modules), &ms); err != nil {
err = ecode.EsportsActModErr
return
}
if arcs, err = s.checkArc(c, ms); err != nil {
return
}
}
// check module
if err = s.dao.DB.Model(&model.Module{}).Where("ma_id=?", param.ID).Where("status=?", _notDeleted).Find(&tmpMs).Error; err != nil {
log.Error("EditAct s.dao.DB.Model Find (%+v) error(%v)", param.ID, err)
return
}
mapMID = make(map[int64]int64, len(tmpMs))
for _, m := range tmpMs {
mapMID[m.ID] = m.MaID
}
pMID = make(map[int64]*model.Module, len(ms))
for _, m := range ms {
if _, ok := mapMID[m.ID]; m.ID > 0 && !ok {
err = ecode.EsportsActModNot
return
}
pMID[m.ID] = m
if m.ID == 0 {
addM = append(addM, m)
}
}
for _, m := range tmpMs {
if mod, ok := pMID[m.ID]; ok {
upM = append(upM, mod)
} else {
delM = append(delM, m.ID)
}
}
// save
tx := s.dao.DB.Begin()
upFields := map[string]interface{}{"sid": param.Sid, "mid": param.Mid, "background": param.Background,
"back_color": param.BackColor, "color_step": param.ColorStep, "live_id": param.LiveID, "intr": param.Intr,
"focus": param.Focus, "url": param.URL, "status": param.Status,
"h5_background": param.H5Background, "h5_back_color": param.H5BackColor,
"h5_focus": param.H5Focus, "h5_url": param.H5URL,
"intr_logo": param.IntrLogo, "intr_title": param.IntrTitle, "intr_text": param.IntrText}
if err = tx.Model(&model.MatchActive{}).Where("id = ?", param.ID).Update(upFields).Error; err != nil {
log.Error("EditAct MatchActive tx.Model Create(%+v) error(%v)", param, err)
err = tx.Rollback().Error
return
}
if len(upM) > 0 {
if err = tx.Model(&model.Module{}).Exec(model.BatchEditModuleSQL(upM)).Error; err != nil {
log.Error("EditAct Module tx.Model Exec(%+v) error(%v)", upM, err)
err = tx.Rollback().Error
return
}
}
if len(delM) > 0 {
if err = tx.Model(&model.Module{}).Where("id IN (?)", delM).Updates(map[string]interface{}{"status": _deleted}).Error; err != nil {
log.Error("EditAct Module tx.Model Updates(%+v) error(%v)", delM, err)
err = tx.Rollback().Error
return
}
}
if len(addM) > 0 {
if err = tx.Model(&model.Module{}).Exec(model.BatchAddModuleSQL(param.ID, addM)).Error; err != nil {
log.Error("EditAct Module tx.Model Create(%+v) error(%v)", addM, err)
err = tx.Rollback().Error
return
}
}
err = tx.Commit().Error
return
}
func (s *Service) checkArc(c context.Context, ms []*model.Module) (rsAids map[string][]int64, err error) {
var (
name string
aids []int64
allAids []int64
tmpMap map[int64]struct{}
repeatAids []int64
wrongAids []int64
isWrong bool
)
rsAids = make(map[string][]int64, 2)
for _, m := range ms {
// check name only .
if m.Name != "" && name == m.Name {
err = ecode.EsportsModNameErr
return
}
name = m.Name
if aids, err = xstr.SplitInts(m.Oids); err != nil {
err = ecode.RequestErr
return
}
tmpMap = make(map[int64]struct{})
for _, aid := range aids {
if _, ok := tmpMap[aid]; ok {
repeatAids = append(repeatAids, aid)
continue
}
tmpMap[aid] = struct{}{}
}
allAids = append(allAids, aids...)
}
// check aids .
if wrongAids, err = s.wrongArc(c, allAids); err != nil {
err = ecode.EsportsArcServerErr
return
}
if len(repeatAids) > 0 {
rsAids["repeat"] = repeatAids
isWrong = true
}
if len(wrongAids) > 0 {
rsAids["wrong"] = wrongAids
isWrong = true
}
if isWrong {
err = ecode.EsportsModArcErr
}
return
}
func (s *Service) wrongArc(c context.Context, aids []int64) (list []int64, err error) {
var (
arcErr error
arcNormal map[int64]struct{}
mutex = sync.Mutex{}
)
group, errCtx := errgroup.WithContext(c)
aidsLen := len(aids)
arcNormal = make(map[int64]struct{}, aidsLen)
for i := 0; i < aidsLen; i += _arcsSize {
var partAids []int64
if i+_arcsSize > aidsLen {
partAids = aids[i:]
} else {
partAids = aids[i : i+_arcsSize]
}
group.Go(func() (err error) {
var tmpRes *arcmdl.ArcsReply
if tmpRes, arcErr = s.arcClient.Arcs(errCtx, &arcmdl.ArcsRequest{Aids: partAids}); arcErr != nil {
log.Error("wrongArc s.arcClient.Arcs(%v) error %v", partAids, err)
return arcErr
}
if tmpRes != nil {
for _, arc := range tmpRes.Arcs {
if arc != nil && arc.IsNormal() {
mutex.Lock()
arcNormal[arc.Aid] = struct{}{}
mutex.Unlock()
}
}
}
return nil
})
}
if err = group.Wait(); err != nil {
return
}
for _, aid := range aids {
if _, ok := arcNormal[aid]; !ok {
list = append(list, aid)
}
}
return
}
// ForbidAct .
func (s *Service) ForbidAct(c context.Context, id int64, state int) (err error) {
if err = s.dao.DB.Model(&model.MatchActive{}).Where("id=?", id).Updates(map[string]interface{}{"status": state}).Error; err != nil {
log.Error("ForbidAct MatchActive s.dao.DB.Model Updates(%d) error(%v)", id, err)
}
return
}
// ListAct .
func (s *Service) ListAct(c context.Context, mid, pn, ps int64) (rs []*model.MatchModule, count int64, err error) {
var (
mas []*model.MatchActive
maIDs, matchIDs, seasonIDs []int64
mapMs map[int64][]*model.Module
mapMatch map[int64]*model.Match
mapSeaon map[int64]*model.Season
matchTitle, matchSub, seasonTitle, seasonSub string
)
maDB := s.dao.DB.Model(&model.MatchActive{})
if mid > 0 {
maDB = maDB.Where("mid=?", mid)
}
maDB.Count(&count)
if count == 0 {
rs = _emptyActive
}
if err = maDB.Offset((pn - 1) * ps).Order("id ASC").Limit(ps).Find(&mas).Error; err != nil {
log.Error("ListAct MatchActive s.dao.DB.Model Find error(%v)", err)
return
}
if len(mas) == 0 {
rs = _emptMatchMod
return
}
for _, ma := range mas {
maIDs = append(maIDs, ma.ID)
matchIDs = append(matchIDs, ma.Mid)
seasonIDs = append(seasonIDs, ma.Sid)
}
if ids := unique(matchIDs); len(ids) > 0 {
var matchs []*model.Match
if err = s.dao.DB.Model(&model.Match{}).Where("id IN (?)", ids).Find(&matchs).Error; err != nil {
log.Error("ListAct match Error (%v)", err)
return
}
mapMatch = make(map[int64]*model.Match, len(matchs))
for _, v := range matchs {
mapMatch[v.ID] = v
}
}
if ids := unique(seasonIDs); len(ids) > 0 {
var seasons []*model.Season
if err = s.dao.DB.Model(&model.Match{}).Where("id IN (?)", ids).Find(&seasons).Error; err != nil {
log.Error("ListAct season Error (%v)", err)
return
}
mapSeaon = make(map[int64]*model.Season, len(seasonIDs))
for _, v := range seasons {
mapSeaon[v.ID] = v
}
}
if mapMs, err = s.modules(maIDs, count); err != nil {
log.Error("ListAct s.modules maIDs(%+v) faild(%+v)", maIDs, err)
return
}
for _, ma := range mas {
if match, ok := mapMatch[ma.Mid]; ok {
matchTitle = match.Title
matchSub = match.SubTitle
} else {
matchTitle = ""
matchSub = ""
}
if season, ok := mapSeaon[ma.Sid]; ok {
seasonTitle = season.Title
seasonSub = season.SubTitle
} else {
seasonTitle = ""
seasonSub = ""
}
if rsMs, ok := mapMs[ma.ID]; ok {
tmpMs := rsMs
rs = append(rs, &model.MatchModule{MatchActive: ma, Modules: tmpMs, MatchTitle: matchTitle, MatchSubTitle: matchSub, SeasonTitle: seasonTitle, SeasonSubTitle: seasonSub})
} else {
rs = append(rs, &model.MatchModule{MatchActive: ma, Modules: _emptyModules, MatchTitle: matchTitle, MatchSubTitle: matchSub, SeasonTitle: seasonTitle, SeasonSubTitle: seasonSub})
}
}
return
}
func (s *Service) modules(maIDs []int64, count int64) (rs map[int64][]*model.Module, err error) {
var ms []*model.Module
if err = s.dao.DB.Model(&model.Module{}).Where("ma_id in(?)", maIDs).Where("status=?", _notDeleted).Find(&ms).Order("ma_id ASC").Error; err != nil {
err = errors.Wrap(err, "modules map Model Find")
return
}
rs = make(map[int64][]*model.Module, count)
for _, m := range ms {
tmpM := m
rs[tmpM.MaID] = append(rs[tmpM.MaID], tmpM)
}
return
}

View File

@@ -0,0 +1,67 @@
package service
import (
"context"
"go-common/app/admin/main/esports/model"
"go-common/library/ecode"
"go-common/library/log"
)
// AddDetail .
func (s *Service) AddDetail(c context.Context, param *model.MatchDetail) (err error) {
if err = s.dao.DB.Model(&model.MatchDetail{}).Create(param).Error; err != nil {
log.Error("AddDetail MatchDetail db.Model Create error(%v)", err)
}
return
}
// EditDetail .
func (s *Service) EditDetail(c context.Context, param *model.MatchDetail) (err error) {
upFields := map[string]interface{}{"ma_id": param.MaID, "game_type": param.GameType, "stime": param.Stime,
"etime": param.Etime, "game_stage": param.GameStage, "knockout_type": param.KnockoutType,
"winner_type": param.WinnerType, "ScoreID": param.ScoreID, "status": param.Status, "online": param.Online}
if err = s.dao.DB.Model(&model.MatchDetail{}).Where("id=?", param.ID).Update(upFields).Error; err != nil {
log.Error("EditDetail MatchDetail db.Model Update error(%v)", err)
}
return
}
// ForbidDetail .
func (s *Service) ForbidDetail(c context.Context, id int64, state int) (err error) {
if err = s.dao.DB.Model(&model.MatchDetail{}).Where("id=?", id).Updates(map[string]interface{}{"status": state}).Error; err != nil {
log.Error("ForbidDetail MatchDetail db.Model Updates(%d) error(%v)", id, err)
}
return
}
// UpOnline .
func (s *Service) UpOnline(c context.Context, id int64, onLine int64) (err error) {
if onLine == _online {
var count int64
treeDB := s.dao.DB.Model(&model.Tree{}).Where("mad_id=?", id).Where("is_deleted=0")
if err = treeDB.Error; err != nil {
log.Error("upOnline treeDB Error (%v)", err)
return
}
treeDB.Count(&count)
if count == 0 {
err = ecode.EsportsTreeEmptyErr
return
}
}
if err = s.dao.DB.Model(&model.MatchDetail{}).Where("id=?", id).Updates(map[string]interface{}{"online": onLine}).Error; err != nil {
log.Error("UpOnline s.dao.DB.Model Updates(%+v) error(%v)", id, err)
}
return
}
// ListDetail .
func (s *Service) ListDetail(c context.Context, maID, pn, ps int64) (rs []*model.MatchDetail, count int64, err error) {
db := s.dao.DB.Model(&model.MatchDetail{}).Offset((pn-1)*ps).Where("ma_id=?", maID).Order("id ASC").Limit(ps).Find(&rs)
if err = db.Error; err != nil {
log.Error("ListDetail MatchDetail db.Model Find error(%v)", err)
}
db.Count(&count)
return
}

View File

@@ -0,0 +1,27 @@
package service
import (
"context"
"testing"
"go-common/app/admin/main/esports/model"
. "github.com/smartystreets/goconvey/convey"
)
func TestService_AddMatch(t *testing.T) {
Convey("test add match", t, WithService(func(s *Service) {
gids := []int64{1}
err := s.AddMatch(context.Background(), &model.Match{Title: "match"}, gids)
So(err, ShouldBeNil)
}))
}
func TestService_ForbidMatch(t *testing.T) {
Convey("test forbid match", t, WithService(func(s *Service) {
mid := int64(1)
state := 0
err := s.ForbidMatch(context.Background(), mid, state)
So(err, ShouldBeNil)
}))
}

View File

@@ -0,0 +1,194 @@
package service
import (
"context"
"go-common/app/admin/main/esports/model"
"go-common/library/ecode"
"go-common/library/log"
)
// SeasonInfo .
func (s *Service) SeasonInfo(c context.Context, id int64) (data *model.SeasonInfo, err error) {
var gameMap map[int64][]*model.Game
season := new(model.Season)
if err = s.dao.DB.Where("id=?", id).First(&season).Error; err != nil {
log.Error("SeasonInfo Error (%v)", err)
return
}
if gameMap, err = s.gameList(c, model.TypeSeason, []int64{id}); err != nil {
return
}
if games, ok := gameMap[id]; ok {
data = &model.SeasonInfo{Season: season, Games: games}
} else {
data = &model.SeasonInfo{Season: season, Games: _emptyGameList}
}
return
}
// SeasonList .
func (s *Service) SeasonList(c context.Context, mid, pn, ps int64) (list []*model.SeasonInfo, count int64, err error) {
var (
seasons []*model.Season
seasonIDs []int64
gameMap map[int64][]*model.Game
)
source := s.dao.DB.Model(&model.Season{})
if mid > 0 {
source = source.Where("mid=?", mid)
}
source.Count(&count)
if err = source.Offset((pn - 1) * ps).Order("rank DESC,id ASC").Limit(ps).Find(&seasons).Error; err != nil {
log.Error("SeasonList Error (%v)", err)
return
}
if len(seasons) == 0 {
return
}
for _, v := range seasons {
seasonIDs = append(seasonIDs, v.ID)
}
if gameMap, err = s.gameList(c, model.TypeSeason, seasonIDs); err != nil {
return
}
for _, v := range seasons {
if games, ok := gameMap[v.ID]; ok {
list = append(list, &model.SeasonInfo{Season: v, Games: games})
} else {
list = append(list, &model.SeasonInfo{Season: v, Games: _emptyGameList})
}
}
return
}
// AddSeason .
func (s *Service) AddSeason(c context.Context, param *model.Season, gids []int64) (err error) {
var (
games []*model.Game
gidMaps []*model.GIDMap
)
// TODO check name exist
if err = s.dao.DB.Model(&model.Game{}).Where("status=?", _statusOn).Where("id IN (?)", gids).Find(&games).Error; err != nil {
log.Error("AddSeason check game ids Error (%v)", err)
return
}
if len(games) == 0 {
log.Error("AddSeason games(%v) not found", gids)
err = ecode.RequestErr
return
}
tx := s.dao.DB.Begin()
if err = tx.Error; err != nil {
log.Error("s.dao.DB.Begin error(%v)", err)
return
}
if err = tx.Model(&model.Season{}).Create(param).Error; err != nil {
log.Error("AddSeason s.dao.DB.Model Create(%+v) error(%v)", param, err)
err = tx.Rollback().Error
return
}
for _, v := range games {
gidMaps = append(gidMaps, &model.GIDMap{Type: model.TypeSeason, Oid: param.ID, Gid: v.ID})
}
if err = tx.Model(&model.GIDMap{}).Exec(model.GidBatchAddSQL(gidMaps)).Error; err != nil {
log.Error("AddSeason s.dao.DB.Model Create(%+v) error(%v)", param, err)
err = tx.Rollback().Error
return
}
err = tx.Commit().Error
return
}
// EditSeason .
func (s *Service) EditSeason(c context.Context, param *model.Season, gids []int64) (err error) {
var (
games []*model.Game
preGidMaps, addGidMaps []*model.GIDMap
upGidMapAdd, upGidMapDel []int64
)
preData := new(model.Season)
if err = s.dao.DB.Where("id=?", param.ID).First(&preData).Error; err != nil {
log.Error("EditSeason s.dao.DB.Where id(%d) error(%d)", param.ID, err)
return
}
if err = s.dao.DB.Model(&model.Game{}).Where("status=?", _statusOn).Where("id IN (?)", gids).Find(&games).Error; err != nil {
log.Error("EditSeason check game ids Error (%v)", err)
return
}
if len(games) == 0 {
log.Error("EditSeason games(%v) not found", gids)
err = ecode.RequestErr
return
}
if err = s.dao.DB.Model(&model.GIDMap{}).Where("oid=?", param.ID).Where("type=?", model.TypeSeason).Find(&preGidMaps).Error; err != nil {
log.Error("EditSeason games(%v) not found", gids)
return
}
gidsMap := make(map[int64]int64, len(gids))
preGidsMap := make(map[int64]int64, len(preGidMaps))
for _, v := range gids {
gidsMap[v] = v
}
for _, v := range preGidMaps {
preGidsMap[v.Gid] = v.Gid
if _, ok := gidsMap[v.Gid]; ok {
if v.IsDeleted == 1 {
upGidMapAdd = append(upGidMapAdd, v.ID)
}
} else {
upGidMapDel = append(upGidMapDel, v.ID)
}
}
for _, gid := range gids {
if _, ok := preGidsMap[gid]; !ok {
addGidMaps = append(addGidMaps, &model.GIDMap{Type: model.TypeSeason, Oid: param.ID, Gid: gid})
}
}
tx := s.dao.DB.Begin()
if err = tx.Error; err != nil {
log.Error("s.dao.DB.Begin error(%v)", err)
return
}
if err = tx.Model(&model.Season{}).Save(param).Error; err != nil {
log.Error("EditSeason Match Update(%+v) error(%v)", param, err)
err = tx.Rollback().Error
return
}
if len(upGidMapAdd) > 0 {
if err = tx.Model(&model.GIDMap{}).Where("id IN (?)", upGidMapAdd).Updates(map[string]interface{}{"is_deleted": _notDeleted}).Error; err != nil {
log.Error("EditSeason GIDMap Add(%+v) error(%v)", upGidMapAdd, err)
err = tx.Rollback().Error
return
}
}
if len(upGidMapDel) > 0 {
if err = tx.Model(&model.GIDMap{}).Where("id IN (?)", upGidMapDel).Updates(map[string]interface{}{"is_deleted": _deleted}).Error; err != nil {
log.Error("EditSeason GIDMap Del(%+v) error(%v)", upGidMapDel, err)
err = tx.Rollback().Error
return
}
}
if len(addGidMaps) > 0 {
if err = tx.Model(&model.GIDMap{}).Exec(model.GidBatchAddSQL(addGidMaps)).Error; err != nil {
log.Error("EditSeason GIDMap Create(%+v) error(%v)", addGidMaps, err)
err = tx.Rollback().Error
return
}
}
err = tx.Commit().Error
return
}
// ForbidSeason .
func (s *Service) ForbidSeason(c context.Context, id int64, state int) (err error) {
preSeason := new(model.Season)
if err = s.dao.DB.Where("id=?", id).First(&preSeason).Error; err != nil {
log.Error("SeasonForbid s.dao.DB.Where id(%d) error(%d)", id, err)
return
}
if err = s.dao.DB.Model(&model.Season{}).Where("id=?", id).Update(map[string]int{"status": state}).Error; err != nil {
log.Error("SeasonForbid s.dao.DB.Model error(%v)", err)
}
return
}

View File

@@ -0,0 +1,62 @@
package service
import (
"context"
"go-common/app/admin/main/esports/conf"
"go-common/app/admin/main/esports/dao"
accclient "go-common/app/service/main/account/api"
accwarden "go-common/app/service/main/account/api"
arcclient "go-common/app/service/main/archive/api"
)
// Service biz service def.
type Service struct {
c *conf.Config
dao *dao.Dao
arcClient arcclient.ArchiveClient
accClient accwarden.AccountClient
}
const (
_notDeleted = 0
_deleted = 1
_online = 1
_downLine = 0
_statusOn = 0
_statusAll = -1
)
// New new a Service and return.
func New(c *conf.Config) (s *Service) {
s = &Service{
c: c,
dao: dao.New(c),
}
var err error
if s.arcClient, err = arcclient.NewClient(c.ArcClient); err != nil {
panic(err)
}
if s.accClient, err = accclient.NewClient(c.AccClient); err != nil {
panic(err)
}
return s
}
// Ping .
func (s *Service) Ping(c context.Context) (err error) {
return s.dao.Ping(c)
}
func unique(ids []int64) (outs []int64) {
idMap := make(map[int64]int64, len(ids))
for _, v := range ids {
if _, ok := idMap[v]; ok {
continue
} else {
idMap[v] = v
}
outs = append(outs, v)
}
return
}

View File

@@ -0,0 +1,24 @@
package service
import (
"flag"
"path/filepath"
"time"
"go-common/app/admin/main/esports/conf"
)
var svf *Service
func WithService(f func(s *Service)) func() {
return func() {
dir, _ := filepath.Abs("../cmd/esports-admin-test.toml")
flag.Set("conf", dir)
conf.Init()
if svf == nil {
svf = New(conf.Conf)
}
time.Sleep(2 * time.Second)
f(svf)
}
}

View File

@@ -0,0 +1,62 @@
package service
import (
"context"
"go-common/app/admin/main/esports/model"
"go-common/library/log"
)
var _emptyTagList = make([]*model.Tag, 0)
// TagInfo .
func (s *Service) TagInfo(c context.Context, id int64) (data *model.Tag, err error) {
data = new(model.Tag)
if err = s.dao.DB.Model(&model.Tag{}).Where("id=?", id).First(&data).Error; err != nil {
log.Error("TagInfo Error (%v)", err)
}
return
}
// TagList .
func (s *Service) TagList(c context.Context, pn, ps int64) (list []*model.Tag, count int64, err error) {
s.dao.DB.Model(&model.Tag{}).Count(&count)
if err = s.dao.DB.Model(&model.Tag{}).Offset((pn - 1) * ps).Limit(ps).Find(&list).Error; err != nil {
log.Error("TagList Error (%v)", err)
}
return
}
// AddTag .
func (s *Service) AddTag(c context.Context, param *model.Tag) (err error) {
if err = s.dao.DB.Model(&model.Tag{}).Create(param).Error; err != nil {
log.Error("AddTag s.dao.DB.Model Create(%+v) error(%v)", param, err)
}
return
}
// EditTag .
func (s *Service) EditTag(c context.Context, param *model.Tag) (err error) {
preData := new(model.Tag)
if err = s.dao.DB.Where("id=?", param.ID).First(&preData).Error; err != nil {
log.Error("EditTag s.dao.DB.Where id(%d) error(%d)", param.ID, err)
return
}
if err = s.dao.DB.Model(&model.Tag{}).Update(param).Error; err != nil {
log.Error("EditTag s.dao.DB.Model Update(%+v) error(%v)", param, err)
}
return
}
// ForbidTag .
func (s *Service) ForbidTag(c context.Context, id int64, state int) (err error) {
preTag := new(model.Tag)
if err = s.dao.DB.Where("id=?", id).First(&preTag).Error; err != nil {
log.Error("TagForbid s.dao.DB.Where id(%d) error(%d)", id, err)
return
}
if err = s.dao.DB.Model(&model.Tag{}).Where("id=?", id).Update(map[string]int{"status": state}).Error; err != nil {
log.Error("TagForbid s.dao.DB.Model error(%v)", err)
}
return
}

View File

@@ -0,0 +1,200 @@
package service
import (
"context"
"fmt"
"go-common/app/admin/main/esports/model"
"go-common/library/ecode"
"go-common/library/log"
)
var _emptyTeamList = make([]*model.Team, 0)
// TeamInfo .
func (s *Service) TeamInfo(c context.Context, id int64) (data *model.TeamInfo, err error) {
var gameMap map[int64][]*model.Game
team := new(model.Team)
if err = s.dao.DB.Where("id=?", id).Where("is_deleted=?", _notDeleted).First(&team).Error; err != nil {
log.Error("TeamInfo Error (%v)", err)
return
}
if gameMap, err = s.gameList(c, model.TypeTeam, []int64{id}); err != nil {
return
}
if games, ok := gameMap[id]; ok {
data = &model.TeamInfo{Team: team, Games: games}
} else {
data = &model.TeamInfo{Team: team, Games: _emptyGameList}
}
return
}
// TeamList .
func (s *Service) TeamList(c context.Context, pn, ps int64, title string, status int) (list []*model.TeamInfo, count int64, err error) {
var (
teams []*model.Team
teamIDs []int64
gameMap map[int64][]*model.Game
)
source := s.dao.DB.Model(&model.Team{})
if status != _statusAll {
source = source.Where("is_deleted=?", _notDeleted)
}
if title != "" {
likeStr := fmt.Sprintf("%%%s%%", title)
source = source.Where("title like ?", likeStr)
}
source.Count(&count)
if err = source.Offset((pn - 1) * ps).Limit(ps).Find(&teams).Error; err != nil {
log.Error("TeamList Error (%v)", err)
return
}
if len(teams) == 0 {
return
}
for _, v := range teams {
teamIDs = append(teamIDs, v.ID)
}
if gameMap, err = s.gameList(c, model.TypeTeam, teamIDs); err != nil {
return
}
for _, v := range teams {
if games, ok := gameMap[v.ID]; ok {
list = append(list, &model.TeamInfo{Team: v, Games: games})
} else {
list = append(list, &model.TeamInfo{Team: v, Games: _emptyGameList})
}
}
return
}
// AddTeam .
func (s *Service) AddTeam(c context.Context, param *model.Team, gids []int64) (err error) {
var (
games []*model.Game
gidMaps []*model.GIDMap
)
if err = s.dao.DB.Model(&model.Game{}).Where("status=?", _statusOn).Where("id IN (?)", gids).Find(&games).Error; err != nil {
log.Error("AddTeam check game ids Error (%v)", err)
return
}
if len(games) == 0 {
log.Error("AddTeam games(%v) not found", gids)
err = ecode.RequestErr
return
}
tx := s.dao.DB.Begin()
if err = tx.Error; err != nil {
log.Error("s.dao.DB.Begin error(%v)", err)
return
}
if err = tx.Model(&model.Team{}).Create(param).Error; err != nil {
log.Error("AddTeam s.dao.DB.Model Create(%+v) error(%v)", param, err)
err = tx.Rollback().Error
return
}
for _, v := range games {
gidMaps = append(gidMaps, &model.GIDMap{Type: model.TypeTeam, Oid: param.ID, Gid: v.ID})
}
if err = tx.Model(&model.GIDMap{}).Exec(model.GidBatchAddSQL(gidMaps)).Error; err != nil {
log.Error("AddTeam s.dao.DB.Model Create(%+v) error(%v)", param, err)
err = tx.Rollback().Error
return
}
err = tx.Commit().Error
return
}
// EditTeam .
func (s *Service) EditTeam(c context.Context, param *model.Team, gids []int64) (err error) {
var (
games []*model.Game
preGidMaps, addGidMaps []*model.GIDMap
upGidMapAdd, upGidMapDel []int64
)
preData := new(model.Team)
if err = s.dao.DB.Where("id=?", param.ID).First(&preData).Error; err != nil {
log.Error("EditTeam s.dao.DB.Where id(%d) error(%d)", param.ID, err)
return
}
if err = s.dao.DB.Model(&model.Game{}).Where("status=?", _statusOn).Where("id IN (?)", gids).Find(&games).Error; err != nil {
log.Error("EditTeam check game ids Error (%v)", err)
return
}
if len(games) == 0 {
log.Error("EditTeam games(%v) not found", gids)
err = ecode.RequestErr
return
}
if err = s.dao.DB.Model(&model.GIDMap{}).Where("oid=?", param.ID).Where("type=?", model.TypeTeam).Find(&preGidMaps).Error; err != nil {
log.Error("EditTeam games(%v) not found", gids)
return
}
gidsMap := make(map[int64]int64, len(gids))
preGidsMap := make(map[int64]int64, len(preGidMaps))
for _, v := range gids {
gidsMap[v] = v
}
for _, v := range preGidMaps {
preGidsMap[v.Gid] = v.Gid
if _, ok := gidsMap[v.Gid]; ok {
if v.IsDeleted == 1 {
upGidMapAdd = append(upGidMapAdd, v.ID)
}
} else {
upGidMapDel = append(upGidMapDel, v.ID)
}
}
for _, gid := range gids {
if _, ok := preGidsMap[gid]; !ok {
addGidMaps = append(addGidMaps, &model.GIDMap{Type: model.TypeTeam, Oid: param.ID, Gid: gid})
}
}
tx := s.dao.DB.Begin()
if err = tx.Error; err != nil {
log.Error("s.dao.DB.Begin error(%v)", err)
return
}
if err = tx.Model(&model.Team{}).Save(param).Error; err != nil {
log.Error("EditTeam Team Update(%+v) error(%v)", param, err)
err = tx.Rollback().Error
return
}
if len(upGidMapAdd) > 0 {
if err = tx.Model(&model.GIDMap{}).Where("id IN (?)", upGidMapAdd).Updates(map[string]interface{}{"is_deleted": _notDeleted}).Error; err != nil {
log.Error("EditTeam GIDMap Add(%+v) error(%v)", upGidMapAdd, err)
err = tx.Rollback().Error
return
}
}
if len(upGidMapDel) > 0 {
if err = tx.Model(&model.GIDMap{}).Where("id IN (?)", upGidMapDel).Updates(map[string]interface{}{"is_deleted": _deleted}).Error; err != nil {
log.Error("EditTeam GIDMap Del(%+v) error(%v)", upGidMapDel, err)
err = tx.Rollback().Error
return
}
}
if len(addGidMaps) > 0 {
if err = tx.Model(&model.GIDMap{}).Exec(model.GidBatchAddSQL(addGidMaps)).Error; err != nil {
log.Error("EditTeam GIDMap Create(%+v) error(%v)", addGidMaps, err)
err = tx.Rollback().Error
return
}
}
err = tx.Commit().Error
return
}
// ForbidTeam .
func (s *Service) ForbidTeam(c context.Context, id int64, state int) (err error) {
preTeam := new(model.Team)
if err = s.dao.DB.Where("id=?", id).First(&preTeam).Error; err != nil {
log.Error("TeamForbid s.dao.DB.Where id(%d) error(%d)", id, err)
return
}
if err = s.dao.DB.Model(&model.Team{}).Where("id=?", id).Update(map[string]int{"is_deleted": state}).Error; err != nil {
log.Error("TeamForbid s.dao.DB.Model error(%v)", err)
}
return
}

View File

@@ -0,0 +1,20 @@
package service
import (
"context"
"go-common/app/admin/main/esports/model"
"testing"
. "github.com/smartystreets/goconvey/convey"
)
func TestService_EditTeam(t *testing.T) {
Convey("test edit team", t, WithService(func(s *Service) {
arg := &model.Team{
ID: 3,
}
gids := []int64{3}
err := s.EditTeam(context.Background(), arg, gids)
So(err, ShouldBeNil)
}))
}

View File

@@ -0,0 +1,218 @@
package service
import (
"context"
"encoding/json"
"go-common/app/admin/main/esports/model"
"go-common/library/ecode"
"go-common/library/log"
"go-common/library/xstr"
"github.com/jinzhu/gorm"
)
var _emptyTreeList = make([][]*model.TreeList, 0)
// AddTree .
func (s *Service) AddTree(c context.Context, param *model.Tree) (rs model.Tree, err error) {
var rootID int64
db := s.dao.DB.Model(&model.Tree{}).Create(param)
if err = db.Error; err != nil {
log.Error("AddTree s.dao.DB.Model Create(%+v) error(%v)", param, err)
return
}
rootID = (db.Value.(*model.Tree)).RootID
rs.ID = (db.Value.(*model.Tree)).ID
rs.MaID = (db.Value.(*model.Tree)).MaID
rs.MadID = (db.Value.(*model.Tree)).MadID
rs.Pid = (db.Value.(*model.Tree)).Pid
rs.Mid = (db.Value.(*model.Tree)).Mid
// update detail online.
s.UpOnline(c, rs.MadID, _downLine)
// update first root_id.
if param.RootID == 0 || rs.Pid == 0 {
upDB := s.dao.DB.Model(&model.Tree{})
if err = upDB.Where("id=?", rs.ID).Updates(map[string]interface{}{"root_id": rs.ID}).Error; err != nil {
log.Error("AddTree db.Model Updates(%+v) error(%v)", rs.ID, err)
return
}
rootID = (upDB.Value.(*model.Tree)).RootID
}
rs.RootID = rootID
return
}
// EditTree .
func (s *Service) EditTree(c context.Context, param *model.TreeEditParam) (err error) {
var (
paramIDs []int64
trees, paramTree []*model.Tree
delIDs []int64
nodes map[int64]int64
)
if err = json.Unmarshal([]byte(param.Nodes), &nodes); err != nil {
err = ecode.RequestErr
return
}
if len(nodes) == 0 {
err = ecode.EsportsTreeEmptyErr
return
}
for id := range nodes {
if id > 0 {
paramIDs = append(paramIDs, id)
} else {
err = ecode.RequestErr
return
}
}
// check tree maid same .
if err = s.dao.DB.Model(&model.Tree{}).Model(&model.Tree{}).Where("id IN (?)", paramIDs).Find(&paramTree).Error; err != nil {
log.Error("EditTree s.dao.DB.Model Find(%+v) error(%v)", paramIDs, err)
}
for _, tmpTree := range paramTree {
if tmpTree.MadID != param.MadID {
err = ecode.EsportsTreeNodeErr
return
}
}
ParamIDCount := len(paramIDs)
treeDB := s.dao.DB.Model(&model.Tree{})
if err = treeDB.Where("mad_id=?", param.MadID).Where("is_deleted=0").Find(&trees).Error; err != nil {
log.Error("EditTree Error (%v)", err)
return
}
treeCount := len(trees)
if ParamIDCount != treeCount {
for _, tree := range trees {
if _, ok := nodes[tree.ID]; !ok {
delIDs = append(delIDs, tree.ID)
}
}
}
// Prevent multiplayer editing
if ParamIDCount != (treeCount - len(delIDs)) {
err = ecode.EsportsMultiEdit
return
}
tx := s.dao.DB.Begin()
if err = tx.Error; err != nil {
log.Error("s.dao.DB.Begin error(%v)", err)
return
}
if err = upTree(tx, delIDs, nodes, param.MadID); err != nil {
err = tx.Rollback().Error
return
}
if err = tx.Commit().Error; err != nil {
log.Error("tx.Commit error(%v)", err)
return
}
return
}
func upTree(tx *gorm.DB, delIDs []int64, nodes map[int64]int64, madID int64) (err error) {
if err = tx.Model(&model.Tree{}).Where("id IN (?)", delIDs).Updates(map[string]interface{}{"is_deleted": _deleted}).Error; err != nil {
log.Error("upTree tx.Model Updates(%+v) error(%v)", delIDs, err)
return
}
if err = tx.Model(&model.Tree{}).Exec(model.BatchEditTreeSQL(nodes)).Error; err != nil {
log.Error("upTree tx.Model Exec(%+v) error(%v)", nodes, err)
}
if err = tx.Model(&model.MatchDetail{}).Where("id=?", madID).Updates(map[string]interface{}{"online": _downLine}).Error; err != nil {
log.Error("upTree MatchDetail tx.Model Updates(%d) error(%v)", madID, err)
}
return
}
// DelTree .
func (s *Service) DelTree(c context.Context, param *model.TreeDelParam) (err error) {
var ids []int64
if ids, err = xstr.SplitInts(param.IDs); err != nil {
err = ecode.RequestErr
return
}
if err = s.dao.DB.Model(&model.Tree{}).Model(&model.Tree{}).Where("id IN (?)", ids).Updates(map[string]interface{}{"is_deleted": _deleted}).Error; err != nil {
log.Error("DelTree treeDB.Model Updates(%+v) error(%v)", ids, err)
}
// update detail online.
s.UpOnline(c, param.MadID, _downLine)
return
}
// TreeList .
func (s *Service) TreeList(c context.Context, param *model.TreeListParam) (res *model.TreeDetailList, err error) {
var (
trees []*model.Tree
mids []int64
contests []*model.Contest
mapContests map[int64]*model.ContestInfo
sTree []*model.TreeList
cInfos []*model.ContestInfo
detail model.MatchDetail
rs [][]*model.TreeList
)
db := s.dao.DB.Model(&model.MatchDetail{}).Where("id=?", param.MadID).First(&detail)
if err = db.Error; err != nil {
log.Error("TreeList MatchDetail db.Model Find error(%v)", err)
}
if detail.ID == 0 {
err = ecode.EsportsTreeDetailErr
return
}
treeDB := s.dao.DB.Model(&model.Tree{})
treeDB = treeDB.Where("mad_id=?", param.MadID).Where("is_deleted=0")
if err = treeDB.Limit(s.c.Rule.MaxTreeContests).Order("root_id ASC,pid ASC,game_rank ASC").Find(&trees).Error; err != nil {
log.Error("TreeList Error (%v)", err)
return
}
for _, tree := range trees {
mids = append(mids, tree.Mid)
}
contestsDB := s.dao.DB.Model(&model.Contest{})
contestsDB = contestsDB.Where("id IN (?)", mids)
count := len(mids)
if err = contestsDB.Offset(0).Limit(count).Find(&contests).Error; err != nil {
log.Error("ContestList Error (%v)", err)
return
}
if cInfos, err = s.contestInfos(c, contests, false); err != nil {
log.Error("s.contestInfos Error (%v)", err)
return
}
mapContests = make(map[int64]*model.ContestInfo, count)
for _, info := range cInfos {
mapContests[info.ID] = info
}
for _, tree := range trees {
if tree.Pid == 0 {
if len(sTree) > 0 {
rs = append(rs, sTree)
}
sTree = nil
if cInfo, ok := mapContests[tree.Mid]; ok {
sTree = append(sTree, &model.TreeList{Tree: tree, ContestInfo: cInfo})
} else {
sTree = append(sTree, &model.TreeList{Tree: tree})
}
} else {
if cInfo, ok := mapContests[tree.Mid]; ok {
sTree = append(sTree, &model.TreeList{Tree: tree, ContestInfo: cInfo})
} else {
sTree = append(sTree, &model.TreeList{Tree: tree})
}
}
}
if len(sTree) > 0 {
rs = append(rs, sTree)
}
res = new(model.TreeDetailList)
if len(trees) == 0 {
res.Tree = _emptyTreeList
} else {
res.Tree = rs
}
res.Detail = &detail
return
}