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,63 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_test",
"go_library",
)
go_test(
name = "go_default_test",
srcs = [
"dao_test.go",
"memcache_test.go",
"mysql_test.go",
"notify_test.go",
],
embed = [":go_default_library"],
rundir = ".",
tags = ["automanaged"],
deps = [
"//app/job/main/coupon/conf:go_default_library",
"//app/job/main/coupon/model: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 = [
"dao.go",
"memcache.go",
"mysql.go",
"notify.go",
],
importpath = "go-common/app/job/main/coupon/dao",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/job/main/coupon/conf:go_default_library",
"//app/job/main/coupon/model:go_default_library",
"//library/cache/memcache:go_default_library",
"//library/database/sql:go_default_library",
"//library/log:go_default_library",
"//library/net/http/blademaster:go_default_library",
"//library/xstr: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,52 @@
package dao
import (
"context"
"go-common/app/job/main/coupon/conf"
"go-common/library/cache/memcache"
xsql "go-common/library/database/sql"
bm "go-common/library/net/http/blademaster"
)
// Dao dao
type Dao struct {
c *conf.Config
db *xsql.DB
client *bm.Client
mc *memcache.Pool
}
// New init mysql db
func New(c *conf.Config) (dao *Dao) {
dao = &Dao{
c: c,
db: xsql.NewMySQL(c.MySQL),
client: bm.NewClient(c.HTTPClient),
mc: memcache.NewPool(c.Memcache),
}
return
}
// Close close the resource.
func (d *Dao) Close() {
d.mc.Close()
d.db.Close()
}
// Ping dao ping
func (d *Dao) Ping(c context.Context) (err error) {
if err = d.db.Ping(c); err != nil {
return
}
err = d.pingMC(c)
return
}
// pingMc ping
func (d *Dao) pingMC(c context.Context) (err error) {
conn := d.mc.Get(c)
defer conn.Close()
item := memcache.Item{Key: "ping", Value: []byte{1}, Expiration: 60}
return conn.Set(&item)
}

View File

@@ -0,0 +1,66 @@
package dao
import (
"context"
"flag"
"os"
"strings"
"testing"
"github.com/smartystreets/goconvey/convey"
"go-common/app/job/main/coupon/conf"
gock "gopkg.in/h2non/gock.v1"
)
var (
d *Dao
)
func TestMain(m *testing.M) {
if os.Getenv("DEPLOY_ENV") != "" {
flag.Set("app_id", "main.account.coupon-job")
flag.Set("conf_token", "ddd3dd8ed06d0ca10b6c8f122581d035")
flag.Set("tree_id", "23029")
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/coupon-job.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
}
func TestDaoPing(t *testing.T) {
convey.Convey("TestDaoPing", t, func(convCtx convey.C) {
err := d.Ping(context.Background())
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaopingMC(t *testing.T) {
convey.Convey("TestDaopingMC", t, func(convCtx convey.C) {
err := d.pingMC(context.Background())
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
}

View File

@@ -0,0 +1,70 @@
package dao
import (
"context"
"fmt"
gmc "go-common/library/cache/memcache"
"go-common/library/log"
"github.com/pkg/errors"
)
const (
_prefixCoupons = "cs:%d:%d"
_prefixCouponBlance = "cbl:%d:%d"
_prefixprizeCard = "nypc:%d:%d:%d" // 元旦活动卡片
_prefixprizeCards = "nypcs:%d:%d" // 元旦活动卡片列表
)
func couponBalancesKey(mid int64, ct int8) string {
return fmt.Sprintf(_prefixCouponBlance, ct, mid)
}
// DelCouponBalancesCache delete user coupons blance cache.
func (d *Dao) DelCouponBalancesCache(c context.Context, mid int64, ct int8) (err error) {
return d.delCache(c, couponBalancesKey(mid, ct))
}
func couponsKey(mid int64, ct int8) string {
return fmt.Sprintf(_prefixCoupons, ct, mid)
}
func prizeCardKey(mid, actID int64, cardType int8) string {
return fmt.Sprintf(_prefixprizeCard, mid, actID, cardType)
}
func prizeCardsKey(mid, actID int64) string {
return fmt.Sprintf(_prefixprizeCards, mid, actID)
}
// DelCouponsCache delete user coupons cache.
func (d *Dao) DelCouponsCache(c context.Context, mid int64, ct int8) (err error) {
return d.delCache(c, couponsKey(mid, ct))
}
// DelCache del cache.
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 {
if err == gmc.ErrNotFound {
log.Warn("delCache ErrNotFound(%s)", key)
err = nil
} else {
err = errors.Wrapf(err, "mc.Delete(%s)", key)
}
}
return
}
// DelPrizeCardKey .
func (d *Dao) DelPrizeCardKey(c context.Context, mid, actID int64, cardType int8) (err error) {
return d.delCache(c, prizeCardKey(mid, actID, cardType))
}
// DelPrizeCardsKey .
func (d *Dao) DelPrizeCardsKey(c context.Context, mid, actID int64) (err error) {
log.Warn("DelPrizeCardsKey(%s)", prizeCardsKey(mid, actID))
return d.delCache(c, prizeCardsKey(mid, actID))
}

View File

@@ -0,0 +1,153 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaocouponBalancesKey(t *testing.T) {
convey.Convey("couponBalancesKey", t, func(convCtx convey.C) {
var (
mid = int64(1)
ct = int8(2)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
p1 := couponBalancesKey(mid, ct)
convCtx.Convey("Then p1 should not be nil.", func(convCtx convey.C) {
convCtx.So(p1, convey.ShouldEqual, "cbl:2:1")
})
})
})
}
func TestDaoDelCouponBalancesCache(t *testing.T) {
convey.Convey("DelCouponBalancesCache", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(0)
ct = int8(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.DelCouponBalancesCache(c, mid, ct)
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaocouponsKey(t *testing.T) {
convey.Convey("couponsKey", t, func(convCtx convey.C) {
var (
mid = int64(22)
ct = int8(33)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
p1 := couponsKey(mid, ct)
convCtx.Convey("Then p1 should not be nil.", func(convCtx convey.C) {
convCtx.So(p1, convey.ShouldEqual, "cs:33:22")
})
})
})
}
func TestDaoprizeCardKey(t *testing.T) {
convey.Convey("prizeCardKey", t, func(convCtx convey.C) {
var (
mid = int64(22)
actID = int64(1)
cardType = int8(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
p1 := prizeCardKey(mid, actID, cardType)
convCtx.Convey("Then p1 should not be nil.", func(convCtx convey.C) {
convCtx.So(p1, convey.ShouldEqual, "nypc:22:1:0")
})
})
})
}
func TestDaoprizeCardsKey(t *testing.T) {
convey.Convey("prizeCardsKey", t, func(convCtx convey.C) {
var (
mid = int64(33)
actID = int64(1)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
p1 := prizeCardsKey(mid, actID)
convCtx.Convey("Then p1 should not be nil.", func(convCtx convey.C) {
convCtx.So(p1, convey.ShouldEqual, "nypcs:33:1")
})
})
})
}
func TestDaoDelCouponsCache(t *testing.T) {
convey.Convey("DelCouponsCache", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(1)
ct = int8(1)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.DelCouponsCache(c, mid, ct)
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaodelCache(t *testing.T) {
convey.Convey("delCache", t, func(convCtx convey.C) {
var (
c = context.Background()
key = "1"
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.delCache(c, key)
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
err = d.delCache(c, "")
convCtx.Convey("Then err should be not nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoDelPrizeCardKey(t *testing.T) {
convey.Convey("DelPrizeCardKey", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(0)
actID = int64(0)
cardType = int8(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.DelPrizeCardKey(c, mid, actID, cardType)
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoDelPrizeCardsKey(t *testing.T) {
convey.Convey("DelPrizeCardsKey", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(0)
actID = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.DelPrizeCardsKey(c, mid, actID)
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
})
}

View File

@@ -0,0 +1,354 @@
package dao
import (
"bytes"
"context"
xsql "database/sql"
"fmt"
"strconv"
"time"
"go-common/app/job/main/coupon/model"
"go-common/library/database/sql"
"go-common/library/xstr"
"github.com/pkg/errors"
)
const (
_updateStateSQL = "UPDATE `coupon_info_%02d` SET `state` = ?,`use_ver` = ?,`ver` = ? WHERE `coupon_token` = ? AND `ver` = ?;"
_couponByTokenSQL = "SELECT `id`,`coupon_token`,`mid`,`state`,`start_time`,`expire_time`,`origin`,`coupon_type`,`order_no`,`oid`,`remark`,`use_ver`,`ver`,`ctime`,`mtime` FROM `coupon_info_%02d` WHERE `coupon_token` = ?;"
_couponsSQL = "SELECT `id`,`coupon_token`,`mid`,`state`,`start_time`,`expire_time`,`origin`,`coupon_type`,`order_no`,`oid`,`remark`,`use_ver`,`ver`,`ctime`,`mtime` FROM `coupon_info_%02d` WHERE `state` = ? AND `mtime` > ?;"
_addCouponChangeLogSQL = "INSERT INTO `coupon_change_log_%02d` (`coupon_token`,`mid`,`state`,`ctime`) VALUES(?,?,?,?);"
// balance coupon
_byOrderNoSQL = "SELECT `id`,`order_no`,`mid`,`count`,`state`,`coupon_type`,`third_trade_no`,`remark`,`tips`,`use_ver`,`ver`,`ctime`,`mtime` FROM `coupon_order` WHERE `order_no` = ?;"
_updateOrderSQL = "UPDATE `coupon_order` SET `state` = ?,`use_ver` =?,`ver` = ? WHERE `order_no` = ? AND `ver` = ?;"
_addOrderLogSQL = "INSERT INTO `coupon_order_log`(`order_no`,`mid`,`state`,`ctime`)VALUES(?,?,?,?);"
_consumeCouponLogSQL = "SELECT `id`,`order_no`,`mid`,`batch_token`,`balance`,`change_balance`,`change_type`,`ctime`,`mtime` FROM `coupon_balance_change_log_%02d` WHERE `order_no` = ? AND `change_type` = ?;"
_byMidAndBatchTokenSQL = "SELECT `id`,`batch_token`,`mid`,`balance`,`start_time`,`expire_time`,`origin`,`coupon_type`,`ver`,`ctime`,`mtime` FROM `coupon_balance_info_%02d` WHERE `mid` = ? AND `batch_token` = ? ;"
_inPayOrderSQL = "SELECT `id`,`order_no`,`mid`,`count`,`state`,`coupon_type`,`third_trade_no`,`remark`,`tips`,`use_ver`,`ver`,`ctime`,`mtime` FROM `coupon_order` WHERE `state` = ? AND `mtime` > ?;"
_batchUpdateBalance = "UPDATE `coupon_balance_info_%02d` SET `ver` =`ver` + 1, `balance` = CASE id"
_addBalanceLogSQL = "INSERT INTO `coupon_balance_change_log_%02d`(`order_no`,`mid`,`batch_token`,`balance`,`change_balance`,`change_type`,`ctime`)VALUES "
_couponBlancesSQL = "SELECT `id`,`batch_token`,`mid`,`balance`,`start_time`,`expire_time`,`origin`,`coupon_type`,`ver`,`ctime`,`mtime` FROM `coupon_balance_info_%02d` WHERE `mid` = ? AND `coupon_type` = ?;"
_updateBlanceSQL = "UPDATE `coupon_balance_info_%02d` SET `balance` = ?,`ver` = `ver` + 1 WHERE `id` = ? AND `ver` = ?;"
_updateUserCardSQL = "UPDATE coupon_user_card SET state=? WHERE mid=? AND coupon_token=? AND batch_token=?"
)
func hitInfo(mid int64) int64 {
return mid % 100
}
func hitChangeLog(mid int64) int64 {
return mid % 100
}
func hitUser(mid int64) int64 {
return mid % 10
}
func hitUserLog(mid int64) int64 {
return mid % 10
}
// UpdateCoupon update coupon in use.
func (d *Dao) UpdateCoupon(c context.Context, tx *sql.Tx, mid int64, state int8, useVer int64, ver int64, couponToken string) (a int64, err error) {
var res xsql.Result
if res, err = tx.Exec(fmt.Sprintf(_updateStateSQL, hitInfo(mid)), state, useVer, ver+1, couponToken, ver); err != nil {
err = errors.WithStack(err)
return
}
if a, err = res.RowsAffected(); err != nil {
err = errors.WithStack(err)
return
}
return
}
// CouponInfo coupon info.
func (d *Dao) CouponInfo(c context.Context, mid int64, token string) (r *model.CouponInfo, err error) {
var row *sql.Row
r = &model.CouponInfo{}
row = d.db.QueryRow(c, fmt.Sprintf(_couponByTokenSQL, hitInfo(mid)), token)
if err = row.Scan(&r.ID, &r.CouponToken, &r.Mid, &r.State, &r.StartTime, &r.ExpireTime, &r.Origin, &r.CouponType, &r.OrderNO, &r.Oid, &r.Remark,
&r.UseVer, &r.Ver, &r.CTime, &r.MTime); err != nil {
if err == xsql.ErrNoRows {
err = nil
r = nil
return
}
err = errors.WithStack(err)
return
}
return
}
// CouponList query .
func (d *Dao) CouponList(c context.Context, index int64, state int8, t time.Time) (res []*model.CouponInfo, err error) {
var rows *sql.Rows
if rows, err = d.db.Query(c, fmt.Sprintf(_couponsSQL, hitInfo(index)), state, t); err != nil {
err = errors.WithStack(err)
return
}
defer rows.Close()
for rows.Next() {
r := &model.CouponInfo{}
if err = rows.Scan(&r.ID, &r.CouponToken, &r.Mid, &r.State, &r.StartTime, &r.ExpireTime, &r.Origin, &r.CouponType, &r.OrderNO, &r.Oid, &r.Remark,
&r.UseVer, &r.Ver, &r.CTime, &r.MTime); err != nil {
err = errors.WithStack(err)
res = nil
return
}
res = append(res, r)
}
err = rows.Err()
return
}
//InsertPointHistory .
func (d *Dao) InsertPointHistory(c context.Context, tx *sql.Tx, l *model.CouponChangeLog) (a int64, err error) {
var res xsql.Result
if res, err = tx.Exec(fmt.Sprintf(_addCouponChangeLogSQL, hitChangeLog(l.Mid)), l.CouponToken, l.Mid, l.State, l.Ctime); err != nil {
err = errors.WithStack(err)
return
}
if a, err = res.RowsAffected(); err != nil {
err = errors.WithStack(err)
}
return
}
// BeginTran begin transaction.
func (d *Dao) BeginTran(c context.Context) (*sql.Tx, error) {
return d.db.Begin(c)
}
// ByOrderNo query order by order no.
func (d *Dao) ByOrderNo(c context.Context, orderNo string) (r *model.CouponOrder, err error) {
var row *sql.Row
r = &model.CouponOrder{}
row = d.db.QueryRow(c, _byOrderNoSQL, orderNo)
if err = row.Scan(&r.ID, &r.OrderNo, &r.Mid, &r.Count, &r.State, &r.CouponType, &r.ThirdTradeNo, &r.Remark, &r.Tips, &r.UseVer, &r.Ver, &r.Ctime, &r.Mtime); err != nil {
if err == sql.ErrNoRows {
err = nil
r = nil
return
}
err = errors.WithStack(err)
return
}
return
}
// UpdateOrderState update order state.
func (d *Dao) UpdateOrderState(c context.Context, tx *sql.Tx, mid int64, state int8, useVer int64, ver int64, orderNo string) (a int64, err error) {
var res xsql.Result
if res, err = tx.Exec(_updateOrderSQL, state, useVer, ver+1, orderNo, ver); err != nil {
err = errors.WithStack(err)
return
}
if a, err = res.RowsAffected(); err != nil {
err = errors.WithStack(err)
return
}
return
}
// AddOrderLog add order log.
func (d *Dao) AddOrderLog(c context.Context, tx *sql.Tx, o *model.CouponOrderLog) (a int64, err error) {
var res xsql.Result
if res, err = tx.Exec(_addOrderLogSQL, o.OrderNo, o.Mid, o.State, o.Ctime); err != nil {
err = errors.WithStack(err)
return
}
if a, err = res.RowsAffected(); err != nil {
err = errors.WithStack(err)
}
return
}
// ConsumeCouponLog consume coupon log.
func (d *Dao) ConsumeCouponLog(c context.Context, mid int64, orderNo string, ct int8) (rs []*model.CouponBalanceChangeLog, err error) {
var rows *sql.Rows
if rows, err = d.db.Query(c, fmt.Sprintf(_consumeCouponLogSQL, hitUserLog(mid)), orderNo, ct); err != nil {
err = errors.WithStack(err)
return
}
defer rows.Close()
for rows.Next() {
r := &model.CouponBalanceChangeLog{}
if err = rows.Scan(&r.ID, &r.OrderNo, &r.Mid, &r.BatchToken, &r.Balance, &r.ChangeBalance, &r.ChangeType, &r.Ctime, &r.Mtime); err != nil {
err = errors.WithStack(err)
rs = nil
return
}
rs = append(rs, r)
}
err = rows.Err()
return
}
// ByMidAndBatchToken query coupon by batch token and mid.
func (d *Dao) ByMidAndBatchToken(c context.Context, mid int64, batchToken string) (r *model.CouponBalanceInfo, err error) {
var row *sql.Row
r = &model.CouponBalanceInfo{}
row = d.db.QueryRow(c, fmt.Sprintf(_byMidAndBatchTokenSQL, hitUser(mid)), mid, batchToken)
if err = row.Scan(&r.ID, &r.BatchToken, &r.Mid, &r.Balance, &r.StartTime, &r.ExpireTime, &r.Origin, &r.CouponType, &r.Ver, &r.CTime, &r.MTime); err != nil {
if err == sql.ErrNoRows {
err = nil
r = nil
return
}
err = errors.WithStack(err)
return
}
return
}
// UpdateBlance update blance.
func (d *Dao) UpdateBlance(c context.Context, tx *sql.Tx, id int64, mid int64, ver int64, balance int64) (a int64, err error) {
var res xsql.Result
if res, err = tx.Exec(fmt.Sprintf(_updateBlanceSQL, hitUser(mid)), balance, id, ver); err != nil {
err = errors.WithStack(err)
return
}
if a, err = res.RowsAffected(); err != nil {
err = errors.WithStack(err)
return
}
return
}
// OrderInPay order in pay.
func (d *Dao) OrderInPay(c context.Context, state int8, t time.Time) (res []*model.CouponOrder, err error) {
var rows *sql.Rows
if rows, err = d.db.Query(c, _inPayOrderSQL, state, t); err != nil {
err = errors.WithStack(err)
return
}
defer rows.Close()
for rows.Next() {
r := &model.CouponOrder{}
if err = rows.Scan(&r.ID, &r.OrderNo, &r.Mid, &r.Count, &r.State, &r.CouponType, &r.ThirdTradeNo, &r.Remark, &r.Tips, &r.UseVer,
&r.Ver, &r.Ctime, &r.Mtime); err != nil {
if err == sql.ErrNoRows {
err = nil
res = nil
return
}
err = errors.WithStack(err)
return
}
res = append(res, r)
}
err = rows.Err()
return
}
// BatchUpdateBlance batch update blance.
func (d *Dao) BatchUpdateBlance(c context.Context, tx *sql.Tx, mid int64, blances []*model.CouponBalanceInfo) (a int64, err error) {
var (
res xsql.Result
buf bytes.Buffer
ids []int64
)
buf.WriteString(fmt.Sprintf(_batchUpdateBalance, hitUser(mid)))
for _, v := range blances {
buf.WriteString(" WHEN ")
buf.WriteString(strconv.FormatInt(v.ID, 10))
buf.WriteString(" THEN ")
buf.WriteString(strconv.FormatInt(v.Balance, 10))
ids = append(ids, v.ID)
}
buf.WriteString(" END WHERE `id` in (")
buf.WriteString(xstr.JoinInts(ids))
buf.WriteString(") AND `ver` = CASE id ")
for _, v := range blances {
buf.WriteString(" WHEN ")
buf.WriteString(strconv.FormatInt(v.ID, 10))
buf.WriteString(" THEN ")
buf.WriteString(strconv.FormatInt(v.Ver, 10))
}
buf.WriteString(" END;")
if res, err = tx.Exec(buf.String()); err != nil {
err = errors.WithStack(err)
return
}
if a, err = res.RowsAffected(); err != nil {
err = errors.WithStack(err)
return
}
return
}
// BatchInsertBlanceLog Batch Insert Balance log
func (d *Dao) BatchInsertBlanceLog(c context.Context, tx *sql.Tx, mid int64, ls []*model.CouponBalanceChangeLog) (a int64, err error) {
var (
buf bytes.Buffer
res xsql.Result
sql string
)
buf.WriteString(fmt.Sprintf(_addBalanceLogSQL, hitUserLog(mid)))
for _, v := range ls {
buf.WriteString("('")
buf.WriteString(v.OrderNo)
buf.WriteString("',")
buf.WriteString(strconv.FormatInt(v.Mid, 10))
buf.WriteString(",'")
buf.WriteString(v.BatchToken)
buf.WriteString("',")
buf.WriteString(strconv.FormatInt(v.Balance, 10))
buf.WriteString(",")
buf.WriteString(strconv.FormatInt(v.ChangeBalance, 10))
buf.WriteString(",")
buf.WriteString(strconv.Itoa(int(v.ChangeType)))
buf.WriteString(",'")
buf.WriteString(fmt.Sprintf("%v", v.Ctime.Time().Format("2006-01-02 15:04:05")))
buf.WriteString("'),")
}
sql = buf.String()
if res, err = tx.Exec(sql[0 : len(sql)-1]); err != nil {
err = errors.WithStack(err)
return
}
if a, err = res.RowsAffected(); err != nil {
err = errors.WithStack(err)
}
return
}
// BlanceList user balance by mid.
func (d *Dao) BlanceList(c context.Context, mid int64, ct int8) (res []*model.CouponBalanceInfo, err error) {
var rows *sql.Rows
if rows, err = d.db.Query(c, fmt.Sprintf(_couponBlancesSQL, hitUser(mid)), mid, ct); err != nil {
err = errors.WithStack(err)
return
}
defer rows.Close()
for rows.Next() {
r := &model.CouponBalanceInfo{}
if err = rows.Scan(&r.ID, &r.BatchToken, &r.Mid, &r.Balance, &r.StartTime, &r.ExpireTime, &r.Origin, &r.CouponType, &r.Ver, &r.CTime, &r.MTime); err != nil {
err = errors.WithStack(err)
res = nil
return
}
res = append(res, r)
}
err = rows.Err()
return
}
// UpdateUserCard .
func (d *Dao) UpdateUserCard(c context.Context, mid int64, state int8, couponToken, batchToken string) (a int64, err error) {
var res xsql.Result
if res, err = d.db.Exec(c, _updateUserCardSQL, state, mid, couponToken, batchToken); 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,413 @@
package dao
import (
"context"
// "database/sql"
"go-common/app/job/main/coupon/model"
"testing"
"time"
"github.com/smartystreets/goconvey/convey"
)
func TestDaohitInfo(t *testing.T) {
convey.Convey("hitInfo", t, func(convCtx convey.C) {
var (
mid = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
p1 := hitInfo(mid)
convCtx.Convey("Then p1 should not be nil.", func(convCtx convey.C) {
convCtx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaohitChangeLog(t *testing.T) {
convey.Convey("hitChangeLog", t, func(convCtx convey.C) {
var (
mid = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
p1 := hitChangeLog(mid)
convCtx.Convey("Then p1 should not be nil.", func(convCtx convey.C) {
convCtx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaohitUser(t *testing.T) {
convey.Convey("hitUser", t, func(convCtx convey.C) {
var (
mid = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
p1 := hitUser(mid)
convCtx.Convey("Then p1 should not be nil.", func(convCtx convey.C) {
convCtx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaohitUserLog(t *testing.T) {
convey.Convey("hitUserLog", t, func(convCtx convey.C) {
var (
mid = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
p1 := hitUserLog(mid)
convCtx.Convey("Then p1 should not be nil.", func(convCtx convey.C) {
convCtx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
// go test -test.v -test.run TestDaoUpdateCoupon
func TestDaoUpdateCoupon(t *testing.T) {
convey.Convey("UpdateCoupon", t, func(convCtx convey.C) {
var (
c = context.Background()
tx, _ = d.BeginTran(context.Background())
mid = int64(1)
state = int8(1)
useVer = int64(11)
ver = int64(2)
couponToken = "729792667120180402161647"
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
a, err := d.UpdateCoupon(c, tx, mid, state, useVer, ver, couponToken)
if err == nil {
if err = tx.Commit(); err != nil {
tx.Rollback()
}
} else {
tx.Rollback()
}
convCtx.Convey("Then err should be nil.a should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(a, convey.ShouldBeGreaterThanOrEqualTo, 0)
})
})
})
}
func TestDaoCouponInfo(t *testing.T) {
convey.Convey("CouponInfo", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(0)
token = ""
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
r, err := d.CouponInfo(c, mid, token)
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 TestDaoCouponList(t *testing.T) {
convey.Convey("CouponList", t, func(convCtx convey.C) {
var (
c = context.Background()
index = int64(0)
state = int8(0)
no, _ = time.Parse("2006-01-02 15:04:05", "2018-12-27 17:28:51")
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
res, err := d.CouponList(c, index, state, no)
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 TestDaoInsertPointHistory(t *testing.T) {
convey.Convey("InsertPointHistory", t, func(convCtx convey.C) {
var (
c = context.Background()
tx, _ = d.BeginTran(context.Background())
l = &model.CouponChangeLog{}
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
a, err := d.InsertPointHistory(c, tx, l)
if err == nil {
if err = tx.Commit(); err != nil {
tx.Rollback()
}
} else {
tx.Rollback()
}
convCtx.Convey("Then err should be nil.a should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(a, convey.ShouldBeGreaterThanOrEqualTo, 0)
})
})
})
}
func TestDaoBeginTran(t *testing.T) {
convey.Convey("BeginTran", t, func(convCtx convey.C) {
var (
c = context.Background()
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
p1, err := d.BeginTran(c)
convCtx.Convey("Then err should be nil.p1 should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoByOrderNo(t *testing.T) {
convey.Convey("ByOrderNo", t, func(convCtx convey.C) {
var (
c = context.Background()
orderNo = ""
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
r, err := d.ByOrderNo(c, orderNo)
convCtx.Convey("Then err should be nil.r should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(r, convey.ShouldBeNil)
})
})
})
}
func TestDaoUpdateOrderState(t *testing.T) {
convey.Convey("UpdateOrderState", t, func(convCtx convey.C) {
var (
c = context.Background()
tx, _ = d.BeginTran(context.Background())
mid = int64(0)
state = int8(0)
useVer = int64(0)
ver = int64(0)
orderNo = ""
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
a, err := d.UpdateOrderState(c, tx, mid, state, useVer, ver, orderNo)
if err == nil {
if err = tx.Commit(); err != nil {
tx.Rollback()
}
} else {
tx.Rollback()
}
convCtx.Convey("Then err should be nil.a should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(a, convey.ShouldBeGreaterThanOrEqualTo, 0)
})
})
})
}
func TestDaoAddOrderLog(t *testing.T) {
convey.Convey("AddOrderLog", t, func(convCtx convey.C) {
var (
c = context.Background()
tx, _ = d.BeginTran(context.Background())
o = &model.CouponOrderLog{}
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
a, err := d.AddOrderLog(c, tx, o)
if err == nil {
if err = tx.Commit(); err != nil {
tx.Rollback()
}
} else {
tx.Rollback()
}
convCtx.Convey("Then err should be nil.a should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(a, convey.ShouldBeGreaterThanOrEqualTo, 0)
})
})
})
}
func TestDaoConsumeCouponLog(t *testing.T) {
convey.Convey("ConsumeCouponLog", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(0)
orderNo = ""
ct = int8(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
rs, err := d.ConsumeCouponLog(c, mid, orderNo, ct)
convCtx.Convey("Then err should be nil.rs should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(rs, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoByMidAndBatchToken(t *testing.T) {
convey.Convey("ByMidAndBatchToken", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(0)
batchToken = ""
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
r, err := d.ByMidAndBatchToken(c, mid, batchToken)
convCtx.Convey("Then err should be nil.r should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(r, convey.ShouldBeNil)
})
})
})
}
func TestDaoUpdateBlance(t *testing.T) {
convey.Convey("UpdateBlance", t, func(convCtx convey.C) {
var (
c = context.Background()
tx, _ = d.BeginTran(context.Background())
id = int64(0)
mid = int64(0)
ver = int64(0)
balance = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
a, err := d.UpdateBlance(c, tx, id, mid, ver, balance)
if err == nil {
if err = tx.Commit(); err != nil {
tx.Rollback()
}
} else {
tx.Rollback()
}
convCtx.Convey("Then err should be nil.a should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(a, convey.ShouldBeGreaterThanOrEqualTo, 0)
})
})
})
}
func TestDaoOrderInPay(t *testing.T) {
convey.Convey("OrderInPay", t, func(convCtx convey.C) {
var (
c = context.Background()
state = int8(0)
no = time.Now()
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
res, err := d.OrderInPay(c, state, no)
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 TestDaoBatchUpdateBlance(t *testing.T) {
convey.Convey("BatchUpdateBlance", t, func(convCtx convey.C) {
var (
c = context.Background()
tx, _ = d.BeginTran(context.Background())
mid = int64(0)
blances = []*model.CouponBalanceInfo{}
blance = &model.CouponBalanceInfo{}
)
blances = append(blances, blance)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
a, err := d.BatchUpdateBlance(c, tx, mid, blances)
if err == nil {
if err = tx.Commit(); err != nil {
tx.Rollback()
}
} else {
tx.Rollback()
}
convCtx.Convey("Then err should be nil.a should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(a, convey.ShouldBeGreaterThanOrEqualTo, 0)
})
})
})
}
func TestDaoBatchInsertBlanceLog(t *testing.T) {
convey.Convey("BatchInsertBlanceLog", t, func(convCtx convey.C) {
var (
c = context.Background()
tx, _ = d.BeginTran(context.Background())
mid = int64(0)
ls = []*model.CouponBalanceChangeLog{}
l = &model.CouponBalanceChangeLog{}
)
ls = append(ls, l)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
a, err := d.BatchInsertBlanceLog(c, tx, mid, ls)
if err == nil {
if err = tx.Commit(); err != nil {
tx.Rollback()
}
} else {
tx.Rollback()
}
convCtx.Convey("Then err should be nil.a should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(a, convey.ShouldBeGreaterThanOrEqualTo, 0)
})
})
})
}
func TestDaoBlanceList(t *testing.T) {
convey.Convey("BlanceList", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(0)
ct = int8(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
res, err := d.BlanceList(c, mid, ct)
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 TestDaoUpdateUserCard(t *testing.T) {
convey.Convey("UpdateUserCard", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(0)
state = int8(0)
couponToken = ""
batchToken = ""
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
a, err := d.UpdateUserCard(c, mid, state, couponToken, batchToken)
convCtx.Convey("Then err should be nil.a should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(a, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoClose(t *testing.T) {
convey.Convey("TestDaoClose", t, func(convCtx convey.C) {
d.Close()
})
}

View File

@@ -0,0 +1,42 @@
package dao
import (
"context"
"fmt"
"net/url"
"go-common/app/job/main/coupon/model"
"go-common/library/log"
"github.com/pkg/errors"
)
const (
_defPltform = "inner"
)
// NotifyRet notify use coupon ret.
func (d *Dao) NotifyRet(c context.Context, notifyURL string, ticketNO string, orderNO string, ip string) (data *model.CallBackRet, err error) {
params := url.Values{}
params.Set("ticket_no", ticketNO)
params.Set("order_no", orderNO)
params.Set("platform", _defPltform)
params.Set("build", "0")
log.Info("call service notify ret %s", notifyURL+"?"+params.Encode())
var res struct {
Code int `json:"code"`
Message string `json:"message"`
Data *model.CallBackRet `json:"result"`
}
if err = d.client.Post(c, notifyURL, ip, params, &res); err != nil {
err = errors.Wrapf(err, "call service(%s) error", notifyURL+"?"+params.Encode())
return
}
if res.Code != 0 {
err = errors.WithStack(fmt.Errorf("call service(%s) error, res code is not 0, resp:%v", notifyURL+"?"+params.Encode(), res))
return
}
data = res.Data
log.Info("call service notify ret suc req(%s) data(%v) ", params.Encode(), data)
return
}

View File

@@ -0,0 +1,45 @@
package dao
import (
"context"
"testing"
gock "gopkg.in/h2non/gock.v1"
"github.com/smartystreets/goconvey/convey"
)
// go test -test.v -test.run TestDaoNotifyRet
func TestDaoNotifyRet(t *testing.T) {
convey.Convey("NotifyRet", t, func(convCtx convey.C) {
var (
c = context.Background()
notifyURL = "http://bangumi.bilibili.com/pay/inner/notify_ticket"
ticketNO = "706821058124120180326154"
orderNO = "20180326153703795"
ip = "127.0.0.1"
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
data, err := d.NotifyRet(c, notifyURL, ticketNO, orderNO, ip)
t.Logf("data (%v)", data)
convCtx.Convey("Then err should be nil.data should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(data, convey.ShouldNotBeNil)
})
convCtx.Convey("res.Code!=0 Then err should not be nil.data should be nil.", func(convCtx convey.C) {
defer gock.OffAll()
httpMock("POST", notifyURL).Reply(200).JSON(`{"code":-1}`)
data, err = d.NotifyRet(c, notifyURL, ticketNO, orderNO, ip)
convCtx.So(err, convey.ShouldNotBeNil)
convCtx.So(data, convey.ShouldBeNil)
})
convCtx.Convey("call service error Then err should not be nil.data should be nil.", func(convCtx convey.C) {
defer gock.OffAll()
httpMock("POST", "").Reply(-400).JSON(`{"code":-1}`)
data, err = d.NotifyRet(c, notifyURL, ticketNO, orderNO, ip)
convCtx.So(err, convey.ShouldNotBeNil)
convCtx.So(data, convey.ShouldBeNil)
})
})
})
}