Initial commit

This commit is contained in:
Donny
2019-04-22 20:46:32 +08:00
commit 49ab8aadd1
25441 changed files with 4055000 additions and 0 deletions

29
app/admin/main/vip/BUILD Normal file
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/vip/cmd:all-srcs",
"//app/admin/main/vip/conf:all-srcs",
"//app/admin/main/vip/dao:all-srcs",
"//app/admin/main/vip/http:all-srcs",
"//app/admin/main/vip/model:all-srcs",
"//app/admin/main/vip/service:all-srcs",
],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

View File

@@ -0,0 +1,117 @@
# v2.9.0
1. 大会员福利社后台管理
2. 大会员福利社客户端
# v2.8.2
1. fix platform is_del=0
2. edit vip_price_config_v2.platform to int64
# v2.8.1
1. 首月价格更新
# v2.8.0
1. 自动续费首月价格
# v2.7.3
1. 联合会员退款限制
# v2.7.2
1. 删除平台配置参数校验
# v2.7.1
1. 删除无用代码
# v2.7.0
1. 权益国际化
# v2.6.0
1. 价格面板后台+build号逻辑
# v2.5.0
1. 新增购买平台配置
# v2.4.1
1. 删除字段wander
# v2.4.0
1. 价格面板v8
2. 包年包季
3. 审核态面板
# v2.3.0
1. 安卓国际版&iPhone蓝版接入
# v2.2.0
1. 支付成功弹窗管理
# v2.1.3
1. 权益内容换行兼容
# v2.1.2
1. 联名副标题非必填
# v2.1.1
1. add order status
# v2.1.0
1. add batch code limit
# v2.0.0
1. 大会员退款
# v1.10.0
1. 大会员权益
# v1.9.0
1. 大会员联名业务
# v1.8.3
1. fix plat check bug
# v1.8.2
1. 新增好友赠送平台
# v1.8.1
1. 去掉vip-admin的point相关
# v1.8.0
1. vip 价格面版 更新的时候平台没用传
# v1.7.0
1. use new bind
# v1.6.0
1. push data mng info
# v1.5.0
1. vip 价格面版功能 V2
# v1.4.1
1. 去掉面板实时变更状态
# v1.4.0
1. 追番列表增加开通提醒
# v1.3.4
1. move reuired type
# v1.3.3
1. 变更面版判断条件
# v1.3.2
1. fix add batch code type
# v1.3.1
1. update build
# v1.3.0
1.暑期活动
# v1.2.2
1.失效无效时间的状态
# v1.2.1
1.vip fix datetime defualt
# v1.2.0
1.vip 价格面版功能
# v1.1.0
1.小黄条配置
# v1.0.0
1.初始化项目

View File

@@ -0,0 +1,8 @@
# Owner
zhaogangtao
# Author
zhaozhihao
# Reviewer
linmiao

14
app/admin/main/vip/OWNERS Normal file
View File

@@ -0,0 +1,14 @@
# See the OWNERS docs at https://go.k8s.io/owners
approvers:
- zhaogangtao
- zhaozhihao
labels:
- admin
- admin/main/vip
- main
options:
no_parent_owners: true
reviewers:
- linmiao
- zhaozhihao

View File

@@ -0,0 +1,13 @@
#### vip
##### 项目简介
> 1.大会员
##### 编译环境
> 请只用golang v1.8.x以上版本编译执行。
##### 依赖包
> 1.公共包go-common
##### 特别说明
> 1.model目录可能会被其他项目引用请谨慎更改并通知各方。

View File

@@ -0,0 +1,42 @@
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 = ["vip-admin-test.toml"],
importpath = "go-common/app/admin/main/vip/cmd",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/admin/main/vip/conf:go_default_library",
"//app/admin/main/vip/http:go_default_library",
"//library/ecode/tip:go_default_library",
"//library/log: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,49 @@
package main
import (
"flag"
"os"
"os/signal"
"syscall"
"go-common/app/admin/main/vip/conf"
"go-common/app/admin/main/vip/http"
ecode "go-common/library/ecode/tip"
"go-common/library/log"
)
func main() {
flag.Parse()
if err := conf.Init(); err != nil {
log.Error("conf.Init() error(%v)", err)
panic(err)
}
// init log
log.Init(conf.Conf.Log)
defer log.Close()
log.Info("/vip start")
// init trace
//trace.Init(conf.Conf.Tracer)
//defer trace.Close()
// ecode init
// ecode.Init(conf.Conf.Ecode)
// service init
http.Init(conf.Conf)
// init pprof conf.Conf.Perf
ecode.Init(conf.Conf.Ecode)
// init signal
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT)
for {
s := <-c
log.Info("/vip get a signal %s", s.String())
switch s {
case syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT:
log.Info("/vip exit")
return
case syscall.SIGHUP:
default:
return
}
}
}

View File

@@ -0,0 +1,157 @@
# This is a TOML document. Boom
version = "1.0.0"
[log]
stdout = true
dir = "/data/log/vip-admin"
[memcache]
name = "vip"
proto = "tcp"
addr = "172.18.33.60:11234"
idle = 5
active = 10
dialTimeout = "1s"
readTimeout = "1s"
writeTimeout = "1s"
idleTimeout = "10s"
expire = "24h"
[payConf]
baseURL = "http://pay.bilibili.co"
customerID = 10004
token ="0ff3d296ee0d7a28b4db1d761d2db907"
orderNotifyURL ="http://vip.bilibili.co/pay/payOrderNotify"
signNotifyURL ="http://vip.bilibili.co/pay/paySignNotify"
planID = 108217
productID ="vip_buy"
version ="1.0"
refundURL = "http://api.bilibili.co/x/internal/vip/notify/refund"
[property]
MsgURI = "http://message.bilibili.com"
PayURI = "http://pay.bilibili.co"
annualVipBcoinDay = 10
annualVipBcoinCouponMoney = 5
annualVipBcoinCouponActivityId = 142
welfareBgHost = "http://uat-i%v.hdslb.com"
[auth]
managerHost = "http://uat-manager.bilibili.co"
dashboardHost = "http://uat-dashboard-mng.bilibili.co"
dashboardCaller = "manager-go"
[auth.DsHTTPClient]
key = "manager-go"
secret = "949bbb2dd3178252638c2407578bc7ad"
dial = "1s"
timeout = "1s"
keepAlive = "60s"
[auth.DsHTTPClient.breaker]
window = "3s"
sleep = "100ms"
bucket = 10
ratio = 0.5
request = 100
[auth.MaHTTPClient]
key = "f6433799dbd88751"
secret = "36f8ddb1806207fe07013ab6a77a3935"
dial = "1s"
timeout = "1s"
keepAlive = "60s"
[auth.MaHTTPClient.breaker]
window = "3s"
sleep = "100ms"
bucket = 10
ratio = 0.5
request = 100
[auth.session]
sessionIDLength = 32
cookieLifeTime = 1800
cookieName = "mng-go"
domain = ".bilibili.co"
[auth.session.Memcache]
name = "go-business/auth"
proto = "tcp"
addr = "172.16.33.54:11211"
active = 5
idle = 5
dialTimeout = "1s"
readTimeout = "1s"
writeTimeout = "1s"
idleTimeout = "80s"
[VipRPC]
pullInterval = "10s"
[VipRPC.client]
token = "123456789"
proto = "tcp"
timeout = "1s"
timer = 1000
[VipRPC.client.breaker]
window ="10s"
sleep ="10ms"
bucket = 10
ratio = 0.5
request = 100
[[backup]]
proto = "tcp"
addr = "127.0.0.1:6009"
timeout = "1s"
timer = 1000
[VipRPC.zookeeper]
root = "/microservice/vip/"
addrs = ["172.18.33.50:2199","172.18.33.51:2199","172.18.33.52:2199"]
timeout = "30s"
[bm]
addr = "0.0.0.0:7531"
maxListen = 1000
timeout = "1000ms"
[httpClient]
key = "ad4bb9b8f5d9d4a7"
secret = "6912080d78d58be7cb94f57d50d438f6"
dial = "2s"
timeout = "2s"
keepAlive = "60s"
timer = 128
[httpClient.breaker]
window = "3s"
sleep = "100ms"
bucket = 10
ratio = 0.5
request = 100
[mysql]
addr = "172.16.33.205"
dsn = "zhaozhihao:MN9havOfnzY3kd6L78IVucRxgywe0p2P@tcp(172.16.33.205:3308)/bilibili_vip?timeout=5s&readTimeout=5s&writeTimeout=5s&parseTime=true&loc=Local&charset=utf8,utf8mb4"
active = 5
idle = 2
IdleTimeout ="4h"
queryTimeout = "2s"
execTimeout = "2s"
tranTimeout = "2s"
[mysql.breaker]
window = "3s"
sleep = "100ms"
bucket = 10
ratio = 0.5
request = 100
[orm]
[orm.vip]
dsn = "zhaozhihao:MN9havOfnzY3kd6L78IVucRxgywe0p2P@tcp(172.16.33.205:3308)/bilibili_vip?timeout=5s&readTimeout=5s&writeTimeout=5s&parseTime=true&loc=Local&charset=utf8,utf8mb4"
active = 5
idle = 5
idleTimeout = "4h"
[bfs]
key="b2f31180234e497c"
secret="e96a241fb05f449502420d9271b2ed"
host = "http://uat-bfs.bilibili.co"
timeout = 1000
maxFileSize = 5242880

View File

@@ -0,0 +1,42 @@
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/vip/conf",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//library/cache/memcache:go_default_library",
"//library/conf:go_default_library",
"//library/database/orm:go_default_library",
"//library/database/sql:go_default_library",
"//library/ecode/tip: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:go_default_library",
"//library/net/trace:go_default_library",
"//library/time: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,153 @@
package conf
import (
"errors"
"flag"
"go-common/library/cache/memcache"
"go-common/library/conf"
"go-common/library/database/orm"
"go-common/library/database/sql"
ecode "go-common/library/ecode/tip"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
"go-common/library/net/http/blademaster/middleware/permit"
"go-common/library/net/rpc"
"go-common/library/net/trace"
"go-common/library/time"
"github.com/BurntSushi/toml"
)
// global var
var (
confPath string
client *conf.Client
// Conf config
Conf = &Config{}
)
// Config config set
type Config struct {
// base
// elk
Log *log.Config
// mc
Memcache *Memcache
// auth
Auth *permit.Config
// MultiHTTP
BM *bm.ServerConfig
// http client
HTTPClient *bm.ClientConfig
// tracer
Tracer *trace.Config
// MySQL
MySQL *sql.Config
ORM *ORM
// VipRPC
VipRPC *rpc.ClientConfig
// business config
Property *Property
// ecode
Ecode *ecode.Config
// pay conf
PayConf *PayConf
// bfs
Bfs *Bfs
}
// Bfs reprensents the bfs config
type Bfs struct {
Key string
Secret string
Host string
Timeout int
MaxFileSize int
}
// ORM .
type ORM struct {
Vip *orm.Config
}
// Memcache .
type Memcache struct {
*memcache.Config
Expire time.Duration
}
func init() {
flag.StringVar(&confPath, "conf", "", "default config path")
}
// Property .
type Property struct {
MsgURI string
PayURI string
AnnualVipBcoinDay int
AnnualVipBcoinCouponMoney int
AnnualVipBcoinCouponActivityID int
WelfareBgHost string
}
//PayConf pay config
type PayConf struct {
BaseURL string
CustomerID int64
Token string
OrderNotifyURL string
SignNotifyURL string
RefundURL string
PlanID int32
ProductID string
Version string
ReturnURL string
}
// Init init conf
func Init() error {
if confPath != "" {
return local()
}
return remote()
}
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.Toml2(); !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
}

View File

@@ -0,0 +1,97 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_test",
"go_library",
)
go_test(
name = "go_default_test",
srcs = [
"bfs_test.go",
"dao_test.go",
"dialog_test.go",
"jointly_test.go",
"memcache_test.go",
"month_test.go",
"mysql_test.go",
"order_test.go",
"panel_test.go",
"platform_test.go",
"privilege_test.go",
"push_test.go",
"resouce_test.go",
"send_test.go",
"tips_test.go",
"vip_test.go",
"welfare_test.go",
],
embed = [":go_default_library"],
rundir = ".",
tags = ["automanaged"],
deps = [
"//app/admin/main/vip/conf:go_default_library",
"//app/admin/main/vip/model:go_default_library",
"//library/database/sql:go_default_library",
"//library/log:go_default_library",
"//library/time:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
"//vendor/gopkg.in/h2non/gock.v1:go_default_library",
],
)
go_library(
name = "go_default_library",
srcs = [
"bfs.go",
"dao.go",
"dialog.go",
"jointly.go",
"memcache.go",
"month.go",
"mysql.go",
"order.go",
"panel.go",
"platform.go",
"privilege.go",
"push.go",
"resouce.go",
"send.go",
"tips.go",
"vip.go",
"welfare.go",
],
importpath = "go-common/app/admin/main/vip/dao",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/admin/main/vip/conf:go_default_library",
"//app/admin/main/vip/model:go_default_library",
"//library/cache/memcache:go_default_library",
"//library/database/orm:go_default_library",
"//library/database/sql:go_default_library",
"//library/ecode:go_default_library",
"//library/log:go_default_library",
"//library/net/http/blademaster:go_default_library",
"//library/stat/prom:go_default_library",
"//library/time:go_default_library",
"//vendor/github.com/google/uuid: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"],
)

View File

@@ -0,0 +1,88 @@
package dao
import (
"bytes"
"context"
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"fmt"
"hash"
"net/http"
"strconv"
"time"
"go-common/app/admin/main/vip/conf"
"go-common/library/ecode"
"go-common/library/log"
)
// bfs info
const (
_uploadURL = "/bfs/%s/%s"
_template = "%s\n%s\n%s\n%d\n"
_method = "PUT"
_bucket = "vip"
)
// Upload upload picture or log file to bfs
func (d *Dao) Upload(c context.Context, fileName string, fileType string, data []byte, bfs *conf.Bfs) (location string, err error) {
var (
req *http.Request
resp *http.Response
code int
client = &http.Client{Timeout: time.Duration(bfs.Timeout) * time.Millisecond}
url = fmt.Sprintf(bfs.Host+_uploadURL, _bucket, fileName)
)
// prepare the data of the file and init the request
buf := new(bytes.Buffer)
_, err = buf.Write(data)
if err != nil {
log.Error("Upload.buf.Write.error(%v)", err)
err = ecode.RequestErr
return
}
if req, err = http.NewRequest(_method, url, buf); err != nil {
log.Error("http.NewRequest() Upload(%v) error(%v)", url, err)
return
}
timing := time.Now().Unix()
// request setting
authorization := authorize(bfs.Key, bfs.Secret, _method, _bucket, fileName, timing)
req.Header.Set("Date", fmt.Sprint(timing))
req.Header.Set("Authorization", authorization)
req.Header.Set("Content-Type", fileType)
resp, err = client.Do(req)
// response treatment
if err != nil {
log.Error("Bfs client.Do(%s) error(%v)", url, err)
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
err = fmt.Errorf("Bfs status code error:%v", resp.StatusCode)
return
}
code, err = strconv.Atoi(resp.Header.Get("code"))
if err != nil || code != 200 {
err = fmt.Errorf("Bfs response code error:%v", code)
return
}
location = resp.Header.Get("Location")
return
}
// authorize returns authorization for upload file to bfs
func authorize(key, secret, method, bucket, file string, expire int64) (authorization string) {
var (
content string
mac hash.Hash
signature string
)
content = fmt.Sprintf(_template, method, bucket, file, expire)
mac = hmac.New(sha1.New, []byte(secret))
mac.Write([]byte(content))
signature = base64.StdEncoding.EncodeToString(mac.Sum(nil))
authorization = fmt.Sprintf("%s:%s:%d", key, signature, expire)
return
}

View File

@@ -0,0 +1,46 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoUpload(t *testing.T) {
convey.Convey("Upload", t, func(ctx convey.C) {
var (
c = context.Background()
fileName = "123"
fileType = "image/png"
data = []byte("1231")
bfs = d.c.Bfs
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
location, err := d.Upload(c, fileName, fileType, data, bfs)
ctx.Convey("Then err should be nil.location should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(location, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoauthorize(t *testing.T) {
convey.Convey("authorize", t, func(ctx convey.C) {
var (
key = ""
secret = ""
method = ""
bucket = ""
file = ""
expire = int64(0)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
authorization := authorize(key, secret, method, bucket, file, expire)
ctx.Convey("Then authorization should not be nil.", func(ctx convey.C) {
ctx.So(authorization, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,65 @@
package dao
import (
"context"
"time"
"go-common/app/admin/main/vip/conf"
"go-common/library/cache/memcache"
"go-common/library/database/orm"
xsql "go-common/library/database/sql"
bm "go-common/library/net/http/blademaster"
"go-common/library/stat/prom"
"github.com/jinzhu/gorm"
)
// Dao dao conf
type Dao struct {
c *conf.Config
db *xsql.DB
vip *gorm.DB
client *bm.Client
mc *memcache.Pool
mcExpire int32
errProm *prom.Prom
}
// New init mysql db
func New(c *conf.Config) (d *Dao) {
d = &Dao{
c: c,
db: xsql.NewMySQL(c.MySQL),
vip: orm.NewMySQL(c.ORM.Vip),
client: bm.NewClient(c.HTTPClient),
mc: memcache.NewPool(c.Memcache.Config),
mcExpire: int32(time.Duration(c.Memcache.Expire) / time.Second),
errProm: prom.BusinessErrCount,
}
d.initORM()
return d
}
// Close close the resource.
func (d *Dao) Close() (err error) {
return d.db.Close()
}
// Ping dao ping
func (d *Dao) Ping(c context.Context) error {
return d.db.Ping(c)
}
// BeginTran start tx .
func (d *Dao) BeginTran(c context.Context) (tx *xsql.Tx, err error) {
return d.db.Begin(c)
}
// BeginGormTran start gorm tx .
func (d *Dao) BeginGormTran(c context.Context) (tx *gorm.DB) {
return d.vip.Begin()
}
func (d *Dao) initORM() {
d.vip.LogMode(true)
}

View File

@@ -0,0 +1,47 @@
package dao
import (
"flag"
"os"
"strings"
"testing"
"go-common/app/admin/main/vip/conf"
"gopkg.in/h2non/gock.v1"
)
var (
d *Dao
)
func TestMain(m *testing.M) {
if os.Getenv("DEPLOY_ENV") != "" {
flag.Set("app_id", "main.account.vip-admin")
flag.Set("conf_appid", "main.account.vip-admin")
flag.Set("conf_token", "12a1ee67d60cfb97ff79216e95ec5576")
flag.Set("tree_id", "20445")
flag.Set("conf_version", "docker-1")
flag.Set("deploy_env", "uat")
flag.Set("conf_env", "10")
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/vip-admin-test.toml")
}
flag.Parse()
if err := conf.Init(); err != nil {
panic(err)
}
d = New(conf.Conf)
d.client.SetTransport(gock.DefaultTransport)
os.Exit(m.Run())
}
func httpMock(method, url string) *gock.Request {
r := gock.New(url)
r.Method = strings.ToUpper(method)
return r
}

View File

@@ -0,0 +1,106 @@
package dao
import (
"context"
"time"
"go-common/app/admin/main/vip/model"
"go-common/library/ecode"
"go-common/library/log"
)
const (
_vipConfDialog = "vip_conf_dialog"
)
// DialogAll .
func (d *Dao) DialogAll(c context.Context, appID, platform int64, status string) (res []*model.ConfDialog, err error) {
db := d.vip.Table(_vipConfDialog)
if appID != 0 {
db = db.Where("app_id=?", appID)
}
if platform != 0 {
db = db.Where("platform=?", platform)
}
if len(status) > 0 {
curr := time.Now().Format("2006-01-02 15:04:05")
//padding待生效active已经生效inactive已经失效
switch status {
case "padding":
db = db.Where("stage = true AND start_time>?", curr)
case "active":
db = db.Where("stage = true AND start_time<=? AND (end_time = '1970-01-01 08:00:00' OR end_time >?)", curr, curr)
case "inactive":
db = db.Where("stage = false OR (end_time > '1970-01-01 08:00:00' AND end_time < ?)", curr)
default:
log.Info("query all dialog.")
}
}
if err := db.Find(&res).Error; err != nil {
return nil, err
}
return
}
// DialogByID vip price config by id.
func (d *Dao) DialogByID(c context.Context, id int64) (dlg *model.ConfDialog, err error) {
dlg = &model.ConfDialog{}
if err := d.vip.Table(_vipConfDialog).Where("id=?", id).First(dlg).Error; err != nil {
if err == ecode.NothingFound {
err = nil
}
return nil, err
}
return
}
// DialogBy vip price config by .
func (d *Dao) DialogBy(c context.Context, appID, platform int64, id int64) (res []*model.ConfDialog, err error) {
if err := d.vip.Table(_vipConfDialog).Where("stage = true AND app_id=? AND platform=? AND id<>?", appID, platform, id).Find(&res).Error; err != nil {
return nil, err
}
return
}
// DialogSave .
func (d *Dao) DialogSave(c context.Context, arg *model.ConfDialog) (eff int64, err error) {
db := d.vip.Table(_vipConfDialog).Save(arg)
if err = db.Error; err != nil {
return
}
eff = db.RowsAffected
return
}
// DialogEnable .
func (d *Dao) DialogEnable(c context.Context, arg *model.ConfDialog) (eff int64, err error) {
stage := map[string]interface{}{
"stage": arg.Stage,
"end_time": time.Now(),
"operator": arg.Operator,
}
db := d.vip.Table(_vipConfDialog).Where("id=?", arg.ID).Updates(stage)
if err = db.Error; err != nil {
return
}
eff = db.RowsAffected
return
}
// DialogDel delete vip price config by id.
func (d *Dao) DialogDel(c context.Context, id int64) (eff int64, err error) {
db := d.vip.Table(_vipConfDialog).Where("id=?", id).Delete(&model.ConfDialog{})
if err = db.Error; err != nil {
return
}
eff = db.RowsAffected
return
}
// CountDialogByPlatID count dialog by platform id .
func (d *Dao) CountDialogByPlatID(c context.Context, plat int64) (count int64, err error) {
if err := d.vip.Table(_vipConfDialog).Where("platform=?", plat).Count(&count).Error; err != nil {
return 0, err
}
return
}

View File

@@ -0,0 +1,54 @@
package dao
import (
"context"
"fmt"
"testing"
"time"
"go-common/app/admin/main/vip/model"
xtime "go-common/library/time"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoDialogSave(t *testing.T) {
curr := xtime.Time(time.Now().Unix())
convey.Convey("DialogSave", t, func() {
dlg := &model.ConfDialog{ID: 1, StartTime: curr, Operator: "tommy"}
eff, err := d.DialogSave(context.TODO(), dlg)
convey.So(err, convey.ShouldBeNil)
convey.So(eff, convey.ShouldNotBeNil)
})
convey.Convey("DialogByID", t, func() {
dlg, err := d.DialogByID(context.TODO(), 1)
convey.So(err, convey.ShouldBeNil)
convey.So(dlg, convey.ShouldNotBeNil)
})
convey.Convey("DialogEnable", t, func() {
dlg := &model.ConfDialog{ID: 1, Stage: false}
eff, err := d.DialogEnable(context.TODO(), dlg)
convey.So(err, convey.ShouldBeNil)
convey.So(eff, convey.ShouldNotBeNil)
})
convey.Convey("DialogEnable", t, func() {
dlg := &model.ConfDialog{ID: 1, Stage: true}
eff, err := d.DialogEnable(context.TODO(), dlg)
convey.So(err, convey.ShouldBeNil)
convey.So(eff, convey.ShouldNotBeNil)
})
convey.Convey("DialogAll", t, func() {
res, err := d.DialogAll(context.TODO(), 0, 0, "active")
convey.So(err, convey.ShouldBeNil)
convey.So(res, convey.ShouldNotBeNil)
})
}
func TestDaoCountDialogByPlatID(t *testing.T) {
convey.Convey("TestDaoCountDialogByPlatID", t, func() {
res, err := d.CountDialogByPlatID(context.TODO(), 1)
fmt.Println(res)
convey.So(err, convey.ShouldBeNil)
convey.So(res, convey.ShouldBeGreaterThanOrEqualTo, 0)
})
}

View File

@@ -0,0 +1,90 @@
package dao
import (
"context"
xsql "database/sql"
"go-common/app/admin/main/vip/model"
"go-common/library/database/sql"
"github.com/pkg/errors"
)
const (
_jointlysWillEffectSQL = "SELECT id,title,content,operator,start_time,end_time,link,is_hot,ctime,mtime FROM vip_jointly WHERE start_time > ? AND deleted = 0 ORDER BY mtime DESC;"
_jointlysEffectSQL = "SELECT id,title,content,operator,start_time,end_time,link,is_hot,ctime,mtime FROM vip_jointly WHERE start_time < ? AND end_time > ? AND deleted = 0 ORDER BY mtime DESC;"
_jointlysLoseEffectSQL = "SELECT id,title,content,operator,start_time,end_time,link,is_hot,ctime,mtime FROM vip_jointly WHERE end_time < ? AND deleted = 0 ORDER BY mtime DESC;"
_addjointlySQL = "INSERT INTO vip_jointly(title,content,operator,start_time,end_time,link,is_hot)VALUES(?,?,?,?,?,?,?);"
_updateJointlySQL = "UPDATE vip_jointly SET title = ?,content = ?,operator = ?,link = ?,is_hot = ?,start_time = ?,end_time = ? WHERE id = ?;"
_deleteJointlySQL = "UPDATE vip_jointly SET deleted = 1 WHERE id = ?;"
)
// AddJointly add jointly.
func (d *Dao) AddJointly(c context.Context, j *model.Jointly) (a int64, err error) {
var res xsql.Result
if res, err = d.db.Exec(c, _addjointlySQL, j.Title, j.Content, j.Operator, j.StartTime, j.EndTime, j.Link, j.IsHot); err != nil {
err = errors.WithStack(err)
return
}
if a, err = res.RowsAffected(); err != nil {
err = errors.WithStack(err)
}
return
}
// JointlysByState jointly by state.
func (d *Dao) JointlysByState(c context.Context, state int8, now int64) (res []*model.Jointly, err error) {
var rows *sql.Rows
switch state {
case model.WillEffect:
rows, err = d.db.Query(c, _jointlysWillEffectSQL, now)
case model.Effect:
rows, err = d.db.Query(c, _jointlysEffectSQL, now, now)
case model.LoseEffect:
rows, err = d.db.Query(c, _jointlysLoseEffectSQL, now)
default:
return
}
if err != nil {
err = errors.WithStack(err)
return
}
defer rows.Close()
for rows.Next() {
r := new(model.Jointly)
if err = rows.Scan(&r.ID, &r.Title, &r.Content, &r.Operator, &r.StartTime, &r.EndTime, &r.Link, &r.IsHot, &r.CTime, &r.MTime); err != nil {
err = errors.WithStack(err)
res = nil
return
}
res = append(res, r)
}
err = rows.Err()
return
}
// UpdateJointly update jointly.
func (d *Dao) UpdateJointly(c context.Context, j *model.Jointly) (a int64, err error) {
var res xsql.Result
if res, err = d.db.Exec(c, _updateJointlySQL, j.Title, j.Content, j.Operator, j.Link, j.IsHot, j.StartTime, j.EndTime, j.ID); err != nil {
err = errors.WithStack(err)
return
}
if a, err = res.RowsAffected(); err != nil {
err = errors.WithStack(err)
}
return
}
// DeleteJointly delete jointly.
func (d *Dao) DeleteJointly(c context.Context, id int64) (a int64, err error) {
var res xsql.Result
if res, err = d.db.Exec(c, _deleteJointlySQL, id); err != nil {
err = errors.WithStack(err)
return
}
if a, err = res.RowsAffected(); err != nil {
err = errors.WithStack(err)
}
return
}

View File

@@ -0,0 +1,65 @@
package dao
import (
"context"
"fmt"
"math/rand"
"testing"
"time"
"go-common/app/admin/main/vip/model"
. "github.com/smartystreets/goconvey/convey"
)
// go test -test.v -test.run TestDaoAddJointly
func TestDaoAddJointly(t *testing.T) {
Convey("TestDaoAddJointly", t, func() {
a, err := d.AddJointly(context.TODO(), &model.Jointly{
Title: "这条是有效的,并且不 hot",
Content: "这叫副标题?",
Operator: "admin",
StartTime: 1533202903,
EndTime: 1543202904,
Link: fmt.Sprintf("https://t.cn/%d", rand.Int63()),
IsHot: 1,
})
So(err, ShouldBeNil)
So(a, ShouldEqual, 1)
})
}
// go test -test.v -test.run TestDaoUpdateJointly
func TestDaoUpdateJointly(t *testing.T) {
Convey("TestDaoUpdateJointly", t, func() {
a, err := d.UpdateJointly(context.TODO(), &model.Jointly{
Title: "这条是有效的,并且no hot",
Content: "这叫副标题??",
Operator: "admin2",
Link: fmt.Sprintf("https://t.cn/%d", rand.Int63()),
IsHot: 0,
ID: 1,
})
So(err, ShouldBeNil)
So(a, ShouldEqual, 1)
})
}
// go test -test.v -test.run TestDaoJointlysByState
func TestDaoJointlysByState(t *testing.T) {
Convey("TestDaoJointlysByState", t, func() {
res, err := d.JointlysByState(context.TODO(), 1, time.Now().Unix())
t.Logf("count %+v", len(res))
So(err, ShouldBeNil)
})
}
// go test -test.v -test.run TestDaoDeleteJointly
func TestDaoDeleteJointly(t *testing.T) {
Convey("TestDaoDeleteJointly", t, func() {
res, err := d.DeleteJointly(context.TODO(), 1)
t.Logf("count %+v", res)
So(res, ShouldBeGreaterThanOrEqualTo, 0)
So(err, ShouldBeNil)
})
}

View File

@@ -0,0 +1,93 @@
package dao
import (
"context"
"fmt"
gmc "go-common/library/cache/memcache"
"go-common/library/log"
"github.com/pkg/errors"
)
const (
_vipInfo = "big:%d"
_ui = "ui:%s"
)
func userinfo(name string) string {
return fmt.Sprintf(_ui, name)
}
func vipInfoKey(mid int64) string {
return fmt.Sprintf(_vipInfo, mid)
}
// DelVipInfoCache delete vipinfo cache.
func (d *Dao) DelVipInfoCache(c context.Context, mid int64) (err error) {
return d.delCache(c, vipInfoKey(mid))
}
func (d *Dao) delCache(c context.Context, key string) (err error) {
conn := d.mc.Get(c)
defer conn.Close()
if err = conn.Delete(key); err != nil {
err = errors.WithStack(err)
d.errProm.Incr("conn_del")
return
}
return
}
// DelSelCode .
func (d *Dao) DelSelCode(c context.Context, username string) (err error) {
return d.delCache(c, userinfo(username))
}
// SetSelCode .
func (d *Dao) SetSelCode(c context.Context, username string, linkmap map[int64]int64) (err error) {
var (
key = userinfo(username)
)
conn := d.mc.Get(c)
defer conn.Close()
item := &gmc.Item{Key: key, Object: linkmap, Expiration: d.mcExpire, Flags: gmc.FlagJSON}
if err = conn.Set(item); err != nil {
err = errors.Wrapf(err, "conn.Set(%s)", key)
d.errProm.Incr("set_selcode")
}
return
}
// GetSelCode .
func (d *Dao) GetSelCode(c context.Context, username string) (linkmap map[int64]int64, err error) {
var (
key = userinfo(username)
)
conn := d.mc.Get(c)
defer conn.Close()
item, err := conn.Get(key)
if err != nil {
if err == gmc.ErrNotFound {
err = nil
return
}
err = errors.Wrapf(err, "conn.Get(%s)", key)
d.errProm.Incr("vipinfo_mc")
return
}
linkmap = make(map[int64]int64)
if err = conn.Scan(item, &linkmap); err != nil {
err = errors.Wrapf(err, "conn.Scan(%s)", key)
}
return
}
// PingMC ping memcache.
func (d *Dao) PingMC(c context.Context) (err error) {
conn := d.mc.Get(c)
defer conn.Close()
if err = conn.Set(&gmc.Item{Key: "ping", Value: []byte{1}, Expiration: d.mcExpire}); err != nil {
log.Error("conn.Store(set, ping, 1) error(%v)", err)
}
return
}

View File

@@ -0,0 +1,38 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestVipInfoKey(t *testing.T) {
convey.Convey("vipInfoKey", t, func() {
p1 := vipInfoKey(0)
convey.So(p1, convey.ShouldNotBeNil)
})
}
func TestDaoSetSelCode(t *testing.T) {
convey.Convey("SetSelCode", t, func() {
linkmap := map[int64]int64{1: 1}
err := d.SetSelCode(context.TODO(), "testSelCode", linkmap)
convey.So(err, convey.ShouldBeNil)
})
convey.Convey("GetSelCode", t, func() {
_, err := d.GetSelCode(context.TODO(), "testSelCode")
convey.So(err, convey.ShouldBeNil)
})
convey.Convey("DelSelCode", t, func() {
err := d.DelSelCode(context.TODO(), "testSelCode")
convey.So(err, convey.ShouldBeNil)
})
}
func TestDaoPingMC(t *testing.T) {
convey.Convey("PingMC", t, func() {
err := d.PingMC(context.TODO())
convey.So(err, convey.ShouldBeNil)
})
}

View File

@@ -0,0 +1,120 @@
package dao
import (
"context"
xsql "database/sql"
"go-common/app/admin/main/vip/model"
"go-common/library/database/sql"
"github.com/pkg/errors"
)
// GetMonth .
func (d *Dao) GetMonth(c context.Context, id int64) (m *model.VipMonth, err error) {
res := d.db.QueryRow(c, _getMonth, id)
m = new(model.VipMonth)
if err = res.Scan(&m.ID, &m.Month, &m.MonthType, &m.Operator, &m.Status, &m.Mtime); err != nil {
if err == sql.ErrNoRows {
err = nil
m = nil
} else {
err = errors.WithStack(err)
}
}
return
}
// MonthList get all month.
func (d *Dao) MonthList(c context.Context) (res []*model.VipMonth, err error) {
var rows *sql.Rows
if rows, err = d.db.Query(c, _allMonth); err != nil {
err = errors.WithStack(err)
return
}
defer rows.Close()
for rows.Next() {
r := &model.VipMonth{}
if err = rows.Scan(&r.ID, &r.Month, &r.MonthType, &r.Operator, &r.Status, &r.Mtime); err != nil {
err = errors.WithStack(err)
res = nil
return
}
res = append(res, r)
}
return
}
// MonthEdit .
func (d *Dao) MonthEdit(c context.Context, id int64, status int8, op string) (eff int64, err error) {
var res xsql.Result
if res, err = d.db.Exec(c, _updateMonthStatus, status, op, id); err != nil {
err = errors.WithStack(err)
return
}
if eff, err = res.RowsAffected(); err != nil {
err = errors.WithStack(err)
}
return
}
// GetPrice .
func (d *Dao) GetPrice(c context.Context, id int64) (r *model.VipMonthPrice, err error) {
row := d.db.QueryRow(c, _monthPriceSQL, id)
r = new(model.VipMonthPrice)
if err = row.Scan(&r.ID, &r.MonthID, &r.MonthType, &r.Money, &r.Selected, &r.FirstDiscountMoney, &r.DiscountMoney, &r.StartTime, &r.EndTime, &r.Remark, &r.Operator); err != nil {
if err == sql.ErrNoRows {
err = nil
r = nil
} else {
err = errors.WithStack(err)
}
}
return
}
// PriceList .
func (d *Dao) PriceList(c context.Context, mID int64) (res []*model.VipMonthPrice, err error) {
var rows *sql.Rows
if rows, err = d.db.Query(c, _allMonthPrice, mID); err != nil {
err = errors.WithStack(err)
return
}
defer rows.Close()
for rows.Next() {
r := &model.VipMonthPrice{}
if err = rows.Scan(&r.ID, &r.MonthID, &r.MonthType, &r.Money, &r.Selected, &r.FirstDiscountMoney, &r.DiscountMoney, &r.StartTime, &r.EndTime, &r.Remark, &r.Operator); err != nil {
err = errors.WithStack(err)
res = nil
return
}
res = append(res, r)
}
return
}
// PriceAdd .
func (d *Dao) PriceAdd(c context.Context, mp *model.VipMonthPrice) (eff int64, err error) {
var res xsql.Result
if res, err = d.db.Exec(c, _addMonthPrice, mp.MonthID, mp.MonthType, mp.Money, mp.FirstDiscountMoney, mp.DiscountMoney, mp.StartTime, mp.EndTime, mp.Remark, mp.Operator); err != nil {
err = errors.WithStack(err)
return
}
if eff, err = res.RowsAffected(); err != nil {
err = errors.WithStack(err)
}
return
}
// PriceEdit .
func (d *Dao) PriceEdit(c context.Context, mp *model.VipMonthPrice) (eff int64, err error) {
var res xsql.Result
if res, err = d.db.Exec(c, _editMonthPrice, mp.MonthType, mp.Money, mp.FirstDiscountMoney, mp.DiscountMoney, mp.StartTime, mp.EndTime, mp.Remark, mp.Operator, mp.ID); err != nil {
err = errors.WithStack(err)
return
}
if eff, err = res.RowsAffected(); err != nil {
err = errors.WithStack(err)
}
return
}

View File

@@ -0,0 +1,78 @@
package dao
import (
"context"
"testing"
"go-common/app/admin/main/vip/model"
. "github.com/smartystreets/goconvey/convey"
)
var (
ctx = context.TODO()
)
func Test_GetMonth(t *testing.T) {
Convey("Test_GetMonth", t, func() {
res, err := d.GetMonth(context.Background(), 11)
So(err, ShouldBeNil)
So(res, ShouldNotBeNil)
})
}
func Test_MonthList(t *testing.T) {
Convey("Test_MonthList", t, func() {
res, err := d.MonthList(context.TODO())
So(err, ShouldBeNil)
So(res, ShouldNotBeEmpty)
})
}
func Test_MonthEdit(t *testing.T) {
var (
id int64 = 31
status int8 = 1
op = "test"
)
Convey("Test_MonthEdit", t, func() {
res, err := d.MonthEdit(context.Background(), id, status, op)
So(err, ShouldBeNil)
So(res, ShouldBeGreaterThanOrEqualTo, 0)
})
}
func Test_GetPrice(t *testing.T) {
var id int64 = 60
Convey("Test_GetPrice", t, func() {
res, err := d.GetPrice(context.Background(), id)
So(err, ShouldBeNil)
So(res, ShouldNotBeNil)
})
}
func Test_MonthPriceList(t *testing.T) {
Convey("Test_MonthPriceList", t, func() {
var (
err error
eff int64
res []*model.VipMonthPrice
)
ap := &model.VipMonthPrice{MonthID: 2, Money: 2.00}
eff, err = d.PriceAdd(ctx, ap)
So(err, ShouldBeNil)
So(eff, ShouldEqual, 1)
res, err = d.PriceList(context.TODO(), 2)
So(err, ShouldBeNil)
So(res, ShouldNotBeEmpty)
})
}
func Test_PriceEdit(t *testing.T) {
var (
vp = &model.VipMonthPrice{MonthID: 2, Money: 2.00}
)
Convey("Test_PriceEdit", t, func() {
res, err := d.PriceEdit(context.Background(), vp)
So(err, ShouldBeNil)
So(res, ShouldBeGreaterThanOrEqualTo, 0)
})
}

View File

@@ -0,0 +1,539 @@
package dao
import (
"context"
xsql "database/sql"
"fmt"
"strconv"
"time"
"go-common/app/admin/main/vip/model"
"go-common/library/database/sql"
"go-common/library/log"
"github.com/pkg/errors"
)
const (
_SelPoolQueryCount = "SELECT COUNT(1) count from vip_resource_pool WHERE 1=1"
_SelBusinessByID = "SELECT id,business_name,business_type,status,app_key,secret,contacts,contacts_number,ctime,mtime FROM vip_business_info WHERE id=?"
_SelBusinessByQuery = "SELECT id,business_name,business_type,status,app_key,secret,contacts,contacts_number,ctime,mtime FROM vip_business_info WHERE 1=1 "
_SelPoolByQuery = "SELECT id,pool_name,business_id,reason,code_expire_time,start_time,end_time,contacts,contacts_number FROM vip_resource_pool WHERE 1=1"
_SelPoolByName = "SELECT id,pool_name,business_id,reason,code_expire_time,start_time,end_time,contacts,contacts_number FROM vip_resource_pool WHERE pool_name = ?"
_SelPoolByID = "SELECT id,pool_name,business_id,reason,code_expire_time,start_time,end_time,contacts,contacts_number FROM vip_resource_pool WHERE id=?"
_AddPool = "INSERT INTO vip_resource_pool(pool_name,business_id,reason,code_expire_time,start_time,end_time,contacts,contacts_number) VALUES(?,?,?,?,?,?,?,?)"
_UpdatePool = "UPDATE vip_resource_pool SET pool_name=?,business_id=?,reason=?,code_expire_time=?,start_time=?,end_time=?,contacts=?,contacts_number=? WHERE id = ?"
_SelBatchByPoolID = "SELECT id,pool_id,unit,count,ver,start_time,end_time,surplus_count,code_use_count,direct_use_count FROM vip_resource_batch WHERE pool_id=?"
_SelBatchByID = "SELECT id,pool_id,unit,count,ver,start_time,end_time,surplus_count,code_use_count,direct_use_count FROM vip_resource_batch WHERE id=?"
_AddBatch = "INSERT INTO vip_resource_batch(pool_id,unit,count,ver,start_time,end_time,surplus_count,code_use_count,direct_use_count) VALUES(?,?,?,?,?,?,?,?,?)"
_UpdateBatch = "UPDATE vip_resource_batch SET count = ?,ver=?,start_time=?,end_time=?,surplus_count=? WHERE id = ? AND ver=?"
_UseBatch = "UPDATE vip_resource_batch SET ver=?,surplus_count = ?,direct_use_count=? WHERE id =? AND ver=?"
_allVersionSQL = "SELECT `id`,`platform_id`,`version`,`tip`,`operator`,`link` FROM `vip_app_version`;"
_updateVersionSQL = "UPDATE `vip_app_version` SET %s WHERE `id` = ?;"
_businessInfosSQL = "SELECT id,business_name,business_type,status,app_key,contacts,contacts_number,ctime,mtime FROM vip_business_info WHERE 1=1 "
_businessCountSQL = "SELECT COUNT(1) FROM vip_business_info WHERE 1=1"
_addBusinessSQL = "INSERT INTO `vip_business_info` (`business_name`,`business_type`,`status`,`app_key`,`secret`,`contacts`,`contacts_number`) VALUES (?,?,?,?,?,?,?);"
_updateBusinessSQL = "UPDATE `vip_business_info` SET `business_name` = ?,`business_type` = ?,`status` = ?,`app_key` = ?,`secret` = ?,`contacts` = ?,`contacts_number` = ? WHERE `id` = ?;"
_allMonth = "SELECT id,month,month_type,operator,status,mtime FROM vip_month WHERE deleted = 0"
_getMonth = "SELECT id,month,month_type,operator,status,mtime FROM vip_month WHERE id=?"
_updateMonthStatus = "UPDATE vip_month SET status=?,operator=? WHERE id=?"
_allMonthPrice = "SELECT id,month_id,month_type,money,selected,first_discount_money,discount_money,start_time,end_time,remark,operator FROM vip_month_price WHERE month_id=?"
_monthPriceSQL = "SELECT id,month_id,month_type,money,selected,first_discount_money,discount_money,start_time,end_time,remark,operator FROM vip_month_price WHERE id=?"
_addMonthPrice = "INSERT INTO vip_month_price (month_id,month_type,money,first_discount_money,discount_money,start_time,end_time,remark,operator) VALUES (?,?,?,?,?,?,?,?,?)"
_editMonthPrice = "UPDATE vip_month_price SET month_type=?,money=?,first_discount_money=?,discount_money=?,start_time=?,end_time=?,remark=?,operator=? WHERE id=?"
//resouce SQL
_addBatchCodeSQL = "INSERT INTO vip_resource_batch_code(business_id,pool_id,status,batch_name,reason,unit,count,surplus_count,price,start_time,end_time,contacts,contacts_number,type,limit_day,max_count,operator) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
_updateBatchCodeSQL = "UPDATE vip_resource_batch_code SET status=?,batch_name=?,reason=?,price=?,contacts=?,contacts_number=?,type=?,limit_day=?,max_count=?,operator=? WHERE id=?"
_selBatchCodeIDSQL = "SELECT id FROM vip_resource_batch_code WHERE 1=1"
_selBatchCodeSQL = "SELECT id,business_id,pool_id,status,type,limit_day,max_count,batch_name,reason,unit,count,surplus_count,price,start_time,end_time,contacts,contacts_number,ctime FROM vip_resource_batch_code WHERE 1=1 "
_selBatchCodeByIDSQL = "SELECT id,business_id,pool_id,status,type,limit_day,max_count,batch_name,reason,unit,count,surplus_count,price,start_time,end_time,contacts,contacts_number,ctime FROM vip_resource_batch_code WHERE id = ?"
_selBatchCodeCountSQL = "SELECT COUNT(1) FROM vip_resource_batch_code WHERE 1=1 "
_selBatchCodeByNameSQL = "SELECT id,business_id,pool_id,status,type,limit_day,max_count,batch_name,reason,unit,count,surplus_count,price,start_time,end_time,contacts,contacts_number,ctime FROM vip_resource_batch_code WHERE batch_name = ?"
_selBatchCodesSQL = "SELECT id,business_id,pool_id,status,type,limit_day,max_count,batch_name,reason,unit,count,surplus_count,price,start_time,end_time,contacts,contacts_number,ctime FROM vip_resource_batch_code WHERE 1=1 AND id in (%v)"
_batchAddCodeSQL = "INSERT INTO vip_resource_code(batch_code_id,status,code) VALUES"
_updateCodeSQL = "UPDATE vip_resource_code SET status=? WHERE id = ?"
_selCodeSQL = "SELECT id,batch_code_id,status,code,mid,use_time,ctime FROM vip_resource_code WHERE 1=1"
_selCodeByIDSQL = "SELECT id,batch_code_id,status,code,mid,use_time,ctime FROM vip_resource_code WHERE id = ?"
//pushData
_selPushDataCountSQL = "SELECT COUNT(1) FROM vip_push_data WHERE 1=1 "
_selPushDataSQL = "SELECT id,disable_type,`group_name`,title,content,push_total_count,pushed_count,progress_status,`status`,platform,link_type,link_url,error_code,expired_day_start,expired_day_end,effect_start_date,effect_end_date,push_start_time,push_end_time,operator FROM vip_push_data WHERE 1=1 "
_selPushDataByIDSQL = "SELECT id,disable_type,`group_name`,title,content,push_total_count,pushed_count,progress_status,`status`,platform,link_type,link_url,error_code,expired_day_start,expired_day_end,effect_start_date,effect_end_date,push_start_time,push_end_time,operator FROM vip_push_data WHERE id=?"
_addPushDataSQL = "INSERT INTO vip_push_data(`group_name`,title,content,push_total_count,pushed_count,progress_status,`status`,platform,link_type,link_url,expired_day_start,expired_day_end,effect_start_date,effect_end_date,push_start_time,push_end_time,operator) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
_updatePushDataSQL = "UPDATE vip_push_data SET group_name=?,title=?,content=?,push_total_count=?,progress_status=?,platform=?,link_type=?,link_url=?,expired_day_start=?,expired_day_end=?,effect_start_date=?,effect_end_date=?,push_start_time=?,push_end_time=?,operator=? WHERE id=?"
_delPushDataSQL = "DELETE FROM vip_push_data WHERE id = ?"
_disablePushDataSQL = "UPDATE vip_push_data SET disable_type=1,progress_status=?,push_total_count=?,effect_end_date=? WHERE id=?"
//order
_vipOrderListSQL = "SELECT id,order_no,app_id,platform,order_type,mid,to_mid,buy_months,money,refund_amount,status,pay_type,recharge_bp,third_trade_no,ver,payment_time,ctime,mtime,app_sub_id FROM vip_pay_order WHERE 1=1"
_vipOrderCountSQL = "SELECT COUNT(1) FROM vip_pay_order WHERE 1=1"
_vipOrderSQL = "SELECT id,order_no,app_id,platform,order_type,mid,to_mid,buy_months,money,refund_amount,status,pay_type,recharge_bp,third_trade_no,ver,payment_time,ctime,mtime,app_sub_id FROM vip_pay_order WHERE order_no = ? "
_addOrderLogSQL = "INSERT INTO vip_pay_order_log(order_no,refund_id,refund_amount,operator,mid,status) VALUES(?,?,?,?,?,?)"
_getUserChangeHistorySQL = "SELECT id,mid,change_type,change_time,days,operator_id,relation_id,batch_id,remark,ctime,mtime FROM vip_user_change_history WHERE 1=1 "
_getUserChangeHistoryCountSQL = "SELECT COUNT(1) FROM `vip_user_change_history` WHERE 1=1 "
_defpn = 1
_defps = 20
_maxps = 100
)
func (d *Dao) joinPoolCondition(sql string, q *model.ResoucePoolBo, pn, ps int) string {
if len(q.PoolName) > 0 {
sql += " and pool_name like '%" + q.PoolName + "%'"
}
if q.BusinessID > 0 {
sql += " and business_id = " + strconv.Itoa(q.BusinessID)
}
if q.StartTime > 0 {
sql += " and start_time >= '" + q.StartTime.Time().Format("2006-01-02 15:04:05") + "'"
}
if q.EndTime > 0 {
sql += " and end_time <='" + q.EndTime.Time().Format("2006-01-02 15:04:05") + "'"
}
if q.ID > 0 || q.ID == -1 {
sql += " and id = " + strconv.Itoa(q.ID)
}
if pn > 0 {
if ps <= 0 {
ps = 20
}
offer := (q.PN - 1) * q.PS
sql += " limit " + strconv.Itoa(offer) + ", " + strconv.Itoa(q.PS)
}
return sql
}
func (d *Dao) joinHistoryCondition(sql string, u *model.UserChangeHistoryReq, iscount bool) string {
if u.Mid > 0 {
sql += " AND mid = " + fmt.Sprintf("%d", u.Mid)
}
if u.ChangeType > 0 {
sql += " AND change_type = " + fmt.Sprintf("%d", u.ChangeType)
}
if u.StartChangeTime > 0 {
stime := time.Unix(u.StartChangeTime, 0).Format("2006-01-02 15:04:05")
sql += " AND change_time >= '" + stime + "'"
}
if u.EndChangeTime > 0 {
etime := time.Unix(u.EndChangeTime, 0).Format("2006-01-02 15:04:05")
sql += " AND change_time <= '" + etime + "'"
}
if u.BatchID > 0 {
sql += " AND batch_id = " + fmt.Sprintf("%d", u.BatchID)
}
if len(u.RelationID) > 0 {
sql += " AND relation_id = " + fmt.Sprintf("'%v'", u.RelationID)
}
if iscount {
return sql
}
if u.Pn == 0 {
u.Pn = _defpn
}
if u.Ps == 0 {
u.Ps = _defps
}
offer := (u.Pn - 1) * u.Ps
sql += " ORDER BY id DESC LIMIT " + strconv.Itoa(offer) + ", " + strconv.Itoa(u.Ps)
return sql
}
// SelPoolByName sel pool by name
func (d *Dao) SelPoolByName(c context.Context, name string) (r *model.VipResourcePool, err error) {
var row *sql.Row
if row = d.db.QueryRow(c, _SelPoolByName, name); err != nil {
log.Error("SelPoolByName db.query() error(%v)", err)
return
}
r = new(model.VipResourcePool)
if err = row.Scan(&r.ID, &r.PoolName, &r.BusinessID, &r.Reason, &r.CodeExpireTime, &r.StartTime, &r.EndTime, &r.Contacts, &r.ContactsNumber); err != nil {
if err == sql.ErrNoRows {
err = nil
r = nil
} else {
log.Error("row.Scan() error(%v)", err)
}
return
}
return
}
// SelCountPool sel count Pool
func (d *Dao) SelCountPool(c context.Context, r *model.ResoucePoolBo) (count int, err error) {
var row *sql.Row
if row = d.db.QueryRow(c, d.joinPoolCondition(_SelPoolQueryCount, r, 0, 0)); err != nil {
log.Error("SelCountPool db.query() error(%v)", err)
return
}
if err = row.Scan(&count); err != nil {
log.Error("row.scan() error(%v)", err)
return
}
return
}
// SelPool sel pool by query condition
func (d *Dao) SelPool(c context.Context, r *model.ResoucePoolBo, pn, ps int) (res []*model.VipResourcePool, err error) {
var rows *sql.Rows
if rows, err = d.db.Query(c, d.joinPoolCondition(_SelPoolByQuery, r, pn, ps)); err != nil {
log.Error("SelPool db.query() error(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
r := new(model.VipResourcePool)
if err = rows.Scan(&r.ID, &r.PoolName, &r.BusinessID, &r.Reason, &r.CodeExpireTime, &r.StartTime, &r.EndTime, &r.Contacts, &r.ContactsNumber); err != nil {
log.Error("row.scan() error(%v)", err)
res = nil
return
}
res = append(res, r)
}
return
}
// SelPoolRow sel pool by id
func (d *Dao) SelPoolRow(c context.Context, id int) (r *model.VipResourcePool, err error) {
var row *sql.Row
if row = d.db.QueryRow(c, _SelPoolByID, id); err != nil {
log.Error("SelPoolRow db.query() error(%v)", err)
return
}
r = new(model.VipResourcePool)
if err = row.Scan(&r.ID, &r.PoolName, &r.BusinessID, &r.Reason, &r.CodeExpireTime, &r.StartTime, &r.EndTime, &r.Contacts, &r.ContactsNumber); err != nil {
if err == sql.ErrNoRows {
err = nil
r = nil
} else {
log.Error("row.Scan() error(%v)", err)
}
return
}
return
}
// AddPool add pool
func (d *Dao) AddPool(c context.Context, r *model.ResoucePoolBo) (a int64, err error) {
var res xsql.Result
if res, err = d.db.Exec(c, _AddPool, r.PoolName, r.BusinessID, r.Reason, r.CodeExpireTime, r.StartTime, r.EndTime, r.Contacts, r.ContactsNumber); err != nil {
log.Error("AddPool d.db.exec(%v) error(%v)", r, err)
return
}
if a, err = res.RowsAffected(); err != nil {
log.Error("AddPool RowsAffected() error(%v)", err)
return
}
return
}
// UpdatePool update pool
func (d *Dao) UpdatePool(c context.Context, r *model.ResoucePoolBo) (a int64, err error) {
var res xsql.Result
if res, err = d.db.Exec(c, _UpdatePool, r.PoolName, r.BusinessID, r.Reason, r.CodeExpireTime, r.StartTime, r.EndTime, r.Contacts, r.ContactsNumber, r.ID); err != nil {
log.Error("UpdatePool d.db.exec(%v) error(%v)", r, err)
return
}
if a, err = res.RowsAffected(); err != nil {
log.Error("UpdatePool RowsAffected() error(%v)", err)
return
}
return
}
// SelBatchRow sel batch by id
func (d *Dao) SelBatchRow(c context.Context, id int) (r *model.VipResourceBatch, err error) {
var row *sql.Row
if row = d.db.QueryRow(c, _SelBatchByID, id); err != nil {
log.Error("SelBatchRow db.query() error(%v)", err)
return
}
r = new(model.VipResourceBatch)
if err = row.Scan(&r.ID, &r.PoolID, &r.Unit, &r.Count, &r.Ver, &r.StartTime, &r.EndTime, &r.SurplusCount, &r.CodeUseCount, &r.DirectUseCount); err != nil {
if err == sql.ErrNoRows {
err = nil
r = nil
} else {
log.Error("row.Scan() error(%v)", err)
}
return
}
return
}
// SelBatchRows sel batch by poolID
func (d *Dao) SelBatchRows(c context.Context, poolID int) (res []*model.VipResourceBatch, err error) {
var rows *sql.Rows
if rows, err = d.db.Query(c, _SelBatchByPoolID, poolID); err != nil {
log.Error("SelBatchRows db.query() error(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
r := new(model.VipResourceBatch)
if err = rows.Scan(&r.ID, &r.PoolID, &r.Unit, &r.Count, &r.Ver, &r.StartTime, &r.EndTime, &r.SurplusCount, &r.CodeUseCount, &r.DirectUseCount); err != nil {
log.Error("row.scan() error(%v)", err)
res = nil
return
}
res = append(res, r)
}
return
}
// AddBatch add batch
func (d *Dao) AddBatch(c context.Context, r *model.ResouceBatchBo) (a int64, err error) {
var res xsql.Result
if res, err = d.db.Exec(c, _AddBatch, r.PoolID, r.Unit, r.Count, 0, r.StartTime, r.EndTime, r.SurplusCount, r.CodeUseCount, r.DirectUseCount); err != nil {
log.Error("AddBatch d.db.exec(%v) error(%v)", r, err)
return
}
if a, err = res.RowsAffected(); err != nil {
log.Error("AddBatch RowsAffected() error(%v)", err)
return
}
return
}
// UpdateBatch update batch data
func (d *Dao) UpdateBatch(c context.Context, r *model.VipResourceBatch, ver int) (a int64, err error) {
var res xsql.Result
if res, err = d.db.Exec(c, _UpdateBatch, r.Count, r.Ver, r.StartTime, r.EndTime, r.SurplusCount, r.ID, ver); err != nil {
log.Error("UpdateBatch d.db.exec(%v) error(%v)", r, err)
return
}
if a, err = res.RowsAffected(); err != nil {
log.Error("UpdateBatch RowsAffected() error(%v)", err)
return
}
return
}
// UseBatch use batch resouce
func (d *Dao) UseBatch(tx *sql.Tx, r *model.VipResourceBatch, ver int) (a int64, err error) {
var res xsql.Result
if res, err = tx.Exec(_UseBatch, r.Ver, r.SurplusCount, r.DirectUseCount, r.ID, ver); err != nil {
log.Error("UseBatch d.db.exec(%v) error(%v)", r, err)
return
}
if a, err = res.RowsAffected(); err != nil {
log.Error("UseBatch RowsAffected() error(%v)", err)
return
}
return
}
// SelBusiness select businessInfo by id
func (d *Dao) SelBusiness(c context.Context, id int) (r *model.VipBusinessInfo, err error) {
var row = d.db.QueryRow(c, _SelBusinessByID, id)
r = new(model.VipBusinessInfo)
if err = row.Scan(&r.ID, &r.BusinessName, &r.BusinessType, &r.Status, &r.AppKey, &r.Secret, &r.Contacts, &r.ContactsNumber, &r.Ctime, &r.Mtime); err != nil {
if err == sql.ErrNoRows {
err = nil
r = nil
} else {
log.Error("row.Scan() error(%v)", err)
}
}
return
}
// SelBusinessByQuery .
func (d *Dao) SelBusinessByQuery(c context.Context, arg *model.QueryBusinessInfo) (r *model.VipBusinessInfo, err error) {
queryStr := ""
if len(arg.Name) > 0 {
queryStr += fmt.Sprintf(" AND business_name = '%v' ", arg.Name)
}
if len(arg.Appkey) > 0 {
queryStr += fmt.Sprintf(" AND app_key = '%v' ", arg.Appkey)
}
var row = d.db.QueryRow(c, _SelBusinessByQuery+queryStr)
r = new(model.VipBusinessInfo)
if err = row.Scan(&r.ID, &r.BusinessName, &r.BusinessType, &r.Status, &r.AppKey, &r.Secret, &r.Contacts, &r.ContactsNumber, &r.Ctime, &r.Mtime); err != nil {
if err == sql.ErrNoRows {
err = nil
r = nil
} else {
log.Error("row.Scan() error(%v)", err)
}
}
return
}
// AllVersion all version.
func (d *Dao) AllVersion(c context.Context) (res []*model.VipAppVersion, err error) {
var rows *sql.Rows
if rows, err = d.db.Query(c, _allVersionSQL); err != nil {
err = errors.WithStack(err)
return
}
defer rows.Close()
for rows.Next() {
r := new(model.VipAppVersion)
if err = rows.Scan(&r.ID, &r.PlatformID, &r.Version, &r.Tip, &r.Operator, &r.Link); err != nil {
err = errors.WithStack(err)
res = nil
return
}
res = append(res, r)
}
return
}
// UpdateVersion update version.
func (d *Dao) UpdateVersion(c context.Context, v *model.VipAppVersion) (ret int64, err error) {
var (
sql string
res xsql.Result
)
if len(v.Version) > 0 {
sql += "`version` = '" + v.Version + "',"
}
if len(v.Tip) > 0 {
sql += "`tip` = '" + v.Tip + "',"
}
if len(v.Link) > 0 {
sql += "`link` = '" + v.Link + "',"
}
sql += "`operator` = '" + v.Operator + "'"
if res, err = d.db.Exec(c, fmt.Sprintf(_updateVersionSQL, sql), v.ID); err != nil {
err = errors.WithStack(err)
return
}
if ret, err = res.RowsAffected(); err != nil {
err = errors.WithStack(err)
return
}
return
}
// BussinessList business infos.
func (d *Dao) BussinessList(c context.Context, pn, ps, status int) (res []*model.VipBusinessInfo, err error) {
var rows *sql.Rows
sqlStr := _businessInfosSQL
if status >= 0 {
sqlStr += fmt.Sprintf(" AND status=%v", status)
}
if pn <= 0 {
pn = _defpn
}
if pn <= 0 || pn > _maxps {
ps = _defps
}
sqlStr += fmt.Sprintf(" ORDER BY id DESC limit %v,%v", (pn-1)*ps, ps)
if rows, err = d.db.Query(c, sqlStr); err != nil {
err = errors.WithStack(err)
return
}
defer rows.Close()
for rows.Next() {
r := new(model.VipBusinessInfo)
if err = rows.Scan(&r.ID, &r.BusinessName, &r.BusinessType, &r.Status, &r.AppKey,
&r.Contacts, &r.ContactsNumber, &r.Ctime, &r.Mtime); err != nil {
err = errors.WithStack(err)
res = nil
return
}
res = append(res, r)
}
return
}
// BussinessCount bussiness info count.
func (d *Dao) BussinessCount(c context.Context, status int) (count int64, err error) {
var row *sql.Row
sqlstr := _businessCountSQL
if status >= 0 {
sqlstr += fmt.Sprintf(" AND status=%v", status)
}
if row = d.db.QueryRow(c, sqlstr); err != nil {
err = errors.WithStack(err)
d.errProm.Incr("query_db")
return
}
if err = row.Scan(&count); err != nil {
err = errors.WithStack(err)
d.errProm.Incr("row_scan_db")
return
}
return
}
// UpdateBusiness update business info.
func (d *Dao) UpdateBusiness(c context.Context, r *model.VipBusinessInfo) (a int64, err error) {
var res xsql.Result
if res, err = d.db.Exec(c, _updateBusinessSQL, r.BusinessName, r.BusinessType, r.Status, r.AppKey, r.Secret, r.Contacts, r.ContactsNumber, r.ID); err != nil {
err = errors.WithStack(err)
d.errProm.Incr("exec_db")
return
}
if a, err = res.RowsAffected(); err != nil {
err = errors.WithStack(err)
d.errProm.Incr("rows_affected_db")
return
}
return
}
// AddBusiness add business info.
func (d *Dao) AddBusiness(c context.Context, r *model.VipBusinessInfo) (a int64, err error) {
var res xsql.Result
if res, err = d.db.Exec(c, _addBusinessSQL, r.BusinessName, r.BusinessType, r.Status, r.AppKey, r.Secret, r.Contacts, r.ContactsNumber); err != nil {
err = errors.WithStack(err)
d.errProm.Incr("exec_db")
return
}
if a, err = res.RowsAffected(); err != nil {
err = errors.WithStack(err)
d.errProm.Incr("rows_affected_db")
return
}
return
}
// HistoryCount user change history.
func (d *Dao) HistoryCount(c context.Context, u *model.UserChangeHistoryReq) (count int, err error) {
var row *sql.Row
if row = d.db.QueryRow(c, d.joinHistoryCondition(_getUserChangeHistoryCountSQL, u, true)); err != nil {
err = errors.WithStack(err)
d.errProm.Incr("query_db")
return
}
if err = row.Scan(&count); err != nil {
err = errors.WithStack(err)
d.errProm.Incr("row_scan_db")
return
}
return
}
// HistoryList history list.
func (d *Dao) HistoryList(c context.Context, u *model.UserChangeHistoryReq) (res []*model.VipChangeHistory, err error) {
var rows *sql.Rows
if rows, err = d.db.Query(c, d.joinHistoryCondition(_getUserChangeHistorySQL, u, false)); err != nil {
err = errors.WithStack(err)
d.errProm.Incr("query_db")
return
}
defer rows.Close()
for rows.Next() {
r := new(model.VipChangeHistory)
if err = rows.Scan(&r.ID, &r.Mid, &r.ChangeType, &r.ChangeTime, &r.Days, &r.OperatorID, &r.RelationID, &r.BatchID, &r.Remark, &r.Ctime, &r.Mtime); err != nil {
err = errors.WithStack(err)
d.errProm.Incr("rows_scan_db")
res = nil
return
}
res = append(res, r)
}
return
}

View File

@@ -0,0 +1,383 @@
package dao
import (
"context"
"fmt"
"go-common/app/admin/main/vip/model"
"testing"
"time"
"github.com/smartystreets/goconvey/convey"
)
func TestDaojoinPoolCondition(t *testing.T) {
convey.Convey("joinPoolCondition", t, func(ctx convey.C) {
var (
sqlStr = ""
q = &model.ResoucePoolBo{}
pn = int(0)
ps = int(0)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
p1 := d.joinPoolCondition(sqlStr, q, pn, ps)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaojoinHistoryCondition(t *testing.T) {
convey.Convey("joinHistoryCondition", t, func(ctx convey.C) {
var (
sql = ""
u = &model.UserChangeHistoryReq{}
iscount bool
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
p1 := d.joinHistoryCondition(sql, u, iscount)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoSelPoolByName(t *testing.T) {
convey.Convey("SelPoolByName", t, func(ctx convey.C) {
var (
c = context.Background()
name = ""
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
_, err := d.SelPoolByName(c, name)
ctx.Convey("Then err should be nil.r should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoSelCountPool(t *testing.T) {
convey.Convey("SelCountPool", t, func(ctx convey.C) {
var (
c = context.Background()
r = &model.ResoucePoolBo{}
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
count, err := d.SelCountPool(c, r)
ctx.Convey("Then err should be nil.count should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(count, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoSelPool(t *testing.T) {
convey.Convey("SelPool", t, func(ctx convey.C) {
var (
c = context.Background()
r = &model.ResoucePoolBo{}
pn = int(0)
ps = int(0)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
res, err := d.SelPool(c, r, pn, ps)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoSelPoolRow(t *testing.T) {
convey.Convey("SelPoolRow", t, func(ctx convey.C) {
var (
c = context.Background()
id = int(0)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
_, err := d.SelPoolRow(c, id)
ctx.Convey("Then err should be nil.r should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoAddPool(t *testing.T) {
convey.Convey("AddPool", t, func(ctx convey.C) {
var (
c = context.Background()
r = &model.ResoucePoolBo{}
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
a, err := d.AddPool(c, r)
ctx.Convey("Then err should be nil.a should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(a, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoUpdatePool(t *testing.T) {
convey.Convey("UpdatePool", t, func(ctx convey.C) {
var (
c = context.Background()
r = &model.ResoucePoolBo{}
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
a, err := d.UpdatePool(c, r)
ctx.Convey("Then err should be nil.a should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(a, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoSelBatchRow(t *testing.T) {
convey.Convey("SelBatchRow", t, func(ctx convey.C) {
var (
c = context.Background()
id = int(0)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
_, err := d.SelBatchRow(c, id)
ctx.Convey("Then err should be nil.r should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoSelBatchRows(t *testing.T) {
convey.Convey("SelBatchRows", t, func(ctx convey.C) {
var (
c = context.Background()
poolID = int(0)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
_, err := d.SelBatchRows(c, poolID)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoAddBatch(t *testing.T) {
convey.Convey("AddBatch", t, func(ctx convey.C) {
var (
c = context.Background()
r = &model.ResouceBatchBo{}
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
a, err := d.AddBatch(c, r)
ctx.Convey("Then err should be nil.a should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(a, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoUpdateBatch(t *testing.T) {
convey.Convey("UpdateBatch", t, func(ctx convey.C) {
var (
c = context.Background()
r = &model.VipResourceBatch{}
ver = int(0)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
a, err := d.UpdateBatch(c, r, ver)
ctx.Convey("Then err should be nil.a should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(a, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoUseBatch(t *testing.T) {
convey.Convey("UseBatch", t, func(ctx convey.C) {
var (
r = &model.VipResourceBatch{}
ver = int(0)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
tx, err := d.BeginTran(context.Background())
ctx.So(err, convey.ShouldBeNil)
ctx.So(tx, convey.ShouldNotBeNil)
a, err := d.UseBatch(tx, r, ver)
ctx.Convey("Then err should be nil.a should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(a, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoSelBusiness(t *testing.T) {
convey.Convey("SelBusiness", t, func(ctx convey.C) {
var (
c = context.Background()
id = int(0)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
_, err := d.SelBusiness(c, id)
ctx.Convey("Then err should be nil.r should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoSelBusinessByQuery(t *testing.T) {
convey.Convey("SelBusinessByQuery", t, func(ctx convey.C) {
var (
c = context.Background()
arg = &model.QueryBusinessInfo{}
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
r, err := d.SelBusinessByQuery(c, arg)
ctx.Convey("Then err should be nil.r should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(r, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoAllVersion(t *testing.T) {
convey.Convey("AllVersion", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
res, err := d.AllVersion(c)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoUpdateVersion(t *testing.T) {
convey.Convey("UpdateVersion", t, func(ctx convey.C) {
var (
c = context.Background()
v = &model.VipAppVersion{}
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
ret, err := d.UpdateVersion(c, v)
ctx.Convey("Then err should be nil.ret should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(ret, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoBussinessList(t *testing.T) {
convey.Convey("BussinessList", t, func(ctx convey.C) {
var (
c = context.Background()
pn = int(0)
ps = int(0)
status = int(0)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
_, err := d.BussinessList(c, pn, ps, status)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoBussinessCount(t *testing.T) {
convey.Convey("BussinessCount", t, func(ctx convey.C) {
var (
c = context.Background()
status = int(0)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
count, err := d.BussinessCount(c, status)
ctx.Convey("Then err should be nil.count should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(count, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoUpdateBusiness(t *testing.T) {
convey.Convey("UpdateBusiness", t, func(ctx convey.C) {
var (
c = context.Background()
r = &model.VipBusinessInfo{}
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
a, err := d.UpdateBusiness(c, r)
ctx.Convey("Then err should be nil.a should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(a, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoAddBusiness(t *testing.T) {
convey.Convey("AddBusiness", t, func(ctx convey.C) {
var (
c = context.Background()
r = &model.VipBusinessInfo{
AppKey: fmt.Sprintf("a:%d", time.Now().Unix()),
}
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
a, err := d.AddBusiness(c, r)
ctx.Convey("Then err should be nil.a should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(a, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoHistoryCount(t *testing.T) {
convey.Convey("HistoryCount", t, func(ctx convey.C) {
var (
c = context.Background()
u = &model.UserChangeHistoryReq{}
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
count, err := d.HistoryCount(c, u)
ctx.Convey("Then err should be nil.count should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(count, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoHistoryList(t *testing.T) {
convey.Convey("HistoryList", t, func(ctx convey.C) {
var (
c = context.Background()
u = &model.UserChangeHistoryReq{}
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
res, err := d.HistoryList(c, u)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,105 @@
package dao
import (
"context"
"fmt"
"go-common/app/admin/main/vip/model"
"go-common/library/database/sql"
"github.com/pkg/errors"
)
//OrderCount order count.
func (d *Dao) OrderCount(c context.Context, arg *model.ArgPayOrder) (count int64, err error) {
if arg.Mid == 0 && len(arg.OrderNo) == 0 {
return
}
sqlStr := _vipOrderCountSQL
if arg.Mid > 0 {
sqlStr += fmt.Sprintf(" AND mid = %v", arg.Mid)
}
if len(arg.OrderNo) > 0 {
sqlStr += fmt.Sprintf(" AND order_no = '%v'", arg.OrderNo)
}
if arg.Status > 0 {
sqlStr += fmt.Sprintf(" AND status = %v", arg.Status)
}
var row = d.db.QueryRow(c, sqlStr)
if err = row.Scan(&count); err != nil {
err = errors.WithStack(err)
d.errProm.Incr("row_scan_db")
return
}
return
}
// OrderList order list.
func (d *Dao) OrderList(c context.Context, arg *model.ArgPayOrder) (res []*model.PayOrder, err error) {
if arg.Mid == 0 && len(arg.OrderNo) == 0 {
return
}
sqlStr := _vipOrderListSQL
if arg.Mid > 0 {
sqlStr += fmt.Sprintf(" AND mid = %v", arg.Mid)
}
if len(arg.OrderNo) > 0 {
sqlStr += fmt.Sprintf(" AND order_no = '%v'", arg.OrderNo)
}
if arg.Status > 0 {
sqlStr += fmt.Sprintf(" AND status = %v", arg.Status)
}
if arg.PN < 0 {
arg.PN = _defpn
}
if arg.PS < 0 || arg.PS > 100 {
arg.PS = _defps
}
sqlStr += fmt.Sprintf(" ORDER BY ID DESC LIMIT %v,%v", (arg.PN-1)*arg.PS, arg.PS)
var rows *sql.Rows
if rows, err = d.db.Query(c, sqlStr); err != nil {
err = errors.WithStack(err)
d.errProm.Incr("query_db")
return
}
defer rows.Close()
for rows.Next() {
r := new(model.PayOrder)
if err = rows.Scan(&r.ID, &r.OrderNo, &r.AppID, &r.Platform, &r.OrderType, &r.Mid, &r.ToMid, &r.BuyMonths, &r.Money, &r.RefundAmount, &r.Status, &r.PayType, &r.RechargeBp,
&r.ThirdTradeNo, &r.Ver, &r.PaymentTime, &r.Ctime, &r.Mtime, &r.AppSubID); err != nil {
err = errors.WithStack(err)
d.errProm.Incr("row_scan_db")
res = nil
return
}
res = append(res, r)
}
err = rows.Err()
return
}
// SelOrder sel order by orderNo.
func (d *Dao) SelOrder(c context.Context, orderNo string) (r *model.PayOrder, err error) {
row := d.db.QueryRow(c, _vipOrderSQL, orderNo)
r = new(model.PayOrder)
if err = row.Scan(&r.ID, &r.OrderNo, &r.AppID, &r.Platform, &r.OrderType, &r.Mid, &r.ToMid, &r.BuyMonths, &r.Money, &r.RefundAmount, &r.Status, &r.PayType, &r.RechargeBp,
&r.ThirdTradeNo, &r.Ver, &r.PaymentTime, &r.Ctime, &r.Mtime, &r.AppSubID); err != nil {
if err == sql.ErrNoRows {
err = nil
r = nil
return
}
err = errors.WithStack(err)
d.errProm.Incr("row_scan_db")
}
return
}
//AddPayOrderLog add order log.
func (d *Dao) AddPayOrderLog(c context.Context, arg *model.PayOrderLog) (err error) {
if _, err = d.db.Exec(c, _addOrderLogSQL, arg.OrderNo, arg.RefundID, arg.RefundAmount, arg.Operator, arg.Mid, arg.Status); err != nil {
err = errors.WithStack(err)
d.errProm.Incr("db_exec")
}
return
}

View File

@@ -0,0 +1,72 @@
package dao
import (
"context"
"go-common/app/admin/main/vip/model"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoOrderCount(t *testing.T) {
convey.Convey("OrderCount", t, func(convCtx convey.C) {
var (
c = context.Background()
arg = &model.ArgPayOrder{Mid: 1, OrderNo: "1"}
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
count, err := d.OrderCount(c, arg)
convCtx.Convey("Then err should be nil.count should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(count, convey.ShouldBeGreaterThanOrEqualTo, 0)
})
})
})
}
func TestDaoOrderList(t *testing.T) {
convey.Convey("OrderList", t, func(convCtx convey.C) {
var (
c = context.Background()
arg = &model.ArgPayOrder{}
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
res, err := d.OrderList(c, arg)
convCtx.Convey("Then err should be nil.res should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(res, convey.ShouldBeNil)
})
})
})
}
func TestDaoSelOrder(t *testing.T) {
convey.Convey("SelOrder", t, func(convCtx convey.C) {
var (
c = context.Background()
orderNo = "2016072617212166230921"
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
r, err := d.SelOrder(c, orderNo)
convCtx.Convey("Then err should be nil.r should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(r, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoAddPayOrderLog(t *testing.T) {
convey.Convey("AddPayOrderLog", t, func(convCtx convey.C) {
var (
c = context.Background()
arg = &model.PayOrderLog{}
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.AddPayOrderLog(c, arg)
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
})
}

View File

@@ -0,0 +1,267 @@
package dao
import (
"context"
"database/sql"
"fmt"
"time"
"go-common/app/admin/main/vip/model"
xsql "go-common/library/database/sql"
xtime "go-common/library/time"
"github.com/pkg/errors"
)
const (
_inVipPriceConfigSQL = "INSERT INTO vip_price_config_v2(platform,product_name,product_id,suit_type,month,sub_type,original_price,selected,remark,status,operator,oper_id,superscript,start_build,end_build) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
_inVipDPriceConfigSQL = "INSERT INTO vip_price_discount_config_v2(vpc_id,product_id,discount_price,stime,etime,remark,operator,oper_id,first_price) VALUES(?,?,?,?,?,?,?,?,?)"
_upVipPriceConfigIDSQL = "UPDATE vip_price_config_v2 SET platform = ?, product_name = ?, product_id = ?, suit_type = ?, month = ?, sub_type = ?, original_price = ?, remark = ?, status = ?, operator = ?, oper_id = ?, selected = ?, superscript = ?, start_build = ?, end_build = ? WHERE id = ?"
_upVipDPriceConfigSQL = "UPDATE vip_price_discount_config_v2 SET product_id = ?, discount_price = ?, stime = ?, etime =?, remark = ?, operator = ?, oper_id = ?,first_price = ? WHERE id = ?"
_delVipPriceConfigIDSQL = "DELETE FROM vip_price_config_v2 WHERE id = ?"
_delVipDPriceConfigIDSQL = "DELETE FROM vip_price_discount_config_v2 WHERE id = ?"
_selVipPriceConfigUQCheckSQL = "SELECT COUNT(*) FROM vip_price_config_v2 WHERE platform = ? AND month = ? AND sub_type = ? AND suit_type = ? %s;"
_selVipPriceConfigsSQL = "SELECT id,platform,product_name,product_id,suit_type,month,sub_type,original_price,selected,remark,status,operator,oper_id,ctime,mtime,superscript,start_build,end_build FROM vip_price_config_v2 ORDER BY id DESC"
_selVipPriceConfigIDSQL = "SELECT id,platform,product_name,product_id,suit_type,month,sub_type,original_price,selected,remark,status,operator,oper_id,ctime,mtime,superscript,start_build,end_build FROM vip_price_config_v2 WHERE id = ?"
_selVipDPriceConfigsSQL = "SELECT id,vpc_id,product_id,discount_price,stime,etime,remark,operator,oper_id,ctime,mtime,first_price FROM vip_price_discount_config_v2 WHERE vpc_id = ? ORDER BY stime ASC"
_selVipDPriceConfigIDSQL = "SELECT id,vpc_id,product_id,discount_price,stime,etime,remark,operator,oper_id,ctime,mtime,first_price FROM vip_price_discount_config_v2 WHERE id = ?"
_selVipDPriceConfigUQTimeSQL = "SELECT id,vpc_id,product_id,discount_price,stime,etime,remark,ctime,mtime FROM vip_price_discount_config_v2 WHERE vpc_id = ? AND ((etime <> '1970-01-01 08:00:00' AND (etime >= ? OR etime >= ?) AND stime <= ?) OR (etime = '1970-01-01 08:00:00' AND stime <= ?))"
_selVipPriceDiscountConfigsSQL = "SELECT vpc_id,product_id,discount_price,stime,etime,remark,ctime,mtime FROM vip_price_discount_config_v2 WHERE stime <= ? AND ((etime > ? AND etime <> '1970-01-01 08:00:00') OR (etime = '1970-01-01 08:00:00'))"
_selVipMaxPriceDiscountSQL = "SELECT MAX(discount_price) FROM vip_price_discount_config_v2 WHERE vpc_id = ?"
_countVipPriceConfigByplatSQL = "SELECT COUNT(*) FROM vip_price_config_v2 WHERE platform = ?"
)
// AddVipPriceConfig insert vip price config .
func (d *Dao) AddVipPriceConfig(c context.Context, v *model.VipPriceConfig) (err error) {
if _, err = d.db.Exec(c, _inVipPriceConfigSQL, v.Plat, v.PdName, v.PdID, v.SuitType, v.Month, v.SubType, v.OPrice, v.Selected, v.Remark, v.Status, v.Operator, v.OpID, v.Superscript, v.StartBuild, v.EndBuild); err != nil {
err = errors.WithStack(err)
}
return
}
// AddVipDPriceConfig insert vip discount price config .
func (d *Dao) AddVipDPriceConfig(c context.Context, v *model.VipDPriceConfig) (err error) {
if _, err = d.db.Exec(c, _inVipDPriceConfigSQL, v.ID, v.PdID, v.DPrice, v.STime, v.ETime, v.Remark, v.Operator, v.OpID, v.FirstPrice); err != nil {
err = errors.WithStack(err)
}
return
}
// UpVipPriceConfig update vip price config .
func (d *Dao) UpVipPriceConfig(c context.Context, v *model.VipPriceConfig) (err error) {
if _, err = d.db.Exec(c, _upVipPriceConfigIDSQL, v.Plat, v.PdName, v.PdID, v.SuitType, v.Month, v.SubType, v.OPrice, v.Remark, v.Status, v.Operator, v.OpID, v.Selected, v.Superscript, v.StartBuild, v.EndBuild, v.ID); err != nil {
err = errors.WithStack(err)
}
return
}
// UpVipDPriceConfig update vip discount price config .
func (d *Dao) UpVipDPriceConfig(c context.Context, v *model.VipDPriceConfig) (err error) {
if _, err = d.db.Exec(c, _upVipDPriceConfigSQL, v.PdID, v.DPrice, v.STime, v.ETime, v.Remark, v.Operator, v.OpID, v.FirstPrice, v.DisID); err != nil {
err = errors.WithStack(err)
}
return
}
// DelVipPriceConfig delete vip price config .
func (d *Dao) DelVipPriceConfig(c context.Context, arg *model.ArgVipPriceID) (err error) {
if _, err = d.db.Exec(c, _delVipPriceConfigIDSQL, arg.ID); err != nil {
err = errors.WithStack(err)
}
return
}
// DelVipDPriceConfig delete vip discount price config .
func (d *Dao) DelVipDPriceConfig(c context.Context, arg *model.ArgVipDPriceID) (err error) {
if _, err = d.db.Exec(c, _delVipDPriceConfigIDSQL, arg.DisID); err != nil {
err = errors.WithStack(err)
}
return
}
// VipPriceConfigUQCheck count vip price config unquie check.
func (d *Dao) VipPriceConfigUQCheck(c context.Context, arg *model.ArgAddOrUpVipPrice) (count int64, err error) {
sqlPostfix := ""
if arg.EndBuild > 0 {
sqlPostfix += fmt.Sprintf(" AND (start_build<= %d )", arg.EndBuild)
}
if arg.StartBuild > 0 {
sqlPostfix += fmt.Sprintf(" AND (end_build >= %d OR end_build = 0 )", arg.StartBuild)
}
if arg.ID > 0 {
// for update
sqlPostfix += fmt.Sprintf(" AND id != %d ", arg.ID)
}
if err = d.db.QueryRow(c,
fmt.Sprintf(_selVipPriceConfigUQCheckSQL, sqlPostfix),
arg.Plat,
arg.Month,
arg.SubType,
arg.SuitType).Scan(&count); err != nil {
err = errors.WithStack(err)
}
return
}
// VipPriceConfigs vip price configs
func (d *Dao) VipPriceConfigs(c context.Context) (vpcs []*model.VipPriceConfig, err error) {
var rows *xsql.Rows
if rows, err = d.db.Query(c, _selVipPriceConfigsSQL); err != nil {
err = errors.WithStack(err)
return
}
defer rows.Close()
for rows.Next() {
vpc := new(model.VipPriceConfig)
if err = rows.Scan(&vpc.ID, &vpc.Plat, &vpc.PdName, &vpc.PdID, &vpc.SuitType, &vpc.Month, &vpc.SubType,
&vpc.OPrice, &vpc.Selected, &vpc.Remark, &vpc.Status, &vpc.Operator, &vpc.OpID, &vpc.CTime, &vpc.MTime,
&vpc.Superscript, &vpc.StartBuild, &vpc.EndBuild); err != nil {
if err == xsql.ErrNoRows {
err = nil
vpc = nil
} else {
err = errors.WithStack(err)
}
return
}
vpcs = append(vpcs, vpc)
}
return
}
// VipPriceConfigID vip price config by id
func (d *Dao) VipPriceConfigID(c context.Context, arg *model.ArgVipPriceID) (vpc *model.VipPriceConfig, err error) {
row := d.db.QueryRow(c, _selVipPriceConfigIDSQL, arg.ID)
vpc = new(model.VipPriceConfig)
if err = row.Scan(&vpc.ID, &vpc.Plat, &vpc.PdName, &vpc.PdID, &vpc.SuitType, &vpc.Month, &vpc.SubType, &vpc.OPrice, &vpc.Selected,
&vpc.Remark, &vpc.Status, &vpc.Operator, &vpc.OpID, &vpc.CTime, &vpc.MTime, &vpc.Superscript, &vpc.StartBuild, &vpc.EndBuild); err != nil {
if err != sql.ErrNoRows {
err = errors.WithStack(err)
return
}
err = nil
vpc = nil
}
return
}
// VipDPriceConfigs vip discount price configs
func (d *Dao) VipDPriceConfigs(c context.Context, arg *model.ArgVipPriceID) (res []*model.VipDPriceConfig, err error) {
var rows *xsql.Rows
if rows, err = d.db.Query(c, _selVipDPriceConfigsSQL, arg.ID); err != nil {
err = errors.WithStack(err)
return
}
defer rows.Close()
for rows.Next() {
v := new(model.VipDPriceConfig)
if err = rows.Scan(&v.DisID, &v.ID, &v.PdID, &v.DPrice, &v.STime, &v.ETime, &v.Remark, &v.Operator, &v.OpID, &v.CTime, &v.MTime, &v.FirstPrice); err != nil {
if err == xsql.ErrNoRows {
err = nil
res = nil
} else {
err = errors.WithStack(err)
}
return
}
res = append(res, v)
}
return
}
// VipDPriceConfigID vip discount price config by id
func (d *Dao) VipDPriceConfigID(c context.Context, arg *model.ArgVipDPriceID) (res *model.VipDPriceConfig, err error) {
row := d.db.QueryRow(c, _selVipDPriceConfigIDSQL, arg.DisID)
res = new(model.VipDPriceConfig)
if err = row.Scan(&res.DisID, &res.ID, &res.PdID, &res.DPrice, &res.STime, &res.ETime, &res.Remark, &res.Operator, &res.OpID, &res.CTime, &res.MTime, &res.FirstPrice); err != nil {
if err != xsql.ErrNoRows {
err = errors.WithStack(err)
return
}
err = nil
res = nil
}
return
}
// VipDPriceConfigUQTime count vip discount price config unquie check time.
func (d *Dao) VipDPriceConfigUQTime(c context.Context, arg *model.ArgAddOrUpVipDPrice) (mvd map[int64]*model.VipDPriceConfig, err error) {
var (
rows *xsql.Rows
etime = arg.ETime
)
if etime == 0 {
etime = xtime.Time(time.Now().AddDate(1000, 0, 0).Unix())
}
mvd = make(map[int64]*model.VipDPriceConfig)
if rows, err = d.db.Query(c, _selVipDPriceConfigUQTimeSQL, arg.ID, arg.STime, etime, etime, arg.STime); err != nil {
err = errors.WithStack(err)
return
}
defer rows.Close()
for rows.Next() {
vdc := new(model.VipDPriceConfig)
if err = rows.Scan(&vdc.DisID, &vdc.ID, &vdc.PdID, &vdc.DPrice, &vdc.STime, &vdc.ETime, &vdc.Remark, &vdc.CTime, &vdc.MTime); err != nil {
if err != xsql.ErrNoRows {
err = errors.WithStack(err)
return
}
mvd = nil
err = nil
return
}
mvd[vdc.DisID] = vdc
}
err = rows.Err()
return
}
// VipPriceDiscountConfigs get vip price discount configs.
func (d *Dao) VipPriceDiscountConfigs(c context.Context) (mvd map[int64]*model.VipDPriceConfig, err error) {
var (
rows *xsql.Rows
now = time.Now()
)
mvd = make(map[int64]*model.VipDPriceConfig)
if rows, err = d.db.Query(c, _selVipPriceDiscountConfigsSQL, now, now); err != nil {
err = errors.WithStack(err)
return
}
defer rows.Close()
for rows.Next() {
vdc := new(model.VipDPriceConfig)
if err = rows.Scan(&vdc.ID, &vdc.PdID, &vdc.DPrice, &vdc.STime, &vdc.ETime, &vdc.Remark, &vdc.CTime, &vdc.MTime); err != nil {
if err != xsql.ErrNoRows {
err = errors.WithStack(err)
return
}
mvd = nil
err = nil
return
}
mvd[vdc.ID] = vdc
}
err = rows.Err()
return
}
// VipMaxPriceDiscount max price discount.
func (d *Dao) VipMaxPriceDiscount(c context.Context, arg *model.ArgAddOrUpVipPrice) (res float64, err error) {
var max sql.NullFloat64
row := d.db.QueryRow(c, _selVipMaxPriceDiscountSQL, arg.ID)
if err = row.Scan(&max); err != nil {
return
}
res = max.Float64
return
}
// CountVipPriceConfigByPlat count vip price config by platform id.
func (d *Dao) CountVipPriceConfigByPlat(c context.Context, plat int64) (count int64, err error) {
row := d.db.QueryRow(c, _countVipPriceConfigByplatSQL, plat)
if err = row.Scan(&count); err != nil {
err = errors.WithStack(err)
}
return
}

View File

@@ -0,0 +1,273 @@
package dao
import (
"context"
"fmt"
"testing"
"time"
"go-common/app/admin/main/vip/model"
xtime "go-common/library/time"
. "github.com/smartystreets/goconvey/convey"
)
func TestDaoAddVipPriceConfig(t *testing.T) {
Convey("Test_AddVipPriceConfig", t, func() {
v := &model.VipPriceConfig{
Plat: 1,
PdName: "ddd",
PdID: "sss",
SuitType: 1,
Month: 1,
SubType: 2,
OPrice: 1,
Selected: 1,
Remark: "",
Status: 0,
Operator: "sss",
OpID: 1,
}
err := d.AddVipPriceConfig(context.TODO(), v)
So(err, ShouldBeNil)
})
Convey("Test_AddVipPriceConfig add build 200-300", t, func() {
v := &model.VipPriceConfig{
Plat: 10,
PdName: "ddd",
PdID: "sss",
SuitType: 1,
Month: 1,
SubType: 1,
OPrice: 1,
Selected: 1,
Remark: "",
Status: 0,
Operator: "sss",
OpID: 1,
StartBuild: 200,
EndBuild: 300,
}
err := d.AddVipPriceConfig(context.TODO(), v)
So(err, ShouldBeNil)
})
Convey("Test_AddVipPriceConfig add build 0-0", t, func() {
v := &model.VipPriceConfig{
Plat: 10,
PdName: "ddd",
PdID: "sss",
SuitType: 1,
Month: 1,
SubType: 1,
OPrice: 1,
Selected: 1,
Remark: "",
Status: 0,
Operator: "sss",
OpID: 1,
StartBuild: 200,
EndBuild: 300,
}
err := d.AddVipPriceConfig(context.TODO(), v)
So(err, ShouldBeNil)
})
}
func TestDaoAddVipDPriceConfig(t *testing.T) {
Convey("Test_AddVipPriceConfig", t, func() {
v := &model.VipDPriceConfig{
DisID: 1,
ID: 1,
PdID: "sss",
DPrice: 1,
STime: xtime.Time(time.Now().Unix()),
Remark: "",
Operator: "sss",
OpID: 1,
}
err := d.AddVipDPriceConfig(context.TODO(), v)
So(err, ShouldBeNil)
})
}
func TestUpVipPriceConfig(t *testing.T) {
Convey("TestUpVipPriceConfig", t, func() {
err := d.UpVipPriceConfig(context.TODO(), &model.VipPriceConfig{
ID: 230,
Plat: 10,
PdName: "ddd",
PdID: "sss",
SuitType: 1,
Month: 1,
SubType: 1,
OPrice: 1,
Selected: 1,
Remark: "",
Status: 0,
Operator: "sss",
OpID: 1,
StartBuild: 250,
EndBuild: 300,
})
So(err, ShouldBeNil)
})
}
func TestDaoUpVipPriceConfig(t *testing.T) {
Convey("Test_UpVipPriceConfig", t, func() {
v := &model.VipPriceConfig{
ID: 1,
Plat: 1,
PdName: "ddd",
PdID: "sss",
SuitType: 1,
Month: 1,
SubType: 2,
OPrice: 1,
Selected: 1,
Remark: "",
Status: 0,
Operator: "sss",
OpID: 1,
}
err := d.AddVipPriceConfig(context.TODO(), v)
So(err, ShouldBeNil)
})
}
func TestDaoUpVipDPriceConfig(t *testing.T) {
Convey("Test_UpVipDPriceConfig", t, func() {
v := &model.VipDPriceConfig{
DisID: 1,
ID: 1,
PdID: "sss",
DPrice: 1,
STime: xtime.Time(time.Now().Unix()),
Remark: "",
Operator: "sss",
OpID: 1,
}
err := d.UpVipDPriceConfig(context.TODO(), v)
So(err, ShouldBeNil)
})
}
func TestDaoDelVipPriceConfig(t *testing.T) {
Convey("Test_DelVipPriceConfig", t, func() {
err := d.DelVipPriceConfig(context.TODO(), &model.ArgVipPriceID{ID: 1})
So(err, ShouldBeNil)
})
}
func TestDaoDelVipDPriceConfig(t *testing.T) {
Convey("Test_DelVipDPriceConfig", t, func() {
err := d.DelVipDPriceConfig(context.TODO(), &model.ArgVipDPriceID{DisID: 1})
So(err, ShouldBeNil)
})
}
func TestDaoVipPriceConfigUQCheck(t *testing.T) {
Convey("Test_VipPriceConfigUQCheck", t, func() {
res, err := d.VipPriceConfigUQCheck(context.TODO(), &model.ArgAddOrUpVipPrice{Plat: 1, Month: 1, SubType: 1, SuitType: 0})
So(err, ShouldBeNil)
So(res, ShouldNotBeNil)
})
Convey("Test_VipPriceConfigUQCheck count 0-0", t, func() {
count, err := d.VipPriceConfigUQCheck(context.TODO(), &model.ArgAddOrUpVipPrice{Plat: 10, Month: 1, SubType: 1, SuitType: 1})
fmt.Println("count:", count)
So(err, ShouldBeNil)
So(count, ShouldNotBeNil)
})
Convey("Test_VipPriceConfigUQCheck count 220-0", t, func() {
count, err := d.VipPriceConfigUQCheck(context.TODO(), &model.ArgAddOrUpVipPrice{Plat: 10, Month: 1, SubType: 1, SuitType: 1, StartBuild: 220, EndBuild: 0})
fmt.Println("count:", count)
So(err, ShouldBeNil)
So(count, ShouldNotBeNil)
})
Convey("Test_VipPriceConfigUQCheck count 120-180", t, func() {
count, err := d.VipPriceConfigUQCheck(context.TODO(), &model.ArgAddOrUpVipPrice{Plat: 10, Month: 1, SubType: 1, SuitType: 1, StartBuild: 120, EndBuild: 180})
fmt.Println("count:", count)
So(err, ShouldBeNil)
So(count, ShouldNotBeNil)
})
Convey("Test_VipPriceConfigUQCheck count 0-180", t, func() {
count, err := d.VipPriceConfigUQCheck(context.TODO(), &model.ArgAddOrUpVipPrice{Plat: 10, Month: 1, SubType: 1, SuitType: 1, StartBuild: 0, EndBuild: 180})
fmt.Println("count:", count)
So(err, ShouldBeNil)
So(count, ShouldNotBeNil)
})
Convey("Test_VipPriceConfigUQCheck count 0-600", t, func() {
count, err := d.VipPriceConfigUQCheck(context.TODO(), &model.ArgAddOrUpVipPrice{Plat: 10, Month: 1, SubType: 1, SuitType: 1, StartBuild: 0, EndBuild: 600})
fmt.Println("count:", count)
So(err, ShouldBeNil)
So(count, ShouldNotBeNil)
})
}
func TestDaoVipPriceConfigs(t *testing.T) {
Convey("Test_VipPriceConfigs", t, func() {
count, err := d.VipPriceConfigs(context.TODO())
So(err, ShouldBeNil)
So(count, ShouldNotBeEmpty)
})
}
func TestDaoVipPriceConfigID(t *testing.T) {
Convey("Test_VipPriceConfigID", t, func() {
ids, err := d.VipPriceConfigID(context.TODO(), &model.ArgVipPriceID{ID: 1})
So(err, ShouldBeNil)
So(ids, ShouldNotBeEmpty)
})
}
func TestDaoVipDPriceConfigs(t *testing.T) {
Convey("Test_VipDPriceConfigs", t, func() {
count, err := d.VipDPriceConfigs(context.TODO(), &model.ArgVipPriceID{ID: 1})
So(err, ShouldBeNil)
So(count, ShouldNotBeEmpty)
})
}
func TestDaoVipDPriceConfigID(t *testing.T) {
Convey("Test_VipDPriceConfigID", t, func() {
res, err := d.VipDPriceConfigID(context.TODO(), &model.ArgVipDPriceID{DisID: 1})
So(err, ShouldBeNil)
So(res, ShouldNotBeEmpty)
})
}
func TestDaoVipDPriceConfigUQTime(t *testing.T) {
Convey("Test_VipDPriceConfigUQTime", t, func() {
arg := &model.ArgAddOrUpVipDPrice{
ID: 992,
STime: xtime.Time(time.Now().Unix()),
ETime: xtime.Time(time.Now().Unix()),
}
_, err := d.VipDPriceConfigUQTime(context.TODO(), arg)
So(err, ShouldBeNil)
})
}
func TestDaoVipPriceDiscountConfigs(t *testing.T) {
Convey("Test_VipPriceDiscountConfigs", t, func() {
res, err := d.VipPriceDiscountConfigs(context.TODO())
So(err, ShouldBeNil)
So(res, ShouldNotBeEmpty)
})
}
func TestDaoVipMaxPriceDiscount(t *testing.T) {
Convey("Test_VipMaxPriceDiscount", t, func() {
res, err := d.VipMaxPriceDiscount(context.TODO(), &model.ArgAddOrUpVipPrice{ID: 1})
So(err, ShouldBeNil)
So(res, ShouldNotBeEmpty)
})
}
func TestDaoCountVipPriceConfigByPlat(t *testing.T) {
Convey("TestDaoCountVipPriceConfigByPlat", t, func() {
res, err := d.CountVipPriceConfigByPlat(context.TODO(), 1)
fmt.Println(res)
So(err, ShouldBeNil)
So(res, ShouldBeGreaterThanOrEqualTo, 0)
})
}

View File

@@ -0,0 +1,80 @@
package dao
import (
"context"
"go-common/app/admin/main/vip/model"
"go-common/library/ecode"
)
const (
_vipConfPlatform = "vip_platform_config"
)
// PlatformAll .
func (d *Dao) PlatformAll(c context.Context, order string) (res []*model.ConfPlatform, err error) {
db := d.vip.Table(_vipConfPlatform)
if err := db.Where("is_del=0").Order("id " + order).Find(&res).Error; err != nil {
return nil, err
}
return
}
// PlatformByID vip platform config by id.
func (d *Dao) PlatformByID(c context.Context, id int64) (re *model.ConfPlatform, err error) {
re = &model.ConfPlatform{}
if err := d.vip.Table(_vipConfPlatform).Where("id=?", id).First(re).Error; err != nil {
if err == ecode.NothingFound {
err = nil
}
return nil, err
}
return
}
// PlatformSave .
func (d *Dao) PlatformSave(c context.Context, arg *model.ConfPlatform) (eff int64, err error) {
db := d.vip.Table(_vipConfPlatform).Omit("ctime").Save(arg)
if err = db.Error; err != nil {
return
}
eff = db.RowsAffected
return
}
// PlatformEnable .
// func (d *Dao) PlatformEnable(c context.Context, arg *model.ConfPlatform) (eff int64, err error) {
// isDel := map[string]interface{}{
// "is_del": arg.IsDel,
// "operator": arg.Operator,
// }
// db := d.vip.Table(_vipConfPlatform).Where("id=?", arg.ID).Updates(isDel)
// if err = db.Error; err != nil {
// return
// }
// eff = db.RowsAffected
// return
// }
// PlatformDel delete vip platform config by id.
func (d *Dao) PlatformDel(c context.Context, id int64, operator string) (eff int64, err error) {
isDel := map[string]interface{}{
"is_del": 1,
"operator": operator,
}
db := d.vip.Table(_vipConfPlatform).Where("id=?", id).Updates(isDel)
if err = db.Error; err != nil {
return
}
eff = db.RowsAffected
return
}
// PlatformTypes .
func (d *Dao) PlatformTypes(c context.Context) (res []*model.TypePlatform, err error) {
db := d.vip.Table(_vipConfPlatform)
if err := db.Select("id, platform_name").Where("is_del=0").Order("id").Find(&res).Error; err != nil {
return nil, err
}
return
}

View File

@@ -0,0 +1,66 @@
package dao
import (
"context"
"testing"
"go-common/app/admin/main/vip/model"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoPlatformSuit(t *testing.T) {
convey.Convey("PlatformSuit", t, func(ctx convey.C) {
var (
c = context.Background()
arg = &model.ConfPlatform{
ID: 1,
PlatformName: "android-ut",
Platform: "android",
Device: "phone",
MobiApp: "android",
PanelType: "normal",
Operator: "test1",
}
)
ctx.Convey("clean data before", func(ctx convey.C) {
d.vip.Table(_vipConfPlatform).Where("platform_name=?", "android-ut").Delete(model.ConfPlatform{})
})
ctx.Convey("PlatformSave", func(ctx convey.C) {
eff, err := d.PlatformSave(c, arg)
ctx.So(err, convey.ShouldBeNil)
ctx.So(eff, convey.ShouldNotBeNil)
})
ctx.Convey("PlatformByID", func(ctx convey.C) {
re, err := d.PlatformByID(c, arg.ID)
ctx.So(err, convey.ShouldBeNil)
ctx.So(re, convey.ShouldNotBeNil)
})
ctx.Convey("PlatformAll", func(ctx convey.C) {
res, err := d.PlatformAll(c, "desc")
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
ctx.Convey("PlatformDel", func(ctx convey.C) {
eff, err := d.PlatformDel(c, arg.ID, arg.Operator)
ctx.So(err, convey.ShouldBeNil)
ctx.So(eff, convey.ShouldBeGreaterThanOrEqualTo, 0)
})
ctx.Convey("clean data", func(ctx convey.C) {
d.vip.Table(_vipConfPlatform).Where("platform_name=?", "android-ut").Delete(model.ConfPlatform{})
})
})
}
func TestDaoPlatformTypes(t *testing.T) {
convey.Convey("PlatformTypes", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
res, err := d.PlatformTypes(c)
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
}

View File

@@ -0,0 +1,144 @@
package dao
import (
"context"
xsql "database/sql"
"go-common/app/admin/main/vip/model"
"github.com/jinzhu/gorm"
"github.com/pkg/errors"
)
const (
_vipPrivileges = "vip_privileges"
_vipPrivilegesResources = "vip_privileges_resources"
updateOrderSQL = "UPDATE vip_privileges a, vip_privileges b SET a.order_num = b.order_num, b.order_num = a.order_num WHERE a.id = ? AND b.id = ?;"
)
// PrivilegeList query .
func (d *Dao) PrivilegeList(c context.Context, langType int8) (res []*model.Privilege, err error) {
db := d.vip.Table(_vipPrivileges).Where("deleted=0 AND lang_type=?", langType).Order("order_num ASC")
if err := db.Find(&res).Error; err != nil {
return nil, err
}
return
}
// PrivilegeResourcesList query privilege resources .
func (d *Dao) PrivilegeResourcesList(c context.Context) (res []*model.PrivilegeResources, err error) {
db := d.vip.Table(_vipPrivilegesResources)
if err := db.Find(&res).Error; err != nil {
return nil, err
}
return
}
// UpdateStatePrivilege update state privilege.
func (d *Dao) UpdateStatePrivilege(c context.Context, p *model.Privilege) (a int64, err error) {
stage := map[string]interface{}{
"state": p.State,
}
db := d.vip.Table(_vipPrivileges).Where("id = ?", p.ID).Updates(stage)
if err = db.Error; err != nil {
return
}
a = db.RowsAffected
return
}
// DeletePrivilege dekete privilege.
func (d *Dao) DeletePrivilege(c context.Context, id int64) (a int64, err error) {
stage := map[string]interface{}{
"deleted": 1,
}
db := d.vip.Table(_vipPrivileges).Where("id = ?", id).Updates(stage)
if err = db.Error; err != nil {
return
}
a = db.RowsAffected
return
}
// AddPrivilege add privilege.
func (d *Dao) AddPrivilege(tx *gorm.DB, ps *model.Privilege) (id int64, err error) {
db := tx.Table(_vipPrivileges).Save(ps)
if err = db.Error; err != nil {
return
}
id = ps.ID
return
}
// MaxOrder max priivilege order.
func (d *Dao) MaxOrder(c context.Context) (order int64, err error) {
p := new(model.Privilege)
db := d.vip.Table(_vipPrivileges).Order("order_num DESC").First(&p)
if err = db.Error; err != nil {
return
}
return p.Order, err
}
// AddPrivilegeResources add privilege resources.
func (d *Dao) AddPrivilegeResources(tx *gorm.DB, p *model.PrivilegeResources) (a int64, err error) {
db := tx.Table(_vipPrivilegesResources).Save(p)
if err = db.Error; err != nil {
return
}
a = db.RowsAffected
return
}
// UpdatePrivilege update privilege .
func (d *Dao) UpdatePrivilege(tx *gorm.DB, ps *model.Privilege) (a int64, err error) {
val := map[string]interface{}{
"privileges_name": ps.Name,
"title": ps.Title,
"explains": ps.Explain,
"privileges_type": ps.Type,
"operator": ps.Operator,
}
if ps.IconURL != "" {
val["icon_url"] = ps.IconURL
}
if ps.IconGrayURL != "" {
val["icon_gray_url"] = ps.IconGrayURL
}
db := tx.Table(_vipPrivileges).Where("id = ?", ps.ID).Updates(val)
if err = db.Error; err != nil {
return
}
a = db.RowsAffected
return
}
// UpdatePrivilegeResources update privilege resources .
func (d *Dao) UpdatePrivilegeResources(tx *gorm.DB, ps *model.PrivilegeResources) (aff int64, err error) {
stage := map[string]interface{}{
"link": ps.Link,
}
if ps.ImageURL != "" {
stage["image_url"] = ps.ImageURL
}
db := tx.Table(_vipPrivilegesResources).Where("pid = ? AND resources_type = ?", ps.PID, ps.Type).Updates(stage)
if err = db.Error; err != nil {
return
}
aff = db.RowsAffected
return
}
// UpdateOrder update privilege order.
func (d *Dao) UpdateOrder(c context.Context, aid, bid int64) (a int64, err error) {
var res xsql.Result
if res, err = d.db.Exec(c, updateOrderSQL, aid, bid); err != nil {
err = errors.WithStack(err)
return
}
if a, err = res.RowsAffected(); err != nil {
err = errors.WithStack(err)
return
}
return
}

View File

@@ -0,0 +1,156 @@
package dao
import (
"context"
"testing"
"go-common/app/admin/main/vip/model"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoPrivilegeResourcesList(t *testing.T) {
convey.Convey("PrivilegeResourcesList", t, func() {
res, err := d.PrivilegeResourcesList(context.TODO())
convey.So(err, convey.ShouldBeNil)
convey.So(res, convey.ShouldNotBeNil)
})
}
// go test -test.v -test.run TestDaoAddPrivilege
func TestDaoAddPrivilege(t *testing.T) {
tx := d.BeginGormTran(context.Background())
p := &model.Privilege{
Name: "超高清",
Title: "超高清标题",
Explain: "超高清描述描述超多字超多字超多字超多字超多字超多字超多字超多字超多字超多字超多字超多字超多字",
Type: 1,
Operator: "admin",
State: 0,
Deleted: 0,
IconURL: "https://activity.hdslb.com/blackboard/activity9757/static/img/title_screen.c529058.jpg",
IconGrayURL: "https://activity.hdslb.com/blackboard/activity9757/static/img/title_screen.c529058.jpg",
Order: 1,
LangType: 1,
}
convey.Convey("get max id", t, func() {
ep := new(model.Privilege)
db := d.vip.Table(_vipPrivileges).Order("order_num DESC").First(&ep)
convey.So(db.Error, convey.ShouldBeNil)
d.vip.Table(_vipPrivilegesResources).Where("pid > ?", ep.ID).Delete(model.PrivilegeResources{})
p.ID = ep.ID + 1
})
convey.Convey("AddPrivilege", t, func() {
id, err := d.AddPrivilege(tx, p)
convey.So(err, convey.ShouldBeNil)
convey.So(id, convey.ShouldNotBeNil)
})
convey.Convey("AddPrivilegeResources", t, func() {
a, err := d.AddPrivilegeResources(tx, &model.PrivilegeResources{
PID: p.ID,
Link: "web",
Type: model.WebResources,
})
convey.So(err, convey.ShouldBeNil)
convey.So(a, convey.ShouldNotBeNil)
a, err = d.AddPrivilegeResources(tx, &model.PrivilegeResources{
PID: p.ID,
Link: "app",
Type: model.AppResources,
})
convey.So(err, convey.ShouldBeNil)
convey.So(a, convey.ShouldNotBeNil)
})
convey.Convey("AddPrivilege Commit", t, func() {
err := tx.Commit().Error
convey.So(err, convey.ShouldBeNil)
})
convey.Convey("PrivilegeList", t, func() {
res, err := d.PrivilegeList(context.TODO(), 1)
convey.So(err, convey.ShouldBeNil)
convey.So(res, convey.ShouldNotBeNil)
})
convey.Convey("clean data", t, func() {
d.vip.Delete(p)
d.vip.Table(_vipPrivilegesResources).Where("pid >= ?", p.ID).Delete(model.PrivilegeResources{})
})
}
func TestDaoMaxOrder(t *testing.T) {
convey.Convey("MaxOrder", t, func() {
order, err := d.MaxOrder(context.TODO())
convey.So(err, convey.ShouldBeNil)
convey.So(order, convey.ShouldNotBeNil)
})
}
// go test -test.v -test.run TestDaoUpdateStatePrivilege
func TestDaoUpdateStatePrivilege(t *testing.T) {
convey.Convey("UpdateStatePrivilege", t, func() {
a, err := d.UpdateStatePrivilege(context.TODO(), &model.Privilege{
ID: 3,
State: 1,
})
convey.So(err, convey.ShouldBeNil)
convey.So(a, convey.ShouldNotBeNil)
})
}
// go test -test.v -test.run TestDaoDeletePrivilege
func TestDaoDeletePrivilege(t *testing.T) {
convey.Convey("DeletePrivilege", t, func() {
a, err := d.DeletePrivilege(context.TODO(), 3)
convey.So(err, convey.ShouldBeNil)
convey.So(a, convey.ShouldNotBeNil)
})
}
// go test -test.v -test.run TestDaoUpdatePrivilege
func TestDaoUpdatePrivilege(t *testing.T) {
convey.Convey("UpdatePrivilege", t, func() {
tx := d.BeginGormTran(context.TODO())
a, err := d.UpdatePrivilege(tx, &model.Privilege{
ID: 3,
Name: "超高清",
Title: "超高清标题",
Explain: "超高清描述描述超多字超多字超多字超多字超多字超多字超多字超多字超多字超多字超多字超多字超多字",
Type: 1,
Operator: "admin",
State: 0,
Deleted: 0,
IconURL: "https://activity.hdslb.com/blackboard/activity9757/static/img/title_screen.c529058.jpg",
IconGrayURL: "https://activity.hdslb.com/blackboard/activity9757/static/img/title_screen.c529058.jpg",
})
convey.So(err, convey.ShouldBeNil)
convey.So(a, convey.ShouldNotBeNil)
err = tx.Commit().Error
convey.So(err, convey.ShouldBeNil)
})
}
// go test -test.v -test.run TestDaoUpdatePrivilegeResources
func TestDaoUpdatePrivilegeResources(t *testing.T) {
convey.Convey("UpdatePrivilegeResources", t, func() {
tx := d.BeginGormTran(context.TODO())
aff, err := d.UpdatePrivilegeResources(tx, &model.PrivilegeResources{
PID: 3,
Link: "app2",
Type: model.AppResources,
})
convey.So(err, convey.ShouldBeNil)
convey.So(aff, convey.ShouldNotBeNil)
err = tx.Commit().Error
convey.So(err, convey.ShouldBeNil)
})
}
// go test -test.v -test.run TestDaoUpdateOrder
func TestDaoUpdateOrder(t *testing.T) {
convey.Convey("UpdateOrder", t, func() {
a, err := d.UpdateOrder(context.TODO(), 4, 5)
convey.So(err, convey.ShouldBeNil)
convey.So(a, convey.ShouldNotBeNil)
})
}

View File

@@ -0,0 +1,129 @@
package dao
import (
"context"
xsql "database/sql"
"fmt"
"go-common/app/admin/main/vip/model"
"go-common/library/database/sql"
"github.com/pkg/errors"
)
// GetPushData get push data by id
func (d *Dao) GetPushData(c context.Context, id int64) (r *model.VipPushData, err error) {
row := d.db.QueryRow(c, _selPushDataByIDSQL, id)
r = new(model.VipPushData)
if err = row.Scan(&r.ID, &r.DisableType, &r.GroupName, &r.Title, &r.Content, &r.PushTotalCount, &r.PushedCount, &r.ProgressStatus, &r.Status, &r.Platform, &r.LinkType, &r.LinkURL, &r.ErrorCode, &r.ExpiredDayStart, &r.ExpiredDayEnd, &r.EffectStartDate, &r.EffectEndDate, &r.PushStartTime, &r.PushEndTime, &r.Operator); err != nil {
if err == sql.ErrNoRows {
r = nil
err = nil
return
}
err = errors.WithStack(err)
d.errProm.Incr("scan_error")
}
return
}
// AddPushData add push data
func (d *Dao) AddPushData(c context.Context, r *model.VipPushData) (id int64, err error) {
var result xsql.Result
if result, err = d.db.Exec(c, _addPushDataSQL, r.GroupName, r.Title, r.Content, r.PushTotalCount, r.PushedCount, r.ProgressStatus, r.Status, r.Platform, r.LinkType, r.LinkURL, r.ExpiredDayStart, r.ExpiredDayEnd, r.EffectStartDate, r.EffectEndDate, r.PushStartTime, r.PushEndTime, r.Operator); err != nil {
err = errors.WithStack(err)
return
}
if id, err = result.LastInsertId(); err != nil {
err = errors.WithStack(err)
}
return
}
// UpdatePushData update push data
func (d *Dao) UpdatePushData(c context.Context, r *model.VipPushData) (eff int64, err error) {
var result xsql.Result
if result, err = d.db.Exec(c, _updatePushDataSQL, r.GroupName, r.Title, r.Content, r.PushTotalCount, r.ProgressStatus, r.Platform, r.LinkType, r.LinkURL, r.ExpiredDayStart, r.ExpiredDayEnd, r.EffectStartDate, r.EffectEndDate, r.PushStartTime, r.PushEndTime, r.Operator, r.ID); err != nil {
err = errors.WithStack(err)
return
}
if eff, err = result.RowsAffected(); err != nil {
err = errors.WithStack(err)
}
return
}
// PushDataCount sel push data count
func (d *Dao) PushDataCount(c context.Context, arg *model.ArgPushData) (count int64, err error) {
row := d.db.QueryRow(c, _selPushDataCountSQL+d.convertPushDataSQL(arg))
if err = row.Scan(&count); err != nil {
err = errors.WithStack(err)
}
return
}
// PushDatas sel push datas
func (d *Dao) PushDatas(c context.Context, arg *model.ArgPushData) (res []*model.VipPushData, err error) {
var rows *sql.Rows
sql := _selPushDataSQL + d.convertPushDataSQL(arg)
if arg.PN == 0 {
arg.PN = 1
}
if arg.PS == 0 || arg.PS > 100 {
arg.PS = _defps
}
sql += fmt.Sprintf(" ORDER BY id DESC LIMIT %v,%v", (arg.PN-1)*arg.PS, arg.PS)
if rows, err = d.db.Query(c, sql); err != nil {
err = errors.WithStack(err)
return
}
defer rows.Close()
for rows.Next() {
r := new(model.VipPushData)
if err = rows.Scan(&r.ID, &r.DisableType, &r.GroupName, &r.Title, &r.Content, &r.PushTotalCount, &r.PushedCount, &r.ProgressStatus, &r.Status, &r.Platform, &r.LinkType, &r.LinkURL, &r.ErrorCode, &r.ExpiredDayStart, &r.ExpiredDayEnd, &r.EffectStartDate, &r.EffectEndDate, &r.PushStartTime, &r.PushEndTime, &r.Operator); err != nil {
err = errors.WithStack(err)
}
res = append(res, r)
}
err = rows.Err()
return
}
func (d *Dao) convertPushDataSQL(arg *model.ArgPushData) string {
sql := " "
if arg.ProgressStatus != 0 {
sql += fmt.Sprintf(" AND progress_status=%v", arg.ProgressStatus)
}
if arg.Status != 0 {
sql += fmt.Sprintf(" AND status=%v", arg.Status)
}
return sql
}
// DelPushData .
func (d *Dao) DelPushData(c context.Context, id int64) (err error) {
if _, err = d.db.Exec(c, _delPushDataSQL, id); err != nil {
err = errors.WithStack(err)
return
}
return
}
// DisablePushData .
func (d *Dao) DisablePushData(c context.Context, res *model.VipPushData) (err error) {
if _, err = d.db.Exec(c, _disablePushDataSQL, res.ProgressStatus, res.PushTotalCount, res.EffectEndDate, res.ID); err != nil {
err = errors.WithStack(err)
return
}
return
}

View File

@@ -0,0 +1,49 @@
package dao
import (
"context"
"go-common/app/admin/main/vip/model"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoAddPushData(t *testing.T) {
var (
id int64
err error
)
convey.Convey("AddPushData", t, func() {
id, err = d.AddPushData(context.TODO(), &model.VipPushData{Title: "test push"})
convey.So(err, convey.ShouldBeNil)
convey.So(id, convey.ShouldNotBeNil)
})
convey.Convey("GetPushData", t, func() {
r, err := d.GetPushData(context.TODO(), id)
convey.So(err, convey.ShouldBeNil)
convey.So(r, convey.ShouldNotBeNil)
})
convey.Convey("UpdatePushData", t, func() {
eff, err := d.UpdatePushData(context.TODO(), &model.VipPushData{ID: id, Title: "push test"})
convey.So(err, convey.ShouldBeNil)
convey.So(eff, convey.ShouldNotBeNil)
})
convey.Convey("PushDataCount", t, func() {
count, err := d.PushDataCount(context.TODO(), &model.ArgPushData{})
convey.So(err, convey.ShouldBeNil)
convey.So(count, convey.ShouldNotBeNil)
})
convey.Convey("PushDatas", t, func() {
res, err := d.PushDatas(context.TODO(), &model.ArgPushData{})
convey.So(err, convey.ShouldBeNil)
convey.So(res, convey.ShouldNotBeNil)
})
convey.Convey("DisablePushData", t, func() {
err := d.DisablePushData(context.TODO(), &model.VipPushData{ID: id, Title: "push test"})
convey.So(err, convey.ShouldBeNil)
})
convey.Convey("DelPushData", t, func() {
err := d.DelPushData(context.TODO(), id)
convey.So(err, convey.ShouldBeNil)
})
}

View File

@@ -0,0 +1,302 @@
package dao
import (
"context"
xsql "database/sql"
"fmt"
"strconv"
"strings"
"go-common/app/admin/main/vip/model"
"go-common/library/database/sql"
"github.com/pkg/errors"
)
// SelBatchCodeCount .
func (d *Dao) SelBatchCodeCount(c context.Context, arg *model.ArgBatchCode) (n int64, err error) {
autoSQLStr := d.batchCodeAutoArg(arg)
row := d.db.QueryRow(c, _selBatchCodeCountSQL+autoSQLStr)
if err = row.Scan(&n); err != nil {
if err == sql.ErrNoRows {
n = 0
err = nil
return
}
err = errors.WithStack(err)
return
}
return
}
func (d *Dao) selBatchCodeIDs(c context.Context, poolID, businessID, batchID int64) (ids []int64, err error) {
var rows *sql.Rows
autoSQL := d.batchCodeAutoArg(&model.ArgBatchCode{
BusinessID: businessID,
PoolID: poolID,
ID: batchID,
})
if rows, err = d.db.Query(c, _selBatchCodeIDSQL+autoSQL); err != nil {
err = errors.WithStack(err)
d.errProm.Incr("db_query")
return
}
for rows.Next() {
var r int64
if err = rows.Scan(&r); err != nil {
err = errors.WithStack(err)
ids = nil
d.errProm.Incr("db_scan")
return
}
ids = append(ids, r)
}
return
}
func (d *Dao) codeAutoArgSQL(arg *model.ArgCode) string {
autoSQLStr := ""
if len(arg.BatchCodeIDs) > 0 {
idStr := ""
for _, v := range arg.BatchCodeIDs {
idStr += "," + strconv.Itoa(int(v))
}
autoSQLStr += fmt.Sprintf(" AND batch_code_id in(%s) ", idStr[1:])
}
if arg.Status != 0 {
autoSQLStr += fmt.Sprintf(" AND status = %v ", arg.Status)
}
if arg.UseStartTime > 0 && arg.UseEndTime > 0 {
autoSQLStr += fmt.Sprintf(" AND use_time >='%v' AND use_time <= '%v'", arg.UseStartTime.Time().Format("2006-01-02 15:04:05"), arg.UseEndTime.Time().Format("2006-01-02 15:04:05"))
}
if len(arg.Code) > 0 {
autoSQLStr += fmt.Sprintf(" AND code = '%v' ", arg.Code)
}
if arg.Mid != 0 {
autoSQLStr += fmt.Sprintf(" AND mid = %v ", arg.Mid)
}
return autoSQLStr
}
// SelCode .
func (d *Dao) SelCode(c context.Context, arg *model.ArgCode, cursor int64, ps int) (res []*model.ResourceCode, err error) {
var batchIDs []int64
if batchIDs, err = d.selBatchCodeIDs(c, arg.PoolID, arg.BusinessID, arg.BatchCodeID); err != nil {
err = errors.WithStack(err)
return
}
arg.BatchCodeIDs = batchIDs
argSQL := d.codeAutoArgSQL(arg)
if ps <= 0 || ps > 2000 {
ps = _defps
}
var rows *sql.Rows
argSQL += fmt.Sprintf(" AND id>%v LIMIT %v", cursor, ps)
if rows, err = d.db.Query(c, _selCodeSQL+argSQL); err != nil {
err = errors.WithStack(err)
return
}
for rows.Next() {
r := new(model.ResourceCode)
if err = rows.Scan(&r.ID, &r.BatchCodeID, &r.Status, &r.Code, &r.Mid, &r.UseTime, &r.Ctime); err != nil {
err = errors.WithStack(err)
res = nil
return
}
res = append(res, r)
}
return
}
// batchCodeAutoArg .
func (d *Dao) batchCodeAutoArg(arg *model.ArgBatchCode) string {
autoSQLStr := ""
if arg.BusinessID > 0 {
autoSQLStr += fmt.Sprintf(" AND business_id=%v ", arg.BusinessID)
}
if arg.PoolID > 0 {
autoSQLStr += fmt.Sprintf(" AND pool_id = %v ", arg.PoolID)
}
if arg.ID > 0 {
autoSQLStr += fmt.Sprintf(" AND id = %v ", arg.ID)
}
if len(arg.Name) > 0 {
autoSQLStr += " AND batch_name like '%" + arg.Name + "%'"
}
if arg.Status > 0 {
autoSQLStr += fmt.Sprintf(" AND status = %v", arg.Status)
}
if arg.StartTime > 0 && arg.EndTime > 0 {
autoSQLStr += fmt.Sprintf(" AND ctime >='%v' AND ctime <= '%v'", arg.StartTime.Time().Format("2006-01-02 15:04:05"), arg.EndTime.Time().Format("2006-01-02 15:04:05"))
}
return autoSQLStr
}
// SelBatchCodes .
func (d *Dao) SelBatchCodes(c context.Context, batchIds []int64) (res []*model.BatchCode, err error) {
var (
rows *sql.Rows
ids []string
)
if len(batchIds) <= 0 {
return
}
for _, v := range batchIds {
ids = append(ids, fmt.Sprintf("%v", v))
}
if rows, err = d.db.Query(c, fmt.Sprintf(_selBatchCodesSQL, strings.Join(ids, ","))); err != nil {
err = errors.WithStack(err)
return
}
for rows.Next() {
r := new(model.BatchCode)
if err = rows.Scan(&r.ID, &r.BusinessID, &r.PoolID, &r.Status, &r.Type, &r.LimitDay, &r.MaxCount, &r.BatchName, &r.Reason, &r.Unit, &r.Count, &r.SurplusCount, &r.Price, &r.StartTime, &r.EndTime, &r.Contacts, &r.ContactsNumber, &r.Ctime); err != nil {
err = errors.WithStack(err)
res = nil
return
}
res = append(res, r)
}
return
}
// SelBatchCode .
func (d *Dao) SelBatchCode(c context.Context, arg *model.ArgBatchCode, pn, ps int) (res []*model.BatchCode, err error) {
var rows *sql.Rows
autoSQLStr := d.batchCodeAutoArg(arg)
if pn <= 0 {
pn = _defpn
}
if ps <= 0 || ps > _maxps {
ps = _defps
}
autoSQLStr += fmt.Sprintf(" LIMIT %v,%v", (pn-1)*ps, ps)
if rows, err = d.db.Query(c, _selBatchCodeSQL+autoSQLStr); err != nil {
err = errors.WithStack(err)
return
}
defer rows.Close()
for rows.Next() {
r := new(model.BatchCode)
if err = rows.Scan(&r.ID, &r.BusinessID, &r.PoolID, &r.Status, &r.Type, &r.LimitDay, &r.MaxCount, &r.BatchName, &r.Reason, &r.Unit, &r.Count, &r.SurplusCount, &r.Price, &r.StartTime, &r.EndTime, &r.Contacts, &r.ContactsNumber, &r.Ctime); err != nil {
err = errors.WithStack(err)
res = nil
return
}
res = append(res, r)
}
return
}
// SelBatchCodeName .
func (d *Dao) SelBatchCodeName(c context.Context, name string) (r *model.BatchCode, err error) {
row := d.db.QueryRow(c, _selBatchCodeByNameSQL, name)
r = new(model.BatchCode)
if err = row.Scan(&r.ID, &r.BusinessID, &r.PoolID, &r.Status, &r.Type, &r.LimitDay, &r.MaxCount, &r.BatchName, &r.Reason, &r.Unit, &r.Count, &r.SurplusCount, &r.Price, &r.StartTime, &r.EndTime, &r.Contacts, &r.ContactsNumber, &r.Ctime); err != nil {
if err == sql.ErrNoRows {
r = nil
err = nil
fmt.Printf("this is %+v", err)
return
}
err = errors.WithStack(err)
return
}
return
}
// SelBatchCodeID .
func (d *Dao) SelBatchCodeID(c context.Context, batchCodeID int64) (r *model.BatchCode, err error) {
row := d.db.QueryRow(c, _selBatchCodeByIDSQL, batchCodeID)
r = new(model.BatchCode)
if err = row.Scan(&r.ID, &r.BusinessID, &r.PoolID, &r.Status, &r.Type, &r.LimitDay, &r.MaxCount, &r.BatchName, &r.Reason, &r.Unit, &r.Count, &r.SurplusCount, &r.Price, &r.StartTime, &r.EndTime, &r.Contacts, &r.ContactsNumber, &r.Ctime); err != nil {
if err == sql.ErrNoRows {
r = nil
err = nil
return
}
err = errors.WithStack(err)
return
}
return
}
// SelCodeID .
func (d *Dao) SelCodeID(c context.Context, codeID int64) (r *model.ResourceCode, err error) {
row := d.db.QueryRow(c, _selCodeByIDSQL, codeID)
r = new(model.ResourceCode)
if err = row.Scan(&r.ID, &r.BatchCodeID, &r.Status, &r.Code, &r.Mid, &r.UseTime, &r.Ctime); err != nil {
if err == sql.ErrNoRows {
r = nil
err = nil
}
err = errors.WithStack(err)
return
}
return
}
// TxAddBatchCode .
func (d *Dao) TxAddBatchCode(tx *sql.Tx, bc *model.BatchCode) (ID int64, err error) {
var result xsql.Result
if result, err = tx.Exec(_addBatchCodeSQL, bc.BusinessID, bc.PoolID, bc.Status, bc.BatchName, bc.Reason, bc.Unit, bc.Count, bc.SurplusCount, bc.Price, bc.StartTime, bc.EndTime, bc.Contacts, bc.ContactsNumber, bc.Type, bc.LimitDay, bc.MaxCount, bc.Operator); err != nil {
err = errors.WithStack(err)
return
}
if ID, err = result.LastInsertId(); err != nil {
err = errors.WithStack(err)
return
}
return
}
// UpdateBatchCode .
func (d *Dao) UpdateBatchCode(c context.Context, bc *model.BatchCode) (eff int64, err error) {
var result xsql.Result
if result, err = d.db.Exec(c, _updateBatchCodeSQL, &bc.Status, &bc.BatchName, &bc.Reason, &bc.Price, &bc.Contacts, &bc.ContactsNumber, &bc.Type, &bc.LimitDay, &bc.MaxCount, &bc.Operator, &bc.ID); err != nil {
err = errors.WithStack(err)
return
}
if eff, err = result.RowsAffected(); err != nil {
err = errors.WithStack(err)
return
}
return
}
// UpdateCode .
func (d *Dao) UpdateCode(c context.Context, codeID int64, status int8) (eff int64, err error) {
var result xsql.Result
if result, err = d.db.Exec(c, _updateCodeSQL, status, codeID); err != nil {
err = errors.WithStack(err)
return
}
if eff, err = result.RowsAffected(); err != nil {
err = errors.WithStack(err)
return
}
return
}
// BatchAddCode .
func (d *Dao) BatchAddCode(tx *sql.Tx, codes []*model.ResourceCode) (err error) {
values := make([]string, 0)
for _, v := range codes {
s := fmt.Sprintf("('%v','%v','%v')", v.BatchCodeID, v.Status, v.Code)
values = append(values, s)
}
valuesStr := strings.Join(values, ",")
if _, err = tx.Exec(_batchAddCodeSQL + valuesStr); err != nil {
err = errors.WithStack(err)
return
}
return
}

View File

@@ -0,0 +1,108 @@
package dao
import (
"context"
"math/rand"
"testing"
"go-common/app/admin/main/vip/model"
xsql "go-common/library/database/sql"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoSelBatchCodeCount(t *testing.T) {
convey.Convey("SelBatchCodeCount", t, func() {
n, err := d.SelBatchCodeCount(context.TODO(), &model.ArgBatchCode{})
convey.So(err, convey.ShouldBeNil)
convey.So(n, convey.ShouldNotBeNil)
})
}
func TestDaoselBatchCodeIDs(t *testing.T) {
convey.Convey("selBatchCodeIDs", t, func() {
ids, err := d.selBatchCodeIDs(context.TODO(), 0, 0, 0)
convey.So(err, convey.ShouldBeNil)
convey.So(ids, convey.ShouldNotBeNil)
})
}
func TestDaocodeAutoArgSQL(t *testing.T) {
convey.Convey("codeAutoArgSQL", t, func() {
p1 := d.codeAutoArgSQL(&model.ArgCode{})
convey.So(p1, convey.ShouldNotBeNil)
})
}
func TestDaoSelCode(t *testing.T) {
convey.Convey("SelCode", t, func() {
_, err := d.SelCode(context.TODO(), &model.ArgCode{}, 0, 0)
convey.So(err, convey.ShouldBeNil)
})
}
func TestDaoSelBatchCodes(t *testing.T) {
convey.Convey("SelBatchCodes", t, func() {
_, err := d.SelBatchCodes(context.TODO(), []int64{})
convey.So(err, convey.ShouldBeNil)
})
}
func TestDaoSelBatchCode(t *testing.T) {
convey.Convey("SelBatchCode", t, func() {
_, err := d.SelBatchCode(context.TODO(), &model.ArgBatchCode{}, 0, 0)
convey.So(err, convey.ShouldBeNil)
})
}
func TestDaoTxAddBatchCode(t *testing.T) {
var (
id int64
err error
)
convey.Convey("TxAddBatchCode", t, func() {
var tx *xsql.Tx
tx, err = d.BeginTran(context.Background())
convey.So(err, convey.ShouldBeNil)
id, err = d.TxAddBatchCode(tx, &model.BatchCode{BusinessID: 1, BatchName: "ut_test"})
convey.So(err, convey.ShouldBeNil)
convey.So(id, convey.ShouldNotBeNil)
tx.Commit()
})
convey.Convey("SelCodeID", t, func() {
r, err := d.SelCodeID(context.TODO(), id)
convey.So(err, convey.ShouldBeNil)
convey.So(r, convey.ShouldNotBeNil)
})
convey.Convey("SelBatchCodeID", t, func() {
r, err := d.SelBatchCodeID(context.TODO(), id)
convey.So(err, convey.ShouldBeNil)
convey.So(r, convey.ShouldNotBeNil)
})
convey.Convey("SelBatchCodeName", t, func() {
_, err := d.SelBatchCodeName(context.TODO(), "ut_test")
convey.So(err, convey.ShouldBeNil)
})
convey.Convey("UpdateBatchCode", t, func() {
eff, err := d.UpdateBatchCode(context.TODO(), &model.BatchCode{ID: id, BusinessID: 11})
convey.So(err, convey.ShouldBeNil)
convey.So(eff, convey.ShouldNotBeNil)
})
convey.Convey("UpdateCode", t, func() {
eff, err := d.UpdateCode(context.TODO(), id, 0)
convey.So(err, convey.ShouldBeNil)
convey.So(eff, convey.ShouldNotBeNil)
})
}
func TestDaoBatchAddCode(t *testing.T) {
codes := []*model.ResourceCode{
{BatchCodeID: int64(rand.Int31())},
}
convey.Convey("BatchAddCode", t, func() {
tx, err := d.BeginTran(context.Background())
convey.So(err, convey.ShouldBeNil)
err = d.BatchAddCode(tx, codes)
convey.So(err, convey.ShouldBeNil)
})
}

View File

@@ -0,0 +1,176 @@
package dao
import (
"bytes"
"context"
"crypto/md5"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"sort"
"strconv"
"strings"
"time"
"go-common/app/admin/main/vip/model"
"go-common/library/ecode"
"go-common/library/log"
"github.com/google/uuid"
"github.com/pkg/errors"
)
const (
_SendUserNotify = "/api/notify/send.user.notify.do"
_payRefund = "/payplatform/refund/request"
_minRead = 1024 * 64
)
// SendMultipMsg send multip msg
func (d *Dao) SendMultipMsg(c context.Context, mids, content, title, mc, ip string, dataType int) (err error) {
params := url.Values{}
params.Set("mc", mc)
params.Set("title", title)
params.Set("context", content)
params.Set("data_type", strconv.FormatInt(int64(dataType), 10))
params.Set("mid_list", mids)
if err = d.client.Post(c, d.c.Property.MsgURI+_SendUserNotify, "127.0.0.1", params, nil); err != nil {
log.Error("SendMultipMsg error(%v)", err)
return
}
return
}
//PayRefund .
func (d *Dao) PayRefund(c context.Context, arg *model.PayOrder, refundAmount float64, refundID string) (err error) {
params := make(map[string]string)
params["customerId"] = strconv.FormatInt(d.c.PayConf.CustomerID, 10)
params["notifyUrl"] = d.c.PayConf.RefundURL
params["version"] = d.c.PayConf.Version
params["signType"] = "MD5"
params["timestamp"] = strconv.FormatInt(time.Now().UnixNano()/1e6, 10)
params["traceId"] = uuid.New().String()
params["refundDesc"] = "大会员退款"
params["customerRefundId"] = refundID
params["txId"] = arg.ThirdTradeNo
params["totalAmount"] = strconv.Itoa(int(arg.Money * 100))
params["refundAmount"] = strconv.Itoa(int(refundAmount * 100))
sign := d.paySign(params, d.c.PayConf.Token)
params["sign"] = sign
resq := new(struct {
Code int `json:"errno"`
Msg string `json:"msg"`
})
if err = d.doPaySend(c, d.c.PayConf.BaseURL, _payRefund, "", nil, nil, params, resq); err != nil {
err = errors.WithStack(err)
return
}
if resq.Code != ecode.OK.Code() {
err = ecode.Int(resq.Code)
}
return
}
func (d *Dao) paySign(params map[string]string, token string) (sign string) {
tmp := d.sortParamsKey(params)
var b bytes.Buffer
b.WriteString(tmp)
b.WriteString(fmt.Sprintf("&token=%s", token))
log.Info("pay sign params:(%s) \n", b.String())
mh := md5.Sum(b.Bytes())
// query
sign = hex.EncodeToString(mh[:])
log.Info("pay sign (%v)", sign)
return
}
func (d *Dao) sortParamsKey(v map[string]string) string {
if v == nil {
return ""
}
var buf bytes.Buffer
keys := make([]string, 0, len(v))
for k := range v {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
vs := v[k]
prefix := k + "="
if buf.Len() > 0 {
buf.WriteByte('&')
}
buf.WriteString(prefix)
buf.WriteString(vs)
}
return buf.String()
}
func (d *Dao) doPaySend(c context.Context, basePath, path, IP string, cookie []*http.Cookie, header map[string]string, params map[string]string, data interface{}) (err error) {
var (
req *http.Request
client = new(http.Client)
resp *http.Response
bs []byte
)
url := basePath + path
marshal, _ := json.Marshal(params)
if req, err = http.NewRequest(http.MethodPost, url, strings.NewReader(string(marshal))); err != nil {
err = errors.WithStack(err)
return
}
req.Header.Add("Content-Type", "application/json")
req.Header.Add("x-backend-bili-real-ip", IP)
for _, v := range cookie {
req.AddCookie(v)
}
for k, v := range header {
req.Header.Add(k, v)
}
if resp, err = client.Do(req); err != nil {
log.Error("call url:%v params:(%+v)", basePath+path, params)
err = errors.WithStack(err)
return
}
defer resp.Body.Close()
if resp.StatusCode >= http.StatusBadRequest {
err = errors.Errorf("incorrect http status:%d host:%s, url:%s", resp.StatusCode, req.URL.Host, req.URL.String())
return
}
if bs, err = readAll(resp.Body, _minRead); err != nil {
err = errors.Wrapf(err, "host:%s, url:%s", req.URL.Host, req.URL.String())
return
}
if err = json.Unmarshal(bs, data); err != nil {
err = errors.WithStack(err)
return
}
log.Info("call url:%v params:%+v result:%+v", url, params, data)
return
}
func readAll(r io.Reader, capacity int64) (b []byte, err error) {
buf := bytes.NewBuffer(make([]byte, 0, capacity))
// If the buffer overflows, we will get bytes.ErrTooLarge.
// Return that as an error. Any other panic remains.
defer func() {
e := recover()
if e == nil {
return
}
if panicErr, ok := e.(error); ok && panicErr == bytes.ErrTooLarge {
err = panicErr
} else {
panic(e)
}
}()
_, err = buf.ReadFrom(r)
return buf.Bytes(), err
}

View File

@@ -0,0 +1,33 @@
package dao
import (
"context"
"go-common/app/admin/main/vip/model"
"testing"
"github.com/smartystreets/goconvey/convey"
gock "gopkg.in/h2non/gock.v1"
)
func TestDaoSendMultipMsg(t *testing.T) {
convey.Convey("SendMultipMsg", t, func() {
defer gock.OffAll()
httpMock("POST", _SendUserNotify).Reply(200).JSON(`{"code":0}`)
err := d.SendMultipMsg(context.TODO(), "", "", "", "", "", 0)
convey.So(err, convey.ShouldBeNil)
})
}
func TestDaoPayRefund(t *testing.T) {
var (
arg = &model.PayOrder{}
refundAmount float64 = 1.0
refundID = "test001"
)
convey.Convey("PayRefund", t, func() {
defer gock.OffAll()
httpMock("POST", _payRefund).Reply(200).JSON(`{"code":0}`)
err := d.PayRefund(context.Background(), arg, refundAmount, refundID)
convey.So(err, convey.ShouldBeNil)
})
}

View File

@@ -0,0 +1,128 @@
package dao
import (
"context"
xsql "database/sql"
"fmt"
"go-common/app/admin/main/vip/model"
"go-common/library/database/sql"
"github.com/pkg/errors"
)
const (
_tipsSQL = "SELECT `id`,`platform`,`version`,`tip`,`link`,`start_time`,`end_time`,`level`,`judge_type`,`operator`,`deleted`, `position`,`ctime`,`mtime`FROM `vip_tips` WHERE `deleted` = 0 "
_tipsByIDSQL = "SELECT `id`,`platform`,`version`,`tip`,`link`,`start_time`,`end_time`,`level`,`judge_type`,`operator`,`deleted`, `position`,`ctime`,`mtime`FROM `vip_tips` WHERE `id` = ?;"
_updateTipSQL = "UPDATE `vip_tips` SET `platform` = ?,`version` = ?,`tip` = ?,`link` = ?,`start_time` = ?,`end_time` = ?,`level` = ?, `judge_type` = ?, `operator` = ?, `position` = ? WHERE `id` = ?;"
_addTipSQL = "INSERT INTO `vip_tips`(`platform`,`version`,`tip`,`link`,`start_time`,`end_time`,`level`,`judge_type`,`operator`,`deleted`,`ctime`, `position`)VALUES(?,?,?,?,?,?,?,?,?,?,?,?);"
_deleteTipSQL = "UPDATE `vip_tips` SET `deleted` = ?,`operator` = ? WHERE `id` = ?;"
_expireTipSQL = "UPDATE `vip_tips` SET `end_time` = ?,`operator` = ? WHERE `id` = ?;"
)
// TipList tips list.
func (d *Dao) TipList(c context.Context, platform int8, state int8, now int64, position int8) (rs []*model.Tips, err error) {
var (
rows *sql.Rows
sql = _tipsSQL
)
switch state {
case model.WaitShowTips:
sql += fmt.Sprintf(" AND `start_time` > %d ", now)
case model.EffectiveTips:
sql += fmt.Sprintf(" AND `start_time` < %d AND `end_time`> %d", now, now)
case model.ExpireTips:
sql += fmt.Sprintf(" AND `end_time` < %d ", now)
}
if platform != 0 {
sql += fmt.Sprintf(" AND `platform` = %d ", platform)
}
if position != 0 {
sql += fmt.Sprintf(" AND `position` = %d ", position)
}
if rows, err = d.db.Query(c, sql); err != nil {
err = errors.WithStack(err)
return
}
defer rows.Close()
for rows.Next() {
r := new(model.Tips)
if err = rows.Scan(&r.ID, &r.Platform, &r.Version, &r.Tip, &r.Link, &r.StartTime, &r.EndTime, &r.Level, &r.JudgeType, &r.Operator, &r.Deleted, &r.Position, &r.Ctime, &r.Mtime); err != nil {
rs = nil
err = errors.WithStack(err)
return
}
rs = append(rs, r)
}
if err = rows.Err(); err != nil {
err = errors.WithStack(err)
}
return
}
// TipByID by id .
func (d *Dao) TipByID(c context.Context, id int64) (r *model.Tips, err error) {
res := d.db.QueryRow(c, _tipsByIDSQL, id)
r = new(model.Tips)
if err = res.Scan(&r.ID, &r.Platform, &r.Version, &r.Tip, &r.Link, &r.StartTime, &r.EndTime, &r.Level, &r.JudgeType, &r.Operator, &r.Deleted, &r.Position, &r.Ctime, &r.Mtime); err != nil {
if err == sql.ErrNoRows {
err = nil
r = nil
return
}
err = errors.WithStack(err)
}
return
}
// TipUpdate tip update.
func (d *Dao) TipUpdate(c context.Context, t *model.Tips) (eff int64, err error) {
var res xsql.Result
if res, err = d.db.Exec(c, _updateTipSQL, t.Platform, t.Version, t.Tip, t.Link, t.StartTime, t.EndTime, t.Level, t.JudgeType, t.Operator, t.Position, t.ID); err != nil {
err = errors.WithStack(err)
return
}
if eff, err = res.RowsAffected(); err != nil {
err = errors.WithStack(err)
}
return
}
// AddTip add tip.
func (d *Dao) AddTip(c context.Context, t *model.Tips) (lid int64, err error) {
var res xsql.Result
if res, err = d.db.Exec(c, _addTipSQL, t.Platform, t.Version, t.Tip, t.Link, t.StartTime, t.EndTime, t.Level, t.JudgeType, t.Operator, t.Deleted, t.Ctime, t.Position); err != nil {
err = errors.WithStack(err)
return
}
if lid, err = res.LastInsertId(); err != nil {
err = errors.WithStack(err)
}
return
}
// DeleteTip tip delete.
func (d *Dao) DeleteTip(c context.Context, id int64, deleted int8, operator string) (eff int64, err error) {
var res xsql.Result
if res, err = d.db.Exec(c, _deleteTipSQL, deleted, operator, id); err != nil {
err = errors.WithStack(err)
return
}
if eff, err = res.RowsAffected(); err != nil {
err = errors.WithStack(err)
}
return
}
// ExpireTip tip expire.
func (d *Dao) ExpireTip(c context.Context, id int64, operator string, t int64) (eff int64, err error) {
var res xsql.Result
if res, err = d.db.Exec(c, _expireTipSQL, t, operator, id); err != nil {
err = errors.WithStack(err)
return
}
if eff, err = res.RowsAffected(); err != nil {
err = errors.WithStack(err)
}
return
}

View File

@@ -0,0 +1,50 @@
package dao
import (
"context"
"testing"
"go-common/app/admin/main/vip/model"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoTipList(t *testing.T) {
convey.Convey("TipList", t, func() {
rs, err := d.TipList(context.TODO(), 0, 0, 0, 0)
convey.So(err, convey.ShouldBeNil)
convey.So(rs, convey.ShouldNotBeNil)
})
}
func TestDaoAddTip(t *testing.T) {
var (
id int64
err error
)
convey.Convey("AddTip", t, func() {
id, err = d.AddTip(context.TODO(), &model.Tips{Tip: "test"})
convey.So(err, convey.ShouldBeNil)
convey.So(id, convey.ShouldNotBeNil)
})
convey.Convey("TipByID", t, func() {
r, err := d.TipByID(context.TODO(), id)
convey.So(err, convey.ShouldBeNil)
convey.So(r, convey.ShouldNotBeNil)
})
convey.Convey("TipUpdate", t, func() {
eff, err := d.TipUpdate(context.TODO(), &model.Tips{ID: id, Tip: "test"})
convey.So(err, convey.ShouldBeNil)
convey.So(eff, convey.ShouldNotBeNil)
})
convey.Convey("ExpireTip", t, func() {
eff, err := d.ExpireTip(context.TODO(), id, "", 0)
convey.So(err, convey.ShouldBeNil)
convey.So(eff, convey.ShouldNotBeNil)
})
convey.Convey("DeleteTip", t, func() {
eff, err := d.DeleteTip(context.TODO(), id, 0, "")
convey.So(err, convey.ShouldBeNil)
convey.So(eff, convey.ShouldNotBeNil)
})
}

View File

@@ -0,0 +1,71 @@
package dao
import (
"context"
xsql "database/sql"
"go-common/app/admin/main/vip/model"
"go-common/library/database/sql"
"go-common/library/log"
"go-common/library/time"
)
// const .
const (
_selVipUserInfoByMid = "SELECT id,mid,vip_type,vip_pay_type,vip_status,vip_start_time,vip_overdue_time,annual_vip_overdue_time,ctime,mtime,vip_recent_time FROM vip_user_info WHERE mid = ?"
_UpdateVipUserInfoByID = "UPDATE vip_user_info SET vip_type=?,vip_status=?,vip_overdue_time=?,annual_vip_overdue_time=?,vip_recent_time=? WHERE id=?"
_InsertVipChangeHistory = "INSERT INTO vip_user_change_history(mid,change_type,change_time,days,operator_id,relation_id,batch_id,remark) VALUES(?,?,?,?,?,?,?,?)"
_DelBcoinSalary = "DELETE FROM vip_user_bcoin_salary WHERE status = 0 AND mid = ? and payday>=?"
)
// DelBcoinSalary del bacoin salary
func (d *Dao) DelBcoinSalary(tx *sql.Tx, mid int64, month time.Time) (err error) {
if _, err = tx.Exec(_DelBcoinSalary, mid, month); err != nil {
log.Error("InertVipBcoinSalary.exec(mid:%v,month:%v) error(%+v)", mid, month, err)
}
return
}
// SelVipUserInfo select user info by mid
func (d *Dao) SelVipUserInfo(c context.Context, mid int64) (r *model.VipUserInfo, err error) {
var row = d.db.QueryRow(c, _selVipUserInfoByMid, mid)
r = new(model.VipUserInfo)
if err = row.Scan(&r.ID, &r.Mid, &r.VipType, &r.VipPayType, &r.VipStatus, &r.VipStartTime, &r.VipOverdueTime, &r.AnnualVipOverdueTime, &r.Ctime, &r.Mtime, &r.VipRecentTime); err != nil {
if err == sql.ErrNoRows {
r = nil
err = nil
} else {
log.Error("row.Scan() error(%v)", err)
}
}
return
}
// UpdateVipUserInfo update vip user info by id
func (d *Dao) UpdateVipUserInfo(tx *sql.Tx, r *model.VipUserInfo) (a int64, err error) {
var res xsql.Result
if res, err = tx.Exec(_UpdateVipUserInfoByID, r.VipType, r.VipStatus, r.VipOverdueTime, r.AnnualVipOverdueTime, r.VipRecentTime, r.ID); err != nil {
log.Error("UpdateVipUserInfo: db.Exec(%v) error(%v)", r, err)
return
}
if a, err = res.RowsAffected(); err != nil {
log.Error("UpdateVipUserInfo: res.RowsAffected error(%v)", err)
return
}
return
}
// InsertVipChangeHistory insert vipChangeHistory
func (d *Dao) InsertVipChangeHistory(tx *sql.Tx, r *model.VipChangeHistory) (id int64, err error) {
var res xsql.Result
if res, err = tx.Exec(_InsertVipChangeHistory, r.Mid, r.ChangeType, r.ChangeTime, r.Days, r.OperatorID, r.RelationID, r.BatchID, r.Remark); err != nil {
log.Error("InsertVipChangeHistory db.Exec(%v) error(%v)", r, err)
} else {
if id, err = res.LastInsertId(); err != nil {
log.Error("InsertVipChangeHistory LastInsertId() error(%v)", err)
}
}
return
}

View File

@@ -0,0 +1,97 @@
package dao
import (
"context"
"testing"
"time"
"go-common/app/admin/main/vip/model"
xtime "go-common/library/time"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoDelBcoinSalary(t *testing.T) {
convey.Convey("DelBcoinSalary", t, func(ctx convey.C) {
var (
tx, _ = d.BeginTran(context.Background())
mid = int64(1)
month = xtime.Time(time.Now().Unix())
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
err := d.DelBcoinSalary(tx, mid, month)
if err == nil {
if err = tx.Commit(); err != nil {
tx.Rollback()
}
} else {
tx.Rollback()
}
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoSelVipUserInfo(t *testing.T) {
convey.Convey("SelVipUserInfo", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(1)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
r, err := d.SelVipUserInfo(c, mid)
ctx.Convey("Then err should be nil.r should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(r, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoUpdateVipUserInfo(t *testing.T) {
convey.Convey("UpdateVipUserInfo", t, func(ctx convey.C) {
var (
tx, _ = d.BeginTran(context.Background())
r = &model.VipUserInfo{}
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
a, err := d.UpdateVipUserInfo(tx, r)
if err == nil {
if err = tx.Commit(); err != nil {
tx.Rollback()
}
} else {
tx.Rollback()
}
ctx.Convey("Then err should be nil.a should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(a, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoInsertVipChangeHistory(t *testing.T) {
convey.Convey("InsertVipChangeHistory", t, func(ctx convey.C) {
var (
tx, _ = d.BeginTran(context.Background())
r = &model.VipChangeHistory{}
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
id, err := d.InsertVipChangeHistory(tx, r)
if err == nil {
if err = tx.Commit(); err != nil {
tx.Rollback()
}
} else {
tx.Rollback()
}
ctx.Convey("Then err should be nil.id should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(id, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,212 @@
package dao
import (
"fmt"
"strings"
"time"
"go-common/app/admin/main/vip/model"
"go-common/library/log"
"github.com/jinzhu/gorm"
"github.com/pkg/errors"
)
const (
_welfareTypeTable = "vip_welfare_type"
_welfareTable = "vip_welfare"
_codeBatchTable = "vip_welfare_code_batch"
_welfareCodeTable = "vip_welfare_code"
_notDelete = 0
_nobody = 0
_noTid = 0
_batchInsertWelfareCode = "INSERT INTO vip_welfare_code (bid, wid, code) VALUES %s"
)
// WelfareTypeAdd add welfare type
func (d *Dao) WelfareTypeAdd(wt *model.WelfareType) (err error) {
if err = d.vip.Save(wt).Error; err != nil {
err = errors.Wrapf(err, "WelfareTypeAdd(%+v)", wt)
}
return
}
// WelfareTypeUpd update welfare type
func (d *Dao) WelfareTypeUpd(wt *model.WelfareType) (err error) {
if err = d.vip.Table(_welfareTypeTable).Where("id = ? and state = ?", wt.ID, _notDelete).
Update(map[string]interface{}{
"oper_id": wt.OperID,
"oper_name": wt.OperName,
"state": wt.State,
"name": wt.Name,
}).Error; err != nil {
err = errors.Wrapf(err, "WelfareTypeUpd(%+v)", wt)
}
return
}
// WelfareTypeState delete welfare type
func (d *Dao) WelfareTypeState(tx *gorm.DB, id, state, operId int, operName string) (err error) {
if err = tx.Table(_welfareTypeTable).Where("id = ?", id).
Update(map[string]interface{}{
"oper_id": operId,
"oper_name": operName,
"state": state,
}).Error; err != nil {
err = errors.Wrapf(err, "WelfareTypeState id(%v) state(%v)", id, state)
}
return
}
// WelfareTypeList get welfare type list
func (d *Dao) WelfareTypeList() (wts []*model.WelfareTypeRes, err error) {
if err = d.vip.Table(_welfareTypeTable).Where("state = ?", _notDelete).Find(&wts).Error; err != nil {
err = errors.Wrapf(err, "WelfareTypeList")
}
return
}
// WelfareAdd add welfare
func (d *Dao) WelfareAdd(wt *model.Welfare) (err error) {
if err = d.vip.Save(wt).Error; err != nil {
err = errors.Wrapf(err, "WelfareAdd(%+v)", wt)
}
return
}
// WelfareUpd update welfare
func (d *Dao) WelfareUpd(wt *model.WelfareReq) (err error) {
if err = d.vip.Table(_welfareTable).Where("id = ? and state = ?", wt.ID, _notDelete).
Update(map[string]interface{}{
"welfare_name": wt.WelfareName,
"welfare_desc": wt.WelfareDesc,
"homepage_uri": wt.HomepageUri,
"backdrop_uri": wt.BackdropUri,
"recommend": wt.Recommend,
"rank": wt.Rank,
"tid": wt.Tid,
"stime": wt.Stime,
"etime": wt.Etime,
"usage_form": wt.UsageForm,
"receive_rate": wt.ReceiveRate,
"receive_uri": wt.ReceiveUri,
"vip_type": wt.VipType,
"oper_id": wt.OperID,
"oper_name": wt.OperName,
}).Error; err != nil {
err = errors.Wrapf(err, "WelfareUpd(%+v)", wt)
}
return
}
// WelfareState delete welfare
func (d *Dao) WelfareState(id, state, operId int, operName string) (err error) {
if err = d.vip.Table(_welfareTable).Where("id = ?", id).
Update(map[string]interface{}{
"oper_id": operId,
"oper_name": operName,
"state": state,
}).Error; err != nil {
err = errors.Wrapf(err, "WelfareState id(%v) state(%v)", id, state)
}
return
}
// ResetWelfareTid reset welfare tid to 0
func (d *Dao) ResetWelfareTid(tx *gorm.DB, tid int) (err error) {
if err = tx.Table(_welfareTable).Where("tid = ?", tid).Update("tid", _noTid).Error; err != nil {
err = errors.Wrapf(err, "ResetWelfareTid(%v)", tid)
}
return
}
// WelfareList get welfare list
func (d *Dao) WelfareList(tid int) (ws []*model.WelfareRes, err error) {
db := d.vip.Table(_welfareTable)
if tid != 0 {
db = db.Where("tid = ?", tid)
}
if err = db.Where("state = ?", _notDelete).Order("recommend desc, rank").Find(&ws).Error; err != nil {
err = errors.Wrapf(err, "WelfareList(%+v)", tid)
}
return
}
// WelfareBatchSave add welfare batch
func (d *Dao) WelfareBatchSave(wcb *model.WelfareCodeBatch) (err error) {
if err = d.vip.Table(_codeBatchTable).Save(wcb).Error; err != nil {
err = errors.Wrapf(err, "WelfareBatchSave(%+v)", wcb)
}
return
}
// WelfareBatchList get welfare list
func (d *Dao) WelfareBatchList(wid int) (wbs []*model.WelfareBatchRes, err error) {
if err = d.vip.Table(_codeBatchTable).Where("wid = ? and state = ?", wid, _notDelete).Find(&wbs).Error; err != nil {
err = errors.Wrapf(err, "WelfareBatchList(%+v)", wid)
}
return
}
// WelfareBatchState delete welfare batch
func (d *Dao) WelfareBatchState(tx *gorm.DB, id, state, operId int, operName string) (err error) {
if err = tx.Table(_codeBatchTable).Where("id = ?", id).
Update(map[string]interface{}{
"oper_id": operId,
"oper_name": operName,
"state": state,
}).Error; err != nil {
err = errors.Wrapf(err, "WelfareBatchState(%+v)", id)
}
return
}
// WelfareCodeBatchInsert insert welfare batch code
func (d *Dao) WelfareCodeBatchInsert(wcs []*model.WelfareCode) (err error) {
log.Info("WelfareCodeBatchInsert start time (%s)", time.Now())
var (
buff = make([]*model.WelfareCode, 2000)
buffEnd = 0
)
for _, wc := range wcs {
buff[buffEnd] = wc
buffEnd++
if buffEnd >= 2000 {
buffEnd = 0
stmt, valueArgs := getBatchInsertSQL(buff)
if err = d.vip.Exec(stmt, valueArgs...).Error; err != nil {
return
}
}
}
if buffEnd > 0 {
stmt, valueArgs := getBatchInsertSQL(buff[:buffEnd])
buffEnd = 0
if err = d.vip.Exec(stmt, valueArgs...).Error; err != nil {
return
}
}
log.Info("WelfareCodeBatchInsert end time (%s)", time.Now())
return
}
// WelfareCodeStatus delete welfare batch code
func (d *Dao) WelfareCodeStatus(tx *gorm.DB, bid, state int) (err error) {
if err = tx.Table(_welfareCodeTable).Where("bid = ? and mid = ?", bid, _nobody).
Update("state", state).Error; err != nil {
err = errors.Wrapf(err, "WelfareCodeStatus(%+v) (%+v)", bid, state)
}
return
}
func getBatchInsertSQL(buff []*model.WelfareCode) (stmt string, valueArgs []interface{}) {
values := []string{}
for _, b := range buff {
values = append(values, "(?,?,?)")
valueArgs = append(valueArgs, b.Bid, b.Wid, b.Code)
}
stmt = fmt.Sprintf(_batchInsertWelfareCode, strings.Join(values, ","))
return
}

View File

@@ -0,0 +1,255 @@
package dao
import (
"context"
"testing"
"go-common/app/admin/main/vip/model"
"go-common/library/log"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoWelfareTypeAdd(t *testing.T) {
convey.Convey("WelfareTypeAdd", t, func(ctx convey.C) {
var (
wt = &model.WelfareType{ID: 1000000, Name: "utTestAdd"}
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
err := d.WelfareTypeAdd(wt)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoWelfareTypeUpd(t *testing.T) {
convey.Convey("WelfareTypeUpd", t, func(ctx convey.C) {
var (
wt = &model.WelfareType{ID: 1000000, Name: "utTestUpd"}
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
err := d.WelfareTypeUpd(wt)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoWelfareTypeState(t *testing.T) {
convey.Convey("WelfareTypeState", t, func(ctx convey.C) {
var (
tx = d.BeginGormTran(context.Background())
id = int(1000000)
state = int(1)
operId = int(0)
operName = "utTest"
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
err := d.WelfareTypeState(tx, id, state, operId, operName)
tx.Commit()
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoWelfareTypeList(t *testing.T) {
convey.Convey("WelfareTypeList", t, func(ctx convey.C) {
ctx.Convey("When everything gose positive", func(ctx convey.C) {
wts, err := d.WelfareTypeList()
ctx.Convey("Then err should be nil.wts should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(wts, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoWelfareAdd(t *testing.T) {
convey.Convey("WelfareAdd", t, func(ctx convey.C) {
var (
wt = &model.Welfare{ID: 100000, Tid: 100000, WelfareName: "utTestAdd"}
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
err := d.WelfareAdd(wt)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoWelfareUpd(t *testing.T) {
convey.Convey("WelfareUpd", t, func(ctx convey.C) {
var (
wt = &model.WelfareReq{ID: 100000, Tid: 100000, WelfareName: "utTestUpd"}
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
err := d.WelfareUpd(wt)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoWelfareState(t *testing.T) {
convey.Convey("WelfareState", t, func(ctx convey.C) {
var (
id = int(100000)
state = int(1)
operId = int(0)
operName = "utTest"
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
err := d.WelfareState(id, state, operId, operName)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoResetWelfareTid(t *testing.T) {
convey.Convey("ResetWelfareTid", t, func(ctx convey.C) {
var (
tx = d.BeginGormTran(context.Background())
tid = int(100000)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
err := d.ResetWelfareTid(tx, tid)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoWelfareList(t *testing.T) {
convey.Convey("WelfareList", t, func(ctx convey.C) {
var (
tid = int(100000)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
ws, err := d.WelfareList(tid)
ctx.Convey("Then err should be nil.ws should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(ws, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoWelfareBatchSave(t *testing.T) {
convey.Convey("WelfareBatchSave", t, func(ctx convey.C) {
var (
wcb = &model.WelfareCodeBatch{ID: 100000, BatchName: "utTest"}
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
err := d.WelfareBatchSave(wcb)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoWelfareBatchList(t *testing.T) {
convey.Convey("WelfareBatchList", t, func(ctx convey.C) {
var (
wid = int(100000)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
wbs, err := d.WelfareBatchList(wid)
ctx.Convey("Then err should be nil.wbs should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(wbs, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoWelfareBatchState(t *testing.T) {
convey.Convey("WelfareBatchState", t, func(ctx convey.C) {
var (
tx = d.BeginGormTran(context.Background())
id = int(100000)
state = int(1)
operId = int(0)
operName = "utTest"
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
err := d.WelfareBatchState(tx, id, state, operId, operName)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoWelfareCodeBatchInsert(t *testing.T) {
convey.Convey("WelfareCodeBatchInsert", t, func(ctx convey.C) {
var (
wcs = []*model.WelfareCode{}
wc = new(model.WelfareCode)
)
wc.Code = "utTest"
wc.Bid = 1000000
wc.Wid = 1000000
wcs = append(wcs, wc)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
err := d.WelfareCodeBatchInsert(wcs)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
d.delCode()
})
}
func (d *Dao) delCode() {
codeInfo := &model.WelfareCode{
Bid: 1000000,
Wid: 1000000,
Code: "utTest",
}
if err := d.vip.Where("bid = ? and wid =? and code = ?", codeInfo.Bid, codeInfo.Wid, codeInfo.Code).Delete(codeInfo).Error; err != nil {
log.Error("DelUser error(%v)", err)
}
}
func TestDaoWelfareCodeStatus(t *testing.T) {
convey.Convey("WelfareCodeStatus", t, func(ctx convey.C) {
var (
tx = d.BeginGormTran(context.Background())
bid = int(100000)
state = int(1)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
err := d.WelfareCodeStatus(tx, bid, state)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaogetBatchInsertSQL(t *testing.T) {
convey.Convey("getBatchInsertSQL", t, func(ctx convey.C) {
var (
buff = []*model.WelfareCode{}
)
buff = append(buff, new(model.WelfareCode))
ctx.Convey("When everything gose positive", func(ctx convey.C) {
stmt, valueArgs := getBatchInsertSQL(buff)
ctx.Convey("Then stmt,valueArgs should not be nil.", func(ctx convey.C) {
ctx.So(valueArgs, convey.ShouldNotBeNil)
ctx.So(stmt, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,54 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = [
"business.go",
"dialog.go",
"http.go",
"jointly.go",
"month.go",
"order.go",
"panel.go",
"platform.go",
"privilege.go",
"push.go",
"resouce.go",
"tips.go",
"version.go",
"vip.go",
"welfare.go",
],
importpath = "go-common/app/admin/main/vip/http",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/admin/main/vip/conf:go_default_library",
"//app/admin/main/vip/model:go_default_library",
"//app/admin/main/vip/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/binding:go_default_library",
"//library/net/http/blademaster/middleware/permit: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,83 @@
package http
import (
"go-common/app/admin/main/vip/model"
"go-common/library/ecode"
bm "go-common/library/net/http/blademaster"
)
const (
_defpn = 1
_defps = 10
)
func business(c *bm.Context) {
var (
err error
r *model.VipBusinessInfo
)
arg := new(model.ArgID)
if err = c.Bind(arg); err != nil {
return
}
if r, err = vipSvc.BusinessInfo(c, int(arg.ID)); err != nil {
c.JSON(nil, err)
return
}
c.JSON(r, nil)
}
func updateBusiness(c *bm.Context) {
var (
err error
arg = new(model.VipBusinessInfo)
)
if err = c.Bind(arg); err != nil {
return
}
if arg.ID == 0 {
c.JSON(nil, ecode.RequestErr)
return
}
c.JSON(nil, vipSvc.UpdateBusinessInfo(c, arg))
}
func addBusiness(c *bm.Context) {
var (
err error
arg = new(model.VipBusinessInfo)
)
if err = c.Bind(arg); err != nil {
return
}
c.JSON(nil, vipSvc.AddBusinessInfo(c, arg))
}
func businessList(c *bm.Context) {
var (
infos []*model.VipBusinessInfo
total int64
err error
arg = new(model.ArgPage)
)
if err = c.Bind(arg); err != nil {
return
}
if arg.Pn == 0 {
arg.Pn = _defpn
}
if arg.Ps == 0 {
arg.Ps = _defps
}
if infos, total, err = vipSvc.BusinessList(c, arg.Pn, arg.Ps, arg.Status); err != nil {
c.JSON(nil, err)
return
}
res := new(struct {
Data []*model.VipBusinessInfo `json:"data"`
Total int64 `json:"total"`
})
res.Data = infos
res.Total = total
c.JSON(res, nil)
}

View File

@@ -0,0 +1,74 @@
package http
import (
"go-common/app/admin/main/vip/model"
"go-common/library/ecode"
bm "go-common/library/net/http/blademaster"
)
func dialogList(c *bm.Context) {
arg := new(struct {
AppID int64 `form:"app_id"`
Platform int64 `form:"platform"`
Status string `form:"status"`
})
if err := c.Bind(arg); err != nil {
return
}
c.JSON(vipSvc.DialogAll(c, arg.AppID, arg.Platform, arg.Status))
}
func dialogInfo(c *bm.Context) {
arg := new(model.ArgID)
if err := c.Bind(arg); err != nil {
return
}
c.JSON(vipSvc.DialogByID(c, arg))
}
func dialogSave(c *bm.Context) {
arg := new(model.ConfDialog)
if err := c.Bind(arg); err != nil {
return
}
if arg.StartTime != 0 && arg.EndTime != 0 && arg.StartTime >= arg.EndTime {
c.JSON(nil, ecode.VipDialogTimeErr)
return
}
username, ok := c.Get("username")
if !ok {
c.JSON(nil, ecode.AccessDenied)
return
}
arg.Operator = username.(string)
c.JSON(vipSvc.DialogSave(c, arg))
}
func dialogEnable(c *bm.Context) {
arg := new(struct {
ID int64 `form:"id" validate:"required"`
Stage bool `form:"stage"`
})
if err := c.Bind(arg); err != nil {
return
}
username, ok := c.Get("username")
if !ok {
c.JSON(nil, ecode.AccessDenied)
return
}
c.JSON(vipSvc.DialogEnable(c, &model.ConfDialog{ID: arg.ID, Stage: arg.Stage, Operator: username.(string)}))
}
func dialogDel(c *bm.Context) {
arg := new(model.ArgID)
if err := c.Bind(arg); err != nil {
return
}
username, ok := c.Get("username")
if !ok {
c.JSON(nil, ecode.AccessDenied)
return
}
c.JSON(vipSvc.DialogDel(c, arg, username.(string)))
}

View File

@@ -0,0 +1,183 @@
package http
import (
"go-common/app/admin/main/vip/conf"
"go-common/app/admin/main/vip/service"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
"go-common/library/net/http/blademaster/middleware/permit"
)
var (
// depend service
vipSvc *service.Service
authSvc *permit.Permit
cf *conf.Config
)
//Init init http
func Init(c *conf.Config) {
cf = c
initService(c)
// init external router
engine := bm.DefaultServer(c.BM)
initRouter(engine)
// init Outer serve
if err := engine.Start(); err != nil {
log.Error("engine.Start error(%v)", err)
panic(err)
}
}
// initService init services.
func initService(c *conf.Config) {
vipSvc = service.New(c)
authSvc = permit.New(c.Auth)
}
// initRouter init outer router api path.
func initRouter(e *bm.Engine) {
e.Ping(moPing)
group := e.Group("/x/admin/vip", authSvc.Verify())
{
monthGroup := group.Group("/month", authSvc.Permit("VIP_MONTH"))
{
monthGroup.GET("/list", monthList)
monthGroup.POST("/edit", monthEdit)
monthGroup.GET("/price/list", priceList)
monthGroup.POST("/price/add", priceAdd)
monthGroup.POST("/price/edit", priceEdit)
}
poolGroup := group.Group("/pool", authSvc.Permit("VIP_POOL"))
{
poolGroup.GET("/list", queryPool)
poolGroup.GET("/info", getPool)
poolGroup.POST("/save", savePool)
batchGroup := poolGroup.Group("/batch")
{
batchGroup.GET("/list", queryBatch)
batchGroup.GET("/info", getBatch)
batchGroup.POST("/add", addBatch)
batchGroup.POST("/edit", saveBatch)
batchGroup.POST("/consume", grantResouce)
}
}
batchCodeGroup := group.Group("/batchCode", authSvc.Permit("VIP_BATCH_CODE"))
{
batchCodeGroup.GET("/list", batchCodes)
batchCodeGroup.POST("/save", saveBatchCode)
batchCodeGroup.POST("/frozen", frozenBatchCode)
batchCodeGroup.GET("/export", exportCodes)
codeGroup := batchCodeGroup.Group("/code")
{
codeGroup.GET("/list", codes)
codeGroup.POST("/frozen", frozenCode)
}
}
pushGroup := group.Group("/push", authSvc.Permit("VIP_PUSH"))
{
pushGroup.GET("/list", pushs)
pushGroup.POST("/save", savePush)
pushGroup.GET("/info", push)
pushGroup.GET("/del", delPush)
pushGroup.GET("/disable", disablePush)
}
vipGroup := group.Group("/user", authSvc.Permit("VIP_USER"))
{
vipGroup.POST("/drawback", drawback)
vipGroup.GET("/log/list", historyList)
vipGroup.GET("/info", vipInfo)
}
bizGroup := group.Group("/biz", authSvc.Permit("VIP_BIZ"))
{
bizGroup.GET("/list", businessList)
bizGroup.POST("/add", addBusiness)
bizGroup.GET("/info", business)
bizGroup.POST("/edit", updateBusiness)
}
verGroup := group.Group("/version", authSvc.Permit("VIP_VERSION"))
{
verGroup.GET("/list", versions)
verGroup.POST("/edit", updateVersion)
}
tipsGroup := group.Group("/tips", authSvc.Permit("VIP_TIPS"))
{
tipsGroup.GET("/list", tips)
tipsGroup.GET("/info", tipbyid)
tipsGroup.POST("/add", tipadd)
tipsGroup.POST("/edit", tipupdate)
tipsGroup.GET("/delete", tipdelete)
tipsGroup.POST("/expire", tipexpire)
}
panelGroup := group.Group("/panel")
{
panelGroup.GET("/conf/types", authSvc.Permit("VIP_PRICE_PANEL"), vipPanelTypes)
panelGroup.GET("/conf/list", authSvc.Permit("VIP_PRICE_PANEL"), vipPriceConfigs)
panelGroup.GET("/conf/info", authSvc.Permit("VIP_PRICE_PANEL"), vipPriceConfigID)
panelGroup.POST("/conf/add", authSvc.Permit("VIP_PRICE_PANEL_CONTROL"), addVipPriceConfig)
panelGroup.POST("/conf/up", authSvc.Permit("VIP_PRICE_PANEL_CONTROL"), upVipPriceConfig)
panelGroup.POST("/conf/del", authSvc.Permit("VIP_PRICE_PANEL_CONTROL"), delVipPriceConfig)
panelGroup.GET("/conf/dprice/list", authSvc.Permit("VIP_PRICE_PANEL"), vipDPriceConfigs)
panelGroup.GET("/conf/dprice/info", authSvc.Permit("VIP_PRICE_PANEL"), vipDPriceConfigID)
panelGroup.POST("/conf/dprice/add", authSvc.Permit("VIP_PRICE_PANEL_CONTROL"), addVipDPriceConfig)
panelGroup.POST("/conf/dprice/up", authSvc.Permit("VIP_PRICE_PANEL_CONTROL"), upVipDPriceConfig)
panelGroup.POST("/conf/dprice/del", authSvc.Permit("VIP_PRICE_PANEL_CONTROL"), delVipDPriceConfig)
}
pgGroup := group.Group("/privilege", authSvc.Permit("VIP_PRIVILEGE"))
{
pgGroup.GET("/list", privileges)
pgGroup.POST("/update/state", updatePrivilegeState)
pgGroup.POST("/delete", deletePrivilege)
pgGroup.POST("/update/order", updateOrder)
pgGroup.POST("/add", addPrivilege)
pgGroup.POST("/modify", updatePrivilege)
}
jointlyGroup := group.Group("/jointly", authSvc.Permit("VIP_JOINTLY"))
{
jointlyGroup.GET("/list", jointlys)
jointlyGroup.POST("/add", addJointly)
jointlyGroup.POST("/modify", modifyJointly)
jointlyGroup.POST("/delete", deleteJointly)
}
refundGroup := group.Group("/order", authSvc.Permit("VIP_ORDER"))
{
refundGroup.GET("/list", orderList)
refundGroup.POST("/refund", authSvc.Permit("VIP_REFUND"), refund)
}
dialogGroup := group.Group("/dialog", authSvc.Permit("VIP_DIALOG"))
{
dialogGroup.GET("/list", dialogList)
dialogGroup.GET("/info", dialogInfo)
dialogGroup.POST("/save", dialogSave)
dialogGroup.POST("/enable", dialogEnable)
dialogGroup.POST("/del", dialogDel)
}
platformGroup := group.Group("/platform", authSvc.Permit("VIP_PLATFORM"))
{
platformGroup.GET("/list", platformList)
platformGroup.GET("/info", platformInfo)
platformGroup.POST("/save", platformSave)
platformGroup.POST("/del", platformDel)
}
welfareGroup := group.Group("/welfare", authSvc.Permit("VIP_WELFARE"))
{
welfareGroup.POST("/type/save", welfareTypeSave)
welfareGroup.POST("/type/state", welfareTypeState)
welfareGroup.GET("/type/list", welfareTypeList)
welfareGroup.POST("/save", welfareSave)
welfareGroup.POST("/state", welfareState)
welfareGroup.GET("/list", welfareList)
welfareGroup.POST("/batch/upload", welfareBatchUpload)
welfareGroup.GET("/batch/list", welfareBatchList)
welfareGroup.POST("/batch/state", welfareBatchState)
}
}
}
func moPing(c *bm.Context) {
vipSvc.Ping(c)
}

View File

@@ -0,0 +1,51 @@
package http
import (
"go-common/app/admin/main/vip/model"
"go-common/library/ecode"
bm "go-common/library/net/http/blademaster"
)
func jointlys(c *bm.Context) {
arg := new(model.ArgQueryJointly)
if err := c.Bind(arg); err != nil {
return
}
c.JSON(vipSvc.JointlysByState(c, arg.State))
}
func addJointly(c *bm.Context) {
arg := new(model.ArgAddJointly)
if err := c.Bind(arg); err != nil {
return
}
username, ok := c.Get("username")
if !ok {
c.JSON(nil, ecode.AccessDenied)
return
}
arg.Operator = username.(string)
c.JSON(nil, vipSvc.AddJointly(c, arg))
}
func modifyJointly(c *bm.Context) {
arg := new(model.ArgModifyJointly)
if err := c.Bind(arg); err != nil {
return
}
username, ok := c.Get("username")
if !ok {
c.JSON(nil, ecode.AccessDenied)
return
}
arg.Operator = username.(string)
c.JSON(nil, vipSvc.ModifyJointly(c, arg))
}
func deleteJointly(c *bm.Context) {
arg := new(model.ArgJointlyID)
if err := c.Bind(arg); err != nil {
return
}
c.JSON(nil, vipSvc.DeleteJointly(c, arg.ID))
}

View File

@@ -0,0 +1,92 @@
package http
import (
"go-common/app/admin/main/vip/model"
"go-common/library/ecode"
bm "go-common/library/net/http/blademaster"
)
func monthList(c *bm.Context) {
var (
res []*model.VipMonth
err error
)
if res, err = vipSvc.MonthList(c); err != nil {
c.JSON(nil, err)
return
}
page := &model.PageInfo{Count: len(res), Item: res}
c.JSON(page, nil)
}
func monthEdit(c *bm.Context) {
var (
err error
arg = new(model.ArgIDExtra)
)
username, ok := c.Get("username")
if !ok {
c.JSON(nil, ecode.AccessDenied)
return
}
if err = c.Bind(arg); err != nil {
return
}
arg.Operator = username.(string)
c.JSON(nil, vipSvc.MonthEdit(c, arg.ID, arg.Status, arg.Operator))
}
func priceList(c *bm.Context) {
var (
res []*model.VipMonthPrice
err error
arg = new(model.ArgID)
)
if err = c.Bind(arg); err != nil {
return
}
if res, err = vipSvc.PriceList(c, arg.ID); err != nil {
c.JSON(nil, err)
return
}
page := &model.PageInfo{Count: len(res), Item: res}
c.JSON(page, nil)
}
func priceAdd(c *bm.Context) {
var (
err error
mp = new(model.VipMonthPrice)
)
username, ok := c.Get("username")
if !ok {
c.JSON(nil, ecode.AccessDenied)
return
}
mp.Operator = username.(string)
if err = c.Bind(mp); err != nil {
return
}
c.JSON(nil, vipSvc.PriceAdd(c, mp))
}
func priceEdit(c *bm.Context) {
var (
err error
mp = new(model.VipMonthPrice)
)
username, ok := c.Get("username")
if !ok {
c.JSON(nil, ecode.AccessDenied)
return
}
mp.Operator = username.(string)
if err = c.Bind(mp); err != nil {
return
}
if mp.ID <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
c.JSON(nil, vipSvc.PriceEdit(c, mp))
}

View File

@@ -0,0 +1,36 @@
package http
import (
"go-common/app/admin/main/vip/model"
"go-common/library/ecode"
bm "go-common/library/net/http/blademaster"
)
func orderList(c *bm.Context) {
arg := new(model.ArgPayOrder)
if err := c.Bind(arg); err != nil {
return
}
res, count, err := vipSvc.OrderList(c, arg)
info := new(model.PageInfo)
info.Count = int(count)
info.Item = res
info.CurrentPage = arg.PN
c.JSON(info, err)
}
func refund(c *bm.Context) {
arg := new(struct {
OrderNo string `form:"order_no" validate:"required"`
RefundAmount float64 `form:"refund_amount" validate:"required"`
})
username, ok := c.Get("username")
if !ok {
c.JSON(nil, ecode.AccessDenied)
return
}
if err := c.Bind(arg); err != nil {
return
}
c.JSON(nil, vipSvc.Refund(c, arg.OrderNo, username.(string), arg.RefundAmount))
}

View File

@@ -0,0 +1,95 @@
package http
import (
"go-common/app/admin/main/vip/model"
"go-common/library/ecode"
bm "go-common/library/net/http/blademaster"
)
func vipPriceConfigs(c *bm.Context) {
arg := new(model.ArgVipPrice)
if err := c.Bind(arg); err != nil {
return
}
c.JSON(vipSvc.VipPriceConfigs(c, arg))
}
func vipPriceConfigID(c *bm.Context) {
arg := new(model.ArgVipPriceID)
if err := c.Bind(arg); err != nil {
return
}
c.JSON(vipSvc.VipPriceConfigID(c, arg))
}
func addVipPriceConfig(c *bm.Context) {
arg := new(model.ArgAddOrUpVipPrice)
if err := c.Bind(arg); err != nil {
return
}
c.JSON(nil, vipSvc.AddVipPriceConfig(c, arg))
}
func upVipPriceConfig(c *bm.Context) {
arg := new(model.ArgAddOrUpVipPrice)
if err := c.Bind(arg); err != nil {
return
}
if arg.ID == 0 {
c.JSON(nil, ecode.RequestErr)
return
}
c.JSON(nil, vipSvc.UpVipPriceConfig(c, arg))
}
func delVipPriceConfig(c *bm.Context) {
arg := new(model.ArgVipPriceID)
if err := c.Bind(arg); err != nil {
return
}
c.JSON(nil, vipSvc.DelVipPriceConfig(c, arg))
}
func vipDPriceConfigs(c *bm.Context) {
arg := new(model.ArgVipPriceID)
if err := c.Bind(arg); err != nil {
return
}
c.JSON(vipSvc.VipDPriceConfigs(c, arg))
}
func vipDPriceConfigID(c *bm.Context) {
arg := new(model.ArgVipDPriceID)
if err := c.Bind(arg); err != nil {
return
}
c.JSON(vipSvc.VipDPriceConfigID(c, arg))
}
func addVipDPriceConfig(c *bm.Context) {
arg := new(model.ArgAddOrUpVipDPrice)
if err := c.Bind(arg); err != nil {
return
}
c.JSON(nil, vipSvc.AddVipDPriceConfig(c, arg))
}
func upVipDPriceConfig(c *bm.Context) {
arg := new(model.ArgAddOrUpVipDPrice)
if err := c.Bind(arg); err != nil {
return
}
c.JSON(nil, vipSvc.UpVipDPriceConfig(c, arg))
}
func delVipDPriceConfig(c *bm.Context) {
arg := new(model.ArgVipDPriceID)
if err := c.Bind(arg); err != nil {
return
}
c.JSON(nil, vipSvc.DelVipDPriceConfig(c, arg))
}
func vipPanelTypes(c *bm.Context) {
c.JSON(vipSvc.PanelPlatFormTypes(c))
}

View File

@@ -0,0 +1,59 @@
package http
import (
"go-common/app/admin/main/vip/model"
"go-common/library/ecode"
bm "go-common/library/net/http/blademaster"
)
func platformList(c *bm.Context) {
arg := new(struct {
Order string `form:"order" default:"desc"`
// PN int `form:"pn" default:"1"`
// PS int `form:"ps" default:"20"`
})
if err := c.Bind(arg); err != nil {
return
}
c.JSON(vipSvc.PlatformAll(c, arg.Order))
}
func platformInfo(c *bm.Context) {
arg := new(model.ArgID)
if err := c.Bind(arg); err != nil {
return
}
c.JSON(vipSvc.PlatformByID(c, arg))
}
func platformSave(c *bm.Context) {
arg := new(model.ConfPlatform)
if err := c.Bind(arg); err != nil {
return
}
username, ok := c.Get("username")
if !ok {
c.JSON(nil, ecode.AccessDenied)
return
}
// platform必填可选项为android、ios、web、public
if _, ok := model.PlatformMap[arg.Platform]; !ok {
c.JSON(nil, ecode.RequestErr)
return
}
arg.Operator = username.(string)
c.JSON(vipSvc.PlatformSave(c, arg))
}
func platformDel(c *bm.Context) {
arg := new(model.ArgID)
if err := c.Bind(arg); err != nil {
return
}
username, ok := c.Get("username")
if !ok {
c.JSON(nil, ecode.AccessDenied)
return
}
c.JSON(vipSvc.PlatformDel(c, arg, username.(string)))
}

View File

@@ -0,0 +1,234 @@
package http
import (
"io/ioutil"
"mime/multipart"
"net/http"
"regexp"
"strings"
"go-common/app/admin/main/vip/model"
"go-common/library/ecode"
bm "go-common/library/net/http/blademaster"
"go-common/library/net/http/blademaster/binding"
)
const (
_maxnamelen = 30
_maxtitlelen = 60
_maxexplainlen = 1200
)
// regexp utf8 char 0x0e0d~0e4A
var (
_emptyUnicodeReg = []*regexp.Regexp{
regexp.MustCompile(`[\x{202e}]+`), // right-to-left override
regexp.MustCompile(`[\x{200b}]+`), // zeroWithChar
regexp.MustCompile(`[\x{1f6ab}]+`), // no_entry_sign
}
// trim
returnReg = regexp.MustCompile(`[\n]{3,}`)
returnReg2 = regexp.MustCompile(`(\r\n){3,}`)
spaceReg = regexp.MustCompile(`[ ]{5,}`) // Chinese quanjiao space character
)
func privileges(c *bm.Context) {
var err error
arg := new(struct {
Langtype int8 `form:"lang_type"`
})
if err = c.Bind(arg); err != nil {
return
}
c.JSON(vipSvc.Privileges(c, arg.Langtype))
}
func updatePrivilegeState(c *bm.Context) {
var err error
arg := new(model.ArgStatePrivilege)
if err = c.Bind(arg); err != nil {
return
}
c.JSON(nil, vipSvc.UpdatePrivilegeState(c, &model.Privilege{
ID: arg.ID,
State: arg.Status,
}))
}
func deletePrivilege(c *bm.Context) {
var err error
arg := new(model.ArgPivilegeID)
if err = c.Bind(arg); err != nil {
return
}
c.JSON(nil, vipSvc.DeletePrivilege(c, arg.ID))
}
func updateOrder(c *bm.Context) {
var err error
arg := new(model.ArgOrder)
if err = c.Bind(arg); err != nil {
return
}
c.JSON(nil, vipSvc.UpdateOrder(c, arg))
}
func addPrivilege(c *bm.Context) {
var err error
arg := new(model.ArgAddPrivilege)
username, ok := c.Get("username")
if !ok {
c.JSON(nil, ecode.AccessDenied)
return
}
arg.Operator = username.(string)
if err = c.BindWith(arg, binding.FormMultipart); err != nil {
return
}
if len(arg.Name) > _maxnamelen {
c.JSON(nil, ecode.VipPrivilegeNameTooLongErr)
return
}
if len(arg.Title) > _maxtitlelen {
c.JSON(nil, ecode.VipPrivilegeTitleTooLongErr)
return
}
if len(arg.Explain) > _maxexplainlen {
c.JSON(nil, ecode.VipPrivilegeExplainTooLongErr)
return
}
img := new(model.ArgImage)
if img.IconBody, img.IconFileType, err = file(c, "icon"); err != nil {
c.JSON(nil, err)
return
}
if img.IconFileType == "" {
c.JSON(nil, ecode.VipFileImgEmptyErr)
return
}
if img.IconGrayBody, img.IconGrayFileType, err = file(c, "gray_icon"); err != nil {
c.JSON(nil, err)
return
}
if img.IconGrayFileType == "" {
c.JSON(nil, ecode.VipFileImgEmptyErr)
return
}
if img.WebImageBody, img.WebImageFileType, err = file(c, "web_image"); err != nil {
c.JSON(nil, err)
return
}
if img.AppImageBody, img.AppImageFileType, err = file(c, "app_image"); err != nil {
c.JSON(nil, err)
return
}
arg.Explain = filterContent(arg.Explain)
c.JSON(nil, vipSvc.AddPrivilege(c, arg, img))
}
func updatePrivilege(c *bm.Context) {
var (
err error
)
arg := new(model.ArgUpdatePrivilege)
username, ok := c.Get("username")
if !ok {
c.JSON(nil, ecode.AccessDenied)
return
}
arg.Operator = username.(string)
if err = c.BindWith(arg, binding.FormMultipart); err != nil {
return
}
if len(arg.Name) > _maxnamelen {
c.JSON(nil, ecode.VipPrivilegeNameTooLongErr)
return
}
if len(arg.Title) > _maxtitlelen {
c.JSON(nil, ecode.VipPrivilegeTitleTooLongErr)
return
}
if len(arg.Explain) > _maxexplainlen {
c.JSON(nil, ecode.VipPrivilegeExplainTooLongErr)
return
}
img := new(model.ArgImage)
if img.IconBody, img.IconFileType, err = file(c, "icon"); err != nil {
c.JSON(nil, err)
return
}
if img.IconGrayBody, img.IconGrayFileType, err = file(c, "gray_icon"); err != nil {
c.JSON(nil, err)
return
}
if img.WebImageBody, img.WebImageFileType, err = file(c, "web_image"); err != nil {
c.JSON(nil, err)
return
}
if img.AppImageBody, img.AppImageFileType, err = file(c, "app_image"); err != nil {
c.JSON(nil, err)
return
}
arg.Explain = filterContent(arg.Explain)
c.JSON(nil, vipSvc.UpdatePrivilege(c, arg, img))
}
func file(c *bm.Context, name string) (body []byte, filetype string, err error) {
var file multipart.File
if file, _, err = c.Request.FormFile(name); err != nil {
if err == http.ErrMissingFile {
err = nil
return
}
err = ecode.RequestErr
return
}
if file == nil {
return
}
defer file.Close()
if body, err = ioutil.ReadAll(file); err != nil {
err = ecode.RequestErr
return
}
filetype = http.DetectContentType(body)
if err = checkImgFileType(filetype); err != nil {
return
}
err = checkFileBody(body)
return
}
func checkImgFileType(filetype string) error {
switch filetype {
case "image/jpeg", "image/jpg":
case "image/png":
default:
return ecode.VipFileTypeErr
}
return nil
}
func checkFileBody(body []byte) error {
if len(body) == 0 {
return ecode.FileNotExists
}
if len(body) > cf.Bfs.MaxFileSize {
return ecode.FileTooLarge
}
return nil
}
func filterContent(str string) string {
tmp := str
// check params
tmp = strings.TrimSpace(tmp)
tmp = spaceReg.ReplaceAllString(tmp, "   ")
tmp = returnReg.ReplaceAllString(tmp, "\n\n\n")
tmp = returnReg2.ReplaceAllString(tmp, "\n\n\n")
// checkout empty
for _, reg := range _emptyUnicodeReg {
tmp = reg.ReplaceAllString(tmp, "")
}
return tmp
}

View File

@@ -0,0 +1,65 @@
package http
import (
"go-common/app/admin/main/vip/model"
"go-common/library/ecode"
bm "go-common/library/net/http/blademaster"
)
func pushs(c *bm.Context) {
arg := new(model.ArgPushData)
if err := c.Bind(arg); err != nil {
return
}
res, count, err := vipSvc.PushDatas(c, arg)
result := make(map[string]interface{})
result["data"] = res
result["total"] = count
c.JSON(result, err)
}
func push(c *bm.Context) {
arg := new(model.ArgID)
if err := c.Bind(arg); err != nil {
return
}
c.JSON(vipSvc.GetPushData(c, arg.ID))
}
func disablePush(c *bm.Context) {
arg := new(model.ArgID)
if err := c.Bind(arg); err != nil {
return
}
c.JSON(nil, vipSvc.DisablePushData(c, arg.ID))
}
func delPush(c *bm.Context) {
arg := new(model.ArgID)
if err := c.Bind(arg); err != nil {
return
}
c.JSON(nil, vipSvc.DelPushData(c, arg.ID))
}
func savePush(c *bm.Context) {
arg := new(model.VipPushData)
username, ok := c.Get("username")
if !ok {
c.JSON(nil, ecode.AccessDenied)
return
}
if err := c.Bind(arg); err != nil {
return
}
arg.Operator = username.(string)
c.JSON(nil, vipSvc.SavePushData(c, arg))
}

View File

@@ -0,0 +1,331 @@
package http
import (
"bufio"
"fmt"
"io"
"mime/multipart"
"net/http"
"strconv"
"go-common/app/admin/main/vip/model"
"go-common/library/ecode"
bm "go-common/library/net/http/blademaster"
)
func queryPool(c *bm.Context) {
var (
arg = new(model.ResoucePoolBo)
pools []*model.VipResourcePool
count int
err error
)
if err = c.Bind(arg); err != nil {
return
}
if pools, count, err = vipSvc.QueryPool(c, arg); err != nil {
c.JSON(nil, err)
return
}
for _, v := range pools {
var business *model.VipBusinessInfo
if business, err = vipSvc.BusinessInfo(c, v.BusinessID); err != nil {
return
}
v.BusinessName = business.BusinessName
}
dataMap := make(map[string]interface{})
dataMap["item"] = pools
dataMap["count"] = count
c.JSONMap(dataMap, nil)
}
func getPool(c *bm.Context) {
var (
err error
arg = new(model.ArgID)
pool *model.VipResourcePool
business *model.VipBusinessInfo
)
if err = c.Bind(arg); err != nil {
return
}
if pool, err = vipSvc.PoolInfo(c, int(arg.ID)); err != nil {
c.JSON(nil, err)
return
}
if pool == nil {
c.JSON(pool, nil)
return
}
if business, err = vipSvc.BusinessInfo(c, pool.BusinessID); err != nil {
return
}
if business != nil {
pool.BusinessName = business.BusinessName
}
c.JSON(pool, nil)
}
func savePool(c *bm.Context) {
arg := new(model.ResoucePoolBo)
if err := c.Bind(arg); err != nil {
return
}
if arg.ID == 0 {
c.JSON(nil, vipSvc.AddPool(c, arg))
return
}
c.JSON(nil, vipSvc.UpdatePool(c, arg))
}
func getBatch(c *bm.Context) {
var (
err error
arg = new(model.ArgID)
batch *model.VipResourceBatch
pool *model.VipResourcePool
)
if err = c.Bind(arg); err != nil {
return
}
if batch, err = vipSvc.BatchInfo(c, int(arg.ID)); err != nil {
c.JSON(nil, err)
return
}
if batch == nil {
c.JSON(nil, nil)
return
}
if pool, err = vipSvc.PoolInfo(c, batch.PoolID); err != nil {
c.JSON(nil, err)
return
}
if pool == nil {
c.JSON(nil, ecode.VipPoolIDErr)
return
}
vo := new(model.ResouceBatchVo)
vo.Unit = batch.Unit
vo.ID = batch.ID
vo.PoolName = pool.PoolName
vo.SurplusCount = batch.SurplusCount
vo.PoolID = batch.PoolID
vo.Count = batch.Count
vo.StartTime = batch.StartTime
vo.EndTime = batch.EndTime
vo.DirectUseCount = batch.DirectUseCount
vo.Ver = batch.Ver
vo.CodeUseCount = batch.CodeUseCount
c.JSON(vo, nil)
}
func queryBatch(c *bm.Context) {
var (
err error
arg = new(model.ArgPoolID)
)
if err = c.Bind(arg); err != nil {
return
}
c.JSON(vipSvc.BatchInfoOfPool(c, arg.PoolID))
}
func addBatch(c *bm.Context) {
var arg = new(model.ResouceBatchBo)
if err := c.Bind(arg); err != nil {
return
}
c.JSON(nil, vipSvc.AddBatch(c, arg))
}
func saveBatch(c *bm.Context) {
var arg = new(model.ArgReSource)
if err := c.Bind(arg); err != nil {
return
}
c.JSON(nil, vipSvc.UpdateBatch(c, arg.ID, arg.Increment, arg.StartTime, arg.EndTime))
}
func grantResouce(c *bm.Context) {
var (
req = c.Request
mids []int
username string
file multipart.File
err error
failMids []int
uc *http.Cookie
)
if file, _, err = req.FormFile("uploadFile"); err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
r := bufio.NewReader(file)
for {
var buf []byte
buf, _, err = r.ReadLine()
if err == io.EOF {
break
}
midStr := string(buf)
if len(midStr) > 0 && midStr != "0" {
mid := 0
if mid, err = strconv.Atoi(midStr); err != nil {
c.JSON(nil, ecode.RequestErr)
return
} else if err == nil {
mids = append(mids, mid)
}
}
}
if uc, err = c.Request.Cookie("username"); err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
username = uc.Value
arg := new(struct {
Mid int `form:"mid"`
BatchID int64 `form:"batch_id" validate:"required"`
Remark string `form:"remark" validate:"required"`
})
if err = c.Bind(arg); err != nil {
return
}
if arg.Mid > 0 {
mids = append(mids, arg.Mid)
}
if failMids, err = vipSvc.GrandResouce(c, arg.Remark, arg.BatchID, mids, username); err != nil {
c.JSON(nil, err)
return
}
c.JSON(failMids, nil)
}
func saveBatchCode(c *bm.Context) {
arg := new(model.BatchCode)
if err := c.Bind(arg); err != nil {
return
}
username, exists := c.Get("username")
if exists {
arg.Operator = username.(string)
}
c.JSON(nil, vipSvc.SaveBatchCode(c, arg))
}
func batchCodes(c *bm.Context) {
arg := new(model.ArgBatchCode)
if err := c.Bind(arg); err != nil {
return
}
pageArg := new(struct {
PN int `form:"pn"`
PS int `form:"ps"`
})
if err := c.Bind(pageArg); err != nil {
return
}
res, total, err := vipSvc.SelBatchCode(c, arg, pageArg.PN, pageArg.PS)
result := make(map[string]interface{})
result["data"] = res
result["total"] = total
c.JSON(result, err)
}
func frozenCode(c *bm.Context) {
arg := new(struct {
ID int64 `form:"id" validate:"required"`
Status int8 `form:"status" validate:"required"`
})
if err := c.Bind(arg); err != nil {
return
}
c.JSON(nil, vipSvc.FrozenCode(c, arg.ID, arg.Status))
}
func frozenBatchCode(c *bm.Context) {
arg := new(struct {
ID int64 `form:"id" validate:"required"`
Status int8 `form:"status" validate:"required"`
})
if err := c.Bind(arg); err != nil {
return
}
c.JSON(nil, vipSvc.FrozenBatchCode(c, arg.ID, arg.Status))
}
func codes(c *bm.Context) {
arg := new(model.ArgCode)
if err := c.Bind(arg); err != nil {
return
}
pageArg := new(struct {
PS int `form:"ps"`
Cursor int64 `form:"cursor"`
Username string `form:"username"`
})
if err := c.Bind(pageArg); err != nil {
return
}
username, exists := c.Get("username")
if exists {
pageArg.Username = username.(string)
}
res, cursor, pre, err := vipSvc.SelCode(c, arg, pageArg.Username, pageArg.Cursor, pageArg.PS)
result := make(map[string]interface{})
result["data"] = res
result["cursor"] = cursor
result["pre"] = pre
c.JSON(result, err)
}
func exportCodes(c *bm.Context) {
var (
batchCodes []*model.BatchCode
err error
codes []string
)
arg := new(struct {
ID int64 `form:"id" validate:"required"`
})
if err = c.Bind(arg); err != nil {
return
}
batchIds := []int64{arg.ID}
if batchCodes, err = vipSvc.SelBatchCodes(c, batchIds); err != nil {
c.JSON(nil, err)
return
}
if len(batchCodes) == 0 {
c.JSON(nil, ecode.VipBatchIDErr)
return
}
if codes, err = vipSvc.ExportCode(c, arg.ID); err != nil {
c.JSON(nil, err)
return
}
writer := c.Writer
header := writer.Header()
header.Add("Content-disposition", "attachment; filename="+fmt.Sprintf("%v", batchCodes[0].BatchName)+".txt")
header.Add("Content-Type", "application/x-download;charset=utf-8")
for _, v := range codes {
writer.Write([]byte(fmt.Sprintf("%v\r\n", v)))
}
}

View File

@@ -0,0 +1,150 @@
package http
import (
"go-common/app/admin/main/vip/model"
"go-common/library/ecode"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
)
// tips info.
func tips(c *bm.Context) {
var (
res []*model.Tips
err error
)
arg := new(struct {
State int8 `form:"state"`
Platform int8 `form:"platform"`
Position int8 `form:"position"`
})
if err = c.Bind(arg); err != nil {
log.Error("c.Bind err(%+v)", err)
return
}
if res, err = vipSvc.TipList(c, arg.Platform, arg.State, arg.Position); err != nil {
log.Error("vipSvc.TipList(%+v) err(%+v)", arg, err)
c.JSON(nil, err)
return
}
c.JSON(res, nil)
}
// tips info.
func tipbyid(c *bm.Context) {
var (
res *model.Tips
err error
)
arg := new(struct {
ID int64 `form:"id" validate:"required,min=1,gte=1"`
})
if err = c.Bind(arg); err != nil {
log.Error("c.Bind err(%+v)", err)
return
}
if res, err = vipSvc.TipByID(c, arg.ID); err != nil {
log.Error("vipSvc.TipByID(%d) err(%+v)", arg.ID, err)
c.JSON(nil, err)
return
}
c.JSON(res, nil)
}
// tips add.
func tipadd(c *bm.Context) {
var (
err error
arg = new(model.Tips)
)
if err = c.Bind(arg); err != nil {
log.Error("c.Bind err(%+v)", err)
return
}
opI, ok := c.Get("username")
if !ok {
c.JSON(nil, ecode.AccessDenied)
return
}
arg.Operator = opI.(string)
if err = vipSvc.AddTip(c, arg); err != nil {
log.Error("vipSvc.AddTip(%v) err(%+v)", arg, err)
c.JSON(nil, err)
return
}
c.JSON(nil, nil)
}
// tips update.
func tipupdate(c *bm.Context) {
var (
err error
arg = new(model.Tips)
)
if err = c.Bind(arg); err != nil {
log.Error("c.Bind err(%+v)", err)
return
}
opI, ok := c.Get("username")
if !ok {
c.JSON(nil, ecode.AccessDenied)
return
}
arg.Operator = opI.(string)
if err = vipSvc.TipUpdate(c, arg); err != nil {
log.Error("vipSvc.TipUpdate(%v) err(%+v)", arg, err)
c.JSON(nil, err)
return
}
c.JSON(nil, nil)
}
// tips delete.
func tipdelete(c *bm.Context) {
var (
err error
)
arg := new(struct {
ID int64 `form:"id" validate:"required,min=1,gte=1"`
})
if err = c.Bind(arg); err != nil {
log.Error("c.Bind err(%+v)", err)
return
}
opI, ok := c.Get("username")
if !ok {
c.JSON(nil, ecode.AccessDenied)
return
}
if err = vipSvc.DeleteTip(c, arg.ID, opI.(string)); err != nil {
log.Error("vipSvc.DeleteTip(%d) err(%+v)", arg.ID, err)
c.JSON(nil, err)
return
}
c.JSON(nil, nil)
}
// tips expire.
func tipexpire(c *bm.Context) {
var (
err error
)
arg := new(struct {
ID int64 `form:"id" validate:"required,min=1,gte=1"`
})
if err = c.Bind(arg); err != nil {
log.Error("c.Bind err(%+v)", err)
return
}
opI, ok := c.Get("username")
if !ok {
c.JSON(nil, ecode.AccessDenied)
return
}
if err = vipSvc.ExpireTip(c, arg.ID, opI.(string)); err != nil {
log.Error("vipSvc.ExpireTip(%d) err(%+v)", arg.ID, err)
c.JSON(nil, err)
return
}
c.JSON(nil, nil)
}

View File

@@ -0,0 +1,50 @@
package http
import (
"go-common/app/admin/main/vip/model"
"go-common/library/ecode"
bm "go-common/library/net/http/blademaster"
)
func updateVersion(c *bm.Context) {
var (
err error
)
arg := new(struct {
ID int64 `form:"id" validate:"required"`
Version string `form:"version" `
Tip string `form:"tip"`
Link string `form:"link"`
})
if err = c.Bind(arg); err != nil {
return
}
operator, ok := c.Get("username")
if !ok {
c.JSON(nil, ecode.AccessDenied)
return
}
if err = vipSvc.UpdateVersion(c, &model.VipAppVersion{
ID: arg.ID,
Version: arg.Version,
Tip: arg.Tip,
Operator: operator.(string),
Link: arg.Link,
}); err != nil {
c.JSON(nil, err)
return
}
c.JSON(nil, nil)
}
func versions(c *bm.Context) {
var (
res []*model.VipAppVersion
err error
)
if res, err = vipSvc.AllVersion(c); err != nil {
c.JSON(nil, err)
return
}
c.JSON(res, nil)
}

View File

@@ -0,0 +1,67 @@
package http
import (
"strconv"
"go-common/app/admin/main/vip/model"
"go-common/library/ecode"
bm "go-common/library/net/http/blademaster"
)
func drawback(c *bm.Context) {
var (
mid int64
params = c.Request.Form
err error
remark = params.Get("remark")
username string
days int
)
if nameInter, ok := c.Get("username"); ok {
username = nameInter.(string)
}
midStr := params.Get("mid")
if mid, err = strconv.ParseInt(midStr, 10, 64); err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
daysStr := params.Get("days")
if days, err = strconv.Atoi(daysStr); err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
if err = vipSvc.Drawback(c, days, mid, username, remark); err != nil {
c.JSON(nil, err)
return
}
c.JSON(nil, nil)
}
func historyList(c *bm.Context) {
var (
err error
count int
res []*model.VipChangeHistory
req = new(model.UserChangeHistoryReq)
)
if err = c.Bind(req); err != nil {
return
}
if res, count, err = vipSvc.HistoryPage(c, req); err != nil {
c.JSON(nil, err)
return
}
page := &model.PageInfo{Count: count, Item: res}
c.JSON(page, nil)
}
func vipInfo(c *bm.Context) {
arg := new(struct {
Mid int64 `form:"mid"`
})
if err := c.Bind(arg); err != nil {
return
}
c.JSON(vipSvc.VipInfo(c, arg.Mid))
}

View File

@@ -0,0 +1,147 @@
package http
import (
"io/ioutil"
"mime/multipart"
"net/http"
"go-common/app/admin/main/vip/model"
"go-common/library/ecode"
bm "go-common/library/net/http/blademaster"
)
const (
_maxFileSize = 1048576
)
func welfareTypeSave(c *bm.Context) {
arg := new(struct {
ID int `form:"id"`
Name string `form:"name" validate:"required"`
})
if err := c.Bind(arg); err != nil {
return
}
username, _ := c.Get("username")
c.JSON(nil, vipSvc.WelfareTypeSave(arg.ID, arg.Name, username.(string)))
}
func welfareTypeState(c *bm.Context) {
arg := new(struct {
ID int `form:"id" validate:"required"`
})
if err := c.Bind(arg); err != nil {
return
}
username, _ := c.Get("username")
c.JSON(nil, vipSvc.WelfareTypeState(c, arg.ID, username.(string)))
}
func welfareTypeList(c *bm.Context) {
c.JSON(vipSvc.WelfareTypeList())
}
func welfareSave(c *bm.Context) {
const _redirectThridPage = 3
wfReq := new(model.WelfareReq)
if err := c.Bind(wfReq); err != nil {
return
}
if wfReq.UsageForm == _redirectThridPage && wfReq.ReceiveUri == "" {
c.JSON(nil, ecode.VipWelfareRequestErr)
return
}
username, _ := c.Get("username")
c.JSON(nil, vipSvc.WelfareSave(username.(string), wfReq))
}
func welfareState(c *bm.Context) {
arg := new(struct {
ID int `form:"id" validate:"required"`
})
if err := c.Bind(arg); err != nil {
return
}
username, _ := c.Get("username")
c.JSON(nil, vipSvc.WelfareState(arg.ID, username.(string)))
}
func welfareList(c *bm.Context) {
arg := new(struct {
TID int `form:"tid"`
})
if err := c.Bind(arg); err != nil {
return
}
c.JSON(vipSvc.WelfareList(arg.TID))
}
func welfareBatchUpload(c *bm.Context) {
arg := new(struct {
WID int `form:"wid"`
Filename string `form:"filename"`
Vtime int `form:"vtime"`
})
if err := c.Bind(arg); err != nil {
return
}
fileBody, _, err := getFileBody(c, "file")
if err != nil {
c.JSON(nil, err)
return
}
username, _ := c.Get("username")
c.JSON(nil, vipSvc.WelfareBatchUpload(fileBody, arg.Filename, username.(string), arg.WID, arg.Vtime))
}
func welfareBatchList(c *bm.Context) {
arg := new(struct {
WID int `form:"wid" validate:"required"`
})
if err := c.Bind(arg); err != nil {
return
}
c.JSON(vipSvc.WelfareBatchList(arg.WID))
}
func welfareBatchState(c *bm.Context) {
arg := new(struct {
ID int `form:"id" validate:"required"`
})
if err := c.Bind(arg); err != nil {
return
}
username, _ := c.Get("username")
c.JSON(nil, vipSvc.WelfareBatchState(c, arg.ID, username.(string)))
}
func getFileBody(c *bm.Context, name string) (body []byte, filetype string, err error) {
var file multipart.File
if file, _, err = c.Request.FormFile(name); err != nil {
if err == http.ErrMissingFile {
err = nil
return
}
err = ecode.RequestErr
return
}
if file == nil {
return
}
defer file.Close()
if body, err = ioutil.ReadAll(file); err != nil {
err = ecode.RequestErr
return
}
filetype = http.DetectContentType(body)
if filetype != "text/plain; charset=utf-8" {
err = ecode.VipFileTypeErr
return
}
if len(body) > _maxFileSize {
err = ecode.FileTooLarge
return
}
return
}

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 = [
"dialog.go",
"jointly.go",
"model.go",
"month.go",
"order.go",
"panel.go",
"params.go",
"platform.go",
"privilege.go",
"push.go",
"query.go",
"reques.go",
"resouce.go",
"tips.go",
"vip.go",
"welfare.go",
],
importpath = "go-common/app/admin/main/vip/model",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = ["//library/time: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,34 @@
package model
import "go-common/library/time"
// ConfDialog .
type ConfDialog struct {
ID int64 `gorm:"column:id" json:"id" form:"id"`
AppID int64 `gorm:"column:app_id" json:"app_id" form:"app_id"`
Platform int64 `gorm:"column:platform" json:"platform" form:"platform"`
StartTime time.Time `gorm:"column:start_time" json:"start_time" form:"start_time"`
EndTime time.Time `gorm:"column:end_time" json:"end_time" form:"end_time" default:"32503651200"` //3000-01-01 00:00:00
Title string `gorm:"column:title" json:"title" form:"title" validate:"required"`
Content string `gorm:"column:content" json:"content" form:"content" validate:"required"`
Follow bool `gorm:"column:follow" json:"follow" form:"follow"`
LeftButton string `gorm:"column:left_button" json:"left_button" form:"left_button"`
LeftLink string `gorm:"column:left_link" json:"left_link" form:"left_link"`
RightButton string `gorm:"column:right_button" json:"right_button" form:"right_button" validate:"required"`
RightLink string `gorm:"column:right_link" json:"right_link" form:"right_link"`
Operator string `gorm:"column:operator" json:"operator"`
Stage bool `gorm:"column:stage" json:"stage" form:"stage" default:"true"`
Ctime time.Time `gorm:"column:ctime" json:"ctime" form:"ctime"`
Mtime time.Time `gorm:"column:mtime" json:"mtime" form:"mtime"`
}
// TableName for grom.
func (c *ConfDialog) TableName() string {
return "vip_conf_dialog"
}
// ConfDialogList admin list model.
type ConfDialogList struct {
*ConfDialog
Status string `json:"status"`
}

View File

@@ -0,0 +1,18 @@
package model
import "go-common/library/time"
// Jointly def.
type Jointly struct {
ID int64 `json:"id"`
Title string `json:"title"`
Content string `json:"content"`
StartTime int64 `json:"start_time"`
EndTime int64 `json:"end_time"`
Link string `json:"link"`
IsHot int8 `json:"is_hot"`
State int8 `json:"state"`
Operator string `json:"operator"`
CTime time.Time `json:"ctime"`
MTime time.Time `json:"mtime"`
}

View File

@@ -0,0 +1,148 @@
package model
// tips status.
const (
WaitShowTips = iota + 1
EffectiveTips
ExpireTips
)
// PlatformByCode .
var PlatformByCode = map[int]string{
DeviceIOS: "ios",
DeviceIPAD: "ipad",
DevicePC: "pc",
DeviceANDROID: "android",
}
// const for vip
const (
DeviceIOS = iota + 1
DeviceIPAD
DevicePC
DeviceANDROID
)
// push progress status
const (
NotStart = iota + 1
Starting
Started
)
// const .
const (
UnDisable = iota
Disable
)
// const .
const (
Normal = iota + 1
Fail
)
// tips judge type .
const (
VersionTypeNone int8 = iota
VersionMoreThan
VersionEqual
VersionLessThan
)
// Delete state
const (
Delete = 1
)
// PageInfo common page info.
type PageInfo struct {
Count int `json:"count"`
CurrentPage int `json:"currentPage,omitempty"`
Item interface{} `json:"item"`
}
// UserChangeHistoryReq user change history request.
type UserChangeHistoryReq struct {
Mid int64 `form:"mid"`
ChangeType int8 `form:"change_type"`
StartChangeTime int64 `form:"startchangetime"`
EndChangeTime int64 `form:"endchangetime"`
BatchID int64 `form:"batch_id"`
RelationID string `form:"relation_id"`
Pn int `form:"pn"`
Ps int `form:"ps"`
}
// PushPlatformMap .
var PushPlatformMap = map[string]string{
"1": "Android",
"2": "iPhone",
"3": "iPad",
}
// PushPlatformNameMap .
var PushPlatformNameMap = map[string]string{
"Android": "1",
"iPhone": "2",
"iPad": "3",
}
// ConditionMap .
var ConditionMap = map[string]string{
"gte": ">=",
"lte": "<=",
"eq": "=",
"neq": "!=",
}
// ConditionNameMap .
var ConditionNameMap = map[string]string{
">=": "gte",
"<=": "lte",
"=": "eq",
"!=": "neq",
}
// privilege resources state.
const (
DisablePrivilege = iota
NormalPrivilege
)
// privilege resources type.
const (
WebResources = iota
AppResources
)
// jointly state.
const (
WillEffect int8 = iota + 1
Effect
LoseEffect
)
// order type
const (
NormalOrder = iota
AutoOrder
IAPAutoOrder
)
// pay order status.
const (
PAYING = iota + 1
SUCCESS
FAILED
SIGN
UNSIGN
REFUNDING
REFUNDED
)
// order type
const (
General int8 = iota
AutoRenew
)

View File

@@ -0,0 +1,30 @@
package model
import "go-common/library/time"
// VipMonth vip month info.
type VipMonth struct {
ID int64 `json:"id"`
Month int8 `json:"month"`
MonthType int8 `json:"month_type"`
Operator string `json:"operator"`
Status int8 `json:"status"`
Mtime time.Time `json:"mtime"`
}
// VipMonthPrice month price info.
type VipMonthPrice struct {
ID int64 `json:"id" form:"id"`
MonthID int8 `json:"month_id" form:"month_id"`
MonthType int8 `json:"month_type" form:"month_type"`
Money float64 `json:"money" form:"money"`
FirstDiscountMoney float64 `json:"first_discount_money" form:"first_discount_money"`
DiscountMoney float64 `json:"discount_money" form:"discount_money"`
Selected int8 `json:"selected" form:"selected"`
StartTime time.Time `json:"start_time" form:"start_time"`
EndTime time.Time `json:"end_time" form:"end_time"`
Remark string `json:"remark" form:"remark"`
Operator string `json:"operator"`
Status int8 `json:"status"`
Mtime time.Time `json:"mtime"`
}

View File

@@ -0,0 +1,37 @@
package model
import "go-common/library/time"
//PayOrder pay order
type PayOrder struct {
ID int64 `json:"_"`
OrderNo string `json:"order_no"`
AppID int64 `json:"app_id"`
Platform int8 `json:"platform"`
OrderType int8 `json:"order_type"`
AppSubID string `json:"app_sub_id"`
Mid int64 `json:"mid"`
ToMid int64 `json:"to_mid"`
BuyMonths int16 `json:"buy_months"`
Money float64 `json:"money"`
RefundAmount float64 `json:"refund_amount"`
Status int8 `json:"status"`
PayType int8 `json:"pay_type"`
RechargeBp float64 `json:"recharge_bp"`
ThirdTradeNo string `json:"third_trade_no"`
Ver int64 `json:"ver"`
PaymentTime time.Time `json:"payment_time"`
Ctime time.Time `json:"ctime"`
Mtime time.Time `json:"mtime"`
}
//PayOrderLog pay order log.
type PayOrderLog struct {
ID int64 `json:"id"`
OrderNo string `json:"order_no"`
RefundID string `json:"refund_id"`
RefundAmount float64 `json:"refund_amount"`
Mid int64 `json:"mid"`
Status int8 `json:"status"`
Operator string `json:"operator"`
}

View File

@@ -0,0 +1,179 @@
package model
import "go-common/library/time"
// VipPriceConfigPlat vip价格面版平台 1. 其他平台 2.IOS平台 3.IOS的HD平台
type VipPriceConfigPlat int64
// VipPriceConfigStatus vip价格面版配置状态 0. 有效 1. 失效 2.待生效
type VipPriceConfigStatus int8
const (
// VipPriceConfigStatusON 有效
VipPriceConfigStatusON VipPriceConfigStatus = iota
// VipPriceConfigStatusOFF 失效
VipPriceConfigStatusOFF
// VipPriceConfigStatusFuture 待生效
VipPriceConfigStatusFuture
)
// vip_price_config suit_type
const (
AllUser int8 = iota
OldVIP
NewVIP
OldSubVIP
NewSubVIP
OldPackVIP
NewPackVIP
)
// const .
const (
DefualtZeroTimeFromDB = 0
TimeFormatDay = "2006-01-02 15:04:05"
DefulatTimeFromDB = "1970-01-01 08:00:00"
)
// VipPriceConfig struct .
type VipPriceConfig struct {
ID int64 `gorm:"column:id" json:"id"`
Plat VipPriceConfigPlat `gorm:"column:platform" json:"platform"`
PdName string `gorm:"column:product_name" json:"product_name"`
PdID string `gorm:"column:product_id" json:"product_id"`
SuitType int8 `gorm:"column:suit_type" json:"suit_type"`
Month int16 `gorm:"column:month" json:"month"`
SubType int8 `gorm:"column:suit_type" json:"sub_type"`
OPrice float64 `gorm:"column:original_price" json:"original_price"`
NPrice float64 `json:"now_price"`
Selected int8 `gorm:"column:selected" json:"selected"`
Remark string `gorm:"column:remark" json:"remark"`
Status VipPriceConfigStatus `gorm:"column:status" json:"status"`
Operator string `gorm:"column:operator" json:"operator"`
OpID int64 `gorm:"column:oper_id" json:"oper_id"`
Superscript string `gorm:"column:superscript" json:"superscript"`
CTime time.Time `gorm:"column:ctime" json:"ctime"`
MTime time.Time `gorm:"column:mtime" json:"mtime"`
StartBuild int64 `json:"start_build"`
EndBuild int64 `json:"end_build"`
}
// VipPriceConfigV2 struct .
type VipPriceConfigV2 struct {
ID int64 `gorm:"column:id" json:"id" form:"id"`
Platform int64 `gorm:"column:platform" json:"platform" form:"platform"`
ProductName string `gorm:"column:product_name" json:"product_name" form:"product_name"`
ProductID string `gorm:"column:product_id" json:"product_id" form:"product_id"`
SuitType int64 `gorm:"column:suit_type" json:"suit_type" form:"suit_type"`
Month int64 `gorm:"column:month" json:"month" form:"month"`
SubType int64 `gorm:"column:sub_type" json:"sub_type" form:"sub_type"`
OriginalPrice float64 `gorm:"column:original_price" json:"original_price" form:"original_price"`
Selected int8 `gorm:"column:selected" json:"selected" form:"selected"`
Remark string `gorm:"column:remark" json:"remark" form:"remark"`
Status int8 `gorm:"column:status" json:"status" form:"status"`
Operator string `gorm:"column:operator" json:"operator" form:"operator"`
OperID int64 `gorm:"column:oper_id" json:"oper_id" form:"oper_id"`
Ctime time.Time `gorm:"column:ctime" json:"ctime" form:"ctime"`
Mtime time.Time `gorm:"column:mtime" json:"mtime" form:"mtime"`
Superscript string `gorm:"column:superscript" json:"superscript" form:"superscript"`
StartBuild int64 `json:"start_build"`
EndBuild int64 `json:"end_build"`
}
// VipDPriceConfig price discount config.
type VipDPriceConfig struct {
DisID int64 `json:"discount_id"`
ID int64 `json:"vpc_id"`
PdID string `json:"product_id"`
DPrice float64 `json:"discount_price"`
STime time.Time `json:"stime"`
ETime time.Time `json:"etime"`
Remark string `json:"remark"`
Operator string `json:"operator"`
OpID int64 `json:"oper_id"`
CTime time.Time `json:"ctime"`
MTime time.Time `json:"mtime"`
FirstPrice float64 `json:"first_price"`
}
// VipPriceDiscountConfigV2 table vip_price_discount_config_v2 struct .
type VipPriceDiscountConfigV2 struct {
ID int64 `gorm:"column:id" json:"id" form:"id"`
VpcID int64 `gorm:"column:vpc_id" json:"vpc_id" form:"vpc_id"`
ProductID string `gorm:"column:product_id" json:"product_id" form:"product_id"`
DiscountPrice float64 `gorm:"column:discount_price" json:"discount_price" form:"discount_price"`
Stime time.Time `gorm:"column:stime" json:"stime" form:"stime"`
Etime time.Time `gorm:"column:etime" json:"etime" form:"etime"`
Remark string `gorm:"column:remark" json:"remark" form:"remark"`
Operator string `gorm:"column:operator" json:"operator" form:"operator"`
OperID int64 `gorm:"column:oper_id" json:"oper_id" form:"oper_id"`
Ctime time.Time `gorm:"column:ctime" json:"ctime" form:"ctime"`
Mtime time.Time `gorm:"column:mtime" json:"mtime" form:"mtime"`
}
// ArgAddOrUpVipPrice .
type ArgAddOrUpVipPrice struct {
ID int64 `form:"id"`
Plat VipPriceConfigPlat `form:"platform" validate:"required"`
PdName string `form:"product_name" validate:"required"`
PdID string `form:"product_id" validate:"required"`
Month int16 `form:"month" validate:"required"`
SubType int8 `form:"sub_type"`
SuitType int8 `form:"suit_type"`
OPrice float64 `form:"original_price" validate:"required"`
Remark string `form:"remark"`
Operator string `form:"operator" validate:"required"`
OpID int64 `form:"oper_id" validate:"required"`
Selected int8 `form:"selected"`
Superscript string `form:"superscript"`
StartBuild int64 `form:"start_build"`
EndBuild int64 `form:"end_build"`
}
// ArgAddOrUpVipDPrice .
type ArgAddOrUpVipDPrice struct {
DisID int64 `form:"discount_id"`
ID int64 `form:"vpc_id" validate:"required"`
PdID string `form:"product_id" validate:"required"`
DPrice float64 `form:"discount_price"`
STime time.Time `form:"stime" validate:"required"`
ETime time.Time `form:"etime"`
Remark string `form:"remark"`
Operator string `form:"operator" validate:"required"`
OpID int64 `form:"oper_id" validate:"required"`
FirstPrice float64 `form:"first_price"`
}
// CheckProductID .
// func (vpc *VipPriceConfig) CheckProductID(arg *ArgAddOrUpVipDPrice) bool {
// return (vpc.Plat == PlatVipPriceConfigIOS || vpc.Plat == PlatVipPriceConfigIOSHD || vpc.Plat == PlatVipPriceConfigIphoneB) && arg.PdID == ""
// }
// ExistPlat .
// func (aavp *ArgAddOrUpVipPrice) ExistPlat() bool {
// return aavp.Plat == PlatVipPriceConfigOther ||
// aavp.Plat == PlatVipPriceConfigIOS ||
// aavp.Plat == PlatVipPriceConfigIOSHD ||
// aavp.Plat == PlatVipPriceConfigFriendsGift ||
// aavp.Plat == PlatVipPriceConfigInternational ||
// aavp.Plat == PlatVipPriceConfigIphoneB ||
// aavp.Plat == PlatVipPriceConfigCheck
// }
// ArgVipPriceID .
type ArgVipPriceID struct {
ID int64 `form:"id" validate:"required"`
}
// ArgVipDPriceID .
type ArgVipDPriceID struct {
DisID int64 `form:"discount_id" validate:"required"`
}
// ArgVipPrice .
type ArgVipPrice struct {
Plat VipPriceConfigPlat `form:"platform" default:"-1"`
Month int16 `form:"month" default:"-1"`
SubType int8 `form:"sub_type" default:"-1"`
SuitType int8 `form:"suit_type" default:"-1"`
}

View File

@@ -0,0 +1,140 @@
package model
import "go-common/library/time"
// ArgID .
type ArgID struct {
ID int64 `form:"id" validate:"required"`
}
// ArgPointHistory .
type ArgPointHistory struct {
Mid int64 `form:"id"`
ChangeType int64 `form:"change_type"`
StartChangeTime int64 `form:"start_change_time"`
EndChangeTime int64 `form:"end_change_time"`
BatchID int64 `form:"batch_id"`
RelationID int64 `form:"relation_id"`
}
// ArgIDExtra .
type ArgIDExtra struct {
ID int64 `form:"id" validate:"required"`
Status int8 `form:"status" validate:"required"`
Operator string
}
// ArgPage .
type ArgPage struct {
Ps int `form:"ps"`
Pn int `form:"pn"`
Status int `form:"status"`
}
// ArgPoolID .
type ArgPoolID struct {
PoolID int `form:"pool_id" validate:"required"`
}
// ArgReSource .
type ArgReSource struct {
ID int `form:"id"`
Increment int `form:"increment"`
StartTime time.Time `form:"start_time"`
EndTime time.Time `form:"end_time"`
}
// ArgAddPrivilege add privilege.
type ArgAddPrivilege struct {
Name string `json:"name" form:"name" validate:"required"`
Title string `json:"title" form:"title" validate:"required"`
Explain string `json:"explain" form:"explain" validate:"required"`
Type int8 `json:"type" form:"type"`
LangType int8 `json:"lang_type" form:"lang_type"`
Operator string `json:"operator"`
WebLink string `json:"web_link" form:"web_link"`
AppLink string `json:"app_link" form:"app_link"`
}
// ArgUpdatePrivilege update privilege.
type ArgUpdatePrivilege struct {
ID int64 `form:"id" validate:"required"`
Name string `json:"name" form:"name" validate:"required"`
Title string `json:"title" form:"title" validate:"required"`
Explain string `json:"explain" form:"explain" validate:"required"`
Type int8 `json:"type" form:"type"`
Operator string `json:"operator"`
WebLink string `json:"web_link" form:"web_link"`
AppLink string `json:"app_link" form:"app_link"`
}
// ArgImage arg image.
type ArgImage struct {
IconFileType string
IconBody []byte
IconGrayFileType string
IconGrayBody []byte
WebImageFileType string
WebImageBody []byte
AppImageFileType string
AppImageBody []byte
}
// ArgStatePrivilege def.
type ArgStatePrivilege struct {
ID int64 `form:"id" validate:"required"`
Status int8 `form:"state"`
}
// ArgPivilegeID def.
type ArgPivilegeID struct {
ID int64 `form:"id" validate:"required"`
}
// ArgOrder def.
type ArgOrder struct {
AID int64 `form:"aid" validate:"required"`
BID int64 `form:"bid" validate:"required"`
}
// ArgAddJointly arg add jointly.
type ArgAddJointly struct {
Title string `form:"title" validate:"required"`
Content string `form:"content"`
StartTime int64 `form:"start_time" validate:"required"`
EndTime int64 `form:"end_time" validate:"required"`
Link string `form:"link" validate:"required"`
IsHot int8 `form:"is_hot" `
Operator string
}
// ArgModifyJointly arg modify jointly.
type ArgModifyJointly struct {
ID int64 `form:"id" validate:"required"`
Title string `form:"title" validate:"required"`
Content string `form:"content" validate:"required"`
Link string `form:"link" validate:"required"`
IsHot int8 `form:"is_hot" `
StartTime int64 `form:"start_time" validate:"required"`
EndTime int64 `form:"end_time" validate:"required"`
Operator string
}
// ArgQueryJointly query jointly params .
type ArgQueryJointly struct {
State int8 `form:"state" `
}
// ArgJointlyID .
type ArgJointlyID struct {
ID int64 `form:"id" validate:"required"`
}
//ArgPayOrder qeury order.
type ArgPayOrder struct {
Mid int64 `form:"mid"`
OrderNo string `form:"order_no"`
Status int8 `form:"status"`
PN int `form:"pn" default:"1"`
PS int `form:"ps" default:"20"`
}

View File

@@ -0,0 +1,40 @@
package model
import "go-common/library/time"
// const .
var (
// PlatformMap 平台
PlatformMap = map[string]string{"android": "android", "ios": "ios", "pc": "pc", "public": "public"}
// Device 对应设备
DeviceMap = map[string]string{"pad": "pad", "phone": "phone"}
// MobiAPPIDIosMap iOS
MobiAPPIDIosMap = map[string]string{"iphone": "iphone", "ipad": "ipad", "iphone_b": "iphone_b"}
// MobiAPPIDAndroidMap Android
MobiAPPIDAndroidMap = map[string]string{"android": "android", "android_tv_yst": "android_tv_yst", "android_tv": "android_tv", "android_i": "android_i", "android_b": "android_b"}
)
// ConfPlatform struct .
type ConfPlatform struct {
ID int64 `gorm:"column:id" json:"id" form:"id"`
PlatformName string `gorm:"column:platform_name" json:"platform_name" form:"platform_name" validate:"required"`
Platform string `gorm:"column:platform" json:"platform" form:"platform" validate:"required"`
Device string `gorm:"column:device" json:"device" form:"device"`
MobiApp string `gorm:"column:mobi_app" json:"mobi_app" form:"mobi_app"`
PanelType string `gorm:"column:panel_type" json:"panel_type" form:"panel_type" default:"normal"`
IsDel int8 `gorm:"column:is_del" json:"is_del" form:"is_del"`
Operator string `gorm:"column:operator" json:"operator" form:"operator"`
Ctime time.Time `gorm:"column:ctime" json:"ctime" form:"ctime"`
Mtime time.Time `gorm:"column:mtime" json:"mtime" form:"mtime"`
}
// TableName for grom.
func (s *ConfPlatform) TableName() string {
return "vip_platform_config"
}
// TypePlatform struct .
type TypePlatform struct {
ID int64 `json:"id"`
PlatformName string `json:"platform_name"`
}

View File

@@ -0,0 +1,63 @@
package model
import (
"go-common/library/time"
)
// Privilege info.
type Privilege struct {
ID int64 `gorm:"column:id" json:"id"`
Name string `gorm:"column:privileges_name" json:"name"`
Title string `gorm:"column:title" json:"title"`
Explain string `gorm:"column:explains" json:"explain"`
Type int8 `gorm:"column:privileges_type" json:"type"`
Operator string `gorm:"column:operator" json:"operator"`
State int8 `gorm:"column:state" json:"state"`
Deleted int8 `gorm:"column:deleted" json:"deleted"`
IconURL string `gorm:"column:icon_url" json:"icon_url"`
IconGrayURL string `gorm:"column:icon_gray_url" json:"icon_gray_url"`
Order int64 `gorm:"column:order_num" json:"order"`
LangType int8 `gorm:"column:lang_type" json:"lang_type"`
Ctime time.Time `gorm:"column:ctime" json:"ctime"`
Mtime time.Time `gorm:"column:mtime" json:"mtime"`
}
// TableName for grom.
func (s *Privilege) TableName() string {
return "vip_privileges"
}
// PrivilegeResources privilege resources.
type PrivilegeResources struct {
ID int64 `gorm:"column:id" json:"id"`
PID int64 `gorm:"column:pid" json:"pid"`
Link string `gorm:"column:link" json:"link"`
ImageURL string `gorm:"column:image_url" json:"image_url"`
Type int8 `gorm:"column:resources_type" json:"type"`
Ctime time.Time `gorm:"column:ctime" json:"ctime"`
Mtime time.Time `gorm:"column:mtime" json:"mtime"`
}
// TableName for grom.
func (s *PrivilegeResources) TableName() string {
return "vip_privileges_resources"
}
// PrivilegeResp resp.
type PrivilegeResp struct {
ID int64 `json:"id"`
Name string `json:"name"`
Title string `json:"title"`
Explain string `json:"explain"`
Type int8 `json:"type"`
Operator string `json:"operator"`
State int8 `json:"state"`
IconURL string `json:"icon_url"`
IconGrayURL string `json:"icon_gray_url"`
Order int64 `json:"order"`
WebLink string `json:"web_link"`
WebImageURL string `json:"web_image_url"`
AppLink string `json:"app_link"`
AppImageURL string `json:"app_image_url"`
LangType int8 `json:"lang_type"`
}

View File

@@ -0,0 +1,36 @@
package model
import "go-common/library/time"
// VipPushData .
type VipPushData struct {
ID int64 `json:"id" form:"id"`
DisableType int8 `json:"disable_type"`
GroupName string `json:"group_name" form:"group_name"`
Title string `json:"title" form:"title"`
Content string `json:"content" form:"content" validate:"required"`
PushTotalCount int32 `json:"-"`
PushedCount int32 `json:"-"`
PushProgress string `json:"push_progress"`
ProgressStatus int8 `json:"progress_status"`
Operator string `json:"operator"`
Status int8 `json:"status"`
Platform string `json:"platform" form:"platform"`
LinkType int32 `json:"link_type" form:"link_type" validate:"required"`
ErrorCode int32 `json:"error_code"`
LinkURL string `json:"link_url" form:"link_url" validate:"required"`
ExpiredDayStart int32 `json:"expired_day_start" form:"expired_day_start"`
ExpiredDayEnd int64 `json:"expired_day_end" form:"expired_day_end"`
EffectStartDate time.Time `json:"effect_start_date" form:"effect_start_date" validate:"required"`
EffectEndDate time.Time `json:"effect_end_date" form:"effect_end_date" validate:"required"`
PushStartTime string `json:"push_start_time" form:"push_start_time" validate:"required"`
PushEndTime string `json:"push_end_time" form:"push_end_time" validate:"required"`
PlatformArr []*PushDataPlatform `json:"platform_arr"`
}
// PushDataPlatform .
type PushDataPlatform struct {
Name string `json:"name"`
Condition string `json:"condition"`
Build int64 `json:"build"`
}

View File

@@ -0,0 +1,7 @@
package model
// QueryBusinessInfo .
type QueryBusinessInfo struct {
Name string `json:"name"`
Appkey string `json:"appkey"`
}

View File

@@ -0,0 +1,90 @@
package model
import "go-common/library/time"
//ResoucePoolBo pool bo
type ResoucePoolBo struct {
PN int `form:"pn" default:"1"`
PS int `form:"ps" default:"20"`
ID int `form:"pool_id"`
PoolName string `form:"pool_name"`
BusinessID int `form:"biz_id"`
StartTime time.Time `form:"start_time"`
EndTime time.Time `form:"end_time"`
BatchID int `form:"batch_id"`
Reason string `form:"reason"`
CodeExpireTime time.Time `form:"code_expire_time"`
Contacts string `form:"contacts"`
ContactsNumber string `form:"contacts_number"`
}
//ResouceBatchBo resouce batch bo
type ResouceBatchBo struct {
ID int `form:"id"`
PoolID int `form:"pool_id"`
Unit int `form:"unit"`
Count int `form:"count"`
StartTime time.Time `form:"start_time"`
EndTime time.Time `form:"end_time"`
SurplusCount int `form:"surplus_count"`
CodeUseCount int `form:"code_use_count"`
DirectUseCount int `form:"direct_use_count"`
}
//ResouceBatchVo resouce batch vo
type ResouceBatchVo struct {
VipResourceBatch
PoolName string `json:"pool_name"`
}
//ArgPrivilege .
type ArgPrivilege struct {
PrivilegeID int `form:"privilege_id"`
Name string `form:"name"`
Remark string `form:"remark"`
PcLink string `form:"pc_link"`
H5Link string `form:"h5_link"`
BgColor string `form:"bg_color"`
Type int `form:"type"`
Mapping []ArgPrivilegeMapping `form:"platforms"`
}
//ArgPrivilegeMapping .
type ArgPrivilegeMapping struct {
Status int `form:"status"`
Platform int `form:"platform"`
Icon string `form:"icon"`
}
// ArgCode .
type ArgCode struct {
ID int64 `form:"id"`
Code string `form:"code"`
Mid int64 `form:"mid"`
BusinessID int64 `form:"business_id"`
PoolID int64 `form:"pool_id"`
BatchCodeID int64 `form:"batch_code_id"`
Status int8 `form:"status"`
UseStartTime time.Time `form:"use_start_time"`
UseEndTime time.Time `form:"use_end_time"`
BatchCodeIDs []int64 `form:"batch_code_ids"`
}
// ArgBatchCode .
type ArgBatchCode struct {
ID int64 `form:"id"`
BusinessID int64 `form:"business_id"`
PoolID int64 `form:"pool_id"`
Name string `form:"name"`
Status int8 `form:"status"`
StartTime time.Time `form:"start_time"`
EndTime time.Time `form:"end_time"`
}
// ArgPushData .
type ArgPushData struct {
ProgressStatus int8 `form:"progress_status"`
Status int8 `form:"status"`
PN int `form:"pn" default:"1"`
PS int `form:"ps" default:"20"`
}

View File

@@ -0,0 +1,47 @@
package model
import "go-common/library/time"
// ResourceCode .
type ResourceCode struct {
ID int64 `json:"id"`
BatchCodeID int64 `json:"batch_code_id"`
Status int8 `json:"status"`
Code string `json:"code"`
Mid int64 `json:"mid"`
UseTime time.Time `json:"use_time"`
Ctime time.Time `json:"ctime"`
}
// BatchCode .
type BatchCode struct {
ID int64 `json:"id" form:"id"`
BusinessID int64 `json:"business_id" form:"business_id" validate:"required"`
PoolID int64 `json:"pool_id" form:"pool_id" validate:"required"`
Status int8 `json:"status" `
Type int8 `json:"type" form:"type"`
BatchName string `json:"batch_name" form:"batch_name" validate:"required"`
MaxCount int64 `json:"max_count" form:"max_count"`
LimitDay int64 `json:"limit_day" form:"limit_day" validate:"max=10000,min=-1"`
Reason string `json:"reason" form:"reason" validate:"required"`
Unit int32 `json:"unit" form:"unit" validate:"required"`
Count int64 `json:"count" form:"count" validate:"required"`
SurplusCount int64 `json:"surplus_count"`
Price float64 `json:"price" form:"price" validate:"required"`
StartTime time.Time `json:"start_time" form:"start_time" validate:"required"`
EndTime time.Time `json:"end_time" form:"end_time" validate:"required"`
Contacts string `json:"contacts" form:"contacts"`
ContactsNumber string `json:"contacts_number" form:"contacts_number"`
Operator string `json:"operator"`
Ctime time.Time `json:"ctime"`
}
// CodeVo .
type CodeVo struct {
ResourceCode
BatchName string `json:"batch_name"`
BatchStatus int8 `json:"batch_status"`
StartTime time.Time `json:"start_time"`
EndTime time.Time `json:"end_time"`
Unit int32 `json:"unit"`
}

View File

@@ -0,0 +1,49 @@
package model
import "go-common/library/time"
// Tips def.
type Tips struct {
ID int64 `json:"id" form:"id"`
Platform int8 `json:"platform" form:"platform" validate:"required,min=1,gte=1"`
Version int64 `json:"version" form:"version"`
Tip string `json:"tip" form:"tip" validate:"required"`
Link string `json:"link" form:"link"`
StartTime int64 `json:"start_time" form:"start_time" validate:"required,min=1,gte=1"`
EndTime int64 `json:"end_time" form:"end_time" validate:"required,min=1,gte=1"`
Level int8 `json:"level" form:"level" validate:"required,min=1,gte=1"`
JudgeType int8 `json:"judge_type" form:"judge_type"`
Operator string `json:"operator"`
Deleted int8 `json:"deleted"`
Position int8 `json:"position" form:"position" validate:"required,min=1,gte=1"`
State int8 `json:"state"`
Ctime time.Time `json:"ctime"`
Mtime time.Time `json:"mtime"`
}
// TipResp def.
type TipResp struct {
ID int64 `json:"id"`
PlatformStr string `json:"platform_str"`
JudgeBuild int8 `json:"judge_build_str"`
StateStr string `json:"state_str"`
State int8 `json:"state"`
Version int64 `json:"version"`
Tip string `json:"tip"`
Link string `json:"link"`
Operator string `json:"operator"`
Position int8 `json:"position"`
Ctime int64 `json:"ctime"`
Mtime int64 `json:"mtime"`
}
// TipState tip state
func (t *Tips) TipState(stime, etime, now int64) {
if stime > now {
t.State = WaitShowTips
} else if etime < now {
t.State = ExpireTips
} else {
t.State = EffectiveTips
}
}

View File

@@ -0,0 +1,216 @@
package model
import "go-common/library/time"
// VipResourcePool vip_resource_pool table
type VipResourcePool struct {
ID int `json:"id"`
PoolName string `json:"pool_name"`
BusinessID int `json:"business_id"`
BusinessName string `json:"business_name"`
Reason string `json:"reason"`
CodeExpireTime time.Time `json:"code_expire_time"`
StartTime time.Time `json:"start_time"`
EndTime time.Time `json:"end_time"`
Contacts string `json:"contacts"`
ContactsNumber string `json:"contacts_number"`
Ctime time.Time `json:"-"`
Mtime time.Time `json:"-"`
}
// VipResourceBatch vip_resource_batch table
type VipResourceBatch struct {
ID int `json:"id"`
PoolID int `json:"pool_id"`
Unit int `json:"unit"`
Count int `json:"count"`
Ver int `json:"ver"`
StartTime time.Time `json:"start_time"`
EndTime time.Time `json:"end_time"`
SurplusCount int `json:"surplus_count"`
CodeUseCount int `json:"code_use_count"`
DirectUseCount int `json:"direct_use_count"`
Ctime time.Time `json:"-"`
Mtime time.Time `json:"-"`
}
//VipBusinessInfo vip_business_info table
type VipBusinessInfo struct {
ID int `json:"id" form:"id"`
BusinessName string `json:"business_name" form:"business_name"`
BusinessType int `json:"business_type" form:"business_type"`
Status int `json:"status" form:"status"`
AppKey string `json:"app_key" form:"app_key"`
Secret string `json:"-" form:"secret"`
Contacts string `json:"contacts" form:"contacts"`
ContactsNumber string `json:"contacts_number" form:"contacts_number"`
Ctime time.Time `json:"ctime"`
Mtime time.Time `json:"mtime"`
}
//VipChangeHistory vip_change_history table
type VipChangeHistory struct {
ID int `json:"id"`
Mid int64 `json:"mid"`
ChangeType int `json:"change_type"`
ChangeTime time.Time `json:"change_time"`
Days int `json:"days"`
OperatorID string `json:"operator_id"`
RelationID string `json:"relation_id"`
BatchID int `json:"batch_id"`
Remark string `json:"remark"`
Ctime time.Time `json:"ctime"`
Mtime time.Time `json:"mtime"`
}
//VipUserInfo vip_user_info table
type VipUserInfo struct {
ID int `json:"id"`
Mid int `json:"mid"`
VipType int `json:"vipType"`
VipPayType int `json:"vipPayType"`
VipStatus int `json:"vipStatus"`
VipStartTime time.Time `json:"vipStartTime"`
VipOverdueTime time.Time `json:"vipOverdueTime"`
AnnualVipOverdueTime time.Time `json:"annualVipOverdueTime"`
VipRecentTime time.Time `json:"vipRecentTime"`
Ctime time.Time `json:"ctime"`
Mtime time.Time `json:"mtime"`
}
//VipChangeBo vip change
type VipChangeBo struct {
Mid int
ChangeType int
ChangeTime time.Time
RelationID string
Remark string
Days int
BatchID int
OperatorID string
}
//HandlerVip vip handler
type HandlerVip struct {
OldVipUser *VipUserInfo
VipUser *VipUserInfo
HistoryID int
Days int
Mid int
}
//BcoinSendBo bcoinSendBo
type BcoinSendBo struct {
Amount int
DayOfMonth int
DueDate time.Time
}
//VipBcoinSalary vip_bcoin_salary table
type VipBcoinSalary struct {
ID int `json:"id"`
Mid int `json:"mid"`
Status int `json:"status"`
GiveNowStatus int `json:"giveNowStatus"`
Month time.Time `json:"month"`
Amount int `json:"amount"`
Memo string `json:"memo"`
Ctime time.Time `json:"ctime"`
Mtime time.Time `json:"mtime"`
}
//VipConfig vipConfig
type VipConfig struct {
ID int `json:"id"`
ConfigKey string `json:"configKey"`
Name string `json:"name"`
Content string `json:"content"`
Description string `json:"description"`
OperatorID int `json:"operatorId"`
OperatorName string `json:"operatorName"`
Mtime time.Time `json:"mtime"`
}
// VipAppVersion app version.
type VipAppVersion struct {
ID int64 `json:"id"`
PlatformID int8 `json:"platform_id"`
Version string `json:"version"`
Tip string `json:"tip"`
Operator string `json:"operator"`
Link string `json:"link"`
}
// VipPrivilege .
type VipPrivilege struct {
ID int `json:"id"`
Name string `json:"name"`
OrderNum int `json:"order_num"`
Remark string `json:"remark"`
BgColor string `json:"bg_color"`
Type int `json:"type"`
Deleted int `json:"deleted"`
PcLink string `json:"pc_link"`
MobileLink string `json:"mobile_link"`
}
// VipPrivilegeMapping .
type VipPrivilegeMapping struct {
ID int `json:"id"`
PrivilegeID int `json:"privilege_id"`
PlatformID int `json:"platform_id"`
Icon string `json:"icon"`
Status int `json:"status"`
Operator string `json:"operator"`
}
// const vip enum value
const (
//ChangeType
ChangeTypePointExhchange = 1 // 积分兑换
ChangeTypeRechange = 2 //充值开通
ChangeTypeSystem = 3 // 系统发放
ChangeTypeActiveGive = 4 //活动赠送
ChangeTypeRepeatDeduction = 5 //重复领取扣除
ChangeTypeSystemDrawback = 7 //系统扣减
VipDaysMonth = 31
VipDaysYear = 366
NotVip = 0 //非大会员
Vip = 1 //月度大会员
AnnualVip = 2 //年度会员
VipStatusOverTime = 0 //过期
VipStatusNotOverTime = 1 //未过期
VipStatusFrozen = 2 //冻结
VipStatusBan = 3 //封禁
VipAppUser = 1 //大会员对接业务方user缓存
VipAppPoint = 2 //大会员对接业务方积分缓存
VipChangeFrozen = -1 //冻结
VipChangeUnFrozen = 0 //解冻
VipChangeOpen = 1 //开通
VipChangeModify = 2 //变更
VipBusinessStatusOpen = 0 //有效
VipBusinessStatusClose = 1 //无效
VipOpenMsgTitle = "大会员开通成功"
VipSystemNotify = 4
VipOpenMsg = "恭喜您已开通大会员服务%s"
VipOpenKMsg = "恭喜您已续期大会员服务%s"
VipBcoinGiveContext = "尊敬的年度大会员,您本月%dB币到账啦请您随意挥霍注意会在次月%d日清零哦"
VipBcoinGiveTitle = "B币到账通知"
VipOpenMsgCode = "10_1_1"
VipBcoinGiveMsgCode = "10_99_2"
)
// const .
const (
NOTUSER = iota + 1
USED
FROZEN
)

View File

@@ -0,0 +1,145 @@
package model
import (
"go-common/library/time"
)
// Welfare vip_welfare table
type Welfare struct {
ID int `json:"id"`
WelfareName string `json:"welfare_name" form:"welfare_name"`
WelfareDesc string `json:"welfare_desc" form:"welfare_desc"`
HomepageUri string `json:"homepage_uri" form:"homepage_uri"`
BackdropUri string `json:"backdrop_uri" form:"backdrop_uri"`
Recommend int `json:"recommend"`
Rank int `json:"rank"`
Tid int `json:"tid"`
UsageForm int `json:"usage_form" form:"usage_form"`
ReceiveRate int `json:"receive_rate" form:"receive_rate"`
ReceiveUri string `json:"receive_uri" form:"receive_uri"`
VipType int `json:"vip_type" form:"vip_type"`
State int `json:"state"`
OperID int `json:"oper_id"`
OperName string `json:"oper_name"`
Stime time.Time `json:"stime"`
Etime time.Time `json:"etime"`
Ctime time.Time `json:"ctime"`
Mtime time.Time `json:"mtime"`
}
// WelfareType vip_welfare_type table
type WelfareType struct {
ID int `json:"id"`
Name string `json:"name"`
State int `json:"state"`
OperID int `json:"oper_id"`
OperName string `json:"oper_name"`
}
// WelfareCodeBatch vip_welfare_code_batch table
type WelfareCodeBatch struct {
ID int `json:"id" gorm:"-;primary_key;AUTO_INCREMENT" form:"id"`
BatchName string `json:"batch_name"`
Wid int `json:"wid"`
Count int `json:"count"`
ReceivedCount int `json:"received_count"`
Ver int `json:"ver"`
State int `json:"state"`
OperID int `json:"oper_id"`
OperName string `json:"oper_name"`
Vtime time.Time `json:"vtime"`
Ctime time.Time `json:"ctime"`
Mtime time.Time `json:"mtime"`
}
// WelfareCode vip_welfare_code table
type WelfareCode struct {
ID int `json:"id"`
Bid int `json:"bid"`
Wid int `json:"wid"`
Code string `json:"code"`
Mid int `json:"mid"`
State int `json:"state"`
Ctime time.Time `json:"ctime"`
Mtime time.Time `json:"mtime"`
}
//WelfareTypeRes welfare type response
type WelfareTypeRes struct {
ID int `json:"id"`
Name string `json:"name"`
}
// WelfareReq save or update welfare params
type WelfareReq struct {
ID int `form:"id"`
WelfareName string `form:"name" validate:"required"`
WelfareDesc string `form:"desc" validate:"required"`
HomepageUri string `form:"homepage_uri"`
BackdropUri string `form:"backdrop_uri"`
Recommend int `form:"recommend"`
Rank int `form:"rank" validate:"required"`
Tid int `form:"tid"`
UsageForm int `form:"usage_form" validate:"required"`
ReceiveRate int `form:"receive_rate"`
ReceiveUri string `form:"receive_uri"`
VipType int `form:"vip_type" validate:"required"`
Stime time.Time `form:"stime" validate:"required"`
Etime time.Time `form:"etime" validate:"required"`
OperID int `json:"-"`
OperName string `json:"-"`
}
//WelfareRes welfare type response
type WelfareRes struct {
ID int `json:"id" gorm:"column:id"`
Name string `json:"name" gorm:"column:welfare_name"`
Desc string `json:"desc" gorm:"column:welfare_desc"`
TID int `json:"tid" gorm:"column:tid"`
HomepageUri string `json:"homepage_uri"`
BackdropUri string `json:"backdrop_uri"`
Recommend int `json:"recommend"`
Rank int `json:"rank"`
UsageForm int `json:"usage_form"`
Stime time.Time `json:"stime"`
Etime time.Time `json:"etime"`
ReceiveRate int `json:"receive_rate"`
ReceiveUri string `json:"receive_uri"`
VipType int `json:"vip_type"`
ReceivedCount int `json:"received_count"`
Count int `json:"count"`
}
//WelfareBatchRes welfare batch response
type WelfareBatchRes struct {
ID int `json:"id"`
Name string `json:"batch_name" gorm:"column:batch_name"`
WID int `json:"wid" gorm:"column:wid"`
Ver int `json:"ver"`
OperId int `json:"oper_id"`
OperName string `json:"oper_name"`
Vtime time.Time `json:"vtime"`
Ctime time.Time `json:"ctime"`
ReceivedCount int `json:"received_count"`
Count int `json:"count"`
}
// TableName vip_welfare_type
func (*WelfareType) TableName() string {
return "vip_welfare_type"
}
// TableName vip_welfare
func (*Welfare) TableName() string {
return "vip_welfare"
}
// TableName vip_welfare_code_batch
func (*WelfareCodeBatch) TableName() string {
return "vip_welfare_code_batch"
}
// TableName vip_welfare_code
func (*WelfareCode) TableName() string {
return "vip_welfare_code"
}

View File

@@ -0,0 +1,85 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_test",
"go_library",
)
go_test(
name = "go_default_test",
srcs = [
"dialog_test.go",
"jointly_test.go",
"order_test.go",
"panel_test.go",
"privilege_test.go",
"push_test.go",
"resouce_test.go",
"service_test.go",
"tips_test.go",
],
embed = [":go_default_library"],
rundir = ".",
tags = ["automanaged"],
deps = [
"//app/admin/main/vip/conf:go_default_library",
"//app/admin/main/vip/model:go_default_library",
"//library/ecode:go_default_library",
"//library/log:go_default_library",
"//library/time:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
],
)
go_library(
name = "go_default_library",
srcs = [
"business.go",
"dialog.go",
"jointly.go",
"month.go",
"order.go",
"panel.go",
"platform.go",
"privilege.go",
"push.go",
"resouce.go",
"service.go",
"tips.go",
"version.go",
"vip.go",
"welfare.go",
],
importpath = "go-common/app/admin/main/vip/service",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/admin/main/vip/conf:go_default_library",
"//app/admin/main/vip/dao:go_default_library",
"//app/admin/main/vip/model:go_default_library",
"//app/service/main/vip/model:go_default_library",
"//library/database/sql:go_default_library",
"//library/ecode:go_default_library",
"//library/log:go_default_library",
"//library/time:go_default_library",
"//vendor/github.com/google/uuid:go_default_library",
"//vendor/github.com/jinzhu/gorm:go_default_library",
"//vendor/github.com/pkg/errors:go_default_library",
"//vendor/golang.org/x/sync/errgroup: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,137 @@
package service
import (
"context"
"crypto/md5"
"encoding/hex"
"fmt"
"math/rand"
"time"
"go-common/app/admin/main/vip/model"
"go-common/library/ecode"
"go-common/library/log"
"github.com/pkg/errors"
)
// BusinessList business list.
func (s *Service) BusinessList(c context.Context, pn, ps, status int) (res []*model.VipBusinessInfo, count int64, err error) {
if count, err = s.dao.BussinessCount(c, status); err != nil {
log.Error("%+v", err)
return
}
if count == 0 {
return
}
if res, err = s.dao.BussinessList(c, pn, ps, status); err != nil {
log.Error("%+v", err)
return
}
return
}
// UpdateBusinessInfo update business info.
func (s *Service) UpdateBusinessInfo(c context.Context, req *model.VipBusinessInfo) (err error) {
var (
business *model.VipBusinessInfo
appkey string
businessName string
)
if business, err = s.dao.SelBusiness(c, req.ID); err != nil {
err = errors.WithStack(err)
return
}
if business == nil {
err = ecode.VipBusinessNotExitErr
return
}
req.Secret = business.Secret
appkey = business.AppKey
businessName = business.BusinessName
arg := new(model.QueryBusinessInfo)
if appkey != req.AppKey {
arg.Appkey = req.AppKey
if business, err = s.dao.SelBusinessByQuery(c, arg); err != nil {
err = errors.WithStack(err)
return
}
if business != nil {
err = ecode.VipAppkeyExitErr
return
}
req.Secret = s.makeSecret(req.AppKey)
}
if businessName != req.BusinessName {
arg = new(model.QueryBusinessInfo)
arg.Name = req.BusinessName
if business, err = s.dao.SelBusinessByQuery(c, arg); err != nil {
err = errors.WithStack(err)
return
}
if business != nil {
err = ecode.VipBusinessNameExitErr
return
}
}
if _, err = s.dao.UpdateBusiness(c, req); err != nil {
log.Error("%+v", err)
return
}
return
}
// AddBusinessInfo add business info.
func (s *Service) AddBusinessInfo(c context.Context, req *model.VipBusinessInfo) (err error) {
var (
business *model.VipBusinessInfo
)
arg := new(model.QueryBusinessInfo)
arg.Appkey = req.AppKey
if business, err = s.dao.SelBusinessByQuery(c, arg); err != nil {
err = errors.WithStack(err)
return
}
if business != nil {
err = ecode.VipAppkeyExitErr
return
}
arg = new(model.QueryBusinessInfo)
arg.Name = req.BusinessName
if business, err = s.dao.SelBusinessByQuery(c, arg); err != nil {
err = errors.WithStack(err)
return
}
if business != nil {
err = ecode.VipBusinessNameExitErr
return
}
req.Secret = s.makeSecret(req.AppKey)
if _, err = s.dao.AddBusiness(c, req); err != nil {
log.Error("%+v", err)
return
}
return
}
func (s *Service) makeSecret(appkey string) string {
key := fmt.Sprintf("%v,%v,%v", appkey, time.Now().UnixNano(), rand.Intn(100000000))
hash := md5.New()
hash.Write([]byte(key))
sum := hash.Sum(nil)
return hex.EncodeToString(sum)
}
// BusinessInfo business info
func (s *Service) BusinessInfo(c context.Context, id int) (r *model.VipBusinessInfo, err error) {
if r, err = s.dao.SelBusiness(c, id); err != nil {
log.Error("%+v", err)
return
}
return
}

View File

@@ -0,0 +1,91 @@
package service
import (
"context"
"time"
"go-common/app/admin/main/vip/model"
"go-common/library/ecode"
"go-common/library/log"
)
// DialogAll .
func (s *Service) DialogAll(c context.Context, appID, platform int64, status string) (res []*model.ConfDialogList, err error) {
var list []*model.ConfDialog
if list, err = s.dao.DialogAll(c, appID, platform, status); err != nil {
return
}
res = make([]*model.ConfDialogList, len(list))
for i, v := range list {
res[i] = &model.ConfDialogList{ConfDialog: v, Status: dialogStatus(v)}
}
return
}
func dialogStatus(v *model.ConfDialog) (status string) {
curr := time.Now()
switch {
case v.Stage && v.StartTime.Time().After(curr):
return "padding"
case v.Stage && v.StartTime.Time().Before(curr) && (int64(v.EndTime) == 0 || v.EndTime.Time().After(curr)):
return "active"
case !v.Stage || (int64(v.EndTime) > 0 && v.EndTime.Time().Before(curr)):
return "inactive"
default:
return ""
}
}
// DialogByID .
func (s *Service) DialogByID(c context.Context, arg *model.ArgID) (dlg *model.ConfDialog, err error) {
return s.dao.DialogByID(c, arg.ID)
}
// DialogSave .
func (s *Service) DialogSave(c context.Context, arg *model.ConfDialog) (eff int64, err error) {
var db *model.ConfDialog
if arg.ID != 0 {
if db, err = s.dao.DialogByID(c, arg.ID); err != nil {
return
}
if db != nil {
arg.Ctime = db.Ctime
arg.Stage = db.Stage
}
}
// PRD: 如果平台、app_id完全相同时生效时间不可冲突否则不允许保存
var exist []*model.ConfDialog
if exist, err = s.dao.DialogBy(c, arg.AppID, arg.Platform, arg.ID); err != nil {
return
}
for _, v := range exist {
if v.StartTime.Time().Unix() <= arg.EndTime.Time().Unix() && v.EndTime.Time().Unix() >= arg.StartTime.Time().Unix() {
err = ecode.VipDialogConflictErr
return
}
}
return s.dao.DialogSave(c, arg)
}
// DialogEnable .
func (s *Service) DialogEnable(c context.Context, arg *model.ConfDialog) (eff int64, err error) {
var db *model.ConfDialog
if arg.ID != 0 {
if db, err = s.dao.DialogByID(c, arg.ID); err != nil {
return
}
}
if db == nil || db.StartTime.Time().After(time.Now()) {
err = ecode.VipDialogTimeErr
return
}
return s.dao.DialogEnable(c, arg)
}
// DialogDel .
func (s *Service) DialogDel(c context.Context, arg *model.ArgID, operator string) (eff int64, err error) {
eff, err = s.dao.DialogDel(c, arg.ID)
log.Warn("user(%s) delete dialog(%d) effect row(%d)", operator, arg.ID, eff)
return
}

View File

@@ -0,0 +1,78 @@
package service
import (
"context"
"go-common/app/admin/main/vip/model"
"go-common/library/ecode"
xtime "go-common/library/time"
"testing"
"time"
"github.com/smartystreets/goconvey/convey"
)
func TestServiceDialogSave(t *testing.T) {
curr := xtime.Time(time.Now().Unix())
convey.Convey("DialogSave", t, func() {
dlg1 := &model.ConfDialog{ID: 1, StartTime: curr, Operator: "tommy"}
eff, err := s.DialogSave(context.TODO(), dlg1)
convey.So(err, convey.ShouldBeNil)
convey.So(eff, convey.ShouldNotBeNil)
})
convey.Convey("DialogSave2", t, func() {
dlg2 := &model.ConfDialog{ID: 2, StartTime: xtime.Time(time.Now().Unix() + 1), Operator: "tommy"}
_, err := s.DialogSave(context.TODO(), dlg2)
convey.So(err, convey.ShouldEqual, ecode.VipDialogConflictErr)
})
convey.Convey("DialogByID", t, func() {
dlg, err := s.DialogByID(context.TODO(), &model.ArgID{ID: 1})
convey.So(err, convey.ShouldBeNil)
convey.So(dlg, convey.ShouldNotBeNil)
})
convey.Convey("DialogEnable", t, func() {
eff, err := s.DialogEnable(context.TODO(), &model.ConfDialog{ID: 1, Stage: true})
convey.So(err, convey.ShouldBeNil)
convey.So(eff, convey.ShouldNotBeNil)
})
convey.Convey("DialogAll", t, func() {
res, err := s.DialogAll(context.TODO(), 0, 0, "active")
convey.So(err, convey.ShouldBeNil)
convey.So(res, convey.ShouldNotBeNil)
})
}
func TestServiceDialogDel(t *testing.T) {
convey.Convey("DialogDel", t, func() {
eff, err := s.DialogDel(context.TODO(), nil, "")
convey.So(err, convey.ShouldBeNil)
convey.So(eff, convey.ShouldNotBeNil)
})
}
func TestServiceDialogStatus(t *testing.T) {
convey.Convey("dialogStatus padding", t, func() {
v := &model.ConfDialog{Stage: true, StartTime: xtime.Time(time.Now().AddDate(1, 1, 1).Unix())}
res := dialogStatus(v)
convey.So(res, convey.ShouldEqual, "padding")
})
convey.Convey("dialogStatus active", t, func() {
v := &model.ConfDialog{Stage: true}
res := dialogStatus(v)
convey.So(res, convey.ShouldEqual, "active")
v.StartTime = xtime.Time(time.Now().AddDate(-1, 1, 1).Unix())
res = dialogStatus(v)
convey.So(res, convey.ShouldEqual, "active")
v.EndTime = xtime.Time(time.Now().AddDate(1, 1, 1).Unix())
res = dialogStatus(v)
convey.So(res, convey.ShouldEqual, "active")
})
convey.Convey("dialogStatus inactive", t, func() {
v := &model.ConfDialog{Stage: false}
res := dialogStatus(v)
convey.So(res, convey.ShouldEqual, "inactive")
v.EndTime = xtime.Time(time.Now().AddDate(-1, 1, 1).Unix())
res = dialogStatus(v)
convey.So(res, convey.ShouldEqual, "inactive")
})
}

View File

@@ -0,0 +1,85 @@
package service
import (
"context"
"time"
"go-common/app/admin/main/vip/model"
"go-common/library/ecode"
)
// JointlysByState jointlys by state.
func (s *Service) JointlysByState(c context.Context, state int8) (res []*model.Jointly, err error) {
now := time.Now().Unix()
res, err = s.dao.JointlysByState(c, state, time.Now().Unix())
for _, v := range res {
switch {
case v.StartTime > now:
v.State = model.WillEffect
case v.StartTime < now && v.EndTime > now:
v.State = model.Effect
case v.EndTime < now:
v.State = model.LoseEffect
}
}
return
}
// AddJointly add jointly.
func (s *Service) AddJointly(c context.Context, j *model.ArgAddJointly) (err error) {
if j.StartTime >= j.EndTime {
err = ecode.VipStartTimeErr
return
}
if len(j.Title) > _maxTitleLen {
err = ecode.VipTitleTooLongErr
return
}
if len(j.Content) > _maxContentLen {
err = ecode.VipContentTooLongErr
return
}
_, err = s.dao.AddJointly(c, &model.Jointly{
Title: j.Title,
Content: j.Content,
Operator: j.Operator,
StartTime: j.StartTime,
EndTime: j.EndTime,
Link: j.Link,
IsHot: j.IsHot,
})
return
}
// ModifyJointly modify jointly.
func (s *Service) ModifyJointly(c context.Context, j *model.ArgModifyJointly) (err error) {
if j.StartTime >= j.EndTime {
err = ecode.VipStartTimeErr
return
}
if len(j.Title) > _maxTitleLen {
err = ecode.VipTitleTooLongErr
return
}
if len(j.Content) > _maxContentLen {
err = ecode.VipContentTooLongErr
return
}
_, err = s.dao.UpdateJointly(c, &model.Jointly{
Title: j.Title,
Content: j.Content,
Operator: j.Operator,
Link: j.Link,
IsHot: j.IsHot,
ID: j.ID,
StartTime: j.StartTime,
EndTime: j.EndTime,
})
return
}
// DeleteJointly delete jointly .
func (s *Service) DeleteJointly(c context.Context, id int64) (err error) {
_, err = s.dao.DeleteJointly(c, id)
return
}

View File

@@ -0,0 +1,49 @@
package service
import (
"testing"
"go-common/app/admin/main/vip/model"
. "github.com/smartystreets/goconvey/convey"
)
// go test -test.v -test.run TestServiceAddJointly
func TestServiceAddJointly(t *testing.T) {
Convey("TestServiceAddJointly", t, func() {
err := s.AddJointly(c, &model.ArgAddJointly{
Title: "这是一条被修改的",
Content: "内容",
StartTime: 1433202904,
EndTime: 1433202905,
Link: "http://www.baidu.com",
IsHot: 1,
Operator: "admin",
})
So(err, ShouldBeNil)
})
}
// go test -test.v -test.run TestServiceModifyJointly
func TestServiceModifyJointly(t *testing.T) {
Convey("TestServiceModifyJointly", t, func() {
err := s.ModifyJointly(c, &model.ArgModifyJointly{
ID: 2,
Title: "无效的记录,修改",
Content: "修改内容",
Link: "http://www.baidu.com",
IsHot: 1,
Operator: "admin",
})
So(err, ShouldBeNil)
})
}
// go test -test.v -test.run TestServiceJointlysByState
func TestServiceJointlysByState(t *testing.T) {
Convey("TestServiceJointlysByState", t, func() {
res, err := s.JointlysByState(c, 2)
t.Logf("count %+v", len(res))
So(err, ShouldBeNil)
})
}

View File

@@ -0,0 +1,60 @@
package service
import (
"context"
"go-common/app/admin/main/vip/model"
"go-common/library/ecode"
"github.com/pkg/errors"
)
// MonthList .
func (s *Service) MonthList(c context.Context) (res []*model.VipMonth, err error) {
return s.dao.MonthList(c)
}
// MonthEdit .
func (s *Service) MonthEdit(c context.Context, id int64, status int8, op string) (err error) {
var (
m *model.VipMonth
)
if m, err = s.dao.GetMonth(c, id); err != nil {
err = errors.WithStack(err)
return
}
if m == nil {
err = ecode.VipMonthErr
return
}
_, err = s.dao.MonthEdit(c, id, status, op)
return
}
// PriceList .
func (s *Service) PriceList(c context.Context, mID int64) (res []*model.VipMonthPrice, err error) {
return s.dao.PriceList(c, mID)
}
// PriceAdd .
func (s *Service) PriceAdd(c context.Context, mp *model.VipMonthPrice) (err error) {
_, err = s.dao.PriceAdd(c, mp)
return
}
// PriceEdit .
func (s *Service) PriceEdit(c context.Context, mp *model.VipMonthPrice) (err error) {
var (
vmp *model.VipMonthPrice
)
if vmp, err = s.dao.GetPrice(c, mp.ID); err != nil {
err = errors.WithStack(err)
return
}
if vmp == nil {
err = ecode.VipMonthPriceErr
return
}
_, err = s.dao.PriceEdit(c, mp)
return
}

View File

@@ -0,0 +1,83 @@
package service
import (
"context"
"strings"
"time"
"go-common/app/admin/main/vip/model"
vipmol "go-common/app/service/main/vip/model"
"go-common/library/ecode"
"github.com/google/uuid"
"github.com/pkg/errors"
)
//OrderList order list.
func (s *Service) OrderList(c context.Context, arg *model.ArgPayOrder) (res []*model.PayOrder, count int64, err error) {
if count, err = s.dao.OrderCount(c, arg); err != nil {
err = errors.WithStack(err)
return
}
if res, err = s.dao.OrderList(c, arg); err != nil {
err = errors.WithStack(err)
}
return
}
//Refund refund order.
func (s *Service) Refund(c context.Context, orderNo, username string, refundAmount float64) (err error) {
var (
order *model.PayOrder
)
if order, err = s.dao.SelOrder(c, orderNo); err != nil {
err = errors.WithStack(err)
return
}
if order == nil {
err = ecode.VipOrderNoErr
return
}
if order.Status != model.SUCCESS {
err = ecode.VipOrderStatusErr
return
}
if order.ToMid > 0 {
err = ecode.VipOrderToMidErr
return
}
if order.AppID == vipmol.EleAppID {
return ecode.VipEleOrderCanNotReFundErr
}
if order.Money < refundAmount {
err = ecode.VipOrderMoneyErr
return
}
if order.Money < refundAmount+order.RefundAmount {
err = ecode.VipOrderMoneyErr
return
}
var timefmt = time.Now().Format("20060102150405")
if len(order.ThirdTradeNo) <= 0 || order.ThirdTradeNo[0:len(timefmt)] == timefmt {
err = ecode.VipOldOrderErr
return
}
refundID := strings.Replace(uuid.New().String(), "-", "", -1)[4:20]
if err = s.dao.PayRefund(c, order, refundAmount, refundID); err != nil {
err = errors.WithStack(err)
return
}
olog := new(model.PayOrderLog)
olog.OrderNo = order.OrderNo
olog.Mid = order.Mid
olog.RefundID = refundID
olog.Status = model.REFUNDING
olog.Operator = username
olog.RefundAmount = refundAmount
if err = s.dao.AddPayOrderLog(c, olog); err != nil {
err = errors.WithStack(err)
}
return
}

View File

@@ -0,0 +1,27 @@
package service
import (
"context"
"testing"
"go-common/app/admin/main/vip/model"
. "github.com/smartystreets/goconvey/convey"
)
func TestService_OrderList(t *testing.T) {
Convey("test order list", t, func() {
order := new(model.ArgPayOrder)
order.Mid = 1001
res, count, err := s.OrderList(context.TODO(), order)
t.Logf("orderlist len:%+v count:%v", res, count)
So(err, ShouldBeNil)
})
}
func TestService_Refund(t *testing.T) {
Convey("test refund ", t, func() {
err := s.Refund(context.TODO(), "93035846180822184113", "zhaozhihao", 10)
So(err, ShouldBeNil)
})
}

View File

@@ -0,0 +1,304 @@
package service
import (
"context"
"go-common/app/admin/main/vip/model"
"go-common/library/ecode"
)
// VipPriceConfigs get vip price configs.
func (s *Service) VipPriceConfigs(c context.Context, arg *model.ArgVipPrice) (res []*model.VipPriceConfig, err error) {
var (
vpcs []*model.VipPriceConfig
mvd map[int64]*model.VipDPriceConfig
)
if vpcs, err = s.dao.VipPriceConfigs(c); err != nil {
return
}
if mvd, err = s.dao.VipPriceDiscountConfigs(c); err != nil {
return
}
for _, item := range vpcs {
if arg.Plat != -1 && item.Plat != arg.Plat {
continue
}
if arg.Month != -1 && item.Month != arg.Month {
continue
}
if arg.SubType != -1 && item.SubType != arg.SubType {
continue
}
if arg.SuitType != -1 && item.SuitType != arg.SuitType {
continue
}
if vdc, ok := mvd[item.ID]; ok {
item.NPrice = vdc.DPrice
item.PdID = vdc.PdID
} else {
item.NPrice = item.OPrice
}
res = append(res, item)
}
return
}
// VipPriceConfigID get vip price config by id.
func (s *Service) VipPriceConfigID(c context.Context, arg *model.ArgVipPriceID) (res *model.VipPriceConfig, err error) {
res, err = s.dao.VipPriceConfigID(c, arg)
return
}
// AddVipPriceConfig add vip price config.
func (s *Service) AddVipPriceConfig(c context.Context, arg *model.ArgAddOrUpVipPrice) (err error) {
var count int64
if len(arg.Superscript) > 18 {
err = ecode.VipPanelSuperscriptTooLongErr
return
}
// 平台校验
platForm, err := s.dao.PlatformByID(c, int64(arg.Plat))
if err != nil || platForm == nil {
err = ecode.VipPanelPlatNotExitErr
return
}
// 价格校验
if arg.OPrice <= 0 {
err = ecode.VipPanelValidOPriceErr
return
}
// 面版冲突
if count, err = s.dao.VipPriceConfigUQCheck(c, arg); err != nil {
return
}
if count > 0 {
err = ecode.VipPanelConfNotUQErr
return
}
vpc := &model.VipPriceConfig{
Plat: arg.Plat,
PdName: arg.PdName,
PdID: arg.PdID,
SuitType: arg.SuitType,
Month: arg.Month,
SubType: arg.SubType,
OPrice: arg.OPrice,
Remark: arg.Remark,
Status: model.VipPriceConfigStatusON,
Operator: arg.Operator,
OpID: arg.OpID,
Superscript: arg.Superscript,
Selected: arg.Selected,
StartBuild: arg.StartBuild,
EndBuild: arg.EndBuild,
}
err = s.dao.AddVipPriceConfig(c, vpc)
return
}
// UpVipPriceConfig update vip price config.
func (s *Service) UpVipPriceConfig(c context.Context, arg *model.ArgAddOrUpVipPrice) (err error) {
var (
count int64
max float64
ovpc *model.VipPriceConfig
)
if len(arg.Superscript) > 18 {
err = ecode.VipPanelSuperscriptTooLongErr
return
}
if ovpc, err = s.dao.VipPriceConfigID(c, &model.ArgVipPriceID{ID: arg.ID}); err != nil {
return
}
if max, err = s.dao.VipMaxPriceDiscount(c, arg); err != nil {
return
}
if ovpc == nil {
err = ecode.VipPanelConfNotExistErr
return
}
// 价格校验
if arg.OPrice <= 0 {
err = ecode.VipPanelValidOPriceErr
return
}
if arg.OPrice < max {
err = ecode.VipPanelValidDPriceErr
return
}
if arg.Plat != ovpc.Plat || arg.Month != ovpc.Month || arg.SubType != ovpc.SubType || arg.SuitType != ovpc.SuitType ||
arg.StartBuild != ovpc.StartBuild || arg.EndBuild != ovpc.EndBuild {
// 面版冲突
if count, err = s.dao.VipPriceConfigUQCheck(c, arg); err != nil {
return
}
if count > 0 {
err = ecode.VipPanelConfNotUQErr
return
}
}
vpc := &model.VipPriceConfig{
ID: arg.ID,
Plat: arg.Plat,
PdName: arg.PdName,
PdID: arg.PdID,
SuitType: arg.SuitType,
Month: arg.Month,
SubType: arg.SubType,
OPrice: arg.OPrice,
Remark: arg.Remark,
Status: model.VipPriceConfigStatusON,
Operator: arg.Operator,
OpID: arg.OpID,
Superscript: arg.Superscript,
Selected: arg.Selected,
StartBuild: arg.StartBuild,
EndBuild: arg.EndBuild,
}
err = s.dao.UpVipPriceConfig(c, vpc)
return
}
// DelVipPriceConfig delete vip price config.
func (s *Service) DelVipPriceConfig(c context.Context, arg *model.ArgVipPriceID) (err error) {
err = s.dao.DelVipPriceConfig(c, arg)
return
}
// VipDPriceConfigs get discount price config list.
func (s *Service) VipDPriceConfigs(c context.Context, arg *model.ArgVipPriceID) (res []*model.VipDPriceConfig, err error) {
res, err = s.dao.VipDPriceConfigs(c, arg)
return
}
// VipDPriceConfigID get discount price config by id.
func (s *Service) VipDPriceConfigID(c context.Context, arg *model.ArgVipDPriceID) (res *model.VipDPriceConfig, err error) {
res, err = s.dao.VipDPriceConfigID(c, arg)
return
}
// AddVipDPriceConfig add vip discount price config.
func (s *Service) AddVipDPriceConfig(c context.Context, arg *model.ArgAddOrUpVipDPrice) (err error) {
var (
vpc *model.VipPriceConfig
mvd map[int64]*model.VipDPriceConfig
)
if vpc, err = s.dao.VipPriceConfigID(c, &model.ArgVipPriceID{ID: arg.ID}); err != nil {
return
}
if vpc == nil {
err = ecode.VipPanelConfNotExistErr
return
}
// if vpc.CheckProductID(arg) {
// err = ecode.VipPanelProductIDNotNilErr
// return
// }
if vpc.OPrice < arg.DPrice {
err = ecode.VipPanelValidDPriceErr
return
}
if vpc.SubType != model.AutoRenew && arg.FirstPrice > 0 {
return ecode.VipPanelFirstPriceNotSupportErr
}
if arg.ETime != 0 && arg.STime >= arg.ETime {
err = ecode.VipPanelSTGeqETErr
return
}
// 面版冲突
if mvd, err = s.dao.VipDPriceConfigUQTime(c, arg); err != nil {
return
}
if len(mvd) > 0 {
err = ecode.VipPanelValidTimeErr
return
}
nvdc := &model.VipDPriceConfig{
ID: arg.ID,
PdID: arg.PdID,
DPrice: arg.DPrice,
STime: arg.STime,
ETime: arg.ETime,
Remark: arg.Remark,
Operator: arg.Operator,
OpID: arg.OpID,
FirstPrice: arg.FirstPrice,
}
err = s.dao.AddVipDPriceConfig(c, nvdc)
return
}
// UpVipDPriceConfig update vip discount price config.
func (s *Service) UpVipDPriceConfig(c context.Context, arg *model.ArgAddOrUpVipDPrice) (err error) {
var (
ovpc *model.VipPriceConfig
ovdc *model.VipDPriceConfig
mvd map[int64]*model.VipDPriceConfig
)
if ovpc, err = s.dao.VipPriceConfigID(c, &model.ArgVipPriceID{ID: arg.ID}); err != nil {
return
}
if ovpc == nil {
err = ecode.VipPanelConfNotExistErr
return
}
if ovdc, err = s.dao.VipDPriceConfigID(c, &model.ArgVipDPriceID{DisID: arg.DisID}); err != nil {
return
}
// if ovpc.CheckProductID(arg) {
// err = ecode.VipPanelProductIDNotNilErr
// return
// }
if ovpc.SubType != model.AutoRenew && arg.FirstPrice > 0 {
return ecode.VipPanelFirstPriceNotSupportErr
}
if ovpc.OPrice < arg.DPrice {
err = ecode.VipPanelValidDPriceErr
return
}
if arg.ETime != 0 && arg.STime >= arg.ETime {
err = ecode.VipPanelSTGeqETErr
return
}
if arg.STime != ovdc.STime || arg.ETime != ovdc.ETime {
// 面版冲突
if mvd, err = s.dao.VipDPriceConfigUQTime(c, arg); err != nil {
return
}
if _, ok := mvd[arg.DisID]; ok {
delete(mvd, arg.DisID)
}
if len(mvd) > 0 {
err = ecode.VipPanelValidTimeErr
return
}
}
vdc := &model.VipDPriceConfig{
DisID: arg.DisID,
ID: arg.ID,
PdID: arg.PdID,
DPrice: arg.DPrice,
STime: arg.STime,
ETime: arg.ETime,
Remark: arg.Remark,
Operator: arg.Operator,
OpID: arg.OpID,
FirstPrice: arg.FirstPrice,
}
err = s.dao.UpVipDPriceConfig(c, vdc)
return
}
// DelVipDPriceConfig delete vip discount price config.
func (s *Service) DelVipDPriceConfig(c context.Context, arg *model.ArgVipDPriceID) (err error) {
err = s.dao.DelVipDPriceConfig(c, arg)
return
}
// PanelPlatFormTypes .
func (s *Service) PanelPlatFormTypes(c context.Context) (res []*model.TypePlatform, err error) {
if res, err = s.dao.PlatformTypes(c); err != nil {
return
}
return
}

View File

@@ -0,0 +1,144 @@
package service
import (
"context"
"fmt"
"go-common/app/admin/main/vip/model"
xtime "go-common/library/time"
"testing"
"time"
. "github.com/smartystreets/goconvey/convey"
)
func TestServiceVipPriceConfigs(t *testing.T) {
Convey("Test_VipPriceConfigs", t, func() {
av := &model.ArgVipPrice{
Plat: 1,
Month: 1,
SubType: 1,
SuitType: 1,
}
res, err := s.VipPriceConfigs(context.TODO(), av)
So(err, ShouldBeNil)
So(res, ShouldNotBeNil)
})
}
func TestServiceVipPriceConfigID(t *testing.T) {
Convey("Test_VipPriceConfigID", t, func() {
res, err := s.VipPriceConfigID(context.TODO(), &model.ArgVipPriceID{ID: 1})
So(err, ShouldBeNil)
So(res, ShouldNotBeNil)
})
}
func TestServiceAddVipPriceConfig(t *testing.T) {
Convey("Test_AddVipPriceConfig", t, func() {
aavpc := &model.ArgAddOrUpVipPrice{
Plat: 1,
PdName: "xxx",
PdID: "xxx",
Month: 1,
SubType: 1,
SuitType: 0,
OPrice: 1,
}
err := s.AddVipPriceConfig(context.TODO(), aavpc)
So(err, ShouldBeNil)
})
}
func TestServiceUpVipPriceConfig(t *testing.T) {
Convey("Test_UpVipPriceConfig", t, func() {
aavpc := &model.ArgAddOrUpVipPrice{
ID: 235,
Plat: 1,
PdName: "xxx",
PdID: "xxx",
Month: 1,
SubType: 1,
SuitType: 1,
OPrice: 1,
StartBuild: 0,
EndBuild: 103,
}
err := s.UpVipPriceConfig(context.TODO(), aavpc)
So(err, ShouldBeNil)
})
}
func TestServiceDelVipPriceConfig(t *testing.T) {
advp := &model.ArgVipPriceID{ID: 1}
Convey("Test_DelVipPriceConfig", t, func() {
err := s.DelVipPriceConfig(context.TODO(), advp)
So(err, ShouldBeNil)
})
}
func TestServiceVipDPriceConfigs(t *testing.T) {
Convey("Test_VipDPriceConfigs", t, func() {
av := &model.ArgVipPriceID{
ID: 155,
}
res, err := s.VipDPriceConfigs(context.TODO(), av)
fmt.Println("res", res)
So(err, ShouldBeNil)
So(res, ShouldNotBeNil)
})
}
func TestServiceVipDPriceConfigID(t *testing.T) {
Convey("Test_VipDPriceConfigID", t, func() {
res, err := s.VipDPriceConfigID(context.TODO(), &model.ArgVipDPriceID{DisID: 10})
fmt.Println("res", res.FirstPrice)
So(err, ShouldBeNil)
So(res, ShouldNotBeNil)
})
}
func TestServiceAddVipDPriceConfig(t *testing.T) {
Convey("Test_AddVipDPriceConfig", t, func() {
aavpc := &model.ArgAddOrUpVipDPrice{
DisID: 1,
ID: 155,
PdID: "tv.danmaku.bilianimexAuto3VIP",
DPrice: 15,
STime: xtime.Time(time.Now().Unix()) + 100000000000,
ETime: xtime.Time(time.Now().Unix()) + 200000000000,
Remark: "test2",
Operator: "admin",
OpID: 11,
FirstPrice: 13,
}
err := s.AddVipDPriceConfig(context.TODO(), aavpc)
So(err, ShouldBeNil)
})
}
func TestServiceUpVipDPriceConfig(t *testing.T) {
Convey("Test_UpVipDPriceConfig", t, func() {
aavpc := &model.ArgAddOrUpVipDPrice{
DisID: 11,
ID: 155,
PdID: "tv.danmaku.bilianimexAuto3VIP",
DPrice: 1.1,
STime: xtime.Time(time.Now().Unix()) + 100000000000,
ETime: xtime.Time(time.Now().Unix()) + 200000000000,
Remark: "test2",
Operator: "admin",
OpID: 11,
FirstPrice: 11,
}
err := s.UpVipDPriceConfig(context.TODO(), aavpc)
So(err, ShouldBeNil)
})
}
func TestServiceDelVipDPriceConfig(t *testing.T) {
advp := &model.ArgVipDPriceID{DisID: 1}
Convey("Test_DelVipDPriceConfig", t, func() {
err := s.DelVipDPriceConfig(context.TODO(), advp)
So(err, ShouldBeNil)
})
}

View File

@@ -0,0 +1,46 @@
package service
import (
"context"
"go-common/app/admin/main/vip/model"
"go-common/library/ecode"
"go-common/library/log"
)
// PlatformAll .
func (s *Service) PlatformAll(c context.Context, order string) (res []*model.ConfPlatform, err error) {
if res, err = s.dao.PlatformAll(c, order); err != nil {
return
}
return
}
// PlatformByID .
func (s *Service) PlatformByID(c context.Context, arg *model.ArgID) (dlg *model.ConfPlatform, err error) {
return s.dao.PlatformByID(c, arg.ID)
}
// PlatformSave .
func (s *Service) PlatformSave(c context.Context, arg *model.ConfPlatform) (eff int64, err error) {
return s.dao.PlatformSave(c, arg)
}
// PlatformDel .
func (s *Service) PlatformDel(c context.Context, arg *model.ArgID, operator string) (eff int64, err error) {
pcount, err := s.dao.CountVipPriceConfigByPlat(c, arg.ID)
if err != nil {
return
}
dcount, err := s.dao.CountDialogByPlatID(c, arg.ID)
if err != nil {
return
}
if pcount > 0 || dcount > 0 {
err = ecode.VipPlatformConfDelErr
return
}
eff, err = s.dao.PlatformDel(c, arg.ID, operator)
log.Warn("user(%s) delete dialog(%d) effect row(%d)", operator, arg.ID, eff)
return
}

View File

@@ -0,0 +1,266 @@
package service
import (
"context"
"go-common/app/admin/main/vip/model"
"go-common/library/ecode"
"go-common/library/log"
"github.com/jinzhu/gorm"
"github.com/pkg/errors"
"golang.org/x/sync/errgroup"
)
// Privileges Privilege list.
func (s *Service) Privileges(c context.Context, langType int8) (res []*model.PrivilegeResp, err error) {
var (
ps []*model.Privilege
prs []*model.PrivilegeResources
)
if ps, err = s.dao.PrivilegeList(c, langType); err != nil {
err = errors.WithStack(err)
return
}
if prs, err = s.dao.PrivilegeResourcesList(c); err != nil {
err = errors.WithStack(err)
return
}
prmap := make(map[int64]map[int8]*model.PrivilegeResources, len(prs))
for _, v := range prs {
if prmap[v.PID] == nil {
prmap[v.PID] = map[int8]*model.PrivilegeResources{}
}
prmap[v.PID][v.Type] = v
}
for i, v := range ps {
r := &model.PrivilegeResp{
ID: v.ID,
Name: v.Name,
Title: v.Title,
Explain: v.Explain,
Type: v.Type,
Operator: v.Operator,
State: v.State,
IconURL: v.IconURL,
IconGrayURL: v.IconGrayURL,
LangType: v.LangType,
Order: int64(i),
}
if prmap[v.ID] != nil && prmap[v.ID][model.WebResources] != nil {
r.WebLink = prmap[v.ID][model.WebResources].Link
r.WebImageURL = prmap[v.ID][model.WebResources].ImageURL
}
if prmap[v.ID] != nil && prmap[v.ID][model.AppResources] != nil {
r.AppLink = prmap[v.ID][model.AppResources].Link
r.AppImageURL = prmap[v.ID][model.AppResources].ImageURL
}
res = append(res, r)
}
return
}
// UpdatePrivilegeState update privilege state.
func (s *Service) UpdatePrivilegeState(c context.Context, p *model.Privilege) (err error) {
if _, err = s.dao.UpdateStatePrivilege(c, p); err != nil {
err = errors.WithStack(err)
}
return
}
// DeletePrivilege delete privilege .
func (s *Service) DeletePrivilege(c context.Context, id int64) (err error) {
if _, err = s.dao.DeletePrivilege(c, id); err != nil {
err = errors.WithStack(err)
}
return
}
// AddPrivilege add privilege.
func (s *Service) AddPrivilege(c context.Context, req *model.ArgAddPrivilege, img *model.ArgImage) (err error) {
var (
iconURL string
iconGrayURL string
order int64
webImageURL string
appImageURL string
id int64
tx *gorm.DB
)
if iconURL, iconGrayURL, webImageURL, appImageURL, err = s.uploadImage(c, img); err != nil {
err = errors.WithStack(err)
return
}
if iconURL == "" || iconGrayURL == "" {
err = ecode.VipFileUploadFaildErr
return
}
if order, err = s.dao.MaxOrder(c); err != nil {
err = errors.WithStack(err)
return
}
order++
tx = s.dao.BeginGormTran(c)
defer func() {
if err != nil {
if err1 := tx.Rollback(); err1 != nil {
err = errors.Wrapf(err, "tx.Rollback(%+v)", req)
}
return
}
if err = tx.Commit().Error; err != nil {
err = errors.Wrapf(err, "tx.Commit(%+v)", req)
}
}()
if id, err = s.dao.AddPrivilege(tx, &model.Privilege{
Name: req.Name,
Title: req.Title,
Explain: req.Explain,
Type: req.Type,
Operator: req.Operator,
State: model.NormalPrivilege,
IconURL: iconURL,
IconGrayURL: iconGrayURL,
Order: order,
LangType: req.LangType,
}); err != nil {
err = errors.WithStack(err)
return
}
if _, err = s.dao.AddPrivilegeResources(tx, &model.PrivilegeResources{
PID: id,
Link: req.AppLink,
ImageURL: appImageURL,
Type: model.AppResources,
}); err != nil {
err = errors.WithStack(err)
return
}
if _, err = s.dao.AddPrivilegeResources(tx, &model.PrivilegeResources{
PID: id,
Link: req.WebLink,
ImageURL: webImageURL,
Type: model.WebResources,
}); err != nil {
err = errors.WithStack(err)
return
}
return
}
// UpdatePrivilege update privilege.
func (s *Service) UpdatePrivilege(c context.Context, req *model.ArgUpdatePrivilege, img *model.ArgImage) (err error) {
var (
iconURL string
iconGrayURL string
webImageURL string
appImageURL string
tx *gorm.DB
)
if iconURL, iconGrayURL, webImageURL, appImageURL, err = s.uploadImage(c, img); err != nil {
err = errors.WithStack(err)
return
}
tx = s.dao.BeginGormTran(c)
defer func() {
if err != nil {
if err1 := tx.Rollback().Error; err1 != nil {
err = errors.Wrapf(err, "tx.Rollback(%+v)", req)
}
return
}
if err = tx.Commit().Error; err != nil {
err = errors.Wrapf(err, "tx.Commit(%+v)", req)
}
}()
if _, err = s.dao.UpdatePrivilege(tx, &model.Privilege{
ID: req.ID,
Name: req.Name,
Title: req.Title,
Explain: req.Explain,
Type: req.Type,
Operator: req.Operator,
State: model.NormalPrivilege,
IconURL: iconURL,
IconGrayURL: iconGrayURL,
}); err != nil {
err = errors.WithStack(err)
return
}
if _, err = s.dao.UpdatePrivilegeResources(tx, &model.PrivilegeResources{
PID: req.ID,
Link: req.AppLink,
ImageURL: appImageURL,
Type: model.AppResources,
}); err != nil {
err = errors.WithStack(err)
return
}
if _, err = s.dao.UpdatePrivilegeResources(tx, &model.PrivilegeResources{
PID: req.ID,
Link: req.WebLink,
ImageURL: webImageURL,
Type: model.WebResources,
}); err != nil {
err = errors.WithStack(err)
return
}
return
}
func (s *Service) uploadImage(c context.Context, req *model.ArgImage) (iconURL, iconGrayURL, webImageURL, appImageURL string, err error) {
var g errgroup.Group
if req.IconFileType == "" &&
req.IconGrayFileType == "" &&
req.WebImageFileType == "" &&
req.AppImageFileType == "" {
return
}
if req.IconFileType != "" {
g.Go(func() (err error) {
//update icon.
if iconURL, err = s.dao.Upload(c, "", req.IconFileType, req.IconBody, s.c.Bfs); err != nil {
log.Error("d.Upload iconURL(%+v) error(%v)", req, err)
}
return
})
}
if req.IconGrayFileType != "" {
g.Go(func() (err error) {
//update gray icon.
if iconGrayURL, err = s.dao.Upload(c, "", req.IconGrayFileType, req.IconGrayBody, s.c.Bfs); err != nil {
log.Error("d.Upload iconGrayURL(%+v) error(%v)", req, err)
}
return
})
}
if req.WebImageFileType != "" {
g.Go(func() (err error) {
if webImageURL, err = s.dao.Upload(c, "", req.WebImageFileType, req.WebImageBody, s.c.Bfs); err != nil {
log.Error("d.Upload webImageURL(%+v) error(%v)", req, err)
}
return
})
}
if req.AppImageFileType != "" {
g.Go(func() (err error) {
if appImageURL, err = s.dao.Upload(c, "", req.AppImageFileType, req.AppImageBody, s.c.Bfs); err != nil {
log.Error("d.Upload appImageURL(%+v) error(%v)", req, err)
}
return
})
}
if err = g.Wait(); err != nil {
log.Error("g.Wait error(%v)", err)
return
}
return
}
// UpdateOrder update order.
func (s *Service) UpdateOrder(c context.Context, a *model.ArgOrder) (err error) {
if _, err = s.dao.UpdateOrder(c, a.AID, a.BID); err != nil {
err = errors.WithStack(err)
}
return
}

View File

@@ -0,0 +1,132 @@
package service
import (
"bytes"
"context"
"image/png"
"os"
"testing"
"go-common/app/admin/main/vip/model"
. "github.com/smartystreets/goconvey/convey"
)
// go test -test.v -test.run TestServicePrivileges
func TestServicePrivileges(t *testing.T) {
Convey("TestServicePrivileges", t, func() {
res, err := s.Privileges(context.TODO(), 0)
for _, v := range res {
t.Logf("%+v", v)
}
So(err, ShouldBeNil)
})
}
// go test -test.v -test.run TestUpdatePrivilegeState
func TestUpdatePrivilegeState(t *testing.T) {
Convey("TestUpdatePrivilegeState", t, func() {
err := s.UpdatePrivilegeState(context.TODO(), &model.Privilege{
ID: 4,
State: 1,
})
So(err, ShouldBeNil)
})
}
// go test -test.v -test.run TestDeletePrivilege
func TestDeletePrivilege(t *testing.T) {
Convey("TestDeletePrivilege", t, func() {
err := s.DeletePrivilege(context.TODO(), 4)
So(err, ShouldBeNil)
})
}
// go test -test.v -test.run TestUpdateOrder
func TestUpdateOrder(t *testing.T) {
Convey("TestUpdateOrder", t, func() {
err := s.UpdateOrder(context.TODO(), &model.ArgOrder{
AID: 5,
BID: 4,
})
So(err, ShouldBeNil)
})
}
// go test -test.v -test.run TestServiceUpload
func TestServiceUpload(t *testing.T) {
Convey("TestServiceUpload", t, func() {
file, _ := os.Open("/Users/baihai/Documents/test.png")
So(file, ShouldNotBeNil)
buf := new(bytes.Buffer)
img, _ := png.Decode(file)
png.Encode(buf, img)
bys := buf.Bytes()
t.Logf("conf %+v", s.c.Bfs)
iconURL, iconGrayURL, webImageURL, appImageURL, err := s.uploadImage(context.TODO(), &model.ArgImage{
IconBody: bys,
IconFileType: "image/png",
IconGrayBody: bys,
IconGrayFileType: "image/png",
})
t.Logf("url iconURL:%s iconGrayURL:%s webImageURL:%s appImageURL:%s", iconURL, iconGrayURL, webImageURL, appImageURL)
So(err, ShouldBeNil)
})
}
// go test -test.v -test.run TestServiceAddPrivilege
func TestServiceAddPrivilege(t *testing.T) {
Convey("TestServiceAddPrivilege", t, func() {
file, _ := os.Open("/Users/baihai/Documents/test.png")
So(file, ShouldNotBeNil)
buf := new(bytes.Buffer)
img, _ := png.Decode(file)
png.Encode(buf, img)
bys := buf.Bytes()
t.Logf("conf %+v", s.c.Bfs)
err := s.AddPrivilege(context.TODO(), &model.ArgAddPrivilege{
Name: "超级",
Title: "超级标题",
Explain: "超级内容",
Type: 0,
Operator: "admin",
WebLink: "http://www.baidu.com",
AppLink: "http://www.baidu.com",
}, &model.ArgImage{
IconBody: bys,
IconFileType: "image/png",
IconGrayBody: bys,
IconGrayFileType: "image/png",
})
So(err, ShouldBeNil)
})
}
// go test -test.v -test.run TestServiceUpdatePrivilege
func TestServiceUpdatePrivilege(t *testing.T) {
Convey("TestServiceUpdatePrivilege", t, func() {
file, _ := os.Open("/Users/baihai/Documents/test.png")
So(file, ShouldNotBeNil)
buf := new(bytes.Buffer)
img, _ := png.Decode(file)
png.Encode(buf, img)
bys := buf.Bytes()
t.Logf("conf %+v", s.c.Bfs)
err := s.UpdatePrivilege(context.TODO(), &model.ArgUpdatePrivilege{
ID: 3,
Name: "超级",
Title: "超级标题",
Explain: "超级内容",
Type: 0,
Operator: "admin",
WebLink: "http://www.baidu.com",
AppLink: "http://www.baidu.com",
}, &model.ArgImage{
IconBody: bys,
IconFileType: "image/png",
IconGrayBody: bys,
IconGrayFileType: "image/png",
})
So(err, ShouldBeNil)
})
}

View File

@@ -0,0 +1,264 @@
package service
import (
"context"
"encoding/json"
"fmt"
"time"
"go-common/app/admin/main/vip/model"
"go-common/library/ecode"
"go-common/library/log"
xtime "go-common/library/time"
"github.com/pkg/errors"
)
// const .
const (
_linkTypeH5 = 7
_linkTypeApp = 10
)
// SavePushData save push data
func (s *Service) SavePushData(c context.Context, arg *model.VipPushData) (err error) {
if err = s.checkPushData(arg); err != nil {
err = errors.WithStack(err)
return
}
if arg.ID == 0 {
arg.ProgressStatus = model.NotStart
arg.Status = model.Normal
if _, err = s.dao.AddPushData(c, arg); err != nil {
err = errors.WithStack(err)
}
return
}
var pushData *model.VipPushData
if pushData, err = s.dao.GetPushData(c, arg.ID); err != nil {
err = errors.WithStack(err)
return
}
if pushData == nil {
err = ecode.VipPushDataNotExitErr
return
}
if pushData.Status == model.Fail {
err = ecode.VipPushDataUpdateErr
return
}
if pushData.ProgressStatus == model.Started {
err = ecode.VipPushDataUpdateErr
return
}
if pushData.GroupName != arg.GroupName || !pushData.EffectStartDate.Time().Equal(arg.EffectStartDate.Time()) {
if !(pushData.Status == model.Normal && pushData.ProgressStatus == model.NotStart) {
err = ecode.VipPushDataUpdateErr
return
}
}
arg.ProgressStatus = pushData.ProgressStatus
if pushData.PushedCount == arg.PushTotalCount {
arg.ProgressStatus = model.Started
}
if _, err = s.dao.UpdatePushData(c, arg); err != nil {
err = errors.WithStack(err)
}
return
}
func (s *Service) checkPushData(arg *model.VipPushData) (err error) {
if len(arg.GroupName) > 10 {
err = ecode.VipPushGroupLenErr
return
}
if len(arg.Title) > 30 {
err = ecode.VipPushTitleLenErr
return
}
if len(arg.Content) > 200 {
err = ecode.VipPushContentLenErr
return
}
if arg.LinkType != _linkTypeH5 && arg.LinkType != _linkTypeApp {
err = ecode.VipPushLinkTypeErr
return
}
if arg.EffectEndDate.Time().Before(arg.EffectStartDate.Time()) {
err = ecode.VipPushEffectTimeErr
return
}
duration := arg.EffectEndDate.Time().Sub(arg.EffectStartDate.Time())
day := duration.Hours() / 24
arg.PushTotalCount = int32(day) + 1
if _, err = time.Parse("15:04:05", arg.PushStartTime); err != nil {
err = ecode.VipPushFmtTimeErr
return
}
if _, err = time.Parse("15:04:05", arg.PushEndTime); err != nil {
err = ecode.VipPushFmtTimeErr
return
}
platformMap := make(map[string]*model.PushDataPlatform)
platformArr := make([]*model.PushDataPlatform, 0)
var (
data []byte
key string
condition string
ok bool
)
if err = json.Unmarshal([]byte(arg.Platform), &platformArr); err != nil {
log.Error("error(%+v)", err)
err = ecode.VipPushPlatformErr
return
}
for _, v := range platformArr {
if key, ok = model.PushPlatformNameMap[v.Name]; !ok {
err = ecode.VipPushPlatformErr
return
}
if condition, ok = model.ConditionNameMap[v.Condition]; !ok {
err = ecode.VipPushPlatformErr
return
}
v.Condition = condition
platformMap[key] = v
}
if data, err = json.Marshal(platformMap); err != nil {
err = errors.WithStack(err)
return
}
arg.Platform = string(data)
return
}
// GetPushData get push data
func (s *Service) GetPushData(c context.Context, id int64) (res *model.VipPushData, err error) {
if res, err = s.dao.GetPushData(c, id); err != nil {
err = errors.WithStack(err)
return
}
if res == nil {
return
}
res.PushProgress = fmt.Sprintf("%v/%v", res.PushedCount, res.PushTotalCount)
if err = s.fmtPushDataPlatform(res); err != nil {
err = errors.WithStack(err)
}
return
}
// DisablePushData .
func (s *Service) DisablePushData(c context.Context, id int64) (err error) {
var (
res *model.VipPushData
now = time.Now()
)
if res, err = s.dao.GetPushData(c, id); err != nil {
err = errors.WithStack(err)
return
}
if res == nil {
err = ecode.VipPushDataNotExitErr
return
}
if !(res.ProgressStatus == model.Starting && res.Status == model.Normal && res.DisableType == model.UnDisable) {
err = ecode.VipPushDataDisableErr
return
}
duration := now.Sub(res.EffectStartDate.Time())
day := duration.Hours() / 24
res.PushTotalCount = int32(day) + 1
res.EffectEndDate = xtime.Time(now.Unix())
if res.PushTotalCount > res.PushedCount {
res.PushTotalCount--
}
if res.PushTotalCount == res.PushedCount {
res.ProgressStatus = model.Started
}
if err = s.dao.DisablePushData(c, res); err != nil {
err = errors.WithStack(err)
}
return
}
// DelPushData .
func (s *Service) DelPushData(c context.Context, id int64) (err error) {
var res *model.VipPushData
if res, err = s.dao.GetPushData(c, id); err != nil {
err = errors.WithStack(err)
return
}
if res == nil {
err = ecode.VipPushDataNotExitErr
return
}
if !(res.ProgressStatus == model.NotStart && res.Status == model.Normal) {
err = ecode.VipPushDataDelErr
return
}
if err = s.dao.DelPushData(c, id); err != nil {
err = errors.WithStack(err)
}
return
}
// PushDatas get push datas
func (s *Service) PushDatas(c context.Context, arg *model.ArgPushData) (res []*model.VipPushData, count int64, err error) {
if count, err = s.dao.PushDataCount(c, arg); err != nil {
err = errors.WithStack(err)
return
}
if res, err = s.dao.PushDatas(c, arg); err != nil {
err = errors.WithStack(err)
return
}
for _, v := range res {
v.PushProgress = fmt.Sprintf("%v/%v", v.PushedCount, v.PushTotalCount)
}
return
}
func (s *Service) fmtPushDataPlatform(res *model.VipPushData) (err error) {
var platformArr []*model.PushDataPlatform
platform := make(map[string]*model.PushDataPlatform)
if err = json.Unmarshal([]byte(res.Platform), &platform); err != nil {
err = errors.WithStack(err)
return
}
for k, v := range platform {
r := new(model.PushDataPlatform)
r.Name = model.PushPlatformMap[k]
r.Build = v.Build
r.Condition = model.ConditionMap[v.Condition]
platformArr = append(platformArr, r)
}
res.PlatformArr = platformArr
return
}

View File

@@ -0,0 +1,57 @@
package service
import (
"context"
"encoding/json"
"testing"
"time"
xtime "go-common/library/time"
"go-common/app/admin/main/vip/model"
. "github.com/smartystreets/goconvey/convey"
)
func TestService_GetPushData(t *testing.T) {
Convey("getpushData should be nil", t, func() {
id := 1
res, err := s.GetPushData(context.TODO(), int64(id))
bytes, _ := json.Marshal(res)
t.Logf("%+v", string(bytes))
So(err, ShouldBeNil)
})
}
func TestService_SavePushData(t *testing.T) {
Convey("save push data should be nil", t, func() {
arg := new(model.VipPushData)
arg.ID = 1
arg.GroupName = "test01"
arg.Title = "title"
arg.Content = "content"
arg.Platform = "[{\"name\":\"Android\",\"condition\":\"=\",\"build\":1},{\"name\":\"iPhone\",\"condition\":\"<=\",\"build\":2},{\"name\":\"iPad\",\"condition\":\"=\",\"build\":3}]"
arg.LinkType = 10
arg.ExpiredDayStart = -1
arg.ExpiredDayEnd = 10
arg.EffectStartDate = xtime.Time(time.Now().Unix())
arg.EffectEndDate = xtime.Time(time.Now().AddDate(0, 0, 7).Unix())
arg.PushStartTime = "18:00:00"
arg.PushEndTime = "20:00:00"
err := s.SavePushData(context.TODO(), arg)
So(err, ShouldBeNil)
})
}
func TestService_PushDatas(t *testing.T) {
Convey("push data should be nil", t, func() {
arg := new(model.ArgPushData)
arg.Status = 0
arg.ProgressStatus = 0
res, count, err := s.PushDatas(context.TODO(), arg)
bytes, _ := json.Marshal(res)
t.Logf("res(%+v) count(%v) ", string(bytes), count)
So(err, ShouldBeNil)
})
}

View File

@@ -0,0 +1,680 @@
package service
import (
"context"
"crypto/md5"
"encoding/hex"
"fmt"
"math"
"math/rand"
"time"
"go-common/app/admin/main/vip/model"
"go-common/library/database/sql"
"go-common/library/ecode"
"go-common/library/log"
xtime "go-common/library/time"
"github.com/pkg/errors"
)
// QueryPool query pool
func (s *Service) QueryPool(c context.Context, r *model.ResoucePoolBo) (res []*model.VipResourcePool, count int, err error) {
var (
batch *model.VipResourceBatch
PN int
PS int
)
PN = r.PN
PS = r.PS
if batch, err = s.dao.SelBatchRow(c, r.BatchID); err != nil {
return
}
if r.BatchID != 0 {
r.ID = -1
}
if batch != nil {
r.ID = batch.PoolID
}
if count, err = s.dao.SelCountPool(c, r); err != nil || count == 0 {
return
}
if res, err = s.dao.SelPool(c, r, PN, PS); err != nil {
return
}
return
}
// PoolInfo pool info
func (s *Service) PoolInfo(c context.Context, id int) (res *model.VipResourcePool, err error) {
if res, err = s.dao.SelPoolRow(c, id); err != nil {
return
}
return
}
// AddPool .
func (s *Service) AddPool(c context.Context, r *model.ResoucePoolBo) (err error) {
var (
p *model.VipResourcePool
)
if err = s.verificationPool(r); err != nil {
return
}
if p, err = s.dao.SelPoolByName(c, r.PoolName); err != nil {
return
}
if p != nil {
err = ecode.VipPoolNameExitErr
return
}
if _, err = s.dao.AddPool(c, r); err != nil {
return
}
return
}
func (s *Service) verificationPool(r *model.ResoucePoolBo) (err error) {
var (
business *model.VipBusinessInfo
)
if len(r.PoolName) == 0 {
err = ecode.VipPoolNameErr
return
}
if len(r.Reason) == 0 {
err = ecode.VipPoolReasonErr
return
}
if r.StartTime <= 0 {
err = ecode.VipPoolStartTimeErr
return
}
if r.EndTime <= 0 {
err = ecode.VipPoolEndTimeErr
return
}
if r.EndTime < r.StartTime {
err = ecode.VipPoolValidityTimeErr
return
}
if business, err = s.dao.SelBusiness(context.TODO(), r.BusinessID); err != nil {
return
}
if business == nil {
err = ecode.VipBusinessNotExitErr
return
}
return
}
// UpdatePool .
func (s *Service) UpdatePool(c context.Context, r *model.ResoucePoolBo) (err error) {
var (
pool *model.VipResourcePool
p *model.VipResourcePool
batchs []*model.VipResourceBatch
)
if err = s.verificationPool(r); err != nil {
return
}
if pool, err = s.dao.SelPoolRow(c, r.ID); err != nil {
return
}
if pool == nil {
err = ecode.VipPoolIDErr
return
}
if p, err = s.dao.SelPoolByName(c, r.PoolName); err != nil {
return
}
if p != nil && pool.PoolName != p.PoolName {
err = ecode.VipPoolNameExitErr
return
}
if batchs, err = s.dao.SelBatchRows(context.TODO(), r.ID); err != nil {
return
}
for _, v := range batchs {
if !(r.StartTime <= v.StartTime && r.EndTime >= v.EndTime) {
err = ecode.VipPoolValidityTimeErr
return
}
}
if _, err = s.dao.UpdatePool(c, r); err != nil {
return
}
return
}
// BatchInfo .
func (s *Service) BatchInfo(c context.Context, id int) (res *model.VipResourceBatch, err error) {
if res, err = s.dao.SelBatchRow(c, id); err != nil {
return
}
return
}
// BatchInfoOfPool .
func (s *Service) BatchInfoOfPool(c context.Context, poolID int) (res []*model.VipResourceBatch, err error) {
if res, err = s.dao.SelBatchRows(c, poolID); err != nil {
return
}
return
}
// AddBatch .
func (s *Service) AddBatch(c context.Context, r *model.ResouceBatchBo) (err error) {
if err = s.verificationBatch(r); err != nil {
return
}
r.SurplusCount = r.Count
if _, err = s.dao.AddBatch(c, r); err != nil {
return
}
return
}
// UpdateBatch .
func (s *Service) UpdateBatch(c context.Context, id, increment int, startTime, endTime xtime.Time) (err error) {
var (
batch *model.VipResourceBatch
r = new(model.ResouceBatchBo)
)
r.ID = id
r.StartTime = startTime
r.EndTime = endTime
if batch, err = s.dao.SelBatchRow(c, id); err != nil {
return
}
if batch == nil {
err = ecode.VipBatchIDErr
return
}
r.PoolID = batch.PoolID
if err = s.verifBatchTime(r); err != nil {
return
}
if increment < 0 {
err = ecode.VipBatchPlusResouceErr
return
}
if batch.Count+increment > math.MaxInt32 || batch.Count+increment < 0 {
err = ecode.VipBatchCountErr
return
}
batch.Count += increment
batch.SurplusCount += increment
batch.StartTime = r.StartTime
batch.EndTime = r.EndTime
ver := batch.Ver
batch.Ver++
if _, err = s.dao.UpdateBatch(c, batch, ver); err != nil {
return
}
return
}
func (s *Service) verifBatchTime(r *model.ResouceBatchBo) (err error) {
var (
pool *model.VipResourcePool
)
if pool, err = s.dao.SelPoolRow(context.TODO(), r.PoolID); err != nil {
return
}
if pool == nil {
err = ecode.VipPoolIDErr
return
}
if pool.StartTime > r.StartTime || pool.EndTime < r.EndTime {
err = ecode.VipPoolValidityTimeErr
return
}
return
}
func (s *Service) verificationBatch(r *model.ResouceBatchBo) (err error) {
if r.Unit <= 0 || r.Unit > 3660 {
err = ecode.VipBatchUnitErr
return
}
if r.Count <= 0 {
err = ecode.VipBatchCountErr
return
}
if err = s.verifBatchTime(r); err != nil {
return
}
return
}
// GrandResouce grand resouce mid
func (s *Service) GrandResouce(c context.Context, remark string, batchID int64, mids []int, username string) (failMid []int, err error) {
var (
batch *model.VipResourceBatch
)
if len(remark) == 0 {
err = ecode.VipRemarkErr
return
}
if batch, err = s.dao.SelBatchRow(c, int(batchID)); err != nil {
return
}
if batch == nil {
err = ecode.VipBatchIDErr
return
}
if err = s.checkBatchValid(batch); err != nil {
return
}
for _, v := range mids {
if err = s.grandMidOfResouce(c, v, int(batchID), username, remark); err != nil {
log.Error("GrandResouce grandMidOfResouce(mid:%v,batchID:%v,username:%v,remark:%v error(%v))", v, batchID, username, remark, err)
failMid = append(failMid, v)
}
}
return
}
func (s *Service) grandMidOfResouce(c context.Context, mid, batchID int, username, remark string) (err error) {
//var (
// batch *model.VipResourceBatch
// tx *sql.Tx
// a int64
// hv *inModel.HandlerVip
//)
//if batch, err = s.dao.SelBatchRow(c, batchID); err != nil {
// return
//}
//if batch.SurplusCount-1 < 0 {
// err = ecode.VipBatchNotEnoughErr
// return
//}
//batch.DirectUseCount++
//batch.SurplusCount--
//ver := batch.Ver
//batch.Ver++
//if tx, err = s.dao.BeginTran(context.TODO()); err != nil {
// return
//}
//defer func() {
// if err != nil {
// if err = tx.Commit(); err != nil {
// tx.Rollback()
// }
// } else {
// tx.Rollback()
// }
//}()
//if a, err = s.dao.UseBatch(tx, batch, ver); err != nil {
// return
//}
//if a > 0 {
// if hv, err = s.exchangeVip(context.TODO(), tx, int(mid), batch.ID, batch.Unit, remark, username); err != nil {
// return
// }
// s.asyncBcoin(func() {
// s.vipRPC.BcoinProcesserHandler(context.TODO(), hv)
// })
//}
return
}
func (s *Service) checkBatchValid(batch *model.VipResourceBatch) (err error) {
var (
pool *model.VipResourcePool
business *model.VipBusinessInfo
ct = time.Now()
)
if !(batch.StartTime.Time().Unix() <= ct.Unix() && ct.Unix() <= batch.EndTime.Time().Unix()) {
err = ecode.VipBatchTTLErr
return
}
if pool, err = s.dao.SelPoolRow(context.TODO(), batch.PoolID); err != nil {
return
}
if pool == nil {
err = ecode.VipPoolIDErr
return
}
if !(pool.StartTime.Time().Unix() <= ct.Unix() && ct.Unix() <= pool.EndTime.Time().Unix()) {
err = ecode.VipPoolValidityTimeErr
return
}
if business, err = s.dao.SelBusiness(context.TODO(), pool.BusinessID); err != nil {
return
}
if business == nil {
err = ecode.VipBusinessNotExitErr
return
}
if business.Status == 1 {
err = ecode.VipBusinessStatusErr
return
}
return
}
// SaveBatchCode .
func (s *Service) SaveBatchCode(c context.Context, arg *model.BatchCode) (err error) {
var batchID int64
if arg.ID == 0 {
if err = s.checkBatchCodeValid(c, arg); err != nil {
return
}
arg.SurplusCount = arg.Count
var tx *sql.Tx
if tx, err = s.dao.BeginTran(c); err != nil {
err = errors.WithStack(err)
return
}
defer func() {
if err == nil {
if err = tx.Commit(); err != nil {
log.Error("commimt error(%+v)", err)
}
} else {
tx.Rollback()
}
}()
arg.Status = 1
if batchID, err = s.dao.TxAddBatchCode(tx, arg); err != nil {
err = errors.WithStack(err)
return
}
if err = s.createCode(tx, batchID, int(arg.Count)); err != nil {
err = errors.WithStack(err)
return
}
} else {
var (
bc *model.BatchCode
bc1 *model.BatchCode
)
if bc, err = s.dao.SelBatchCodeID(c, arg.ID); err != nil {
err = errors.WithStack(err)
return
}
if bc == nil {
err = ecode.VipBatchIDErr
return
}
if bc.BatchName != arg.BatchName {
if bc1, err = s.dao.SelBatchCodeName(c, arg.BatchName); err != nil {
err = errors.WithStack(err)
return
}
if bc1 != nil {
err = ecode.VipBatchCodeNameErr
return
}
}
bc.BatchName = arg.BatchName
bc.Reason = arg.Reason
bc.Price = arg.Price
bc.Contacts = arg.Contacts
bc.ContactsNumber = arg.ContactsNumber
bc.Type = arg.Type
bc.MaxCount = arg.MaxCount
bc.LimitDay = arg.LimitDay
if _, err = s.dao.UpdateBatchCode(c, bc); err != nil {
err = errors.WithStack(err)
return
}
}
return
}
func (s *Service) checkBatchCodeValid(c context.Context, arg *model.BatchCode) (err error) {
var (
b *model.VipBusinessInfo
p *model.VipResourcePool
bc *model.BatchCode
)
if b, err = s.BusinessInfo(c, int(arg.BusinessID)); err != nil {
err = errors.WithStack(err)
return
}
if b == nil {
err = ecode.VipBusinessNotExitErr
return
}
if p, err = s.PoolInfo(c, int(arg.PoolID)); err != nil {
err = errors.WithStack(err)
return
}
if p == nil {
err = ecode.VipPoolIDErr
return
}
if p.EndTime.Time().Before(arg.EndTime.Time()) || p.StartTime.Time().After(arg.StartTime.Time()) {
err = ecode.VipPoolValidityTimeErr
return
}
if bc, err = s.dao.SelBatchCodeName(c, arg.BatchName); err != nil {
err = errors.WithStack(err)
return
}
if bc != nil {
err = ecode.VipBatchCodeNameErr
return
}
if arg.Unit <= 0 || arg.Unit > 3660 {
err = ecode.VipBatchUnitErr
return
}
if arg.Count <= 0 || arg.Count > 200000 {
err = ecode.VipBatchCodeCountErr
}
if arg.Price > 10000 || arg.Price < 0 {
err = ecode.VipBatchPriceErr
return
}
return
}
// FrozenCode .
func (s *Service) FrozenCode(c context.Context, codeID int64, status int8) (err error) {
var (
code *model.ResourceCode
)
if code, err = s.dao.SelCodeID(c, codeID); err != nil {
err = errors.WithStack(err)
return
}
if code == nil {
err = ecode.VipCodeIDErr
return
}
code.Status = status
if _, err = s.dao.UpdateCode(c, codeID, status); err != nil {
err = errors.WithStack(err)
return
}
return
}
// FrozenBatchCode .
func (s *Service) FrozenBatchCode(c context.Context, BatchCodeID int64, status int8) (err error) {
var bc *model.BatchCode
if bc, err = s.dao.SelBatchCodeID(c, BatchCodeID); err != nil {
err = errors.WithStack(err)
return
}
if bc == nil {
err = ecode.VipBatchIDErr
return
}
bc.Status = status
if _, err = s.dao.UpdateBatchCode(c, bc); err != nil {
err = errors.WithStack(err)
return
}
return
}
func (s *Service) createCode(tx *sql.Tx, batchCodeID int64, size int) (err error) {
var (
hash = md5.New()
batchSize = 2000
codes = make([]*model.ResourceCode, 0)
)
for i := 1; i <= size; i++ {
unix := time.Now().UnixNano()
key := fmt.Sprintf("%v,%v,%v,%v", unix, batchCodeID, i, rand.Intn(10000000))
hash.Write([]byte(key))
sum := hash.Sum(nil)
code := hex.EncodeToString(sum)
code = code[8:24]
r := new(model.ResourceCode)
r.Code = code
r.Status = model.NOTUSER
r.BatchCodeID = batchCodeID
codes = append(codes, r)
if i%batchSize == 0 || i == size {
if err = s.dao.BatchAddCode(tx, codes); err != nil {
log.Error("batch add code %+v", err)
return
}
codes = make([]*model.ResourceCode, 0)
}
}
return
}
// SelBatchCodes .
func (s *Service) SelBatchCodes(c context.Context, batchIDs []int64) (res []*model.BatchCode, err error) {
if res, err = s.dao.SelBatchCodes(c, batchIDs); err != nil {
err = errors.WithStack(err)
return
}
return
}
// SelCode .
func (s *Service) SelCode(c context.Context, arg *model.ArgCode, username string, curID int64, ps int) (res []*model.CodeVo, cursor int64, pre int64, err error) {
var (
codes []*model.ResourceCode
batchIDs []int64
batchMap = make(map[int64]*model.BatchCode)
batchCodes []*model.BatchCode
linkmap map[int64]int64
)
if linkmap, err = s.dao.GetSelCode(c, username); err != nil {
err = errors.WithStack(err)
return
}
fmt.Printf("cur link map(%+v) \n", linkmap)
if len(linkmap) == 0 {
linkmap = make(map[int64]int64)
}
if codes, err = s.dao.SelCode(c, arg, curID, ps); err != nil {
err = errors.WithStack(err)
return
}
if len(codes) > 0 {
cursor = codes[len(codes)-1].ID
} else {
return
}
linkmap[cursor] = curID
pre = linkmap[curID]
if err = s.dao.SetSelCode(c, username, linkmap); err != nil {
err = errors.WithStack(err)
return
}
for _, v := range codes {
batchIDs = append(batchIDs, v.BatchCodeID)
}
if batchCodes, err = s.dao.SelBatchCodes(c, batchIDs); err != nil {
err = errors.WithStack(err)
return
}
for _, v := range batchCodes {
batchMap[v.ID] = v
}
for _, v := range codes {
r := new(model.CodeVo)
r.ID = v.ID
r.BatchCodeID = v.BatchCodeID
r.Mid = v.Mid
r.Ctime = v.Ctime
r.Code = v.Code
r.Status = v.Status
r.UseTime = v.UseTime
batchCode := batchMap[v.BatchCodeID]
if batchCode == nil {
err = ecode.VipBatchIDErr
res = nil
return
}
r.Unit = batchCode.Unit
r.BatchName = batchCode.BatchName
r.BatchStatus = batchCode.Status
r.StartTime = batchCode.StartTime
r.EndTime = batchCode.EndTime
res = append(res, r)
}
return
}
// ExportCode .
func (s *Service) ExportCode(c context.Context, batchID int64) (codes []string, err error) {
var (
rc []*model.ResourceCode
curID int64
ps = 2000
)
arg := new(model.ArgCode)
arg.BatchCodeID = batchID
arg.Status = model.NOTUSER
for {
if rc, err = s.dao.SelCode(c, arg, curID, ps); err != nil {
err = errors.WithStack(err)
return
}
if len(rc) == 0 {
return
}
for _, v := range rc {
codes = append(codes, v.Code)
}
curID = rc[len(rc)-1].ID
}
}
// SelBatchCode .
func (s *Service) SelBatchCode(c context.Context, arg *model.ArgBatchCode, pn, ps int) (res []*model.BatchCode, total int64, err error) {
if total, err = s.dao.SelBatchCodeCount(c, arg); err != nil {
err = errors.WithStack(err)
return
}
if res, err = s.dao.SelBatchCode(c, arg, pn, ps); err != nil {
err = errors.WithStack(err)
return
}
return
}

View File

@@ -0,0 +1,109 @@
package service
import (
"context"
"testing"
"time"
"go-common/app/admin/main/vip/model"
xtime "go-common/library/time"
. "github.com/smartystreets/goconvey/convey"
)
func Test_GrandResouce(t *testing.T) {
Convey("should return true err == nil and failMids is empty", t, func() {
var (
mids []int
remark = "系统备注"
batchID = 5
username = "system"
)
mids = append(mids, 110)
failMids, err := s.GrandResouce(context.TODO(), remark, int64(batchID), mids, username)
So(err, ShouldBeNil)
So(failMids, ShouldBeEmpty)
})
}
func TestService_BatchInfo(t *testing.T) {
Convey("batch info", t, func() {
id := 12
_, err := s.BatchInfo(context.TODO(), id)
So(err, ShouldBeNil)
})
}
func TestService_PoolInfo(t *testing.T) {
Convey("pool info", t, func() {
id := 12
_, err := s.PoolInfo(context.TODO(), id)
So(err, ShouldBeNil)
})
}
func Test_UpdateResouce(t *testing.T) {
Convey("should ", t, func() {
pojo := new(model.ResoucePoolBo)
pojo.ID = 25
pojo.PoolName = "test123123112311"
pojo.BusinessID = 3
pojo.Reason = "zhaozhihao"
pojo.CodeExpireTime = xtime.Time(time.Now().Unix())
pojo.StartTime = xtime.Time(time.Now().AddDate(0, 0, -1).Unix())
pojo.EndTime = xtime.Time(time.Now().AddDate(0, 0, 10).Unix())
pojo.Contacts = "阿斯顿发"
pojo.ContactsNumber = "123124123"
err := s.UpdatePool(context.TODO(), pojo)
So(err, ShouldBeNil)
})
}
func Test_SaveBatchCode(t *testing.T) {
Convey("testing ", t, func() {
arg := new(model.BatchCode)
arg.ID = 26
arg.PoolID = 25
arg.Type = 1
arg.BusinessID = 3
arg.BatchName = "测试123"
arg.SurplusCount = 100000
arg.Count = 20000
arg.Unit = 366
arg.LimitDay = 9
arg.MaxCount = 5
arg.StartTime = xtime.Time(time.Now().Unix())
arg.EndTime = xtime.Time(time.Now().AddDate(0, 0, 1).Unix())
arg.Price = 10
arg.Reason = "zhaozhihao"
err := s.SaveBatchCode(context.TODO(), arg)
So(err, ShouldBeNil)
})
}
func Test_vipInfo(t *testing.T) {
Convey("testing", t, func() {
mid := 123
res, err := s.VipInfo(context.TODO(), int64(mid))
t.Logf("%+v", res)
So(err, ShouldBeNil)
})
}
func Test_drawback(t *testing.T) {
Convey("drawback", t, func() {
mid := 2089809
username := "zhaozhihao"
remark := "zhaozhihao"
day := 10
err := s.Drawback(context.TODO(), day, int64(mid), username, remark)
So(err, ShouldBeNil)
})
}
func TestService_ExportCode(t *testing.T) {
Convey(" export code", t, func() {
codes, err := s.ExportCode(context.TODO(), 13)
So(codes, ShouldNotBeEmpty)
So(err, ShouldBeNil)
})
}

View File

@@ -0,0 +1,57 @@
package service
import (
"context"
"go-common/app/admin/main/vip/conf"
"go-common/app/admin/main/vip/dao"
)
var (
_maxTipLen = 28
_maxTitleLen = 36
_maxContentLen = 36
)
// Service struct
type Service struct {
c *conf.Config
dao *dao.Dao
sendBcoin chan func()
}
// New init
func New(c *conf.Config) (s *Service) {
s = &Service{
c: c,
dao: dao.New(c),
sendBcoin: make(chan func(), 10240),
}
go s.bcoinproc()
return s
}
// Ping check db live
func (s *Service) Ping(c context.Context) (err error) {
return s.dao.Ping(c)
}
// func (s *Service) asyncBcoin(f func()) {
// select {
// case s.sendBcoin <- f:
// default:
// log.Warn("bcoinproc chan full")
// }
// }
func (s *Service) bcoinproc() {
for {
f := <-s.sendBcoin
f()
}
}
// Close Service
func (s *Service) Close() {
s.dao.Close()
}

View File

@@ -0,0 +1,103 @@
package service
import (
"context"
"flag"
"testing"
"time"
"go-common/app/admin/main/vip/conf"
"go-common/app/admin/main/vip/model"
"go-common/library/log"
. "github.com/smartystreets/goconvey/convey"
)
var (
//once sync.Once
s *Service
c = context.TODO()
)
func init() {
flag.Set("conf", "../cmd/vip-admin-test.toml")
if err := conf.Init(); err != nil {
panic(err)
}
log.Init(conf.Conf.Log)
defer log.Close()
s = New(conf.Conf)
time.Sleep(time.Second)
}
func Test_ScanUserInfo(t *testing.T) {
Convey("should return true err == nil", t, func() {
})
}
func TestService_FrozenCode(t *testing.T) {
Convey("frozenCode", t, func() {
codeID := 12
status := 1
err := s.FrozenCode(context.TODO(), int64(codeID), int8(status))
So(err, ShouldBeNil)
})
}
func TestService_FrozenBatchCode(t *testing.T) {
Convey("frozen batch code", t, func() {
batchCodeID := 12
status := 2
err := s.FrozenBatchCode(context.TODO(), int64(batchCodeID), int8(status))
So(err, ShouldBeNil)
})
}
func TestService_BusinessInfo(t *testing.T) {
Convey("businessInfo", t, func() {
id := 12
_, err := s.BusinessInfo(context.TODO(), id)
So(err, ShouldBeNil)
})
}
func TestService_AllVersion(t *testing.T) {
Convey("version", t, func() {
_, err := s.AllVersion(context.TODO())
So(err, ShouldBeNil)
})
}
func TestService_SelCode(t *testing.T) {
Convey("sel code", t, func() {
arg := new(model.ArgCode)
arg.ID = 12
cursor := 1
ps := 20
res, _, _, err := s.SelCode(context.TODO(), arg, "zhaozhihao", int64(cursor), ps)
So(res, ShouldNotBeEmpty)
So(err, ShouldBeNil)
})
}
func TestService_VipInfo(t *testing.T) {
Convey("vip info", t, func() {
mid := 1233
_, err := s.VipInfo(context.TODO(), int64(mid))
So(err, ShouldBeNil)
})
}
func TestService_BatchInfoOfPool(t *testing.T) {
Convey("batchn info ", t, func() {
poolID := 12
_, err := s.BatchInfoOfPool(context.TODO(), poolID)
So(err, ShouldBeNil)
})
}
func TestService_BusinessList(t *testing.T) {
Convey("business list", t, func() {
res, _, err := s.BusinessList(context.TODO(), 1, 20, -1)
So(res, ShouldNotBeNil)
So(err, ShouldBeNil)
})
}

View File

@@ -0,0 +1,131 @@
package service
import (
"context"
"time"
"unicode/utf8"
"go-common/app/admin/main/vip/model"
"go-common/library/ecode"
xtime "go-common/library/time"
"github.com/pkg/errors"
)
// TipList tip list.
func (s *Service) TipList(c context.Context, platform int8, state int8, position int8) (ts []*model.Tips, err error) {
var now = time.Now().Unix()
if ts, err = s.dao.TipList(c, platform, state, now, position); err != nil {
err = errors.WithStack(err)
}
for _, v := range ts {
v.TipState(v.StartTime, v.EndTime, now)
}
return
}
// TipByID tip by id.
func (s *Service) TipByID(c context.Context, id int64) (t *model.Tips, err error) {
if t, err = s.dao.TipByID(c, id); err != nil {
err = errors.WithStack(err)
}
if t == nil {
err = ecode.VipTipNotFoundErr
return
}
t.TipState(t.StartTime, t.EndTime, time.Now().Unix())
return
}
// AddTip add tip.
func (s *Service) AddTip(c context.Context, t *model.Tips) (err error) {
if t.StartTime >= t.EndTime {
err = ecode.RequestErr
return
}
if utf8.RuneCountInString(t.Tip) > _maxTipLen {
err = ecode.VipTipTooLoogErr
return
}
t.Ctime = xtime.Time(time.Now().Unix())
if _, err = s.dao.AddTip(c, t); err != nil {
err = errors.WithStack(err)
}
return
}
// TipUpdate update tip.
func (s *Service) TipUpdate(c context.Context, t *model.Tips) (err error) {
var (
old *model.Tips
now = time.Now().Unix()
)
if t.ID == 0 {
err = ecode.RequestErr
return
}
if old, err = s.TipByID(c, t.ID); err != nil {
err = errors.WithStack(err)
return
}
if t.StartTime >= t.EndTime {
err = ecode.VipTipTimeErr
return
}
if utf8.RuneCountInString(t.Tip) > _maxTipLen {
err = ecode.VipTipTooLoogErr
return
}
if old.StartTime != t.StartTime && old.StartTime < now {
err = ecode.VipTipStartTimeCatNotModifyErr
return
}
if old.EndTime != t.EndTime && old.EndTime < now {
err = ecode.VipTipEndTimeCatNotModifyErr
return
}
if _, err = s.dao.TipUpdate(c, t); err != nil {
err = errors.WithStack(err)
}
return
}
// DeleteTip delete tip.
func (s *Service) DeleteTip(c context.Context, id int64, operator string) (err error) {
var (
old *model.Tips
now = time.Now().Unix()
)
if old, err = s.TipByID(c, id); err != nil {
err = errors.WithStack(err)
return
}
if old.StartTime <= now {
err = ecode.VipTipCatNotDeleteErr
return
}
if _, err = s.dao.DeleteTip(c, id, model.Delete, operator); err != nil {
err = errors.WithStack(err)
}
return
}
// ExpireTip expire tip.
func (s *Service) ExpireTip(c context.Context, id int64, operator string) (err error) {
var (
old *model.Tips
now = time.Now().Unix()
)
if old, err = s.TipByID(c, id); err != nil {
err = errors.WithStack(err)
return
}
if old.StartTime > now || old.EndTime < now {
err = ecode.VipTipCatNotExpireErr
return
}
if _, err = s.dao.ExpireTip(c, id, operator, now); err != nil {
err = errors.WithStack(err)
}
return
}

View File

@@ -0,0 +1,101 @@
package service
import (
"testing"
"go-common/app/admin/main/vip/model"
. "github.com/smartystreets/goconvey/convey"
)
// go test -test.v -test.run TestServiceTipList
func TestServiceTipList(t *testing.T) {
Convey("TestServiceTipList", t, func() {
var (
platform = int8(0)
state = int8(0)
position = int8(2)
)
res, err := s.TipList(c, platform, state, position)
for _, v := range res {
t.Logf("%+v", v)
}
So(len(res) != 0, ShouldBeTrue)
So(err, ShouldBeNil)
})
}
// go test -test.v -test.run TestServiceTipByID
func TestServiceTipByID(t *testing.T) {
Convey("TestServiceTipByID", t, func() {
var (
id int64 = 1
)
res, err := s.TipByID(c, id)
t.Logf("%+v", res)
So(err, ShouldBeNil)
})
}
// go test -test.v -test.run TestServiceAddTip
func TestServiceAddTip(t *testing.T) {
Convey("TestServiceAddTip", t, func() {
t := &model.Tips{
Platform: 2,
Version: 4000,
Tip: "一样",
Link: "http://www.baidu.com",
StartTime: 1528315928,
EndTime: 1538315928,
Level: 2,
JudgeType: 1,
Operator: "baihai",
Position: 2,
}
err := s.AddTip(c, t)
So(err, ShouldBeNil)
})
}
// go test -test.v -test.run TestServiceUpdateTip
func TestServiceUpdateTip(t *testing.T) {
Convey("TestServiceUpdateTip", t, func() {
t := &model.Tips{
ID: 1,
Platform: 2,
Version: 4000,
Tip: "一样2",
Link: "http://www.baidu.com",
StartTime: 1528315928,
EndTime: 1538315928,
Level: 2,
JudgeType: 1,
Position: 1,
Operator: "baihai",
}
err := s.TipUpdate(c, t)
So(err, ShouldBeNil)
})
}
// go test -test.v -test.run TestServiceDeleteTip
func TestServiceDeleteTip(t *testing.T) {
Convey("TestServiceDeleteTip", t, func() {
var (
id int64 = 2
)
err := s.DeleteTip(c, id, "baihai")
So(err, ShouldBeNil)
})
}
// go test -test.v -test.run TestServiceExpireTip
func TestServiceExpireTip(t *testing.T) {
Convey("TestServiceExpireTip", t, func() {
var (
id int64 = 3
)
err := s.ExpireTip(c, id, "baihai")
So(err, ShouldBeNil)
})
}

Some files were not shown because too many files have changed in this diff Show More