Create & Init Project...

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

View File

@@ -0,0 +1,88 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
"go_test",
)
go_library(
name = "go_default_library",
srcs = [
"account.go",
"change_history.go",
"contract.go",
"dao.cache.go",
"dao.go",
"lock.go",
"main_vip.go",
"mc.cache.go",
"mc.cache.key.go",
"pay_order.go",
"price_config.go",
"user_info.go",
"yst.go",
],
importpath = "go-common/app/service/main/tv/internal/dao",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/service/main/account/api:go_default_library",
"//app/service/main/tv/internal/conf:go_default_library",
"//app/service/main/tv/internal/model:go_default_library",
"//app/service/main/tv/internal/pkg:go_default_library",
"//app/service/main/vipinfo/api:go_default_library",
"//library/cache/memcache: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/sync/pipeline/fanout:go_default_library",
"//library/time:go_default_library",
"//vendor/github.com/pkg/errors:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)
go_test(
name = "go_default_test",
srcs = [
"account_test.go",
"change_history_test.go",
"contract_test.go",
"dao.cache_test.go",
"dao_test.go",
"lock_test.go",
"main_vip_test.go",
"mc.cache.key_test.go",
"mc.cache_test.go",
"pay_order_test.go",
"price_config_test.go",
"user_info_test.go",
"yst_test.go",
],
embed = [":go_default_library"],
tags = ["automanaged"],
deps = [
"//app/service/main/tv/internal/conf:go_default_library",
"//app/service/main/tv/internal/model:go_default_library",
"//library/ecode:go_default_library",
"//library/net/http/blademaster:go_default_library",
"//library/time:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
],
)

View File

@@ -0,0 +1,19 @@
package dao
import (
"context"
"go-common/app/service/main/account/api"
"go-common/library/log"
)
// AccountInfo queries account info by user id.
func (d *Dao) AccountInfo(c context.Context, mid int64) (ai *api.Info, err error) {
req := &api.MidReq{Mid: int64(mid)}
res, err := d.accCli.Info3(c, req)
if err != nil {
log.Error("d.AccountInfo(%d) err(%v)", mid, err)
return
}
log.Info("d.AccountInfo(%d) res(%+v)", mid, res.Info)
return res.Info, nil
}

View File

@@ -0,0 +1,24 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoAccountInfo(t *testing.T) {
convey.Convey("AccountInfo", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(27515308)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
ai, err := d.AccountInfo(c, mid)
ctx.Convey("Then err should be nil.ai should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(ai, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,110 @@
package dao
import (
"context"
"database/sql"
"go-common/app/service/main/tv/internal/model"
xsql "go-common/library/database/sql"
"go-common/library/log"
xtime "go-common/library/time"
"github.com/pkg/errors"
)
const (
_getUserChangeHistoryByID = "SELECT `id`, `mid`, `change_type`, `change_time`, `order_no`, `days`, `operator_id`, `remark`, `ctime`, `mtime` FROM `tv_user_change_history` WHERE `id`=?"
_getUserChangeHistorysByMid = "SELECT `id`, `mid`, `change_type`, `change_time`, `order_no`, `days`, `operator_id`, `remark`, `ctime`, `mtime` FROM `tv_user_change_history` WHERE `mid`=? ORDER BY `ctime` DESC LIMIT ?,?"
_countUserChangeHistoryByMid = "SELECT count(*) FROM `tv_user_change_history` WHERE `mid`=?"
_getUserChangeHistorysByMidAndCtime = "SELECT `id`, `mid`, `change_type`, `change_time`, `order_no`, `days`, `operator_id`, `remark`, `ctime`, `mtime` FROM `tv_user_change_history` WHERE `mid`=? AND `ctime`>=? AND `ctime`<? ORDER BY `ctime` DESC LIMIT ?,?"
_countUserChangeHistoryByMidAndCtime = "SELECT count(*) FROM `tv_user_change_history` WHERE `mid`=? AND `ctime`>=? AND `ctime`<?"
_insertUserChangeHistory = "INSERT INTO tv_user_change_history (`mid`, `change_type`, `change_time`, `order_no`, `days`, `operator_id`, `remark`) VALUES (?,?,?,?,?,?,?)"
)
// UserChangeHistoryByID quires one row from tv_user_change_history.
func (d *Dao) UserChangeHistoryByID(c context.Context, id int32) (uch *model.UserChangeHistory, err error) {
row := d.db.QueryRow(c, _getUserChangeHistoryByID, id)
uch = &model.UserChangeHistory{}
err = row.Scan(&uch.ID, &uch.Mid, &uch.ChangeType, &uch.ChangeTime, &uch.OrderNo, &uch.Days, &uch.OperatorId, &uch.Remark, &uch.Ctime, &uch.Mtime)
if err != nil {
log.Error("rows.Scan(%s) error(%v)", _getUserChangeHistoryByID, err)
err = errors.WithStack(err)
return nil, err
}
return uch, nil
}
// UserChangeHistorysByMid quires rows from tv_user_change_history.
func (d *Dao) UserChangeHistorysByMid(c context.Context, mid int64, pn, ps int32) (res []*model.UserChangeHistory, total int, err error) {
res = make([]*model.UserChangeHistory, 0)
totalRow := d.db.QueryRow(c, _countUserChangeHistoryByMid, mid)
if err = totalRow.Scan(&total); err != nil {
log.Error("row.ScanCount error(%v)", err)
err = errors.WithStack(err)
return
}
rows, err := d.db.Query(c, _getUserChangeHistorysByMid, mid, (pn-1)*ps, ps)
if err != nil {
log.Error("db.Query(%s) error(%v)", _getUserChangeHistorysByMid, err)
err = errors.WithStack(err)
return
}
defer rows.Close()
for rows.Next() {
uch := &model.UserChangeHistory{}
if err = rows.Scan(&uch.ID, &uch.Mid, &uch.ChangeType, &uch.ChangeTime, &uch.OrderNo, &uch.Days, &uch.OperatorId, &uch.Remark, &uch.Ctime, &uch.Mtime); err != nil {
log.Error("rows.Scan() error(%v)", err)
err = errors.WithStack(err)
return
}
res = append(res, uch)
}
return
}
// UserChangeHistorysByMidAndCtime quires rows from tv_user_change_history.
func (d *Dao) UserChangeHistorysByMidAndCtime(c context.Context, mid int64, from, to xtime.Time, pn, ps int32) (res []*model.UserChangeHistory, total int, err error) {
res = make([]*model.UserChangeHistory, 0)
totalRow := d.db.QueryRow(c, _countUserChangeHistoryByMidAndCtime, mid, from, to)
if err = totalRow.Scan(&total); err != nil {
log.Error("row.ScanCount error(%v)", err)
err = errors.WithStack(err)
return
}
rows, err := d.db.Query(c, _getUserChangeHistorysByMidAndCtime, mid, from, to, (pn-1)*ps, ps)
if err != nil {
log.Error("db.Query(%s) error(%v)", _getUserChangeHistorysByMidAndCtime, err)
err = errors.WithStack(err)
return
}
defer rows.Close()
for rows.Next() {
uch := &model.UserChangeHistory{}
if err = rows.Scan(&uch.ID, &uch.Mid, &uch.ChangeType, &uch.ChangeTime, &uch.OrderNo, &uch.Days, &uch.OperatorId, &uch.Remark, &uch.Ctime, &uch.Mtime); err != nil {
log.Error("rows.Scan() error(%v)", err)
err = errors.WithStack(err)
return
}
res = append(res, uch)
}
return
}
// TxInsertUserChangeHistory insert one row into tv_user_change_history.
func (d *Dao) TxInsertUserChangeHistory(ctx context.Context, tx *xsql.Tx, uch *model.UserChangeHistory) (id int64, err error) {
var (
res sql.Result
)
if res, err = tx.Exec(_insertUserChangeHistory, uch.Mid, uch.ChangeType, uch.ChangeTime, uch.OrderNo, uch.Days, uch.OperatorId, uch.Remark); err != nil {
log.Error("tx.Exec(%s) error(%v)", _insertUserChangeHistory, err)
err = errors.WithStack(err)
return
}
if id, err = res.LastInsertId(); err != nil {
log.Error("res.LastInsertId(%s) error(%v)", _insertUserChangeHistory, err)
err = errors.WithStack(err)
return
}
return
}

View File

@@ -0,0 +1,95 @@
package dao
import (
"context"
"go-common/app/service/main/tv/internal/model"
xtime "go-common/library/time"
"testing"
"time"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoUserChangeHistoryByID(t *testing.T) {
convey.Convey("UserChangeHistoryByID", t, func(ctx convey.C) {
var (
c = context.Background()
id = int32(10)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
uch, err := d.UserChangeHistoryByID(c, id)
ctx.Convey("Then err should be nil.uch should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(uch, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoUserChangeHistorysByMid(t *testing.T) {
convey.Convey("UserChangeHistorysByMid", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(27515308)
pn = int32(1)
ps = int32(10)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
res, total, err := d.UserChangeHistorysByMid(c, mid, pn, ps)
ctx.Convey("Then err should be nil.res,total should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(total, convey.ShouldNotBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoUserChangeHistorysByMidAndCtime(t *testing.T) {
convey.Convey("UserChangeHistorysByMidAndCtime", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(27515308)
from = xtime.Time(0)
to = xtime.Time(time.Now().Unix())
pn = int32(1)
ps = int32(10)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
res, total, err := d.UserChangeHistorysByMidAndCtime(c, mid, from, to, pn, ps)
ctx.Convey("Then err should be nil.res,total should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(total, convey.ShouldNotBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoTxInsertUserChangeHistory(t *testing.T) {
convey.Convey("TxInsertUserChangeHistory", t, func(ctx convey.C) {
var (
c = context.Background()
tx, _ = d.BeginTran(c)
uch = &model.UserChangeHistory{
Mid: 27515308,
ChangeType: model.UserChangeTypeCancelContract,
ChangeTime: xtime.Time(time.Now().Unix()),
OrderNo: "T12345678345678",
Days: 31,
OperatorId: "",
Remark: "test",
}
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
id, err := d.TxInsertUserChangeHistory(c, tx, uch)
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)
})
})
ctx.Reset(func() {
tx.Commit()
})
})
}

View File

@@ -0,0 +1,81 @@
package dao
import (
"context"
"database/sql"
"go-common/app/service/main/tv/internal/model"
xsql "go-common/library/database/sql"
"go-common/library/log"
"github.com/pkg/errors"
)
const (
_getUserContractByMid = "SELECT `id`, `mid`, `contract_id`, `order_no`, `is_deleted`, `ctime`, `mtime` FROM `tv_user_contract` WHERE `mid`=? AND `is_deleted`=0"
_getUserContractByContractId = "SELECT `id`, `mid`, `contract_id`, `order_no`, `is_deleted`, `ctime`, `mtime` FROM `tv_user_contract` WHERE `contract_id`=? AND `is_deleted`=0"
_deleteUserContract = "UPDATE `tv_user_contract` SET `is_deleted`=1 WHERE `id`=?"
_insertUserContract = "INSERT INTO tv_user_contract (`mid`, `contract_id`, `order_no`) VALUES (?,?,?)"
)
// UserContractByMid quires one row from tv_user_contract.
func (d *Dao) UserContractByMid(c context.Context, mid int64) (uc *model.UserContract, err error) {
row := d.db.QueryRow(c, _getUserContractByMid, mid)
uc = &model.UserContract{}
err = row.Scan(&uc.ID, &uc.Mid, &uc.ContractId, &uc.OrderNo, &uc.IsDeleted, &uc.Ctime, &uc.Mtime)
if err == sql.ErrNoRows {
return nil, nil
}
if err != nil {
log.Error("rows.Scan(%s) error(%v)", _getUserContractByMid, err)
err = errors.WithStack(err)
return nil, err
}
return uc, nil
}
// UserContractByContractId quires one row from tv_user_contract.
func (d *Dao) UserContractByContractId(c context.Context, contractId string) (uc *model.UserContract, err error) {
row := d.db.QueryRow(c, _getUserContractByContractId, contractId)
uc = &model.UserContract{}
err = row.Scan(&uc.ID, &uc.Mid, &uc.ContractId, &uc.OrderNo, &uc.IsDeleted, &uc.Ctime, &uc.Mtime)
if err == sql.ErrNoRows {
return nil, nil
}
if err != nil {
log.Error("rows.Scan(%s) error(%v)", _getUserContractByContractId, err)
err = errors.WithStack(err)
return nil, err
}
return uc, nil
}
// TxDeleteUserContract deletes one user contract record.
func (d *Dao) TxDeleteUserContract(ctx context.Context, tx *xsql.Tx, id int32) (err error) {
if _, err = tx.Exec(_deleteUserContract, id); err != nil {
log.Error("rows.Scan(%s) error(%v)", _deleteUserContract, err)
err = errors.WithStack(err)
return
}
return
}
// TxInsertUserContract insert one row into tv_user_contract.
func (d *Dao) TxInsertUserContract(ctx context.Context, tx *xsql.Tx, uc *model.UserContract) (id int64, err error) {
var (
res sql.Result
)
if res, err = tx.Exec(_insertUserContract, uc.Mid, uc.ContractId, uc.OrderNo); err != nil {
log.Error("d.TxInsertUserContract(%+v) err(%+v)", uc, err)
err = errors.WithStack(err)
return
}
if id, err = res.LastInsertId(); err != nil {
log.Error("d.TxInsertUserContract(%+v) err(%+v)", uc, err)
err = errors.WithStack(err)
return
}
return
}

View File

@@ -0,0 +1,85 @@
package dao
import (
"context"
"testing"
"go-common/app/service/main/tv/internal/model"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoUserContractByMid(t *testing.T) {
convey.Convey("UserContractByMid", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(27515308)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
uc, err := d.UserContractByMid(c, mid)
ctx.Convey("Then err should be nil.uc should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(uc, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoUserContractByContractId(t *testing.T) {
convey.Convey("UserContractByContractId", t, func(ctx convey.C) {
var (
c = context.Background()
contractId = "Wx45678934567893456789"
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
uc, err := d.UserContractByContractId(c, contractId)
ctx.Convey("Then err should be nil.uc should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(uc, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoTxDeleteUserContract(t *testing.T) {
convey.Convey("TxDeleteUserContract", t, func(ctx convey.C) {
var (
c = context.Background()
tx, _ = d.BeginTran(c)
id = int32(1)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
err := d.TxDeleteUserContract(c, tx, id)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
ctx.Reset(func() {
tx.Commit()
})
})
}
func TestDaoTxInsertUserContract(t *testing.T) {
convey.Convey("TxInsertUserContract", t, func(ctx convey.C) {
var (
c = context.Background()
tx, _ = d.BeginTran(c)
uc = &model.UserContract{
Mid: 27515308,
ContractId: "Wx45678934567893456789",
OrderNo: "T234567890456789",
}
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
id, err := d.TxInsertUserContract(c, tx, uc)
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)
})
})
ctx.Reset(func() {
tx.Commit()
})
})
}

View File

@@ -0,0 +1,52 @@
// Code generated by $GOPATH/src/go-common/app/tool/cache/gen. DO NOT EDIT.
/*
Package dao is a generated cache proxy package.
It is generated from:
type _cache interface {
// cache: -nullcache=&model.UserInfo{ID:-1} -check_null_code=$.ID==-1
UserInfoByMid(c context.Context, key int64) (*model.UserInfo, error)
}
*/
package dao
import (
"context"
"go-common/app/service/main/tv/internal/model"
"go-common/library/stat/prom"
)
var _ _cache
// UserInfoByMid get data from cache if miss will call source method, then add to cache.
func (d *Dao) UserInfoByMid(c context.Context, id int64) (res *model.UserInfo, err error) {
addCache := true
res, err = d.CacheUserInfoByMid(c, id)
if err != nil {
addCache = false
err = nil
}
if res != nil {
prom.CacheHit.Incr("UserInfoByMid")
return
}
prom.CacheMiss.Incr("UserInfoByMid")
res, err = d.RawUserInfoByMid(c, id)
if err != nil {
return
}
miss := res
if miss == nil {
miss = &model.UserInfo{ID: -1}
res = miss
}
if !addCache {
return
}
d.cache.Do(c, func(c context.Context) {
d.AddCacheUserInfoByMid(c, id, miss)
})
return
}

View File

@@ -0,0 +1,24 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoUserInfoByMid(t *testing.T) {
convey.Convey("UserInfoByMid", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(27515308)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
res, err := d.UserInfoByMid(c, id)
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,115 @@
package dao
import (
"context"
acclgrpc "go-common/app/service/main/account/api"
"go-common/app/service/main/tv/internal/conf"
"go-common/app/service/main/tv/internal/model"
"go-common/app/service/main/tv/internal/pkg"
mvipgrpc "go-common/app/service/main/vipinfo/api"
"go-common/library/cache/memcache"
xsql "go-common/library/database/sql"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
"go-common/library/sync/pipeline/fanout"
)
// Dao dao
type Dao struct {
c *conf.Config
mc *memcache.Pool
db *xsql.DB
httpCli *bm.Client
mvipCli mvipgrpc.VipInfoClient
mvipHttpCli *bm.Client
accCli acclgrpc.AccountClient
ystCli *YstClient
cache *fanout.Fanout
cacheTTL *conf.CacheTTL
signer *pkg.Signer
}
// New init mysql db
func New(c *conf.Config) (dao *Dao) {
httpCli := bm.NewClient(c.HTTPClient)
mvipHttpCli := bm.NewClient(c.HTTPClient)
mvipCli, err := mvipgrpc.NewClient(c.MVIPClient)
if err != nil {
panic(err)
}
accCli, err := acclgrpc.NewClient(c.ACCClient)
if err != nil {
panic(err)
}
dao = &Dao{
c: c,
mc: memcache.NewPool(c.Memcache),
db: xsql.NewMySQL(c.MySQL),
mvipCli: mvipCli,
mvipHttpCli: mvipHttpCli,
accCli: accCli,
httpCli: httpCli,
ystCli: NewYstClient(httpCli),
cache: fanout.New("cache", fanout.Worker(1), fanout.Buffer(1024)),
cacheTTL: c.CacheTTL,
signer: &pkg.Signer{Key: c.YST.Key},
}
return
}
// Close close the resource.
func (d *Dao) Close() {
d.mc.Close()
d.db.Close()
}
// Ping dao ping
func (d *Dao) Ping(ctx context.Context) error {
return d.db.Ping(ctx)
}
// BeginTran begins transaction.
func (d *Dao) BeginTran(c context.Context) (*xsql.Tx, error) {
return d.db.Begin(c)
}
// EndTran ends transaction.
func (d *Dao) EndTran(tx *xsql.Tx, err error) error {
if err != nil {
log.Info("d.EndTran.Rollback(%+v) err(%+v)", tx, err)
tx.Rollback()
} else {
err = tx.Commit()
}
return err
}
// Signer returns yst signer.
func (d *Dao) Signer() *pkg.Signer {
return d.signer
}
//go:generate $GOPATH/src/go-common/app/tool/cache/gen
type _cache interface {
// cache: -nullcache=&model.UserInfo{ID:-1} -check_null_code=$.ID==-1
UserInfoByMid(c context.Context, key int64) (*model.UserInfo, error)
}
//go:generate $GOPATH/src/go-common/app/tool/cache/mc
type _mc interface {
// mc: -key=userInfoKey
CacheUserInfoByMid(c context.Context, key int64) (*model.UserInfo, error)
// mc: -key=userInfoKey -expire=d.cacheTTL.UserInfoTTL -encode=json
AddCacheUserInfoByMid(c context.Context, key int64, value *model.UserInfo) error
// mc: -key=userInfoKey
DelCacheUserInfoByMid(c context.Context, key int64) error
// mc: -key=payParamKey
CachePayParamByToken(c context.Context, token string) (*model.PayParam, error)
// mc: -key=payParamKey
CachePayParamsByTokens(c context.Context, tokens []string) (map[string]*model.PayParam, error)
// mc: -key=payParamKey -expire=d.cacheTTL.PayParamTTL -encode=json
AddCachePayParam(c context.Context, key string, value *model.PayParam) error
// mc: -type=replace -key=payParamKey -expire=d.cacheTTL.PayParamTTL -encode=json
UpdateCachePayParam(c context.Context, key string, value *model.PayParam) error
}

View File

@@ -0,0 +1,61 @@
package dao
import (
"context"
"flag"
"github.com/smartystreets/goconvey/convey"
"go-common/app/service/main/tv/internal/conf"
"os"
"testing"
)
var (
d *Dao
)
func TestMain(m *testing.M) {
if os.Getenv("DEPLOY_ENV") != "" {
flag.Set("app_id", "main.web-svr.tv-service")
flag.Set("conf_token", "c6efbe82ac5d9c68e5e619c30a26d32e")
flag.Set("tree_id", "74910")
flag.Set("conf_version", "docker-1")
flag.Set("deploy_env", "uat")
flag.Set("conf_host", "config.bilibili.co")
flag.Set("conf_path", "/tmp")
flag.Set("region", "sh")
flag.Set("zone", "sh001")
} else {
flag.Set("conf", "../../cmd/test.toml")
}
flag.Parse()
if err := conf.Init(); err != nil {
panic(err)
}
d = New(conf.Conf)
os.Exit(m.Run())
}
func TestDaoPing(t *testing.T) {
convey.Convey("Ping", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
err := d.Ping(c)
ctx.Convey("Then err should be nil.ai should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoSigner(t *testing.T) {
convey.Convey("Signer", t, func(ctx convey.C) {
ctx.Convey("When everything gose positive", func(ctx convey.C) {
s := d.Signer()
ctx.Convey("Then err should be nil.ai should not be nil.", func(ctx convey.C) {
ctx.So(s, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,72 @@
package dao
import (
"context"
"fmt"
"go-common/library/cache/memcache"
"go-common/library/log"
"go-common/library/stat/prom"
)
func (d *Dao) Lock(c context.Context, key string, val string) (err error) {
if val == "" {
return
}
conn := d.mc.Get(c)
defer conn.Close()
obj := &struct {
Value string
}{
Value: val,
}
item := &memcache.Item{Key: key, Object: obj, Expiration: d.cacheTTL.LockTTL, Flags: memcache.FlagJSON}
if err = conn.Add(item); err != nil {
prom.BusinessErrCount.Incr("mc:Lock")
log.Errorv(c, log.KV("Lock", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}
// no thread-safe, but it's works.
// bad case of unlocking
// 1, process-a gets lock
// 2, lock expires
// 3, process-b gets lock
// 4, process-a releases lock
func (d *Dao) Unlock(c context.Context, key string, val string) (err error) {
conn := d.mc.Get(c)
defer conn.Close()
reply, err := conn.Get(key)
if err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
prom.BusinessErrCount.Incr("mc:Unlock")
log.Errorv(c, log.KV("Unlock", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
res := &struct {
Value string
}{}
err = conn.Scan(reply, &res)
if err != nil {
prom.BusinessErrCount.Incr("mc:Unlock")
log.Errorv(c, log.KV("Unlock", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
if res.Value != val {
return nil
}
if err = conn.Delete(key); err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
prom.BusinessErrCount.Incr("mc:Unlock")
log.Errorv(c, log.KV("Unlock", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}

View File

@@ -0,0 +1,40 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoLock(t *testing.T) {
convey.Convey("Lock", t, func(ctx convey.C) {
var (
c = context.Background()
key = "LOCK:ORDER:12345"
val = "123456789"
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
err := d.Lock(c, key, val)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoUnlock(t *testing.T) {
convey.Convey("Unlock", t, func(ctx convey.C) {
var (
c = context.Background()
key = "LOCK:ORDER:12345"
val = "123456789"
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
err := d.Unlock(c, key, val)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}

View File

@@ -0,0 +1,64 @@
package dao
import (
"context"
"net/url"
"strconv"
"go-common/app/service/main/tv/internal/model"
mvip "go-common/app/service/main/vipinfo/api"
"go-common/library/ecode"
"go-common/library/log"
)
const (
_mvipGiftRemark = "电视大会员赠送"
)
// MainVip returns main vip info.
func (d *Dao) MainVip(c context.Context, mid int64) (mv *model.MainVip, err error) {
var (
res *mvip.InfoReply
)
res, err = d.mvipCli.Info(c, &mvip.InfoReq{Mid: int64(mid)})
if err != nil {
log.Error("d.MainVip(%d) err(%v)", mid, err)
return
}
mv = &model.MainVip{
Mid: int64(mid),
VipType: int8(res.Res.Type),
VipStatus: int8(res.Res.Status),
VipDueDate: res.Res.DueDate,
}
log.Info("d.MainVip(%d) res(%+v)", mid, res)
return
}
// GiveMVipGift gives bilibili vip to user.
func (d *Dao) GiveMVipGift(c context.Context, mid int64, batchId int, orderNo string) error {
var (
err error
)
res := new(struct {
Code int `json:"code"`
Message string `json:"message"`
TTL int `json:"ttl"`
})
params := url.Values{}
params.Set("batchId", strconv.Itoa(batchId))
params.Set("mid", strconv.Itoa(int(mid)))
params.Set("orderNo", orderNo)
params.Set("remark", _mvipGiftRemark)
url := d.c.MVIP.BatchUserInfoUrl
if err = d.mvipHttpCli.Post(c, url, "", params, res); err != nil {
log.Error("d.mvipHttpCli.Post(%s, %+v) err(%+v)", url, params, err)
return err
}
if res.Code != 0 {
log.Error("d.mvipHttpCli.Post(%s, %+v) res(%+v)", url, params, res)
return ecode.TVIPGiveMVipFailed
}
log.Info("d.GiveMVipGift(%d, %d, %s) res(%+v)", mid, batchId, orderNo, res)
return nil
}

View File

@@ -0,0 +1,42 @@
package dao
import (
"context"
"github.com/smartystreets/goconvey/convey"
"math/rand"
"strconv"
"testing"
)
func TestDaoMainVip(t *testing.T) {
convey.Convey("MainVip", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(27515308)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
mv, err := d.MainVip(c, mid)
ctx.Convey("Then err should be nil.mv should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(mv, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoGiveMVipGift(t *testing.T) {
convey.Convey("GiveMVipGift", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(27515308)
batchId = int(21)
orderNo = "1" + strconv.Itoa(rand.Int()/100000)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
err := d.GiveMVipGift(c, mid, batchId, orderNo)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}

View File

@@ -0,0 +1,192 @@
// Code generated by $GOPATH/src/go-common/app/tool/cache/mc. DO NOT EDIT.
/*
Package dao is a generated mc cache package.
It is generated from:
type _mc interface {
// mc: -key=userInfoKey
CacheUserInfoByMid(c context.Context, key int64) (*model.UserInfo, error)
// mc: -key=userInfoKey -expire=d.cacheTTL.UserInfoTTL -encode=json
AddCacheUserInfoByMid(c context.Context, key int64, value *model.UserInfo) error
// mc: -key=userInfoKey
DelCacheUserInfoByMid(c context.Context, key int64) error
// mc: -key=payParamKey
CachePayParamByToken(c context.Context, token string) (*model.PayParam, error)
// mc: -key=payParamKey
CachePayParamsByTokens(c context.Context, tokens []string) (map[string]*model.PayParam, error)
// mc: -key=payParamKey -expire=d.cacheTTL.PayParamTTL -encode=json
AddCachePayParam(c context.Context, key string, value *model.PayParam) error
// mc: -type=replace -key=payParamKey -expire=d.cacheTTL.PayParamTTL -encode=json
UpdateCachePayParam(c context.Context, key string, value *model.PayParam) error
}
*/
package dao
import (
"context"
"fmt"
"go-common/app/service/main/tv/internal/model"
"go-common/library/cache/memcache"
"go-common/library/log"
"go-common/library/stat/prom"
)
var _ _mc
// CacheUserInfoByMid get data from mc
func (d *Dao) CacheUserInfoByMid(c context.Context, id int64) (res *model.UserInfo, err error) {
conn := d.mc.Get(c)
defer conn.Close()
key := userInfoKey(id)
reply, err := conn.Get(key)
if err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
prom.BusinessErrCount.Incr("mc:CacheUserInfoByMid")
log.Errorv(c, log.KV("CacheUserInfoByMid", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
res = &model.UserInfo{}
err = conn.Scan(reply, res)
if err != nil {
prom.BusinessErrCount.Incr("mc:CacheUserInfoByMid")
log.Errorv(c, log.KV("CacheUserInfoByMid", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}
// AddCacheUserInfoByMid Set data to mc
func (d *Dao) AddCacheUserInfoByMid(c context.Context, id int64, val *model.UserInfo) (err error) {
if val == nil {
return
}
conn := d.mc.Get(c)
defer conn.Close()
key := userInfoKey(id)
item := &memcache.Item{Key: key, Object: val, Expiration: d.cacheTTL.UserInfoTTL, Flags: memcache.FlagJSON}
if err = conn.Set(item); err != nil {
prom.BusinessErrCount.Incr("mc:AddCacheUserInfoByMid")
log.Errorv(c, log.KV("AddCacheUserInfoByMid", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}
// DelCacheUserInfoByMid delete data from mc
func (d *Dao) DelCacheUserInfoByMid(c context.Context, id int64) (err error) {
conn := d.mc.Get(c)
defer conn.Close()
key := userInfoKey(id)
if err = conn.Delete(key); err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
prom.BusinessErrCount.Incr("mc:DelCacheUserInfoByMid")
log.Errorv(c, log.KV("DelCacheUserInfoByMid", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}
// CachePayParamByToken get data from mc
func (d *Dao) CachePayParamByToken(c context.Context, id string) (res *model.PayParam, err error) {
conn := d.mc.Get(c)
defer conn.Close()
key := payParamKey(id)
reply, err := conn.Get(key)
if err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
prom.BusinessErrCount.Incr("mc:CachePayParamByToken")
log.Errorv(c, log.KV("CachePayParamByToken", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
res = &model.PayParam{}
err = conn.Scan(reply, res)
if err != nil {
prom.BusinessErrCount.Incr("mc:CachePayParamByToken")
log.Errorv(c, log.KV("CachePayParamByToken", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}
// CachePayParamsByTokens get data from mc
func (d *Dao) CachePayParamsByTokens(c context.Context, ids []string) (res map[string]*model.PayParam, err error) {
l := len(ids)
if l == 0 {
return
}
keysMap := make(map[string]string, l)
keys := make([]string, 0, l)
for _, id := range ids {
key := payParamKey(id)
keysMap[key] = id
keys = append(keys, key)
}
conn := d.mc.Get(c)
defer conn.Close()
replies, err := conn.GetMulti(keys)
if err != nil {
prom.BusinessErrCount.Incr("mc:CachePayParamsByTokens")
log.Errorv(c, log.KV("CachePayParamsByTokens", fmt.Sprintf("%+v", err)), log.KV("keys", keys))
return
}
for key, reply := range replies {
var v *model.PayParam
v = &model.PayParam{}
err = conn.Scan(reply, v)
if err != nil {
prom.BusinessErrCount.Incr("mc:CachePayParamsByTokens")
log.Errorv(c, log.KV("CachePayParamsByTokens", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
if res == nil {
res = make(map[string]*model.PayParam, len(keys))
}
res[keysMap[key]] = v
}
return
}
// AddCachePayParam Set data to mc
func (d *Dao) AddCachePayParam(c context.Context, id string, val *model.PayParam) (err error) {
if val == nil {
return
}
conn := d.mc.Get(c)
defer conn.Close()
key := payParamKey(id)
item := &memcache.Item{Key: key, Object: val, Expiration: d.cacheTTL.PayParamTTL, Flags: memcache.FlagJSON}
if err = conn.Set(item); err != nil {
prom.BusinessErrCount.Incr("mc:AddCachePayParam")
log.Errorv(c, log.KV("AddCachePayParam", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}
// UpdateCachePayParam Replace data to mc
func (d *Dao) UpdateCachePayParam(c context.Context, id string, val *model.PayParam) (err error) {
if val == nil {
return
}
conn := d.mc.Get(c)
defer conn.Close()
key := payParamKey(id)
item := &memcache.Item{Key: key, Object: val, Expiration: d.cacheTTL.PayParamTTL, Flags: memcache.FlagJSON}
if err = conn.Replace(item); err != nil {
prom.BusinessErrCount.Incr("mc:UpdateCachePayParam")
log.Errorv(c, log.KV("UpdateCachePayParam", fmt.Sprintf("%+v", err)), log.KV("key", key))
return
}
return
}

View File

@@ -0,0 +1,11 @@
package dao
import "fmt"
func userInfoKey(mid int64) string {
return fmt.Sprintf("cache_tv_vip_ui_%d", mid)
}
func payParamKey(token string) string {
return token
}

View File

@@ -0,0 +1,39 @@
package dao
import (
"context"
"go-common/app/service/main/tv/internal/model"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaouserInfoKey(t *testing.T) {
convey.Convey("userInfoKey", t, func(ctx convey.C) {
var (
mid = int64(27515308)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
p1 := userInfoKey(mid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaopayParamKey(t *testing.T) {
convey.Convey("payParamKey", t, func(ctx convey.C) {
var (
token = "TOKEN:34567345678"
)
d.AddCachePayParam(context.TODO(), token, &model.PayParam{})
ctx.Convey("When everything gose positive", func(ctx convey.C) {
p1 := payParamKey(token)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,123 @@
package dao
import (
"context"
"go-common/app/service/main/tv/internal/model"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoCacheUserInfoByMid(t *testing.T) {
convey.Convey("CacheUserInfoByMid", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(27515308)
)
d.AddCacheUserInfoByMid(c, id, &model.UserInfo{})
ctx.Convey("When everything gose positive", func(ctx convey.C) {
res, err := d.CacheUserInfoByMid(c, id)
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 TestDaoAddCacheUserInfoByMid(t *testing.T) {
convey.Convey("AddCacheUserInfoByMid", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(27515308)
val = &model.UserInfo{}
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
err := d.AddCacheUserInfoByMid(c, id, val)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoDelCacheUserInfoByMid(t *testing.T) {
convey.Convey("DelCacheUserInfoByMid", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(27515308)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
err := d.DelCacheUserInfoByMid(c, id)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoCachePayParamByToken(t *testing.T) {
convey.Convey("CachePayParamByToken", t, func(ctx convey.C) {
var (
c = context.Background()
id = "TOKEN:34567345678"
)
d.AddCachePayParam(context.TODO(), id, &model.PayParam{})
ctx.Convey("When everything gose positive", func(ctx convey.C) {
res, err := d.CachePayParamByToken(c, id)
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 TestDaoCachePayParamsByTokens(t *testing.T) {
convey.Convey("CachePayParamsByTokens", t, func(ctx convey.C) {
var (
c = context.Background()
ids = []string{"TOKEN:34567345678"}
)
d.AddCachePayParam(context.TODO(), ids[0], &model.PayParam{})
ctx.Convey("When everything gose positive", func(ctx convey.C) {
res, err := d.CachePayParamsByTokens(c, ids)
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 TestDaoAddCachePayParam(t *testing.T) {
convey.Convey("AddCachePayParam", t, func(ctx convey.C) {
var (
c = context.Background()
id = "TOKEN:34567345678"
val = &model.PayParam{}
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
err := d.AddCachePayParam(c, id, val)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoUpdateCachePayParam(t *testing.T) {
convey.Convey("UpdateCachePayParam", t, func(ctx convey.C) {
var (
c = context.Background()
id = "TOKEN:34567345678"
val = &model.PayParam{}
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
err := d.UpdateCachePayParam(c, id, val)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}

View File

@@ -0,0 +1,194 @@
package dao
import (
"context"
"database/sql"
"time"
"go-common/app/service/main/tv/internal/model"
xsql "go-common/library/database/sql"
"go-common/library/log"
xtime "go-common/library/time"
"github.com/pkg/errors"
)
const (
_getPayOrderByID = "SELECT `id`, `order_no`, `platform`, `order_type`, `mid`, `buy_months`, `product_id`, `money`, `quantity`, `refund_amount`, `status`, `third_trade_no`, `payment_money`, `payment_type`, `payment_time`, `ver`, `token`, `ctime`, `mtime` FROM `tv_pay_order` WHERE `id`=?"
_getPayOrderByOrderNo = "SELECT `id`, `order_no`, `platform`, `order_type`, `mid`, `buy_months`, `product_id`, `money`, `quantity`, `refund_amount`, `status`, `third_trade_no`, `payment_money`, `payment_type`, `payment_time`, `ver`, `token`, `ctime`, `mtime` FROM `tv_pay_order` WHERE `order_no`=?"
_getPayOrdersByMid = "SELECT `id`, `order_no`, `platform`, `order_type`, `mid`, `buy_months`, `product_id`, `money`, `quantity`, `refund_amount`, `status`, `third_trade_no`, `payment_money`, `payment_type`, `payment_time`, `ver`, `token`, `ctime`, `mtime` FROM `tv_pay_order` WHERE `mid`=? ORDER BY `ctime` DESC LIMIT ?,?"
_countPayOrderByMid = "SELECT count(*) FROM `tv_pay_order` WHERE `mid`=?"
_getPayOrdersByMidAndStatus = "SELECT `id`, `order_no`, `platform`, `order_type`, `mid`, `buy_months`, `product_id`, `money`, `quantity`, `refund_amount`, `status`, `third_trade_no`, `payment_money`, `payment_type`, `payment_time`, `ver`, `token`, `ctime`, `mtime` FROM `tv_pay_order` WHERE `mid`=? AND `status`=? ORDER BY `ctime` DESC LIMIT ?,?"
_countPayOrderByMidAndStatus = "SELECT count(*) FROM `tv_pay_order` WHERE `mid`=? AND `status`=?"
_getPayOrdersByMidAndStatusAndCtime = "SELECT `id`, `order_no`, `platform`, `order_type`, `mid`, `buy_months`, `product_id`, `money`, `quantity`, `refund_amount`, `status`, `third_trade_no`, `payment_money`, `payment_type`, `payment_time`, `ver`, `ctime`, `mtime`, `token` FROM `tv_pay_order` WHERE `mid`=? AND `status`=? AND `ctime`>= ? AND `ctime` <= ? ORDER BY `ctime` DESC LIMIT ?,?"
_countPayOrderByMidAndStatusAndCtime = "SELECT count(*) FROM `tv_pay_order` WHERE `mid`=? AND `status`=? AND `ctime`>= ? AND `ctime` <= ?"
_insertPayOrder = "INSERT INTO tv_pay_order (`order_no`, `platform`, `order_type`, `mid`, `buy_months`, `product_id`, `money`, `quantity`, `refund_amount`, `status`, `third_trade_no`, `payment_money`, `payment_type`, `payment_time`, `ver`, `token`, `app_channel`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
_updatePayOrder = "UPDATE `tv_pay_order` SET `status`=?, `payment_time`=?, `ver` = `ver` + 1 WHERE `id`=? AND `ver`=?"
_getUnpaidNoCallbackOrder = "SELECT `id`, `order_no`, `platform`, `order_type`, `mid`, `buy_months`, `product_id`, `money`, `quantity`, `refund_amount`, `status`, `third_trade_no`, `payment_money`, `payment_type`, `payment_time`, `ver`, `token`, `ctime`, `mtime` FROM `tv_pay_order` WHERE `status` = 1 and ctime > ? and ctime < ? order by id LIMIT ?,?"
)
// PayOrderByID quires one row from tv_pay_order.
func (d *Dao) PayOrderByID(c context.Context, id int) (po *model.PayOrder, err error) {
row := d.db.QueryRow(c, _getPayOrderByID, id)
po = &model.PayOrder{}
err = row.Scan(&po.ID, &po.OrderNo, &po.Platform, &po.OrderType, &po.Mid, &po.BuyMonths, &po.ProductId, &po.Money, &po.Quantity, &po.RefundAmount, &po.Status, &po.ThirdTradeNo, &po.PaymentMoney, &po.PaymentType, &po.PaymentTime, &po.Ver, &po.Token, &po.Ctime, &po.Mtime)
if err == sql.ErrNoRows {
return nil, nil
}
if err != nil {
log.Error("rows.Scan(%s) error(%v)", _getPayOrderByID, err)
err = errors.WithStack(err)
return nil, err
}
return po, nil
}
// PayOrderByOrderNo quires one row from tv_pay_order.
func (d *Dao) PayOrderByOrderNo(c context.Context, orderNo string) (po *model.PayOrder, err error) {
row := d.db.QueryRow(c, _getPayOrderByOrderNo, orderNo)
po = &model.PayOrder{}
err = row.Scan(&po.ID, &po.OrderNo, &po.Platform, &po.OrderType, &po.Mid, &po.BuyMonths, &po.ProductId, &po.Money, &po.Quantity, &po.RefundAmount, &po.Status, &po.ThirdTradeNo, &po.PaymentMoney, &po.PaymentType, &po.PaymentTime, &po.Ver, &po.Token, &po.Ctime, &po.Mtime)
if err == sql.ErrNoRows {
return nil, nil
}
if err != nil {
log.Error("rows.Scan(%s) error(%v)", _getPayOrderByOrderNo, err)
err = errors.WithStack(err)
return nil, err
}
return po, nil
}
// PayOrdersByMid quires rows from tv_pay_order.
func (d *Dao) PayOrdersByMid(c context.Context, mid int, pn, ps int) (res []*model.PayOrder, total int, err error) {
res = make([]*model.PayOrder, 0)
totalRow := d.db.QueryRow(c, _countPayOrderByMid, mid)
if err = totalRow.Scan(&total); err != nil {
log.Error("row.ScanCount error(%v)", err)
err = errors.WithStack(err)
return
}
rows, err := d.db.Query(c, _getPayOrdersByMid, mid, (pn-1)*ps, ps)
if err != nil {
log.Error("db.Query(%s) error(%v)", _getPayOrdersByMid, err)
err = errors.WithStack(err)
return
}
defer rows.Close()
for rows.Next() {
po := &model.PayOrder{}
if err = rows.Scan(&po.ID, &po.OrderNo, &po.Platform, &po.OrderType, &po.Mid, &po.BuyMonths, &po.ProductId, &po.Money, &po.Quantity, &po.RefundAmount, &po.Status, &po.ThirdTradeNo, &po.PaymentMoney, &po.PaymentType, &po.PaymentTime, &po.Ver, &po.Token, &po.Ctime, &po.Mtime); err != nil {
log.Error("rows.Scan() error(%v)", err)
err = errors.WithStack(err)
return
}
res = append(res, po)
}
return
}
// PayOrdersByMidAndStatus quires rows from tv_pay_order.
func (d *Dao) PayOrdersByMidAndStatus(c context.Context, mid int, status int8, pn, ps int) (res []*model.PayOrder, total int, err error) {
res = make([]*model.PayOrder, 0)
totalRow := d.db.QueryRow(c, _countPayOrderByMidAndStatus, mid, status)
if err = totalRow.Scan(&total); err != nil {
log.Error("row.ScanCount error(%v)", err)
err = errors.WithStack(err)
return
}
rows, err := d.db.Query(c, _getPayOrdersByMidAndStatus, mid, status, (pn-1)*ps, ps)
if err != nil {
log.Error("db.Query(%s) error(%v)", _getPayOrdersByMidAndStatus, err)
err = errors.WithStack(err)
return
}
defer rows.Close()
for rows.Next() {
po := &model.PayOrder{}
if err = rows.Scan(&po.ID, &po.OrderNo, &po.Platform, &po.OrderType, &po.Mid, &po.BuyMonths, &po.ProductId, &po.Money, &po.Quantity, &po.RefundAmount, &po.Status, &po.ThirdTradeNo, &po.PaymentMoney, &po.PaymentType, &po.PaymentTime, &po.Ver, &po.Token, &po.Ctime, &po.Mtime); err != nil {
log.Error("rows.Scan() error(%v)", err)
err = errors.WithStack(err)
return
}
res = append(res, po)
}
return
}
// PayOrdersByMidAndStatusAndCtime quires rows from tv_pay_order.
func (d *Dao) PayOrdersByMidAndStatusAndCtime(c context.Context, mid int64, status int8, from, to xtime.Time, pn, ps int) (res []*model.PayOrder, total int, err error) {
res = make([]*model.PayOrder, 0)
totalRow := d.db.QueryRow(c, _countPayOrderByMidAndStatusAndCtime, mid, status, from, to)
if err = totalRow.Scan(&total); err != nil {
log.Error("row.ScanCount error(%v)", err)
err = errors.WithStack(err)
return
}
rows, err := d.db.Query(c, _getPayOrdersByMidAndStatusAndCtime, mid, status, from, to, (pn-1)*ps, ps)
if err != nil {
log.Error("db.Query(%s) error(%v)", _getPayOrdersByMidAndStatusAndCtime, err)
err = errors.WithStack(err)
return
}
defer rows.Close()
for rows.Next() {
po := &model.PayOrder{}
if err = rows.Scan(&po.ID, &po.OrderNo, &po.Platform, &po.OrderType, &po.Mid, &po.BuyMonths, &po.ProductId, &po.Money, &po.Quantity, &po.RefundAmount, &po.Status, &po.ThirdTradeNo, &po.PaymentMoney, &po.PaymentType, &po.PaymentTime, &po.Ver, &po.Ctime, &po.Mtime, &po.Token); err != nil {
log.Error("rows.Scan() error(%v)", err)
err = errors.WithStack(err)
return
}
res = append(res, po)
}
return
}
// TxInsertPayOrder insert one row into tv_pay_order.
func (d *Dao) TxInsertPayOrder(ctx context.Context, tx *xsql.Tx, po *model.PayOrder) (id int64, err error) {
var (
res sql.Result
)
if res, err = tx.Exec(_insertPayOrder, po.OrderNo, po.Platform, po.OrderType, po.Mid, po.BuyMonths, po.ProductId, po.Money, po.Quantity, po.RefundAmount, po.Status, po.ThirdTradeNo, po.PaymentMoney, po.PaymentType, po.PaymentTime, po.Ver, po.Token, po.AppChannel); err != nil {
log.Error("tx.Exec(%s) error(%v)", _insertPayOrder, err)
err = errors.WithStack(err)
return
}
if id, err = res.LastInsertId(); err != nil {
err = errors.WithStack(err)
return
}
return
}
// TxUpdatePayOrder updates status, third party no and payment time.
func (d *Dao) TxUpdatePayOrder(ctx context.Context, tx *xsql.Tx, po *model.PayOrder) error {
if _, err := tx.Exec(_updatePayOrder, po.Status, xtime.Time(time.Now().Unix()), po.ID, po.Ver); err != nil {
log.Error("tx.Exec(%s) error(%v)", _updatePayOrder, err)
err = errors.WithStack(err)
return err
}
return nil
}
//UnpaidNotCallbackOrder get orders not paid where stime < ctime < etime
func (d *Dao) UnpaidNotCallbackOrder(c context.Context, stime, etime xtime.Time, pn, ps int) (res []*model.PayOrder, err error) {
rows, err := d.db.Query(c, _getUnpaidNoCallbackOrder, stime, etime, (pn-1)*ps, ps)
if err != nil {
log.Error("db.Query(%s) error(%v)", _getUnpaidNoCallbackOrder, err)
err = errors.WithStack(err)
return
}
for rows.Next() {
po := &model.PayOrder{}
if err = rows.Scan(&po.ID, &po.OrderNo, &po.Platform, &po.OrderType, &po.Mid, &po.BuyMonths, &po.ProductId, &po.Money, &po.Quantity, &po.RefundAmount, &po.Status, &po.ThirdTradeNo, &po.PaymentMoney, &po.PaymentType, &po.PaymentTime, &po.Ver, &po.Token, &po.Ctime, &po.Mtime); err != nil {
log.Error("rows.Scan() error(%v)", err)
err = errors.WithStack(err)
return
}
res = append(res, po)
}
return
}

View File

@@ -0,0 +1,181 @@
package dao
import (
"context"
"go-common/app/service/main/tv/internal/model"
"math/rand"
"strconv"
"testing"
"time"
xtime "go-common/library/time"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoPayOrderById(t *testing.T) {
convey.Convey("PayOrderById", t, func(ctx convey.C) {
var (
c = context.Background()
id = 20
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
po, err := d.PayOrderByID(c, id)
ctx.Convey("Then err should be nil.po should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(po, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoPayOrderByOrderNo(t *testing.T) {
convey.Convey("PayOrderByOrderNo", t, func(ctx convey.C) {
var (
c = context.Background()
orderNo = "T123456789"
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
po, err := d.PayOrderByOrderNo(c, orderNo)
ctx.Convey("Then err should be nil.po should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(po, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoPayOrdersByMid(t *testing.T) {
convey.Convey("PayOrdersByMid", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int(27515308)
pn = int(1)
ps = int(10)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
res, total, err := d.PayOrdersByMid(c, mid, pn, ps)
ctx.Convey("Then err should be nil.res,total should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(total, convey.ShouldNotBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoPayOrdersByMidAndStatus(t *testing.T) {
convey.Convey("PayOrdersByMidAndStatus", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int(27515308)
status = int8(1)
pn = int(1)
ps = int(10)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
res, total, err := d.PayOrdersByMidAndStatus(c, mid, status, pn, ps)
ctx.Convey("Then err should be nil.res,total should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(total, convey.ShouldNotBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoPayOrdersByMidAndStatusAndCtime(t *testing.T) {
convey.Convey("PayOrdersByMidAndStatusAndCtime", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(27515308)
status = int8(1)
from = xtime.Time(time.Now().Add(-time.Hour * 24).Unix())
to = xtime.Time(time.Now().Unix())
pn = int(1)
ps = int(10)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
res, total, err := d.PayOrdersByMidAndStatusAndCtime(c, mid, status, from, to, pn, ps)
ctx.Convey("Then err should be nil.res,total should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(total, convey.ShouldNotBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoTxInsertPayOrder(t *testing.T) {
convey.Convey("TxInsertPayOrder", t, func(ctx convey.C) {
var (
c = context.Background()
tx, _ = d.BeginTran(c)
po = &model.PayOrder{
OrderNo: "T123456789",
Platform: 1,
OrderType: 1,
Mid: 27515308,
BuyMonths: 1,
ProductId: "wx345678",
Quantity: 1,
Status: 1,
PaymentMoney: 100,
PaymentType: "wechat",
Ver: 1,
Token: "TOKEN:123456789",
AppChannel: "master",
}
)
d.TxInsertPayOrder(c, tx, po)
po.OrderNo = "T" + strconv.Itoa(rand.Int()/100000)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
id, err := d.TxInsertPayOrder(c, tx, po)
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)
})
})
ctx.Reset(func() {
tx.Commit()
})
})
}
func TestDaoUnpaidNotCallbackOrder(t *testing.T) {
convey.Convey("UnpaidNotCallbackOrder", t, func(ctx convey.C) {
var (
c = context.Background()
stime xtime.Time
etime = xtime.Time(time.Now().Unix())
ps = int(500)
pn = int(1)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
res, err := d.UnpaidNotCallbackOrder(c, stime, etime, 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 TestDaoTxUpdatePayOrder(t *testing.T) {
convey.Convey("TxUpdatePayOrder", t, func(ctx convey.C) {
var (
c = context.Background()
tx, _ = d.BeginTran(c)
)
po, _ := d.PayOrderByID(c, 60)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
err := d.TxUpdatePayOrder(c, tx, po)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
ctx.Reset(func() {
tx.Commit()
})
})
}

View File

@@ -0,0 +1,73 @@
package dao
import (
"context"
"go-common/app/service/main/tv/internal/model"
"go-common/library/log"
"github.com/pkg/errors"
)
const (
_getPriceConfigsByStatusAndPid = "SELECT `id`, `pid`, `platform`, `product_name`, `product_id`, `suit_type`, `month`, `sub_type`, `price`, `selected`, `remark`, `status`, `superscript`, `operator`, `oper_id`, `stime`, `etime`, `ctime`, `mtime` FROM `tv_price_config` WHERE `status`=? AND `pid`=? ORDER BY `ctime` ASC "
_countPriceConfigByStatusAndPid = "SELECT count(*) FROM `tv_price_config` WHERE `status`=? AND `pid`=?"
_getSaledPriceConfigsByStatusAndPid = "SELECT `id`, `pid`, `platform`, `product_name`, `product_id`, `suit_type`, `month`, `sub_type`, `price`, `selected`, `remark`, `status`, `superscript`, `operator`, `oper_id`, `stime`, `etime`, `ctime`, `mtime` FROM `tv_price_config` WHERE `status`=? AND `pid`!=0 AND `stime`<=now() AND `etime`>now() ORDER BY `ctime` ASC "
_countSaledPriceConfigByStatusAndPid = "SELECT count(*) FROM `tv_price_config` WHERE `status`=? AND `pid`!=0 AND `stime`<=now() AND `etime`>now()"
)
// PriceConfigsByStatus quires rows from tv_price_config.
func (d *Dao) PriceConfigsByStatus(c context.Context, status int8) (res []*model.PriceConfig, total int, err error) {
res = make([]*model.PriceConfig, 0)
pid := 0
totalRow := d.db.QueryRow(c, _countPriceConfigByStatusAndPid, status, pid)
if err = totalRow.Scan(&total); err != nil {
log.Error("row.ScanCount error(%v)", err)
err = errors.WithStack(err)
return
}
rows, err := d.db.Query(c, _getPriceConfigsByStatusAndPid, status, pid)
if err != nil {
log.Error("db.Query(%s) error(%v)", _getPriceConfigsByStatusAndPid, err)
err = errors.WithStack(err)
return
}
defer rows.Close()
for rows.Next() {
pc := &model.PriceConfig{}
if err = rows.Scan(&pc.ID, &pc.Pid, &pc.Platform, &pc.ProductName, &pc.ProductId, &pc.SuitType, &pc.Month, &pc.SubType, &pc.Price, &pc.Selected, &pc.Remark, &pc.Status, &pc.Superscript, &pc.Operator, &pc.OperId, &pc.Stime, &pc.Etime, &pc.Ctime, &pc.Mtime); err != nil {
log.Error("rows.Scan() error(%v)", err)
err = errors.WithStack(err)
return
}
res = append(res, pc)
}
return
}
// SaledPriceConfigsByStatus quires rows from tv_price_config.
func (d *Dao) SaledPriceConfigsByStatus(c context.Context, status int8) (res []*model.PriceConfig, total int, err error) {
res = make([]*model.PriceConfig, 0)
totalRow := d.db.QueryRow(c, _countSaledPriceConfigByStatusAndPid, status)
if err = totalRow.Scan(&total); err != nil {
log.Error("row.ScanCount error(%v)", err)
err = errors.WithStack(err)
return
}
rows, err := d.db.Query(c, _getSaledPriceConfigsByStatusAndPid, status)
if err != nil {
log.Error("db.Query(%s) error(%v)", _getPriceConfigsByStatusAndPid, err)
err = errors.WithStack(err)
return
}
defer rows.Close()
for rows.Next() {
pc := &model.PriceConfig{}
if err = rows.Scan(&pc.ID, &pc.Pid, &pc.Platform, &pc.ProductName, &pc.ProductId, &pc.SuitType, &pc.Month, &pc.SubType, &pc.Price, &pc.Selected, &pc.Remark, &pc.Status, &pc.Superscript, &pc.Operator, &pc.OperId, &pc.Stime, &pc.Etime, &pc.Ctime, &pc.Mtime); err != nil {
log.Error("rows.Scan() error(%v)", err)
err = errors.WithStack(err)
return
}
res = append(res, pc)
}
return
}

View File

@@ -0,0 +1,42 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoPriceConfigsByStatus(t *testing.T) {
convey.Convey("PriceConfigsByStatus", t, func(ctx convey.C) {
var (
c = context.Background()
status = int8(0)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
res, total, err := d.PriceConfigsByStatus(c, status)
ctx.Convey("Then err should be nil.res,total should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(total, convey.ShouldNotBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoSaledPriceConfigsByStatus(t *testing.T) {
convey.Convey("SaledPriceConfigsByStatus", t, func(ctx convey.C) {
var (
c = context.Background()
status = int8(0)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
res, total, err := d.SaledPriceConfigsByStatus(c, status)
ctx.Convey("Then err should be nil.res,total should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(total, convey.ShouldNotBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,85 @@
package dao
import (
"context"
"database/sql"
"go-common/app/service/main/tv/internal/model"
xsql "go-common/library/database/sql"
"go-common/library/log"
"github.com/pkg/errors"
)
const (
_getUserInfoByMid = "SELECT `id`, `mid`, `ver`, `vip_type`, `pay_type`, `pay_channel_id`, `status`, `overdue_time`, `recent_pay_time`, `ctime`, `mtime` FROM `tv_user_info` WHERE `mid`=?"
_insertUserInfo = "INSERT INTO tv_user_info (`mid`, `ver`, `vip_type`, `pay_type`, `pay_channel_id`, `status`, `overdue_time`, `recent_pay_time`) VALUES (?,?,?,?,?,?,?,?)"
_updateUserInfo = "UPDATE tv_user_info SET `status` = ?, `vip_type` = ?, `overdue_time`=?, `recent_pay_time`=?, `ver` = `ver` + 1 WHERE `mid` = ? AND `ver` = ?"
_updateUserStatus = "UPDATE tv_user_info SET `status` = ?, `ver` = `ver` + 1 WHERE `mid` = ? AND `ver` = ?"
_updateUserPayType = "UPDATE tv_user_info SET `pay_type` = ?, `ver` = `ver` + 1 WHERE `mid` = ? AND `ver` = ?"
)
// UserInfoByMid quires one row from tv_user_info.
func (d *Dao) RawUserInfoByMid(c context.Context, mid int64) (ui *model.UserInfo, err error) {
row := d.db.QueryRow(c, _getUserInfoByMid, mid)
ui = &model.UserInfo{}
err = row.Scan(&ui.ID, &ui.Mid, &ui.Ver, &ui.VipType, &ui.PayType, &ui.PayChannelId, &ui.Status, &ui.OverdueTime, &ui.RecentPayTime, &ui.Ctime, &ui.Mtime)
if err == sql.ErrNoRows {
return nil, nil
}
if err != nil {
log.Error("rows.Scan(%s) error(%v)", _getUserInfoByMid, err)
err = errors.WithStack(err)
return nil, err
}
return ui, nil
}
// TxInsertUserInfo insert one row into tv_user_info.
func (d *Dao) TxInsertUserInfo(ctx context.Context, tx *xsql.Tx, ui *model.UserInfo) (id int64, err error) {
var (
res sql.Result
)
if res, err = tx.Exec(_insertUserInfo, ui.Mid, ui.Ver, ui.VipType, ui.PayType, ui.PayChannelId, ui.Status, ui.OverdueTime, ui.RecentPayTime); err != nil {
log.Error("tx.Exec(%s) error(%v)", _insertUserInfo, err)
err = errors.WithStack(err)
return
}
if id, err = res.LastInsertId(); err != nil {
err = errors.WithStack(err)
return
}
return
}
// TxUpdateUserInfo updates user info.
func (d *Dao) TxUpdateUserInfo(ctx context.Context, tx *xsql.Tx, ui *model.UserInfo) (err error) {
if _, err = tx.Exec(_updateUserInfo, ui.Status, ui.VipType, ui.OverdueTime, ui.RecentPayTime, ui.Mid, ui.Ver); err != nil {
log.Error("tx.Exec(%s) error(%v)", _updateUserInfo, err)
err = errors.WithStack(err)
return
}
return
}
// TxUpdateUserInfo updates vip status of user.
func (d *Dao) TxUpdateUserStatus(ctx context.Context, tx *xsql.Tx, ui *model.UserInfo) (err error) {
if _, err = tx.Exec(_updateUserStatus, ui.Status, ui.Mid, ui.Ver); err != nil {
log.Error("tx.Exec(%s) error(%v)", _updateUserStatus, err)
err = errors.WithStack(err)
return
}
return
}
// TxUpdateUserPayType updates pay type of user.
func (d *Dao) TxUpdateUserPayType(ctx context.Context, tx *xsql.Tx, ui *model.UserInfo) (err error) {
if _, err = tx.Exec(_updateUserPayType, ui.PayType, ui.Mid, ui.Ver); err != nil {
log.Error("tx.Exec(%s) error(%v)", _updateUserPayType, err)
err = errors.WithStack(err)
return
}
return
}

View File

@@ -0,0 +1,122 @@
package dao
import (
"context"
"go-common/app/service/main/tv/internal/model"
"math/rand"
"testing"
"time"
xtime "go-common/library/time"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoRawUserInfoByMid(t *testing.T) {
convey.Convey("RawUserInfoByMid", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(27515308)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
ui, err := d.RawUserInfoByMid(c, mid)
ctx.Convey("Then err should be nil.ui should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(ui, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoTxInsertUserInfo(t *testing.T) {
convey.Convey("TxInsertUserInfo", t, func(ctx convey.C) {
var (
c = context.Background()
tx, _ = d.BeginTran(c)
ui = &model.UserInfo{
Mid: int64(rand.Int() / 10000000000),
Ver: 1,
VipType: 1,
OverdueTime: xtime.Time(time.Now().Unix() + 60*60*24*31),
}
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
id, err := d.TxInsertUserInfo(c, tx, ui)
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)
})
})
ctx.Reset(func() {
tx.Commit()
})
})
}
func TestDaoTxUpdateUserInfo(t *testing.T) {
convey.Convey("TxUpdateUserInfo", t, func(ctx convey.C) {
var (
c = context.Background()
tx, _ = d.BeginTran(c)
ui = &model.UserInfo{
Mid: 27515308,
Ver: 1,
VipType: 1,
OverdueTime: xtime.Time(time.Now().Unix() + 60*60*24*31),
}
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
err := d.TxUpdateUserInfo(c, tx, ui)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
ctx.Reset(func() {
tx.Commit()
})
})
}
func TestDaoTxUpdateUserStatus(t *testing.T) {
convey.Convey("TxUpdateUserStatus", t, func(ctx convey.C) {
var (
c = context.Background()
tx, _ = d.BeginTran(c)
ui = &model.UserInfo{
Mid: 27515308,
Status: 1,
}
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
err := d.TxUpdateUserStatus(c, tx, ui)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
ctx.Reset(func() {
tx.Commit()
})
})
}
func TestDaoTxUpdateUserPayType(t *testing.T) {
convey.Convey("TxUpdateUserPayType", t, func(ctx convey.C) {
var (
c = context.Background()
tx, _ = d.BeginTran(c)
ui = &model.UserInfo{
Mid: 27515308,
PayType: 1,
}
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
err := d.TxUpdateUserPayType(c, tx, ui)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
ctx.Reset(func() {
tx.Commit()
})
})
}

View File

@@ -0,0 +1,127 @@
package dao
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"go-common/app/service/main/tv/internal/model"
"go-common/library/ecode"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
)
const (
ystUrl = "https://%s/%s"
ystCreateOrderPath = "getBiliOrder"
ystRenewOrderPath = "papPayApply"
ystOrderStatePath = "getBiliOrderState"
)
// YstClient represents http client for sending requests to yst.
type YstClient struct {
cli *bm.Client
}
// NewYstClient news a yst client.
func NewYstClient(cli *bm.Client) *YstClient {
return &YstClient{cli: cli}
}
// Post sends one post request.
func (yc *YstClient) Post(c context.Context, uri string, data interface{}, res interface{}) error {
req, err := yc.NewRequest(uri, data)
if err != nil {
return err
}
return yc.cli.Do(c, req, res)
}
// NewRequest news a post request.
func (yc *YstClient) NewRequest(uri string, data interface{}) (request *http.Request, err error) {
var dataBytes []byte
dataBytes, err = json.Marshal(data)
if err != nil {
return
}
request, err = http.NewRequest(http.MethodPost, uri, bytes.NewBuffer(dataBytes))
if err != nil {
return
}
request.Header.Set("Content-Type", "application/json")
return request, nil
}
func resultCode2err(code string) error {
switch code {
case model.YstResultFail:
return ecode.TVIPYstRequestErr
case model.YstResultSysErr:
return ecode.TVIPYstSystemErr
default:
return ecode.TVIPYstUnknownErr
}
}
// CreateYstOrder creates one yst order.
func (d *Dao) CreateYstOrder(c context.Context, req *model.YstCreateOrderReq) (res *model.YstCreateOrderReply, err error) {
req.Sign, err = d.signer.Sign(req)
if err != nil {
return
}
res = &model.YstCreateOrderReply{}
uri := fmt.Sprintf(ystUrl, d.c.YST.Domain, ystCreateOrderPath)
if err = d.ystCli.Post(c, uri, req, res); err != nil {
log.Error("d.ystCli.Post(%s, %+v) err(%+v)", uri, req, err)
return
}
if res.ResultCode != model.YstResultSuccess {
log.Error("d.ystCli.Post(%s, %+v) res(%+v)", uri, req, res)
return nil, resultCode2err(res.ResultCode)
}
log.Info("dao.CreateYstOrder(%+v) res(%+v)", req, res)
return
}
// RenewYstOrder creates one renew order.
func (d *Dao) RenewYstOrder(c context.Context, req *model.YstRenewOrderReq) (res *model.YstRenewOrderReply, err error) {
req.Sign, err = d.signer.Sign(req)
if err != nil {
return
}
res = &model.YstRenewOrderReply{}
uri := fmt.Sprintf(ystUrl, d.c.YST.Domain, ystRenewOrderPath)
if err = d.ystCli.Post(c, uri, req, res); err != nil {
log.Error("d.ystCli.Post(%s, %+v) err(%+v)", uri, req, err)
return
}
if res.ResultCode != model.YstResultSuccess {
log.Error("d.ystCli.Post(%s, %+v) res(%+v)", uri, req, res)
return nil, resultCode2err(res.ResultCode)
}
log.Info("dao.RenewYstOrder(%+v) res(%+v)", req, res)
return
}
// YstOrderState queries order details from yst.
func (d *Dao) YstOrderState(c context.Context, req *model.YstOrderStateReq) (res *model.YstOrderStateReply, err error) {
req.Sign, err = d.signer.Sign(req)
if err != nil {
return
}
res = &model.YstOrderStateReply{}
uri := fmt.Sprintf(ystUrl, d.c.YST.Domain, ystOrderStatePath)
if err = d.ystCli.Post(c, uri, req, res); err != nil {
log.Error("d.ystCli.Post(%s, %+v) err(%+v)", uri, req, err)
return
}
if res.Result != model.YstResultSuccess {
log.Error("d.ystCli.Post(%s, %+v) res(%+v)", uri, req, res)
return nil, resultCode2err(res.Result)
}
log.Info("dao.YstOrderState(%+v) res(%+v)", req, res)
return
}

View File

@@ -0,0 +1,75 @@
package dao
import (
"context"
"go-common/app/service/main/tv/internal/model"
"go-common/library/ecode"
bm "go-common/library/net/http/blademaster"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoNewYstClient(t *testing.T) {
convey.Convey("NewYstClient", t, func(ctx convey.C) {
var (
cli = &bm.Client{}
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
p1 := NewYstClient(cli)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoNewRequest(t *testing.T) {
convey.Convey("NewRequest", t, func(ctx convey.C) {
var (
cli = NewYstClient(&bm.Client{})
uri = ""
data = interface{}(0)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
request, err := cli.NewRequest(uri, data)
ctx.Convey("Then err should be nil.request should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(request, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoresultCode2err(t *testing.T) {
convey.Convey("resultCode2err", t, func(ctx convey.C) {
var (
code = "999"
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
err := resultCode2err(code)
ctx.Convey("Then err should be TVIPYstSystemErr.", func(ctx convey.C) {
ctx.So(err, convey.ShouldEqual, ecode.TVIPYstSystemErr)
})
})
})
}
func TestDaoYstOrderState(t *testing.T) {
convey.Convey("YstOrderState", t, func(ctx convey.C) {
var (
c = context.Background()
req = &model.YstOrderStateReq{
SeqNo: "08265187190109103054",
TraceNo: "CA20190109102306315819491155",
}
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
res, err := d.YstOrderState(c, req)
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)
})
})
})
}