Initial commit

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

View File

@@ -0,0 +1,77 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_test",
"go_library",
)
go_test(
name = "go_default_test",
srcs = [
"allowance_test.go",
"captcha_api_test.go",
"code_test.go",
"dao_test.go",
"http_test.go",
"memcache_test.go",
"mysql_test.go",
"prize_test.go",
],
embed = [":go_default_library"],
rundir = ".",
tags = ["automanaged"],
deps = [
"//app/service/main/coupon/conf:go_default_library",
"//app/service/main/coupon/model:go_default_library",
"//library/database/sql:go_default_library",
"//library/ecode:go_default_library",
"//library/time:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
"//vendor/gopkg.in/h2non/gock.v1:go_default_library",
],
)
go_library(
name = "go_default_library",
srcs = [
"allowance.go",
"captcha_api.go",
"code.go",
"dao.go",
"http.go",
"memcache.go",
"mysql.go",
"prize.go",
],
importpath = "go-common/app/service/main/coupon/dao",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/service/main/coupon/conf:go_default_library",
"//app/service/main/coupon/model: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/net/metadata:go_default_library",
"//library/stat/prom: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,277 @@
package dao
import (
"bytes"
"context"
xsql "database/sql"
"fmt"
"go-common/app/service/main/coupon/model"
"go-common/library/database/sql"
"strconv"
"time"
"github.com/pkg/errors"
)
const (
_couponAllowanceNoStartCheckSQL = "SELECT id,coupon_token,mid,state,start_time,expire_time,origin,ver,batch_token,order_no,amount,full_amount,ctime,mtime FROM coupon_allowance_info_%02d WHERE mid = ? AND expire_time > ? AND state = ?;"
_couponByOrderNOSQL = "SELECT id,coupon_token,mid,state,start_time,expire_time,origin,ver,batch_token,order_no,amount,full_amount,ctime,mtime,remark FROM coupon_allowance_info_%02d WHERE order_no = ?;"
_couponUsableAllowanceSQL = "SELECT id,coupon_token,mid,state,start_time,expire_time,origin,ver,batch_token,order_no,amount,full_amount,ctime,mtime FROM coupon_allowance_info_%02d WHERE mid = ? AND expire_time > ? AND start_time < ? AND state = ?;"
_couponAllowanceByTokenSQL = "SELECT id,coupon_token,mid,state,start_time,expire_time,origin,ver,batch_token,order_no,amount,full_amount,ctime,mtime FROM coupon_allowance_info_%02d WHERE coupon_token = ?;"
_updateCouponAllowanceInUseSQL = "UPDATE coupon_allowance_info_%02d SET state =?, order_no = ?, remark = ?, ver =ver+1 WHERE coupon_token = ? AND ver = ?;"
_updateCouponAllowanceToUseSQL = "UPDATE coupon_allowance_info_%02d SET state =?, order_no = ?, ver =ver+1 WHERE coupon_token = ? AND ver = ? AND state = ?;"
_getCouponByOrderNoSQL = "SELECT mid,coupon_token,order_no,amount,full_amount,state,ver FROM coupon_allowance_info_%02d WHERE order_no = ?"
_addCouponAllowanceChangeLogSQL = "INSERT INTO coupon_allowance_change_log_%02d (coupon_token,order_no,mid,state,ctime, change_type) VALUES(?,?,?,?,?,?);"
_batchAllowanceCountByMid = "SELECT COUNT(1) FROM coupon_allowance_info_%02d WHERE mid = ? AND batch_token = ?;"
_batchAddAllowanceCouponSQL = "INSERT INTO coupon_allowance_info_%02d(coupon_token,mid,state,start_time,expire_time,origin,batch_token,amount,full_amount,ctime,app_id) VALUES "
_addAllowanceCouponSQL = "INSERT INTO coupon_allowance_info_%02d(coupon_token,mid,state,start_time,expire_time,origin,batch_token,amount,full_amount,app_id) VALUES (?,?,?,?,?,?,?,?,?,?)"
_couponAllowancePageNotUsedSQL = "SELECT id,coupon_token,mid,state,start_time,expire_time,origin,ver,batch_token,order_no,amount,full_amount,ctime,mtime,remark FROM coupon_allowance_info_%02d WHERE mid = ? AND (state = 0 OR state = 1) AND expire_time > ? AND start_time < ? AND ctime > ? ORDER BY id DESC"
_couponAllowancePageUsedSQL = "SELECT id,coupon_token,mid,state,start_time,expire_time,origin,ver,batch_token,order_no,amount,full_amount,ctime,mtime,remark FROM coupon_allowance_info_%02d WHERE mid = ? AND state = 2 AND ctime > ? ORDER BY id DESC "
_couponAllowancePageExpireSQL = "SELECT id,coupon_token,mid,state,start_time,expire_time,origin,ver,batch_token,order_no,amount,full_amount,ctime,mtime,remark FROM coupon_allowance_info_%02d WHERE mid = ? AND state <> 2 AND expire_time < ? AND ctime > ? ORDER BY id DESC "
)
func hitAllowanceInfo(mid int64) int64 {
return mid % 10
}
func hitAllowanceChangeLog(mid int64) int64 {
return mid % 10
}
// ByStateAndExpireAllowances query by coupon state and expire .
func (d *Dao) ByStateAndExpireAllowances(c context.Context, mid int64, state int8, t int64) (res []*model.CouponAllowanceInfo, err error) {
var rows *sql.Rows
if rows, err = d.db.Query(c, fmt.Sprintf(_couponAllowanceNoStartCheckSQL, hitAllowanceInfo(mid)), mid, t, state); err != nil {
err = errors.WithStack(err)
return
}
defer rows.Close()
for rows.Next() {
r := &model.CouponAllowanceInfo{}
if err = rows.Scan(&r.ID, &r.CouponToken, &r.Mid, &r.State, &r.StartTime, &r.ExpireTime, &r.Origin, &r.Ver, &r.BatchToken,
&r.OrderNO, &r.Amount, &r.FullAmount, &r.CTime, &r.MTime); err != nil {
err = errors.WithStack(err)
res = nil
return
}
res = append(res, r)
}
err = rows.Err()
return
}
// AllowanceByOrderNO query coupon by orderno.
func (d *Dao) AllowanceByOrderNO(c context.Context, mid int64, orderNO string) (r *model.CouponAllowanceInfo, err error) {
var row *sql.Row
r = &model.CouponAllowanceInfo{}
row = d.db.QueryRow(c, fmt.Sprintf(_couponByOrderNOSQL, hitAllowanceInfo(mid)), orderNO)
if err = row.Scan(&r.ID, &r.CouponToken, &r.Mid, &r.State, &r.StartTime, &r.ExpireTime, &r.Origin, &r.Ver, &r.BatchToken,
&r.OrderNO, &r.Amount, &r.FullAmount, &r.CTime, &r.MTime, &r.Remark); err != nil {
if err == sql.ErrNoRows {
err = nil
r = nil
return
}
err = errors.WithStack(err)
return
}
return
}
// UsableAllowances usable allowance .
func (d *Dao) UsableAllowances(c context.Context, mid int64, state int8, t int64) (res []*model.CouponAllowanceInfo, err error) {
var rows *sql.Rows
if rows, err = d.db.Query(c, fmt.Sprintf(_couponUsableAllowanceSQL, hitAllowanceInfo(mid)), mid, t, t, state); err != nil {
err = errors.WithStack(err)
return
}
defer rows.Close()
for rows.Next() {
r := &model.CouponAllowanceInfo{}
if err = rows.Scan(&r.ID, &r.CouponToken, &r.Mid, &r.State, &r.StartTime, &r.ExpireTime, &r.Origin, &r.Ver, &r.BatchToken,
&r.OrderNO, &r.Amount, &r.FullAmount, &r.CTime, &r.MTime); err != nil {
err = errors.WithStack(err)
res = nil
return
}
res = append(res, r)
}
err = rows.Err()
return
}
// AllowanceByToken query coupon by token.
func (d *Dao) AllowanceByToken(c context.Context, mid int64, token string) (r *model.CouponAllowanceInfo, err error) {
var row *sql.Row
r = &model.CouponAllowanceInfo{}
row = d.db.QueryRow(c, fmt.Sprintf(_couponAllowanceByTokenSQL, hitAllowanceInfo(mid)), token)
if err = row.Scan(&r.ID, &r.CouponToken, &r.Mid, &r.State, &r.StartTime, &r.ExpireTime, &r.Origin, &r.Ver, &r.BatchToken,
&r.OrderNO, &r.Amount, &r.FullAmount, &r.CTime, &r.MTime); err != nil {
if err == sql.ErrNoRows {
err = nil
r = nil
return
}
err = errors.WithStack(err)
return
}
return
}
// UpdateAllowanceCouponInUse update coupon in use.
func (d *Dao) UpdateAllowanceCouponInUse(c context.Context, tx *sql.Tx, cp *model.CouponAllowanceInfo) (a int64, err error) {
var res xsql.Result
if res, err = tx.Exec(fmt.Sprintf(_updateCouponAllowanceInUseSQL, hitAllowanceInfo(cp.Mid)), cp.State, cp.OrderNO, cp.Remark, cp.CouponToken, cp.Ver); err != nil {
err = errors.WithStack(err)
return
}
if a, err = res.RowsAffected(); err != nil {
err = errors.WithStack(err)
return
}
return
}
// UpdateAllowanceCouponToUse update coupon in use.
func (d *Dao) UpdateAllowanceCouponToUse(c context.Context, tx *sql.Tx, cp *model.CouponAllowanceInfo) (a int64, err error) {
var res xsql.Result
if res, err = tx.Exec(fmt.Sprintf(_updateCouponAllowanceToUseSQL, hitAllowanceInfo(cp.Mid)), cp.State, cp.OrderNO, cp.CouponToken, cp.Ver, model.InUse); err != nil {
err = errors.WithStack(err)
return
}
if a, err = res.RowsAffected(); err != nil {
err = errors.WithStack(err)
return
}
return
}
// UpdateAllowanceCouponToUsed update coupon in used.
func (d *Dao) UpdateAllowanceCouponToUsed(c context.Context, tx *sql.Tx, cp *model.CouponAllowanceInfo) (a int64, err error) {
var res xsql.Result
if res, err = tx.Exec(fmt.Sprintf(_updateCouponAllowanceToUseSQL, hitAllowanceInfo(cp.Mid)), cp.State, cp.OrderNO, cp.CouponToken, cp.Ver, model.NotUsed); err != nil {
err = errors.WithStack(err)
return
}
if a, err = res.RowsAffected(); err != nil {
err = errors.WithStack(err)
return
}
return
}
//InsertCouponAllowanceHistory insert coupon history .
func (d *Dao) InsertCouponAllowanceHistory(c context.Context, tx *sql.Tx, l *model.CouponAllowanceChangeLog) (a int64, err error) {
var res xsql.Result
if res, err = tx.Exec(fmt.Sprintf(_addCouponAllowanceChangeLogSQL, hitAllowanceChangeLog(l.Mid)), l.CouponToken, l.OrderNO, l.Mid, l.State, l.Ctime, l.ChangeType); err != nil {
err = errors.WithStack(err)
return
}
if a, err = res.RowsAffected(); err != nil {
err = errors.WithStack(err)
}
return
}
// CountByAllowanceBranchToken get user count by bratch token.
func (d *Dao) CountByAllowanceBranchToken(c context.Context, mid int64, token string) (count int64, err error) {
row := d.db.QueryRow(c, fmt.Sprintf(_batchAllowanceCountByMid, hitAllowanceInfo(mid)), mid, token)
if err = row.Scan(&count); err != nil {
err = errors.WithStack(err)
}
return
}
// GetCouponByOrderNo .
func (d *Dao) GetCouponByOrderNo(c context.Context, mid int64, orderNo string) (res *model.CouponAllowanceInfo, err error) {
res = &model.CouponAllowanceInfo{}
row := d.db.QueryRow(c, fmt.Sprintf(_getCouponByOrderNoSQL, hitAllowanceInfo(mid)), orderNo)
if err = row.Scan(&res.Mid, &res.CouponToken, &res.OrderNO, &res.Amount, &res.FullAmount, &res.State, &res.Ver); err != nil {
err = errors.WithStack(err)
}
return
}
//TxAddAllowanceCoupon tx add lowance coupon
func (d *Dao) TxAddAllowanceCoupon(tx *sql.Tx, cp *model.CouponAllowanceInfo) (err error) {
if _, err = tx.Exec(fmt.Sprintf(_addAllowanceCouponSQL, hitAllowanceInfo(cp.Mid)), cp.CouponToken, cp.Mid, cp.State, cp.StartTime, cp.ExpireTime, cp.Origin, cp.BatchToken, cp.Amount, cp.FullAmount, cp.AppID); err != nil {
err = errors.WithStack(err)
}
return
}
// BatchAddAllowanceCoupon batch add allowance coupon.
func (d *Dao) BatchAddAllowanceCoupon(c context.Context, tx *sql.Tx, mid int64, cps []*model.CouponAllowanceInfo) (a int64, err error) {
var (
buf bytes.Buffer
res xsql.Result
sql string
)
buf.WriteString(fmt.Sprintf(_batchAddAllowanceCouponSQL, hitAllowanceInfo(mid)))
for _, v := range cps {
buf.WriteString("('")
buf.WriteString(v.CouponToken)
buf.WriteString("',")
buf.WriteString(strconv.FormatInt(v.Mid, 10))
buf.WriteString(",")
buf.WriteString(fmt.Sprintf("%d", v.State))
buf.WriteString(",")
buf.WriteString(strconv.FormatInt(v.StartTime, 10))
buf.WriteString(",")
buf.WriteString(strconv.FormatInt(v.ExpireTime, 10))
buf.WriteString(",")
buf.WriteString(fmt.Sprintf("%d", v.Origin))
buf.WriteString(",'")
buf.WriteString(v.BatchToken)
buf.WriteString("',")
buf.WriteString(fmt.Sprintf("%f", v.Amount))
buf.WriteString(",")
buf.WriteString(fmt.Sprintf("%f", v.FullAmount))
buf.WriteString(",'")
buf.WriteString(v.CTime.Time().Format("2006-01-02 15:04:05"))
buf.WriteString("',")
buf.WriteString(strconv.FormatInt(v.AppID, 10))
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
}
// AllowanceList list.
func (d *Dao) AllowanceList(c context.Context, mid int64, state int8, t int64, stime time.Time) (res []*model.CouponAllowanceInfo, err error) {
var rows *sql.Rows
switch state {
case model.NotUsed:
rows, err = d.db.Query(c, fmt.Sprintf(_couponAllowancePageNotUsedSQL, hitAllowanceInfo(mid)), mid, t, t, stime)
case model.Used:
rows, err = d.db.Query(c, fmt.Sprintf(_couponAllowancePageUsedSQL, hitAllowanceInfo(mid)), mid, stime)
case model.Expire:
rows, err = d.db.Query(c, fmt.Sprintf(_couponAllowancePageExpireSQL, hitAllowanceInfo(mid)), mid, t, stime)
default:
return
}
if err != nil {
err = errors.WithStack(err)
return
}
defer rows.Close()
for rows.Next() {
r := new(model.CouponAllowanceInfo)
if err = rows.Scan(&r.ID, &r.CouponToken, &r.Mid, &r.State, &r.StartTime, &r.ExpireTime, &r.Origin, &r.Ver, &r.BatchToken, &r.OrderNO, &r.Amount, &r.FullAmount,
&r.CTime, &r.MTime, &r.Remark); err != nil {
err = errors.WithStack(err)
res = nil
return
}
res = append(res, r)
}
err = rows.Err()
return
}

View File

@@ -0,0 +1,279 @@
package dao
import (
"context"
"math/rand"
"strconv"
"testing"
"time"
"go-common/app/service/main/coupon/model"
"go-common/library/database/sql"
xtime "go-common/library/time"
"github.com/smartystreets/goconvey/convey"
)
func TestDaohitAllowanceInfo(t *testing.T) {
var (
mid = int64(1)
)
convey.Convey("hitAllowanceInfo", t, func(ctx convey.C) {
p1 := hitAllowanceInfo(mid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
}
func TestDaohitAllowanceChangeLog(t *testing.T) {
var (
mid = int64(1)
)
convey.Convey("hitAllowanceChangeLog", t, func(ctx convey.C) {
p1 := hitAllowanceChangeLog(mid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
}
func TestDaoByStateAndExpireAllowances(t *testing.T) {
var (
c = context.TODO()
mid = int64(1)
state = int8(0)
no = int64(0)
)
convey.Convey("ByStateAndExpireAllowances", t, func(ctx convey.C) {
res, err := d.ByStateAndExpireAllowances(c, mid, state, no)
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 TestDaoAllowanceByOrderNO(t *testing.T) {
var (
c = context.TODO()
mid = int64(0)
orderNO = "1"
)
convey.Convey("AllowanceByOrderNO", t, func(ctx convey.C) {
_, err := d.AllowanceByOrderNO(c, mid, orderNO)
ctx.Convey("Then err should be nil.r should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoUsableAllowances(t *testing.T) {
var (
c = context.TODO()
mid = int64(1)
state = int8(0)
no = int64(0)
)
convey.Convey("UsableAllowances", t, func(ctx convey.C) {
_, err := d.UsableAllowances(c, mid, state, no)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoAllowanceByToken(t *testing.T) {
var (
c = context.TODO()
mid = int64(0)
token = "1"
)
convey.Convey("AllowanceByToken", t, func(ctx convey.C) {
_, err := d.AllowanceByToken(c, mid, token)
ctx.Convey("Then err should be nil.r should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoUpdateAllowanceCouponInUse(t *testing.T) {
var (
c = context.TODO()
tx = &sql.Tx{}
cp = &model.CouponAllowanceInfo{}
err error
)
convey.Convey("UpdateAllowanceCouponInUse", t, func(ctx convey.C) {
tx, err = d.BeginTran(c)
ctx.So(err, convey.ShouldBeNil)
a, err := d.UpdateAllowanceCouponInUse(c, tx, cp)
ctx.Convey("Then err should be nil.a should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(a, convey.ShouldNotBeNil)
})
})
}
func TestDaoUpdateAllowanceCouponToUse(t *testing.T) {
var (
c = context.Background()
tx, _ = d.BeginTran(c)
cp = &model.CouponAllowanceInfo{}
)
convey.Convey("UpdateAllowanceCouponToUse ", t, func(ctx convey.C) {
a, err := d.UpdateAllowanceCouponToUse(c, tx, cp)
if err == nil {
if err = tx.Commit(); err != nil {
tx.Rollback()
}
} else {
tx.Rollback()
}
ctx.Convey("Then err should be nil.a should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(a, convey.ShouldBeGreaterThanOrEqualTo, 0)
})
})
}
func TestDaoUpdateAllowanceCouponToUsed(t *testing.T) {
var (
c = context.Background()
tx, _ = d.BeginTran(c)
cp = &model.CouponAllowanceInfo{}
)
convey.Convey("UpdateAllowanceCouponToUsed ", t, func(ctx convey.C) {
a, err := d.UpdateAllowanceCouponToUsed(c, tx, cp)
if err == nil {
if err = tx.Commit(); err != nil {
tx.Rollback()
}
} else {
tx.Rollback()
}
ctx.Convey("Then err should be nil.a should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(a, convey.ShouldBeGreaterThanOrEqualTo, 0)
})
})
}
func TestDaoInsertCouponAllowanceHistory(t *testing.T) {
var (
c = context.TODO()
tx = &sql.Tx{}
l = &model.CouponAllowanceChangeLog{
CouponToken: token(),
OrderNO: "1",
}
err error
)
convey.Convey("InsertCouponAllowanceHistory", t, func(ctx convey.C) {
tx, err = d.BeginTran(c)
ctx.So(err, convey.ShouldBeNil)
a, err := d.InsertCouponAllowanceHistory(c, tx, l)
ctx.Convey("Then err should be nil.a should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(a, convey.ShouldNotBeNil)
})
})
}
func TestDaoCountByAllowanceBranchToken(t *testing.T) {
var (
c = context.TODO()
mid = int64(0)
token = "allowance_test1"
)
convey.Convey("CountByAllowanceBranchToken", t, func(ctx convey.C) {
count, err := d.CountByAllowanceBranchToken(c, mid, token)
ctx.Convey("Then err should be nil.count should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(count, convey.ShouldNotBeNil)
})
})
}
func TestDaoGetCouponByOrderNo(t *testing.T) {
var (
c = context.TODO()
mid = int64(0)
orderNo = "allowance_test1"
)
convey.Convey("GetCouponByOrderNo ", t, func(ctx convey.C) {
res, err := d.GetCouponByOrderNo(c, mid, orderNo)
ctx.Convey("Then err should be not nil.res should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldNotBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
}
func TestDaoTxAddAllowanceCoupon(t *testing.T) {
var (
c = context.Background()
tx, _ = d.BeginTran(c)
cp = &model.CouponAllowanceInfo{CouponToken: strconv.FormatInt(rand.Int63n(999999), 10)}
)
convey.Convey("TxAddAllowanceCoupon ", t, func(ctx convey.C) {
err := d.TxAddAllowanceCoupon(tx, cp)
if err == nil {
if err = tx.Commit(); err != nil {
tx.Rollback()
}
} else {
tx.Rollback()
}
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoBatchAddAllowanceCoupon(t *testing.T) {
var (
c = context.TODO()
tx = &sql.Tx{}
mid = int64(0)
cps = []*model.CouponAllowanceInfo{}
err error
)
convey.Convey("BatchAddAllowanceCoupon", t, func(ctx convey.C) {
cps = append(cps, &model.CouponAllowanceInfo{
CouponToken: token(),
Mid: mid,
State: model.NotUsed,
StartTime: time.Now().Unix(),
ExpireTime: time.Now().AddDate(0, 0, 10).Unix(),
Origin: int64(1),
CTime: xtime.Time(time.Now().Unix()),
BatchToken: "1",
Amount: float64(1),
FullAmount: float64(100),
AppID: int64(1),
})
tx, err = d.BeginTran(c)
ctx.So(err, convey.ShouldBeNil)
_, err = d.BatchAddAllowanceCoupon(c, tx, mid, cps)
ctx.Convey("Then err should be nil.a should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoAllowanceList(t *testing.T) {
var (
c = context.TODO()
mid = int64(0)
state = int8(0)
no = int64(0)
stime = time.Now()
)
convey.Convey("AllowanceList", t, func(ctx convey.C) {
_, err := d.AllowanceList(c, mid, state, no, stime)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}

View File

@@ -0,0 +1,50 @@
package dao
import (
"context"
"net/url"
"go-common/app/service/main/coupon/model"
"go-common/library/ecode"
"github.com/pkg/errors"
)
//CaptchaToken get captcha token.
func (d *Dao) CaptchaToken(c context.Context, bid string, ip string) (res *model.Token, err error) {
args := url.Values{}
args.Add("bid", bid)
resq := new(struct {
Code int `json:"code"`
Data *model.Token `json:"data"`
})
if err = d.client.Get(c, d.c.Property.CaptchaTokenURL, ip, args, resq); err != nil {
err = errors.Wrapf(err, "dao captcha token do")
return
}
if resq.Code != ecode.OK.Code() {
err = ecode.Int(resq.Code)
err = errors.Wrapf(err, "dao captcha token code")
return
}
res = resq.Data
return
}
//CaptchaVerify get captcha verify.
func (d *Dao) CaptchaVerify(c context.Context, code string, token string, ip string) (err error) {
args := url.Values{}
args.Add("token", token)
args.Add("code", code)
resq := new(struct {
Code int `json:"code"`
})
if err = d.client.Post(c, d.c.Property.CaptchaVerifyURL, ip, args, resq); err != nil {
err = errors.Wrapf(err, "dao captcha verify do")
return
}
if resq.Code != ecode.OK.Code() {
err = ecode.CouponCodeVerifyFaildErr
}
return
}

View File

@@ -0,0 +1,45 @@
package dao
import (
"context"
"testing"
"go-common/library/ecode"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoCaptchaToken(t *testing.T) {
convey.Convey("CaptchaToken", t, func(convCtx convey.C) {
var (
c = context.Background()
bid = d.c.Property.CaptchaBID
ip = "127.0.0.1"
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
res, err := d.CaptchaToken(c, bid, ip)
convCtx.Convey("Then err should be nil.res should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoCaptchaVerify(t *testing.T) {
convey.Convey("CaptchaVerify", t, func(convCtx convey.C) {
var (
c = context.Background()
code = "xxxx"
token = "xxxx"
ip = ""
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.CaptchaVerify(c, code, token, ip)
if err == ecode.CouponCodeVerifyFaildErr {
err = nil
}
convCtx.So(err, convey.ShouldBeNil)
})
})
}

View File

@@ -0,0 +1,50 @@
package dao
import (
"context"
xsql "database/sql"
"go-common/app/service/main/coupon/model"
"go-common/library/database/sql"
"github.com/pkg/errors"
)
const (
_couponCodeSQL = "SELECT id,batch_token,state,code,mid,coupon_type,ver FROM coupon_code WHERE code = ?;"
_countCouponCountSQL = "SELECT COUNT(1) FROM coupon_code WHERE mid = ? AND batch_token = ?;"
_updateCodeStateSQL = "UPDATE coupon_code SET state = ?, mid = ?,coupon_token = ?, ver = ver + 1 WHERE code = ? AND ver = ? AND state = 1;"
)
// CouponCode get open info by code.
func (d *Dao) CouponCode(c context.Context, code string) (res *model.CouponCode, err error) {
res = new(model.CouponCode)
if err = d.db.QueryRow(c, _couponCodeSQL, code).
Scan(&res.ID, &res.BatchToken, &res.State, &res.Code, &res.Mid, &res.CouponType, &res.Ver); err != nil {
if err == sql.ErrNoRows {
res = nil
err = nil
return
}
err = errors.Wrapf(err, "dao coupon code(%s)", code)
}
return
}
// CountCodeByMid get count code by mid.
func (d *Dao) CountCodeByMid(c context.Context, mid int64, batckToken string) (count int64, err error) {
if err = d.db.QueryRow(c, _countCouponCountSQL, mid, batckToken).Scan(&count); err != nil {
err = errors.Wrapf(err, "dao count code")
}
return
}
// TxUpdateCodeState update code state.
func (d *Dao) TxUpdateCodeState(tx *sql.Tx, a *model.CouponCode) (aff int64, err error) {
var res xsql.Result
if res, err = tx.Exec(_updateCodeStateSQL, a.State, a.Mid, a.CouponToken, a.Code, a.Ver); err != nil {
err = errors.Wrapf(err, "dao update code state(%+v)", a)
return
}
return res.RowsAffected()
}

View File

@@ -0,0 +1,67 @@
package dao
import (
"context"
"testing"
"go-common/app/service/main/coupon/model"
"go-common/library/database/sql"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoCouponCode(t *testing.T) {
convey.Convey("CouponCode", t, func(convCtx convey.C) {
var (
c = context.Background()
code = "2asazxcvfdsb"
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
res, err := d.CouponCode(c, code)
convCtx.Convey("Then err should be nil.res should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoCountCodeByMid(t *testing.T) {
convey.Convey("CountCodeByMid", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(1)
batckToken = "allowance_batch100"
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
count, err := d.CountCodeByMid(c, mid, batckToken)
convCtx.Convey("Then err should be nil.count should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(count, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoTxUpdateCodeState(t *testing.T) {
convey.Convey("TxUpdateCodeState", t, func(convCtx convey.C) {
var (
tx = &sql.Tx{}
a = &model.CouponCode{
State: 2,
Mid: 1,
Ver: 1,
}
err error
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
tx, err = d.BeginTran(context.Background())
convCtx.So(err, convey.ShouldBeNil)
aff, err := d.TxUpdateCodeState(tx, a)
convCtx.Convey("Then err should be nil.aff should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(aff, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,61 @@
package dao
import (
"context"
"time"
"go-common/app/service/main/coupon/conf"
"go-common/library/cache/memcache"
xsql "go-common/library/database/sql"
bm "go-common/library/net/http/blademaster"
"go-common/library/stat/prom"
)
// Dao dao
type Dao struct {
c *conf.Config
mc *memcache.Pool
db *xsql.DB
errProm *prom.Prom
mcExpire int32
prizeExpire int32
client *bm.Client
}
// New init mysql db
func New(c *conf.Config) (dao *Dao) {
dao = &Dao{
c: c,
mc: memcache.NewPool(c.Memcache.Config),
db: xsql.NewMySQL(c.MySQL),
errProm: prom.BusinessErrCount,
mcExpire: int32(time.Duration(c.Memcache.Expire) / time.Second),
prizeExpire: int32(time.Duration(c.Memcache.PrizeExpire) / time.Second),
client: bm.NewClient(c.HTTPClient),
}
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 {
d.errProm.Incr("ping_db")
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: d.mcExpire}
return conn.Set(&item)
}

View File

@@ -0,0 +1,65 @@
package dao
import (
"context"
"flag"
"os"
"strings"
"testing"
"go-common/app/service/main/coupon/conf"
"github.com/smartystreets/goconvey/convey"
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-service")
flag.Set("conf_token", "6f73e99036aecfafd140c193c036120b")
flag.Set("tree_id", "22595")
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-service.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,36 @@
package dao
import (
"context"
"go-common/library/log"
"go-common/library/net/metadata"
"net/url"
"strconv"
"github.com/pkg/errors"
)
const (
couponSystemNotify = 4
couponMC = "10_99_1"
sendMessage = "/api/notify/send.user.notify.do"
)
//SendMessage send message.
func (d *Dao) SendMessage(c context.Context, mids, content, title string) (err error) {
params := url.Values{}
params.Set("mc", couponMC)
params.Set("title", title)
params.Set("context", content)
params.Set("data_type", strconv.FormatInt(couponSystemNotify, 10))
params.Set("mid_list", mids)
defer func() {
log.Info("send message url:%+v params:%+v err:%+v ", d.c.Property.MessageURL+sendMessage, params, err)
}()
ip := metadata.String(c, metadata.RemoteIP)
if err = d.client.Post(c, d.c.Property.MessageURL+sendMessage, ip, params, nil); err != nil {
err = errors.WithStack(err)
}
return
}

View File

@@ -0,0 +1,29 @@
package dao
import (
"context"
"testing"
gock "gopkg.in/h2non/gock.v1"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoSendMessage(t *testing.T) {
convey.Convey("SendMessage", t, func(convCtx convey.C) {
var (
c = context.Background()
mids = ""
content = ""
title = ""
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
defer gock.OffAll()
httpMock("POST", sendMessage).Reply(200).JSON(`{"code":0}`)
err := d.SendMessage(c, mids, content, title)
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
})
}

View File

@@ -0,0 +1,507 @@
package dao
import (
"context"
"fmt"
"go-common/app/service/main/coupon/model"
gmc "go-common/library/cache/memcache"
"go-common/library/log"
"github.com/pkg/errors"
)
const (
_prefixCoupons = "cs:%d:%d"
_prefixUseUnique = "cu:%s:%d"
_prefixCouponBlance = "cbl:%d:%d"
_prefixGrantUnique = "gr:%s:%d"
_prefixBranchCount = "bcu:%s"
_useLockTimeout = 10
_prefixCouponAllowances = "cas:%d:%d"
_receiveLog = "rl:%s%s%d"
_uniqueNo = "uq:%s"
_useUniqueNoTimeout = 1296000 //15天
_prefixprizeCard = "nypc:%d:%d:%d" // 元旦活动卡片
_prefixprizeCards = "nypcs:%d:%d" // 元旦活动卡片列表
)
func receiveLogKey(appkey, orderNo string, ct int8) string {
return fmt.Sprintf(_receiveLog, appkey, orderNo, ct)
}
func couponsKey(mid int64, ct int8) string {
return fmt.Sprintf(_prefixCoupons, ct, mid)
}
func useUniqueKey(orderNO string, ct int8) string {
return fmt.Sprintf(_prefixUseUnique, orderNO, ct)
}
func couponBalancesKey(mid int64, ct int8) string {
return fmt.Sprintf(_prefixCouponBlance, ct, mid)
}
func userGrantKey(token string, mid int64) string {
return fmt.Sprintf(_prefixGrantUnique, token, mid)
}
func branchCurrentCount(token string) string {
return fmt.Sprintf(_prefixBranchCount, token)
}
func couponAllowancesKey(mid int64, state int8) string {
return fmt.Sprintf(_prefixCouponAllowances, mid, state)
}
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)
}
func couponuniqueNoKey(uniqueno string) string {
return fmt.Sprintf(_uniqueNo, uniqueno)
}
// DelUniqueKey delete use coupon lock cache.
func (d *Dao) DelUniqueKey(c context.Context, orderNO string, ct int8) (err error) {
return d.delCache(c, useUniqueKey(orderNO, ct))
}
// 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))
}
// 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))
}
// DelGrantKey delete user grant lock cache.
func (d *Dao) DelGrantKey(c context.Context, token string, mid int64) (err error) {
return d.delCache(c, userGrantKey(token, mid))
}
// DelBranchCurrentCountKey delete branch current cache.
func (d *Dao) DelBranchCurrentCountKey(c context.Context, token string) (err error) {
return d.delCache(c, branchCurrentCount(token))
}
// DelCouponAllowancesKey delete allowances cache.
func (d *Dao) DelCouponAllowancesKey(c context.Context, mid int64, state int8) (err error) {
return d.delCache(c, couponAllowancesKey(mid, state))
}
// 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) {
return d.delCache(c, prizeCardsKey(mid, actID))
}
// CouponsCache coupons cache.
func (d *Dao) CouponsCache(c context.Context, mid int64, ct int8) (coupons []*model.CouponInfo, err error) {
var (
key = couponsKey(mid, ct)
item *gmc.Item
)
conn := d.mc.Get(c)
defer conn.Close()
item, err = conn.Get(key)
if err != nil {
if err == gmc.ErrNotFound {
err = nil
return
}
err = errors.Wrapf(err, "mc.Get(%s)", key)
d.errProm.Incr("get_mc")
return
}
couponInfoList := &model.PointInfoList{}
if err = conn.Scan(item, couponInfoList); err != nil {
err = errors.Wrapf(err, "mc.Scan(%s)", key)
d.errProm.Incr("scan_mc")
return
}
coupons = couponInfoList.PointInfoList
if coupons == nil {
coupons = []*model.CouponInfo{}
}
return
}
// SetCouponsCache set coupons cache.
func (d *Dao) SetCouponsCache(c context.Context, mid int64, ct int8, coupons []*model.CouponInfo) (err error) {
var (
expire = d.mcExpire
key = couponsKey(mid, ct)
)
conn := d.mc.Get(c)
defer conn.Close()
item := &gmc.Item{Key: key, Object: &model.PointInfoList{PointInfoList: coupons}, Expiration: expire, Flags: gmc.FlagProtobuf}
if err = conn.Set(item); err != nil {
err = errors.Wrapf(err, "mc.Set(%s)", key)
d.errProm.Incr("set_mc")
}
return
}
// AddUseUniqueLock add coupon use lock.
func (d *Dao) AddUseUniqueLock(c context.Context, orderNO string, ct int8) (succeed bool) {
var (
key = useUniqueKey(orderNO, ct)
conn = d.mc.Get(c)
err error
)
defer conn.Close()
item := &gmc.Item{
Key: key,
Value: []byte("0"),
Expiration: _useLockTimeout,
}
if err = conn.Add(item); err != nil {
if err != gmc.ErrNotStored {
log.Error("mc.Add(%s) error(%v)", key, err)
d.errProm.Incr("add_mc")
}
} else {
succeed = true
}
return
}
// AddReceiveUniqueLock add coupon use lock.
func (d *Dao) AddReceiveUniqueLock(c context.Context, appkey, orderNO string, ct int8) (succeed bool) {
var (
key = receiveLogKey(appkey, orderNO, ct)
conn = d.mc.Get(c)
err error
)
defer conn.Close()
item := &gmc.Item{
Key: key,
Value: []byte("0"),
Expiration: _useLockTimeout,
}
if err = conn.Add(item); err != nil {
if err != gmc.ErrNotStored {
log.Error("mc.Add(%s) error(%v)", key, err)
d.errProm.Incr("add_mc")
}
} else {
succeed = true
}
return
}
//DelReceiveUniqueLock del receive lock.
func (d *Dao) DelReceiveUniqueLock(c context.Context, appkey, orderNO string, ct int8) (err error) {
err = d.delCache(c, receiveLogKey(appkey, orderNO, ct))
return
}
// 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 {
err = nil
} else {
err = errors.Wrapf(err, "mc.Delete(%s)", key)
d.errProm.Incr("del_mc")
}
}
return
}
// CouponBlanceCache coupon blance cache.
func (d *Dao) CouponBlanceCache(c context.Context, mid int64, ct int8) (coupons []*model.CouponBalanceInfo, err error) {
var (
key = couponBalancesKey(mid, ct)
item *gmc.Item
)
conn := d.mc.Get(c)
defer conn.Close()
item, err = conn.Get(key)
if err != nil {
if err == gmc.ErrNotFound {
err = nil
return
}
err = errors.Wrapf(err, "mc.Get(%s)", key)
d.errProm.Incr("get_mc")
return
}
couponBlanceList := &model.CouponBalanceList{}
if err = conn.Scan(item, couponBlanceList); err != nil {
err = errors.Wrapf(err, "mc.Scan(%s)", key)
d.errProm.Incr("scan_mc")
return
}
coupons = couponBlanceList.CouponBalanceList
if coupons == nil {
coupons = []*model.CouponBalanceInfo{}
}
return
}
// SetCouponBlanceCache set coupon blance cache.
func (d *Dao) SetCouponBlanceCache(c context.Context, mid int64, ct int8, coupons []*model.CouponBalanceInfo) (err error) {
var (
expire = d.mcExpire
key = couponBalancesKey(mid, ct)
)
conn := d.mc.Get(c)
defer conn.Close()
item := &gmc.Item{Key: key, Object: &model.CouponBalanceList{CouponBalanceList: coupons}, Expiration: expire, Flags: gmc.FlagProtobuf}
if err = conn.Set(item); err != nil {
err = errors.Wrapf(err, "mc.Set(%s)", key)
d.errProm.Incr("set_mc")
}
return
}
// AddUniqueNoLock add grant coupon use lock.
func (d *Dao) AddUniqueNoLock(c context.Context, uniqueno string) (succeed bool) {
var (
key = couponuniqueNoKey(uniqueno)
conn = d.mc.Get(c)
err error
)
defer conn.Close()
item := &gmc.Item{
Key: key,
Value: []byte("0"),
Expiration: _useUniqueNoTimeout,
}
if err = conn.Add(item); err != nil {
if err != gmc.ErrNotStored {
log.Error("mc.Add(%s) error(%v)", key, err)
d.errProm.Incr("add_mc")
}
} else {
succeed = true
}
return
}
// AddGrantUniqueLock add grant unique coupon use lock.
func (d *Dao) AddGrantUniqueLock(c context.Context, token string, mid int64) (succeed bool) {
var (
key = userGrantKey(token, mid)
conn = d.mc.Get(c)
err error
)
defer conn.Close()
item := &gmc.Item{
Key: key,
Value: []byte("0"),
Expiration: _useLockTimeout,
}
if err = conn.Add(item); err != nil {
if err != gmc.ErrNotStored {
log.Error("mc.Add(%s) error(%v)", key, err)
d.errProm.Incr("add_mc")
}
} else {
succeed = true
}
return
}
//BranchCurrentCountCache branchInfo current count cache.
func (d *Dao) BranchCurrentCountCache(c context.Context, token string) (count int, err error) {
var (
key = branchCurrentCount(token)
conn = d.mc.Get(c)
item *gmc.Item
)
defer conn.Close()
if item, err = conn.Get(key); err != nil {
if err == gmc.ErrNotFound {
err = nil
count = -1
return
}
err = errors.Wrapf(err, "conn.Get(%s)", key)
return
}
if err = conn.Scan(item, &count); err != nil {
err = errors.Wrapf(err, "conn.Scan(%+v)", item)
return
}
return
}
// SetBranchCurrentCountCache set branch current cache.
func (d *Dao) SetBranchCurrentCountCache(c context.Context, token string, count int) (err error) {
var (
key = branchCurrentCount(token)
conn = d.mc.Get(c)
)
defer conn.Close()
if err = conn.Set(&gmc.Item{Key: key, Object: count, Flags: gmc.FlagJSON, Expiration: d.mcExpire}); err != nil {
err = errors.Wrapf(err, "conn.Set(%s,%+v)", key, count)
return
}
return
}
// IncreaseBranchCurrentCountCache increase branch current count cache.
func (d *Dao) IncreaseBranchCurrentCountCache(c context.Context, token string, count uint64) (err error) {
var (
key = branchCurrentCount(token)
conn = d.mc.Get(c)
)
defer conn.Close()
if _, err = conn.Increment(key, count); err != nil {
err = errors.Wrapf(err, "conn.Increment(%s,%d)", key, count)
return
}
return
}
// CouponAllowanceCache coupon allowance cache.
func (d *Dao) CouponAllowanceCache(c context.Context, mid int64, state int8) (coupons []*model.CouponAllowanceInfo, err error) {
var (
key = couponAllowancesKey(mid, state)
item *gmc.Item
)
conn := d.mc.Get(c)
defer conn.Close()
item, err = conn.Get(key)
if err != nil {
if err == gmc.ErrNotFound {
err = nil
coupons = nil
return
}
err = errors.Wrapf(err, "mc.Get(%s)", key)
d.errProm.Incr("get_mc")
return
}
couponAllowanceList := &model.CouponAllowanceList{}
if err = conn.Scan(item, couponAllowanceList); err != nil {
err = errors.Wrapf(err, "mc.Scan(%s)", key)
d.errProm.Incr("scan_mc")
return
}
coupons = couponAllowanceList.CouponAllowanceList
if coupons == nil {
coupons = []*model.CouponAllowanceInfo{}
}
return
}
// SetCouponAllowanceCache set coupon allowance cache.
func (d *Dao) SetCouponAllowanceCache(c context.Context, mid int64, state int8, coupons []*model.CouponAllowanceInfo) (err error) {
var (
expire = d.mcExpire
key = couponAllowancesKey(mid, state)
)
conn := d.mc.Get(c)
defer conn.Close()
item := &gmc.Item{Key: key, Object: &model.CouponAllowanceList{CouponAllowanceList: coupons}, Expiration: expire, Flags: gmc.FlagProtobuf}
if err = conn.Set(item); err != nil {
err = errors.Wrapf(err, "mc.Set(%s)", key)
d.errProm.Incr("set_mc")
}
return
}
// SetPrizeCardCache .
func (d *Dao) SetPrizeCardCache(c context.Context, mid, actID int64, prizeCard *model.PrizeCardRep) (err error) {
var (
expire = d.prizeExpire
key = prizeCardKey(mid, actID, prizeCard.CardType)
)
conn := d.mc.Get(c)
defer conn.Close()
item := &gmc.Item{Key: key, Object: prizeCard, Expiration: expire, Flags: gmc.FlagJSON}
if err = conn.Set(item); err != nil {
err = errors.Wrapf(err, "mc.Set(%s)", key)
d.errProm.Incr("set_mc")
}
return
}
// SetPrizeCardsCache .
func (d *Dao) SetPrizeCardsCache(c context.Context, mid, actID int64, prizeCards []*model.PrizeCardRep) (err error) {
var (
expire = d.prizeExpire
key = prizeCardsKey(mid, actID)
)
conn := d.mc.Get(c)
defer conn.Close()
item := &gmc.Item{Key: key, Object: &model.PrizeCards{List: prizeCards}, Expiration: expire, Flags: gmc.FlagJSON}
if err = conn.Set(item); err != nil {
err = errors.Wrapf(err, "mc.Set(%s)", key)
d.errProm.Incr("set_mc")
}
return
}
// PrizeCardCache .
func (d *Dao) PrizeCardCache(c context.Context, mid, actID int64, cardType int8) (prizeCard *model.PrizeCardRep, err error) {
var (
key = prizeCardKey(mid, actID, cardType)
item *gmc.Item
)
conn := d.mc.Get(c)
defer conn.Close()
item, err = conn.Get(key)
if err != nil {
if err == gmc.ErrNotFound {
err = nil
return
}
err = errors.Wrapf(err, "mc.Get(%s)", key)
d.errProm.Incr("get_mc")
return
}
prizeCard = &model.PrizeCardRep{}
if err = conn.Scan(item, &prizeCard); err != nil {
err = errors.Wrapf(err, "mc.Scan(%s)", key)
d.errProm.Incr("scan_mc")
return
}
return
}
// PrizeCardsCache .
func (d *Dao) PrizeCardsCache(c context.Context, mid, actID int64) (prizeCards []*model.PrizeCardRep, err error) {
var (
key = prizeCardsKey(mid, actID)
item *gmc.Item
)
conn := d.mc.Get(c)
defer conn.Close()
item, err = conn.Get(key)
if err != nil {
if err == gmc.ErrNotFound {
err = nil
return
}
err = errors.Wrapf(err, "mc.Get(%s)", key)
d.errProm.Incr("get_mc")
return
}
PrizeCardlist := &model.PrizeCards{}
if err = conn.Scan(item, PrizeCardlist); err != nil {
err = errors.Wrapf(err, "mc.Scan(%s)", key)
d.errProm.Incr("scan_mc")
return
}
prizeCards = PrizeCardlist.List
if prizeCards == nil {
prizeCards = []*model.PrizeCardRep{}
}
return
}

View File

@@ -0,0 +1,519 @@
package dao
import (
"context"
"testing"
"go-common/app/service/main/coupon/model"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoreceiveLogKey(t *testing.T) {
var (
appkey = "123"
orderNo = "456"
ct = int8(0)
)
convey.Convey("TestDaoreceiveLogKey ", t, func(ctx convey.C) {
p1 := receiveLogKey(appkey, orderNo, ct)
ctx.Convey("Then p1 should equal.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldEqual, "rl:1234560")
})
})
}
func TestDaoprizeCardKey(t *testing.T) {
var (
mid int64 = 22
actID int64 = 1
ct = int8(0)
)
convey.Convey("TestDaoprizeCardKey ", t, func(ctx convey.C) {
p1 := prizeCardKey(mid, actID, ct)
ctx.Convey("Then p1 should equal.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldEqual, "nypc:22:1:0")
})
})
}
func TestDaoprizeCardsKey(t *testing.T) {
var (
mid int64 = 22
actID int64 = 1
)
convey.Convey("TestDaoprizeCardsKey ", t, func(ctx convey.C) {
p1 := prizeCardsKey(mid, actID)
ctx.Convey("Then p1 should equal.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldEqual, "nypcs:22:1")
})
})
}
func TestDaocouponuniqueNoKey(t *testing.T) {
var (
uniqueno string = "uniqueno"
)
convey.Convey("TestDaocouponuniqueNoKey ", t, func(ctx convey.C) {
p1 := couponuniqueNoKey(uniqueno)
ctx.Convey("Then p1 should equal.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldEqual, "uq:uniqueno")
})
})
}
func TestDaocouponsKey(t *testing.T) {
var (
mid = int64(0)
ct = int8(0)
)
convey.Convey("couponsKey ", t, func(ctx convey.C) {
p1 := couponsKey(mid, ct)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
}
func TestDaouseUniqueKey(t *testing.T) {
var (
orderNO = "1"
ct = int8(0)
)
convey.Convey("useUniqueKey", t, func(ctx convey.C) {
p1 := useUniqueKey(orderNO, ct)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
}
func TestDaocouponBalancesKey(t *testing.T) {
var (
mid = int64(0)
ct = int8(0)
)
convey.Convey("couponBalancesKey", t, func(ctx convey.C) {
p1 := couponBalancesKey(mid, ct)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
}
func TestDaouserGrantKey(t *testing.T) {
var (
token = "1"
mid = int64(0)
)
convey.Convey("userGrantKey", t, func(ctx convey.C) {
p1 := userGrantKey(token, mid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
}
func TestDaobranchCurrentCount(t *testing.T) {
var (
token = "1"
)
convey.Convey("branchCurrentCount", t, func(ctx convey.C) {
p1 := branchCurrentCount(token)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
}
func TestDaocouponAllowancesKey(t *testing.T) {
var (
mid = int64(0)
)
convey.Convey("couponAllowancesKey", t, func(ctx convey.C) {
p1 := couponAllowancesKey(mid, 0)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
}
func TestDaoDelUniqueKey(t *testing.T) {
var (
c = context.TODO()
orderNO = "1"
ct = int8(0)
)
convey.Convey("DelUniqueKey", t, func(ctx convey.C) {
err := d.DelUniqueKey(c, orderNO, ct)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoDelCouponsCache(t *testing.T) {
var (
c = context.TODO()
mid = int64(0)
ct = int8(0)
)
convey.Convey("DelCouponsCache", t, func(ctx convey.C) {
err := d.DelCouponsCache(c, mid, ct)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoDelCouponBalancesCache(t *testing.T) {
var (
c = context.TODO()
mid = int64(0)
ct = int8(0)
)
convey.Convey("DelCouponBalancesCache", t, func(ctx convey.C) {
err := d.DelCouponBalancesCache(c, mid, ct)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoDelGrantKey(t *testing.T) {
var (
c = context.TODO()
token = "1"
mid = int64(0)
)
convey.Convey("DelGrantKey", t, func(ctx convey.C) {
err := d.DelGrantKey(c, token, mid)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoDelBranchCurrentCountKey(t *testing.T) {
var (
c = context.TODO()
token = "1"
)
convey.Convey("DelBranchCurrentCountKey", t, func(ctx convey.C) {
err := d.DelBranchCurrentCountKey(c, token)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoDelCouponAllowancesKey(t *testing.T) {
var (
c = context.Background()
mid = int64(0)
)
convey.Convey("DelCouponAllowancesKey", t, func(ctx convey.C) {
err := d.DelCouponAllowancesKey(c, mid, 0)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoDelPrizeCardKey(t *testing.T) {
var (
c = context.Background()
mid int64 = 22
actID int64 = 1
ct = int8(0)
)
convey.Convey("DelPrizeCardKey", t, func(ctx convey.C) {
err := d.DelPrizeCardKey(c, mid, actID, ct)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoDelPrizeCardsKey(t *testing.T) {
var (
c = context.Background()
mid int64 = 22
actID int64 = 1
)
convey.Convey("DelCouponAllowancesKey", t, func(ctx convey.C) {
err := d.DelPrizeCardsKey(c, mid, actID)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoCouponsCache(t *testing.T) {
var (
c = context.TODO()
mid = int64(0)
ct = int8(0)
coupons = []*model.CouponInfo{}
err error
)
convey.Convey("CouponsCache", t, func(ctx convey.C) {
coupons, err = d.CouponsCache(c, mid, ct)
ctx.Convey("Then err should be nil.coupons should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(coupons, convey.ShouldBeNil)
})
err = d.SetCouponsCache(c, mid, ct, coupons)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
coupons, err = d.CouponsCache(c, mid, ct)
ctx.Convey("Then err should be nil.coupons should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(coupons, convey.ShouldNotBeNil)
})
})
}
func TestDaoAddUseUniqueLock(t *testing.T) {
var (
c = context.TODO()
orderNO = "1"
ct = int8(0)
)
convey.Convey("AddUseUniqueLock", t, func(ctx convey.C) {
succeed := d.AddUseUniqueLock(c, orderNO, ct)
ctx.Convey("Then succeed should not be nil.", func(ctx convey.C) {
ctx.So(succeed, convey.ShouldNotBeNil)
})
})
}
func TestDaoAddReceiveUniqueLock(t *testing.T) {
var (
c = context.TODO()
appkey = "1"
orderNO = "2"
ct = int8(0)
)
convey.Convey("AddReceiveUniqueLock", t, func(ctx convey.C) {
succeed := d.AddReceiveUniqueLock(c, appkey, orderNO, ct)
ctx.Convey("Then succeed should not be nil.", func(ctx convey.C) {
ctx.So(succeed, convey.ShouldNotBeNil)
})
})
}
func TestDaoDelReceiveUniqueLock(t *testing.T) {
var (
c = context.TODO()
appkey = "1"
orderNO = "1"
ct = int8(0)
)
convey.Convey("DelReceiveUniqueLock ", t, func(ctx convey.C) {
err := d.DelReceiveUniqueLock(c, appkey, orderNO, ct)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaodelCache(t *testing.T) {
var (
c = context.TODO()
key = "1"
)
convey.Convey("delCache", t, func(ctx convey.C) {
err := d.delCache(c, key)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoCouponBlanceCache(t *testing.T) {
var (
c = context.TODO()
mid = int64(0)
ct = int8(0)
coupons = []*model.CouponBalanceInfo{}
)
convey.Convey("CouponBlanceCache", t, func(ctx convey.C) {
err := d.SetCouponBlanceCache(c, mid, ct, coupons)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
coupons, err := d.CouponBlanceCache(c, mid, ct)
ctx.Convey("Then err should be nil.coupons should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(coupons, convey.ShouldNotBeNil)
})
})
}
func TestDaoAddUniqueNoLock(t *testing.T) {
var (
c = context.TODO()
uniqueno = "1"
)
convey.Convey("AddUniqueNoLock", t, func(ctx convey.C) {
succeed := d.AddUniqueNoLock(c, uniqueno)
ctx.Convey("Then succeed should not be nil.", func(ctx convey.C) {
ctx.So(succeed, convey.ShouldNotBeNil)
})
})
}
func TestDaoAddGrantUniqueLock(t *testing.T) {
var (
c = context.TODO()
token = "1"
mid = int64(0)
)
convey.Convey("AddGrantUniqueLock", t, func(ctx convey.C) {
succeed := d.AddGrantUniqueLock(c, token, mid)
ctx.Convey("Then succeed should not be nil.", func(ctx convey.C) {
ctx.So(succeed, convey.ShouldNotBeNil)
})
})
}
func TestDaoBranchCurrentCountCache(t *testing.T) {
var (
c = context.TODO()
token = "1"
)
convey.Convey("BranchCurrentCountCache", t, func(ctx convey.C) {
count, err := d.BranchCurrentCountCache(c, token)
ctx.Convey("Then err should be nil.count should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(count, convey.ShouldNotBeNil)
})
})
}
func TestDaoSetBranchCurrentCountCache(t *testing.T) {
var (
c = context.TODO()
token = "1"
count = int(0)
)
convey.Convey("SetBranchCurrentCountCache", t, func(ctx convey.C) {
err := d.SetBranchCurrentCountCache(c, token, count)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoIncreaseBranchCurrentCountCache(t *testing.T) {
var (
c = context.TODO()
token = "1"
count = uint64(0)
)
convey.Convey("IncreaseBranchCurrentCountCache", t, func(ctx convey.C) {
err := d.IncreaseBranchCurrentCountCache(c, token, count)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoCouponAllowanceCache(t *testing.T) {
var (
c = context.TODO()
mid = int64(0)
coupons = []*model.CouponAllowanceInfo{}
)
convey.Convey("CouponAllowanceCache", t, func(ctx convey.C) {
err := d.SetCouponAllowanceCache(c, mid, 0, coupons)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
coupons, err := d.CouponAllowanceCache(c, mid, 0)
ctx.Convey("Then err should be nil.coupons should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(coupons, convey.ShouldNotBeNil)
})
})
}
func TestDaoSetPrizeCardCache(t *testing.T) {
var (
c = context.TODO()
mid int64 = 1
actID int64 = 1
prizeCard = &model.PrizeCardRep{}
)
convey.Convey("SetPrizeCardCache ", t, func(ctx convey.C) {
err := d.SetPrizeCardCache(c, mid, actID, prizeCard)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoSetPrizeCardsCache(t *testing.T) {
var (
c = context.TODO()
mid = int64(1)
actID = int64(1)
prizeCards = make([]*model.PrizeCardRep, 0)
prizeCard = &model.PrizeCardRep{}
)
prizeCards = append(prizeCards, prizeCard)
convey.Convey("SetPrizeCardsCache ", t, func(ctx convey.C) {
err := d.SetPrizeCardsCache(c, mid, actID, prizeCards)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoPrizeCardCache(t *testing.T) {
var (
c = context.TODO()
mid = int64(1)
actID = int64(1)
ct = int8(0)
prizeCard = &model.PrizeCardRep{}
)
convey.Convey("PrizeCardCache", t, func(ctx convey.C) {
d.SetPrizeCardCache(c, mid, actID, prizeCard)
res, err := d.PrizeCardCache(c, mid, actID, ct)
ctx.Convey("Then err should be nil.res should be not nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
d.DelPrizeCardKey(c, mid, actID, ct)
res, err = d.PrizeCardCache(c, mid, actID, ct)
ctx.Convey("Then err should be nil.res should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldBeNil)
})
})
}
func TestDaoPrizeCardsCache(t *testing.T) {
var (
c = context.TODO()
mid = int64(1)
actID = int64(1)
prizeCards = make([]*model.PrizeCardRep, 0)
prizeCard = &model.PrizeCardRep{}
)
prizeCards = append(prizeCards, prizeCard)
convey.Convey("PrizeCardCache", t, func(ctx convey.C) {
d.SetPrizeCardsCache(c, mid, actID, prizeCards)
res, err := d.PrizeCardsCache(c, mid, actID)
ctx.Convey("Then err should be nil.res should be not nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
d.DelPrizeCardsKey(c, mid, actID)
res, err = d.PrizeCardsCache(c, mid, actID)
ctx.Convey("Then err should be nil.res should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldBeNil)
})
})
}

View File

@@ -0,0 +1,741 @@
package dao
import (
"bytes"
"context"
xsql "database/sql"
"fmt"
"strconv"
"time"
"go-common/app/service/main/coupon/model"
"go-common/library/database/sql"
"go-common/library/xstr"
"github.com/pkg/errors"
)
const (
_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 mid = ? AND state = ? AND coupon_type = ? AND expire_time > ? AND start_time < ? ORDER BY expire_time;"
_couponsNoStartCheckSQL = "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 mid = ? AND state = ? AND coupon_type = ? AND expire_time > ? ORDER BY expire_time;"
_couponByOrderNOAndTypeSQL = "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 order_no = ? AND coupon_type = ?;"
_updateCouponInUseSQL = "UPDATE coupon_info_%02d SET state =?, order_no = ?, oid = ?, remark = ?,use_ver = ?,ver = ? WHERE coupon_token = ? AND ver = ?;"
_addCouponChangeLogSQL = "INSERT INTO coupon_change_log_%02d (coupon_token,mid,state,ctime) VALUES(?,?,?,?);"
_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 = ?;"
_couponPageNotUsedSQL = "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 mid = ? AND state = ? AND expire_time > ? AND start_time < ? AND ctime > ? ORDER BY mtime DESC LIMIT ?,?;"
_couponPageUsedSQL = "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 mid = ? AND state = ? AND ctime > ? ORDER BY mtime DESC LIMIT ?,?;"
_couponPageExpireSQL = "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 mid = ? AND state = 0 AND expire_time < ? AND ctime > ? ORDER BY mtime DESC LIMIT ?,?;"
_countNotUsedSQL = "SELECT COUNT(1) FROM coupon_info_%02d WHERE mid = ? AND state = ? AND expire_time > ? AND start_time < ? AND ctime > ? ;"
_countUsedSQL = "SELECT COUNT(1) FROM coupon_info_%02d WHERE mid = ? AND state = ? AND ctime > ? ;"
_countExpireSQL = "SELECT COUNT(1) FROM coupon_info_%02d WHERE mid = ? AND state = 0 AND expire_time < ? AND ctime > ? ;"
_addCouponSQL = "INSERT INTO coupon_info_%02d (coupon_token,mid,state,start_time,expire_time,origin,coupon_type,ctime)VALUES(?,?,?,?,?,?,?,?);"
_updateStateSQL = "UPDATE coupon_info_%02d SET state = ?,use_ver = ?,ver = ? WHERE coupon_token = ? AND ver = ? "
_batchAddCouponSQL = "INSERT INTO coupon_info_%02d (coupon_token,mid,state,start_time,expire_time,origin,coupon_type,ctime,batch_token)VALUES "
_batchCountByMid = "SELECT COUNT(1) FROM coupon_info_%02d WHERE mid = ? AND batch_token = ?;"
//coupon blance
_couponBlanceNoStartCheckSQL = "SELECT id,batch_token,mid,balance,start_time,expire_time,origin,coupon_type,ver,ctime,mtime FROM coupon_balance_info_%02d WHERE mid = ? AND expire_time > ? AND coupon_type = ? ORDER BY expire_time;"
_couponBlanceSQL = "SELECT id,batch_token,mid,balance,start_time,expire_time,origin,coupon_type,ver,ctime,mtime FROM coupon_balance_info_%02d WHERE mid = ? AND expire_time > ? AND coupon_type = ? AND start_time < ? ORDER BY expire_time;"
_orderByThirdTradeNoSQL = "SELECT id,order_no,mid,count,state,coupon_type,third_trade_no,remark,tips,use_ver,ver,ctime,mtime FROM coupon_order WHERE third_trade_no = ? AND coupon_type= ?;"
_updateBlanceSQL = "UPDATE coupon_balance_info_%02d SET balance = ?,ver = ver + 1 WHERE id = ? AND ver = ?;"
_addOrderSQL = "INSERT INTO coupon_order(order_no,mid,count,state,coupon_type,third_trade_no,remark,tips,use_ver,ver,ctime)VALUES(?,?,?,?,?,?,?,?,?,?,?);"
_addOrderLogSQL = "INSERT INTO coupon_order_log(order_no,mid,state,ctime)VALUES(?,?,?,?);"
_addBalanceLogSQL = "INSERT INTO coupon_balance_change_log_%02d(order_no,mid,batch_token,balance,change_balance,change_type,ctime)VALUES "
_batchUpdateBalance = "UPDATE coupon_balance_info_%02d SET ver =ver + 1, balance = CASE id"
_countBalanceNotUsed = "SELECT COUNT(1) FROM coupon_balance_info_%02d WHERE mid = ? AND expire_time > ? AND start_time < ? AND coupon_type = ? AND balance > 0 AND ctime > ? ;"
_countUseListSQL = "SELECT COUNT(1) FROM coupon_order WHERE mid= ? AND state= ? AND coupon_type = ? AND ctime > ? ;"
_countBalanceExpire = "SELECT COUNT(1) FROM coupon_balance_info_%02d WHERE mid = ? AND expire_time < ? AND coupon_type = ? AND balance > 0 AND ctime > ? ;"
_balanceNotUsedPageSQL = "SELECT id,batch_token,mid,balance,start_time,expire_time,origin,coupon_type,ver,ctime,mtime FROM coupon_balance_info_%02d WHERE mid = ? AND expire_time > ? AND start_time < ? AND coupon_type = ? AND balance > 0 AND ctime > ? ORDER BY id DESC LIMIT ?,?;"
_useOrderPageSQL = "SELECT id,order_no,mid,count,state,coupon_type,third_trade_no,remark,tips,use_ver,ver,ctime,mtime FROM coupon_order WHERE mid= ? AND state= ? AND coupon_type = ? AND ctime > ? ORDER BY id DESC LIMIT ?,?;"
_balanceExpirePageSQL = "SELECT id,batch_token,mid,balance,start_time,expire_time,origin,coupon_type,ver,ctime,mtime FROM coupon_balance_info_%02d WHERE mid = ? AND expire_time < ? AND coupon_type = ? AND balance > 0 AND ctime > ? ORDER BY id DESC LIMIT ?,?;"
_addBalanceCouponSQL = "INSERT INTO coupon_balance_info_%02d(batch_token,mid,balance,start_time,expire_time,origin,coupon_type,ver,ctime) VALUES(?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE balance = balance + ?,ver = ver + 1 ;"
_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 = ? ;"
_addBlanceChangeLog = "INSERT INTO coupon_balance_change_log_%02d(order_no,mid,batch_token,balance,change_balance,change_type,ctime)VALUES(?,?,?,?,?,?,?);"
_batchInfoSQL = "SELECT id,app_id,name,batch_token,max_count,current_count,start_time,expire_time,expire_day,ver,ctime,limit_count,full_amount,amount,state,coupon_type FROM coupon_batch_info WHERE batch_token = ?;"
_updateBatchSQL = "UPDATE coupon_batch_info SET current_count = current_count + ? WHERE batch_token = ?;"
_updateBatchLimitSQL = "UPDATE coupon_batch_info SET current_count = current_count + ? WHERE batch_token = ? AND current_count + ? <= max_count;"
_grantCouponLogSQL = "SELECT id,order_no,mid,batch_token,balance,change_balance,change_type,ctime,mtime FROM coupon_balance_change_log_%02d WHERE mid = ? AND batch_token = ? AND change_type = ?;"
_allBatchInfoSQL = "SELECT id,app_id,name,batch_token,max_count,current_count,start_time,expire_time,expire_day,ver,ctime,limit_count,full_amount,amount,state,coupon_type,platform_limit,product_limit_month,product_limit_renewal FROM coupon_batch_info;"
_couponReceiveSQL = "SELECT id,appkey,order_no,mid,coupon_token,coupon_type FROM coupon_receive_log WHERE order_no=? AND appkey=? AND coupon_type=?"
_addReceiveSQL = "INSERT INTO coupon_receive_log(appkey,order_no,mid,coupon_token,coupon_type) VALUES(?,?,?,?,?)"
)
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
}
// BeginTran begin transaction.
func (d *Dao) BeginTran(c context.Context) (*sql.Tx, error) {
return d.db.Begin(c)
}
// CouponList query .
func (d *Dao) CouponList(c context.Context, mid int64, state int8, ct int8, t int64) (res []*model.CouponInfo, err error) {
var rows *sql.Rows
if rows, err = d.db.Query(c, fmt.Sprintf(_couponsSQL, hitInfo(mid)), mid, state, ct, t, 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
}
// CouponNoStartCheckList had not check start query .
func (d *Dao) CouponNoStartCheckList(c context.Context, mid int64, state int8, ct int8, t int64) (res []*model.CouponInfo, err error) {
var rows *sql.Rows
if rows, err = d.db.Query(c, fmt.Sprintf(_couponsNoStartCheckSQL, hitInfo(mid)), mid, state, ct, 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
}
// BlanceNoStartCheckList had not check start query .
func (d *Dao) BlanceNoStartCheckList(c context.Context, mid int64, ct int8, t int64) (res []*model.CouponBalanceInfo, err error) {
var rows *sql.Rows
if rows, err = d.db.Query(c, fmt.Sprintf(_couponBlanceNoStartCheckSQL, hitUser(mid)), mid, t, 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
}
// ByOrderNO query coupon by orderno and type.
func (d *Dao) ByOrderNO(c context.Context, mid int64, orderNO string, ct int8) (r *model.CouponInfo, err error) {
var row *sql.Row
r = &model.CouponInfo{}
row = d.db.QueryRow(c, fmt.Sprintf(_couponByOrderNOAndTypeSQL, hitInfo(mid)), orderNO, ct)
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 == sql.ErrNoRows {
err = nil
r = nil
return
}
err = errors.WithStack(err)
return
}
return
}
// UpdateCouponInUse update coupon in use.
func (d *Dao) UpdateCouponInUse(c context.Context, tx *sql.Tx, cp *model.CouponInfo) (a int64, err error) {
var res xsql.Result
if res, err = tx.Exec(fmt.Sprintf(_updateCouponInUseSQL, hitInfo(cp.Mid)), cp.State, cp.OrderNO, cp.Oid, cp.Remark, cp.UseVer, cp.Ver+1,
cp.CouponToken, cp.Ver); err != nil {
err = errors.WithStack(err)
return
}
if a, err = res.RowsAffected(); err != nil {
err = errors.WithStack(err)
return
}
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
}
// 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 == sql.ErrNoRows {
err = nil
r = nil
return
}
err = errors.WithStack(err)
return
}
return
}
// CountByState coupon count buy state.
func (d *Dao) CountByState(c context.Context, mid int64, state int8, t int64, stime time.Time) (count int64, err error) {
var row *sql.Row
switch state {
case model.NotUsed:
row = d.db.QueryRow(c, fmt.Sprintf(_countNotUsedSQL, hitInfo(mid)), mid, state, t, t, stime)
case model.Used:
row = d.db.QueryRow(c, fmt.Sprintf(_countUsedSQL, hitInfo(mid)), mid, state, stime)
case model.Expire:
row = d.db.QueryRow(c, fmt.Sprintf(_countExpireSQL, hitInfo(mid)), mid, t, stime)
default:
return
}
if err = row.Scan(&count); err != nil {
if err == sql.ErrNoRows {
err = nil
} else {
err = errors.WithStack(err)
}
}
return
}
// CouponPage page.
func (d *Dao) CouponPage(c context.Context, mid int64, state int8, t int64, start int, ps int, stime time.Time) (res []*model.CouponInfo, err error) {
var rows *sql.Rows
switch state {
case model.NotUsed:
rows, err = d.db.Query(c, fmt.Sprintf(_couponPageNotUsedSQL, hitInfo(mid)), mid, state, t, t, stime, start, ps)
case model.Used:
rows, err = d.db.Query(c, fmt.Sprintf(_couponPageUsedSQL, hitInfo(mid)), mid, state, stime, start, ps)
case model.Expire:
rows, err = d.db.Query(c, fmt.Sprintf(_couponPageExpireSQL, hitInfo(mid)), mid, t, stime, start, ps)
default:
return
}
if 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
}
// AddCoupon add coupon.
func (d *Dao) AddCoupon(c context.Context, cp *model.CouponInfo) (a int64, err error) {
var res xsql.Result
if res, err = d.db.Exec(c, fmt.Sprintf(_addCouponSQL, hitInfo(cp.Mid)), cp.CouponToken, cp.Mid, cp.State, cp.StartTime, cp.ExpireTime, cp.Origin, cp.CouponType, cp.CTime); err != nil {
err = errors.WithStack(err)
return
}
if a, err = res.RowsAffected(); err != nil {
err = errors.WithStack(err)
return
}
return
}
// BatchAddCoupon batch add coupon.
func (d *Dao) BatchAddCoupon(c context.Context, tx *sql.Tx, mid int64, cps []*model.CouponInfo) (a int64, err error) {
var (
buf bytes.Buffer
res xsql.Result
sql string
)
buf.WriteString(fmt.Sprintf(_batchAddCouponSQL, hitInfo(mid)))
for _, v := range cps {
buf.WriteString("('")
buf.WriteString(v.CouponToken)
buf.WriteString("',")
buf.WriteString(strconv.FormatInt(v.Mid, 10))
buf.WriteString(",")
buf.WriteString(strconv.FormatInt(v.State, 10))
buf.WriteString(",")
buf.WriteString(strconv.FormatInt(v.StartTime, 10))
buf.WriteString(",")
buf.WriteString(strconv.FormatInt(v.ExpireTime, 10))
buf.WriteString(",")
buf.WriteString(strconv.FormatInt(v.Origin, 10))
buf.WriteString(",")
buf.WriteString(strconv.FormatInt(v.CouponType, 10))
buf.WriteString(",'")
buf.WriteString(v.CTime.Time().Format("2006-01-02 15:04:05"))
buf.WriteString("','")
buf.WriteString(v.BatchToken)
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
}
// UpdateCoupon update coupon in use.
func (d *Dao) UpdateCoupon(c context.Context, mid int64, state int8, useVer int64, ver int64, couponToken string) (a int64, err error) {
var res xsql.Result
if res, err = d.db.Exec(c, 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
}
// ByThirdTradeNo query order by third trade no.
func (d *Dao) ByThirdTradeNo(c context.Context, thirdTradeNo string, ct int8) (r *model.CouponOrder, err error) {
var row *sql.Row
r = &model.CouponOrder{}
row = d.db.QueryRow(c, _orderByThirdTradeNoSQL, thirdTradeNo, ct)
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
}
// CouponBlances query coupon blances .
func (d *Dao) CouponBlances(c context.Context, mid int64, ct int8, t int64) (res []*model.CouponBalanceInfo, err error) {
var rows *sql.Rows
if rows, err = d.db.Query(c, fmt.Sprintf(_couponBlanceSQL, hitUser(mid)), mid, t, ct, t); 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
}
// 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
}
// 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
}
// AddOrder add order.
func (d *Dao) AddOrder(c context.Context, tx *sql.Tx, o *model.CouponOrder) (a int64, err error) {
var res xsql.Result
if res, err = tx.Exec(_addOrderSQL, o.OrderNo, o.Mid, o.Count, o.State, o.CouponType, o.ThirdTradeNo, o.Remark, o.Tips, o.UseVer, o.Ver, o.Ctime); err != nil {
err = errors.WithStack(err)
return
}
if a, err = res.RowsAffected(); err != nil {
err = errors.WithStack(err)
}
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
}
// CouponCarToonCount coupon cartoon page.
func (d *Dao) CouponCarToonCount(c context.Context, mid int64, t int64, ct int8, state int8, stime time.Time) (count int64, err error) {
var row *sql.Row
switch state {
case model.NotUsed:
row = d.db.QueryRow(c, fmt.Sprintf(_countBalanceNotUsed, hitUser(mid)), mid, t, t, ct, stime)
case model.Used:
row = d.db.QueryRow(c, _countUseListSQL, mid, state, ct, stime)
case model.Expire:
row = d.db.QueryRow(c, fmt.Sprintf(_countBalanceExpire, hitUser(mid)), mid, t, ct, stime)
default:
return
}
if err = row.Scan(&count); err != nil {
if err == sql.ErrNoRows {
err = nil
} else {
err = errors.WithStack(err)
}
}
return
}
// CouponNotUsedPage query coupon page .
func (d *Dao) CouponNotUsedPage(c context.Context, mid int64, ct int8, t int64, stime time.Time, pn int, ps int) (res []*model.CouponBalanceInfo, err error) {
var rows *sql.Rows
if rows, err = d.db.Query(c, fmt.Sprintf(_balanceNotUsedPageSQL, hitUser(mid)), mid, t, t, ct, stime, (pn-1)*ps, ps); 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
}
// CouponExpirePage query coupon page .
func (d *Dao) CouponExpirePage(c context.Context, mid int64, ct int8, t int64, stime time.Time, pn int, ps int) (res []*model.CouponBalanceInfo, err error) {
var rows *sql.Rows
if rows, err = d.db.Query(c, fmt.Sprintf(_balanceExpirePageSQL, hitUser(mid)), mid, t, ct, stime, (pn-1)*ps, ps); 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
}
// OrderUsedPage order used page.
func (d *Dao) OrderUsedPage(c context.Context, mid int64, state int8, ct int8, stime time.Time, pn int, ps int) (res []*model.CouponOrder, err error) {
var rows *sql.Rows
if rows, err = d.db.Query(c, _useOrderPageSQL, mid, state, ct, stime, (pn-1)*ps, ps); 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
}
// AddBalanceCoupon add balance coupon.
func (d *Dao) AddBalanceCoupon(c context.Context, tx *sql.Tx, b *model.CouponBalanceInfo) (a int64, err error) {
var res xsql.Result
if res, err = tx.Exec(fmt.Sprintf(_addBalanceCouponSQL, hitUser(b.Mid)), b.BatchToken, b.Mid, b.Balance, b.StartTime, b.ExpireTime, b.Origin, b.CouponType, b.Ver, b.CTime,
b.Balance); err != nil {
err = errors.WithStack(err)
return
}
if a, err = res.RowsAffected(); err != nil {
err = errors.WithStack(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
}
// AddBalanceChangeLog add coupon balance change log.
func (d *Dao) AddBalanceChangeLog(c context.Context, tx *sql.Tx, bl *model.CouponBalanceChangeLog) (a int64, err error) {
var res xsql.Result
if res, err = tx.Exec(fmt.Sprintf(_addBlanceChangeLog, hitUserLog(bl.Mid)), bl.OrderNo, bl.Mid, bl.BatchToken, bl.Balance, bl.ChangeBalance, bl.ChangeType, bl.Ctime); err != nil {
err = errors.WithStack(err)
return
}
if a, err = res.RowsAffected(); err != nil {
err = errors.WithStack(err)
return
}
return
}
// BatchInfo batch info.
func (d *Dao) BatchInfo(c context.Context, token string) (r *model.CouponBatchInfo, err error) {
var row *sql.Row
r = new(model.CouponBatchInfo)
row = d.db.QueryRow(c, _batchInfoSQL, token)
if err = row.Scan(&r.ID, &r.AppID, &r.Name, &r.BatchToken, &r.MaxCount, &r.CurrentCount, &r.StartTime, &r.ExpireTime, &r.ExpireDay, &r.Ver, &r.Ctime, &r.LimitCount,
&r.FullAmount, &r.Amount, &r.State, &r.CouponType); err != nil {
if err == sql.ErrNoRows {
err = nil
r = nil
return
}
err = errors.WithStack(err)
return
}
return
}
// UpdateBatchInfo update batch info.
func (d *Dao) UpdateBatchInfo(c context.Context, tx *sql.Tx, token string, count int) (a int64, err error) {
var res xsql.Result
if res, err = tx.Exec(_updateBatchSQL, count, token); err != nil {
err = errors.WithStack(err)
return
}
if a, err = res.RowsAffected(); err != nil {
err = errors.WithStack(err)
return
}
return
}
// UpdateBatchLimitInfo update batch limit info.
func (d *Dao) UpdateBatchLimitInfo(c context.Context, tx *sql.Tx, token string, count int) (a int64, err error) {
var res xsql.Result
if res, err = tx.Exec(_updateBatchLimitSQL, count, token, count); err != nil {
err = errors.WithStack(err)
return
}
if a, err = res.RowsAffected(); err != nil {
err = errors.WithStack(err)
return
}
return
}
// GrantCouponLog grant coupon log.
func (d *Dao) GrantCouponLog(c context.Context, mid int64, token string, ct int8) (rs []*model.CouponBalanceChangeLog, err error) {
var rows *sql.Rows
if rows, err = d.db.Query(c, fmt.Sprintf(_grantCouponLogSQL, hitUserLog(mid)), mid, token, 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
}
// AllBranchInfo query all branch info .
func (d *Dao) AllBranchInfo(c context.Context) (res []*model.CouponBatchInfo, err error) {
var rows *sql.Rows
if rows, err = d.db.Query(c, _allBatchInfoSQL); err != nil {
err = errors.WithStack(err)
return
}
defer rows.Close()
for rows.Next() {
r := &model.CouponBatchInfo{}
if err = rows.Scan(&r.ID, &r.AppID, &r.Name, &r.BatchToken, &r.MaxCount, &r.CurrentCount, &r.StartTime, &r.ExpireTime, &r.ExpireDay, &r.Ver, &r.Ctime,
&r.LimitCount, &r.FullAmount, &r.Amount, &r.State, &r.CouponType, &r.PlatformLimit, &r.ProdLimMonth, &r.ProdLimRenewal); err != nil {
err = errors.WithStack(err)
res = nil
return
}
res = append(res, r)
}
err = rows.Err()
return
}
// CountByBranchToken get user count by bratch token.
func (d *Dao) CountByBranchToken(c context.Context, mid int64, token string) (count int64, err error) {
row := d.db.QueryRow(c, fmt.Sprintf(_batchCountByMid, hitInfo(mid)), mid, token)
if err = row.Scan(&count); err != nil {
err = errors.WithStack(err)
}
return
}
//ReceiveLog get receive log.
func (d *Dao) ReceiveLog(c context.Context, appkey, orderNo string, ct int8) (r *model.CouponReceiveLog, err error) {
row := d.db.QueryRow(c, _couponReceiveSQL, orderNo, appkey, ct)
r = new(model.CouponReceiveLog)
if err = row.Scan(&r.ID, &r.Appkey, &r.OrderNo, &r.Mid, &r.CouponToken, &r.CouponType); err != nil {
if err == sql.ErrNoRows {
r = nil
err = nil
return
}
err = errors.WithStack(err)
}
return
}
//TxAddReceiveLog add receive log.
func (d *Dao) TxAddReceiveLog(tx *sql.Tx, rlog *model.CouponReceiveLog) (err error) {
if _, err = tx.Exec(_addReceiveSQL, rlog.Appkey, rlog.OrderNo, rlog.Mid, rlog.CouponToken, rlog.CouponType); err != nil {
err = errors.WithStack(err)
}
return
}

View File

@@ -0,0 +1,708 @@
package dao
import (
"bytes"
"context"
"fmt"
"math/rand"
"testing"
"time"
"go-common/app/service/main/coupon/model"
"go-common/library/database/sql"
xtime "go-common/library/time"
"github.com/smartystreets/goconvey/convey"
)
func TestDaohitInfo(t *testing.T) {
var (
mid = int64(0)
)
convey.Convey("hitInfo", t, func(ctx convey.C) {
p1 := hitInfo(mid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
}
func TestDaohitChangeLog(t *testing.T) {
var (
mid = int64(0)
)
convey.Convey("hitChangeLog", t, func(ctx convey.C) {
p1 := hitChangeLog(mid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
}
func TestDaohitUser(t *testing.T) {
var (
mid = int64(0)
)
convey.Convey("hitUser", t, func(ctx convey.C) {
p1 := hitUser(mid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
}
func TestDaohitUserLog(t *testing.T) {
var (
mid = int64(0)
)
convey.Convey("hitUserLog", t, func(ctx convey.C) {
p1 := hitUserLog(mid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
}
func TestDaoBeginTran(t *testing.T) {
var (
c = context.TODO()
)
convey.Convey("BeginTran", t, func(ctx convey.C) {
p1, err := d.BeginTran(c)
ctx.Convey("Then err should be nil.p1 should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(p1, convey.ShouldNotBeNil)
})
})
}
func TestDaoCouponList(t *testing.T) {
var (
c = context.TODO()
mid = int64(0)
state = int8(0)
ct = int8(0)
no = int64(0)
)
convey.Convey("CouponList", t, func(ctx convey.C) {
_, err := d.CouponList(c, mid, state, ct, no)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoCouponNoStartCheckList(t *testing.T) {
var (
c = context.TODO()
mid = int64(0)
state = int8(0)
ct = int8(0)
no = int64(0)
)
convey.Convey("CouponNoStartCheckList", t, func(ctx convey.C) {
_, err := d.CouponNoStartCheckList(c, mid, state, ct, no)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoBlanceNoStartCheckList(t *testing.T) {
var (
c = context.TODO()
mid = int64(0)
ct = int8(0)
no = int64(0)
)
convey.Convey("BlanceNoStartCheckList", t, func(ctx convey.C) {
_, err := d.BlanceNoStartCheckList(c, mid, ct, no)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoByOrderNO(t *testing.T) {
var (
c = context.TODO()
mid = int64(1)
orderNO = "1235378892"
ct = int8(1)
)
convey.Convey("ByOrderNO", t, func(ctx convey.C) {
r, err := d.ByOrderNO(c, mid, orderNO, ct)
ctx.Convey("Then err should be nil.r should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(r, convey.ShouldNotBeNil)
})
})
}
func TestDaoUpdateCouponInUse(t *testing.T) {
var (
c = context.TODO()
tx = &sql.Tx{}
cp = &model.CouponInfo{}
a int64
err error
)
convey.Convey("UpdateCouponInUse", t, func(ctx convey.C) {
tx, err = d.BeginTran(c)
ctx.So(err, convey.ShouldBeNil)
a, err = d.UpdateCouponInUse(c, tx, cp)
ctx.Convey("Then err should be nil.a should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(a, convey.ShouldNotBeNil)
})
})
}
func TestDaoInsertPointHistory(t *testing.T) {
var (
c = context.TODO()
tx = &sql.Tx{}
l = &model.CouponChangeLog{}
err error
)
convey.Convey("InsertPointHistory", t, func(ctx convey.C) {
tx, err = d.BeginTran(c)
ctx.So(err, convey.ShouldBeNil)
a, err := d.InsertPointHistory(c, tx, l)
ctx.Convey("Then err should be nil.a should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(a, convey.ShouldNotBeNil)
})
})
}
func TestDaoCouponInfo(t *testing.T) {
var (
c = context.TODO()
mid = int64(27515401)
token = "581807988720180417190545"
)
convey.Convey("CouponInfo", t, func(ctx convey.C) {
r, err := d.CouponInfo(c, mid, token)
ctx.Convey("Then err should be nil.r should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(r, convey.ShouldNotBeNil)
})
})
}
func TestDaoCountByState(t *testing.T) {
var (
c = context.TODO()
mid = int64(0)
state = int8(0)
no = int64(0)
stime = time.Now()
)
convey.Convey("CountByState", t, func(ctx convey.C) {
count, err := d.CountByState(c, mid, state, no, stime)
ctx.Convey("Then err should be nil.count should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(count, convey.ShouldNotBeNil)
})
})
}
func TestDaoCouponPage(t *testing.T) {
var (
c = context.TODO()
mid = int64(0)
state = int8(0)
no = int64(0)
start = int(0)
ps = int(0)
stime = time.Now()
)
convey.Convey("CouponPage", t, func(ctx convey.C) {
_, err := d.CouponPage(c, mid, state, no, start, ps, stime)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoAddCoupon(t *testing.T) {
var (
c = context.TODO()
cp = &model.CouponInfo{
Mid: 1,
CouponToken: token(),
State: 0,
StartTime: time.Now().Unix(),
ExpireTime: time.Now().AddDate(0, 0, 1).Unix(),
}
)
convey.Convey("AddCoupon", t, func(ctx convey.C) {
a, err := d.AddCoupon(c, cp)
ctx.Convey("Then err should be nil.a should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(a, convey.ShouldNotBeNil)
})
})
}
func TestDaoBatchAddCoupon(t *testing.T) {
var (
c = context.TODO()
tx = &sql.Tx{}
mid = int64(0)
cps = []*model.CouponInfo{}
err error
a int64
)
convey.Convey("BatchAddCoupon", t, func(ctx convey.C) {
cp := &model.CouponInfo{}
cp.CouponToken = token()
cp.Mid = mid
cp.State = model.NotUsed
cp.StartTime = time.Now().Unix()
cp.ExpireTime = time.Now().AddDate(0, 0, 2).Unix()
cp.Origin = 1
cp.CouponType = 1
cp.CTime = xtime.Time(time.Now().Unix())
cp.BatchToken = "1234"
cps = append(cps, cp)
tx, err = d.BeginTran(c)
ctx.So(err, convey.ShouldBeNil)
a, err = d.BatchAddCoupon(c, tx, mid, cps)
ctx.Convey("Then err should be nil.a should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(a, convey.ShouldNotBeNil)
})
})
}
func TestDaoUpdateCoupon(t *testing.T) {
var (
c = context.TODO()
mid = int64(27515800)
state = int8(0)
useVer = int64(0)
ver = int64(1)
couponToken = "510204683920180420110002"
)
convey.Convey("UpdateCoupon", t, func(ctx convey.C) {
_, err := d.UpdateCoupon(c, mid, state, useVer, ver, couponToken)
ctx.Convey("Then err should be nil.a should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoByThirdTradeNo(t *testing.T) {
var (
c = context.TODO()
thirdTradeNo = "12156121892"
ct = int8(2)
)
convey.Convey("ByThirdTradeNo", t, func(ctx convey.C) {
r, err := d.ByThirdTradeNo(c, thirdTradeNo, ct)
ctx.Convey("Then err should be nil.r should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(r, convey.ShouldNotBeNil)
})
})
}
func TestDaoCouponBlances(t *testing.T) {
var (
c = context.TODO()
mid = int64(520)
ct = int8(2)
no = int64(0)
)
convey.Convey("CouponBlances", t, func(ctx convey.C) {
_, err := d.CouponBlances(c, mid, ct, no)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoUpdateBlance(t *testing.T) {
var (
c = context.TODO()
tx = &sql.Tx{}
id = int64(0)
mid = int64(0)
ver = int64(0)
balance = int64(0)
a int64
err error
)
convey.Convey("UpdateBlance", t, func(ctx convey.C) {
tx, err = d.BeginTran(c)
ctx.So(err, convey.ShouldBeNil)
a, err = d.UpdateBlance(c, tx, id, mid, ver, balance)
ctx.Convey("Then err should be nil.a should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(a, convey.ShouldNotBeNil)
})
})
}
func TestDaoBatchUpdateBlance(t *testing.T) {
var (
c = context.TODO()
tx = &sql.Tx{}
mid = int64(1)
blances = []*model.CouponBalanceInfo{}
err error
)
blances = append(blances, &model.CouponBalanceInfo{
ID: 116197,
Balance: 1,
Ver: 0,
})
convey.Convey("BatchUpdateBlance", t, func(ctx convey.C) {
tx, err = d.BeginTran(c)
ctx.So(err, convey.ShouldBeNil)
_, err = d.BatchUpdateBlance(c, tx, mid, blances)
ctx.Convey("Then err should be nil.a should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
err = tx.Commit()
ctx.So(err, convey.ShouldBeNil)
})
}
func TestDaoBatchInsertBlanceLog(t *testing.T) {
var (
c = context.TODO()
tx = &sql.Tx{}
mid = int64(0)
ls = []*model.CouponBalanceChangeLog{}
err error
)
convey.Convey("BatchInsertBlanceLog", t, func(ctx convey.C) {
blog := new(model.CouponBalanceChangeLog)
blog.OrderNo = "11"
blog.Mid = mid
blog.BatchToken = "123"
blog.ChangeType = model.Consume
blog.Ctime = xtime.Time(time.Now().Unix())
ls = append(ls, blog)
tx, err = d.BeginTran(c)
ctx.So(err, convey.ShouldBeNil)
_, err = d.BatchInsertBlanceLog(c, tx, mid, ls)
ctx.Convey("Then err should be nil.a should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
err = tx.Commit()
ctx.So(err, convey.ShouldBeNil)
})
}
func TestDaoAddOrder(t *testing.T) {
var (
c = context.TODO()
tx = &sql.Tx{}
o = &model.CouponOrder{}
a int64
err error
)
convey.Convey("AddOrder", t, func(ctx convey.C) {
tx, err = d.BeginTran(c)
ctx.So(err, convey.ShouldBeNil)
a, err = d.AddOrder(c, tx, o)
ctx.Convey("Then err should be nil.a should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(a, convey.ShouldNotBeNil)
})
})
}
func TestDaoAddOrderLog(t *testing.T) {
var (
c = context.TODO()
tx = &sql.Tx{}
o = &model.CouponOrderLog{}
a int64
err error
)
convey.Convey("AddOrderLog", t, func(ctx convey.C) {
tx, err = d.BeginTran(c)
ctx.So(err, convey.ShouldBeNil)
a, err = d.AddOrderLog(c, tx, o)
ctx.Convey("Then err should be nil.a should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(a, convey.ShouldNotBeNil)
})
})
}
func TestDaoCouponCarToonCount(t *testing.T) {
var (
c = context.TODO()
mid = int64(0)
no = int64(0)
ct = int8(0)
state = int8(0)
stime = time.Now()
)
convey.Convey("CouponCarToonCount", t, func(ctx convey.C) {
count, err := d.CouponCarToonCount(c, mid, no, ct, state, stime)
ctx.Convey("Then err should be nil.count should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(count, convey.ShouldNotBeNil)
})
})
}
func TestDaoCouponNotUsedPage(t *testing.T) {
var (
c = context.TODO()
mid = int64(0)
ct = int8(0)
no = int64(0)
stime = time.Now()
pn = int(0)
ps = int(0)
)
convey.Convey("CouponNotUsedPage", t, func(ctx convey.C) {
_, err := d.CouponNotUsedPage(c, mid, ct, no, stime, pn, ps)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoCouponExpirePage(t *testing.T) {
var (
c = context.TODO()
mid = int64(27515301)
ct = int8(1)
no = time.Now().Unix()
stime = time.Now().AddDate(-1, 0, 0)
pn = int(1)
ps = int(10)
)
convey.Convey("CouponExpirePage", t, func(ctx convey.C) {
_, err := d.CouponExpirePage(c, mid, ct, no, stime, pn, ps)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoOrderUsedPage(t *testing.T) {
var (
c = context.TODO()
mid = int64(0)
state = int8(0)
ct = int8(0)
stime = time.Now()
pn = int(0)
ps = int(0)
)
convey.Convey("OrderUsedPage", t, func(ctx convey.C) {
_, err := d.OrderUsedPage(c, mid, state, ct, stime, pn, ps)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoAddBalanceCoupon(t *testing.T) {
var (
c = context.TODO()
tx = &sql.Tx{}
b = &model.CouponBalanceInfo{}
a int64
err error
)
convey.Convey("AddBalanceCoupon", t, func(ctx convey.C) {
tx, err = d.BeginTran(c)
ctx.So(err, convey.ShouldBeNil)
a, err = d.AddBalanceCoupon(c, tx, b)
ctx.Convey("Then err should be nil.a should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(a, convey.ShouldNotBeNil)
})
})
}
func TestDaoByMidAndBatchToken(t *testing.T) {
var (
c = context.TODO()
mid = int64(1)
batchToken = "441539420220180806174505"
)
convey.Convey("ByMidAndBatchToken", t, func(ctx convey.C) {
_, err := d.ByMidAndBatchToken(c, mid, batchToken)
ctx.Convey("Then err should be nil.r should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoAddBalanceChangeLog(t *testing.T) {
var (
c = context.TODO()
tx = &sql.Tx{}
bl = &model.CouponBalanceChangeLog{}
a int64
err error
)
convey.Convey("AddBalanceChangeLog", t, func(ctx convey.C) {
tx, err = d.BeginTran(c)
ctx.So(err, convey.ShouldBeNil)
a, err = d.AddBalanceChangeLog(c, tx, bl)
ctx.Convey("Then err should be nil.a should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(a, convey.ShouldNotBeNil)
})
})
}
func TestDaoBatchInfo(t *testing.T) {
var (
c = context.TODO()
token = "900364604420180912170927"
)
convey.Convey("BatchInfo", t, func(ctx convey.C) {
r, err := d.BatchInfo(c, token)
ctx.Convey("Then err should be nil.r should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(r, convey.ShouldNotBeNil)
})
})
}
func TestDaoUpdateBatchInfo(t *testing.T) {
var (
c = context.TODO()
tx = &sql.Tx{}
token = ""
count = int(0)
a int64
err error
)
convey.Convey("UpdateBatchInfo", t, func(ctx convey.C) {
tx, err = d.BeginTran(c)
ctx.So(err, convey.ShouldBeNil)
a, err = d.UpdateBatchInfo(c, tx, token, count)
ctx.Convey("Then err should be nil.a should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(a, convey.ShouldNotBeNil)
})
})
}
func TestDaoUpdateBatchLimitInfo(t *testing.T) {
var (
c = context.TODO()
tx = &sql.Tx{}
token = ""
count = int(0)
a int64
err error
)
convey.Convey("UpdateBatchLimitInfo", t, func(ctx convey.C) {
tx, err = d.BeginTran(c)
ctx.So(err, convey.ShouldBeNil)
a, err = d.UpdateBatchLimitInfo(c, tx, token, count)
ctx.Convey("Then err should be nil.a should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(a, convey.ShouldNotBeNil)
})
})
}
func TestDaoGrantCouponLog(t *testing.T) {
var (
c = context.TODO()
mid = int64(0)
token = ""
ct = int8(0)
)
convey.Convey("GrantCouponLog", t, func(ctx convey.C) {
_, err := d.GrantCouponLog(c, mid, token, ct)
ctx.Convey("Then err should be nil.rs should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoAllBranchInfo(t *testing.T) {
var (
c = context.TODO()
)
convey.Convey("AllBranchInfo", t, func(ctx convey.C) {
res, err := d.AllBranchInfo(c)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
}
func TestDaoCountByBranchToken(t *testing.T) {
var (
c = context.TODO()
mid = int64(0)
token = ""
)
convey.Convey("CountByBranchToken", t, func(ctx convey.C) {
count, err := d.CountByBranchToken(c, mid, token)
ctx.Convey("Then err should be nil.count should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(count, convey.ShouldNotBeNil)
})
})
}
// get coupon token
func token() string {
var b bytes.Buffer
b.WriteString(fmt.Sprintf("%03d", time.Now().UnixNano()/1e6%1000))
b.WriteString(time.Now().Format("20060102150405"))
return b.String()
}
func TestDaoReceiveLog(t *testing.T) {
var (
c = context.Background()
appkey = "7c7ac0db1aa05587"
orderNo = "1536657724"
ct int8 = 3
)
convey.Convey("ReceiveLog ", t, func(ctx convey.C) {
r, err := d.ReceiveLog(c, appkey, orderNo, ct)
ctx.Convey("Then err should be nil.r should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(r, convey.ShouldNotBeNil)
})
r, err = d.ReceiveLog(c, "", "", 21)
ctx.Convey("Then err should be nil.r should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(r, convey.ShouldBeNil)
})
})
}
func TestDaoTxAddReceiveLog(t *testing.T) {
var (
c = context.Background()
tx, _ = d.BeginTran(c)
rlog = &model.CouponReceiveLog{Appkey: fmt.Sprintf("%d", time.Now().Unix()), CouponType: int8(rand.Int63n(127))}
)
convey.Convey("TxAddReceiveLog ", t, func(ctx convey.C) {
err := d.TxAddReceiveLog(tx, rlog)
if err == nil {
if err = tx.Commit(); err != nil {
tx.Rollback()
}
} else {
tx.Rollback()
}
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}

View File

@@ -0,0 +1,84 @@
package dao
import (
"context"
xsql "database/sql"
"go-common/app/service/main/coupon/model"
"go-common/library/database/sql"
"github.com/pkg/errors"
)
const (
_userCardSQL = "SELECT card_type,state,batch_token,coupon_token,act_id FROM coupon_user_card WHERE mid=? AND act_id=? AND card_type=?"
_userCardsSQL = "SELECT card_type,state,batch_token,coupon_token,act_id FROM coupon_user_card WHERE mid=? AND act_id=?"
_addUserCardSQL = "INSERT INTO coupon_user_card(mid,card_type,state,batch_token,coupon_token,act_id) VALUES (?,?,?,?,?,?)"
_updateUserCardSQL = "UPDATE coupon_user_card SET state=? WHERE mid=? AND coupon_token=?"
)
// UserCard .
func (d *Dao) UserCard(c context.Context, mid, actID int64, cardType int8) (r *model.CouponUserCard, err error) {
var row *sql.Row
r = &model.CouponUserCard{}
row = d.db.QueryRow(c, _userCardSQL, mid, actID, cardType)
if err = row.Scan(&r.CardType, &r.State, &r.BatchToken, &r.CouponToken, &r.ActID); err != nil {
if err == sql.ErrNoRows {
err = nil
r = nil
return
}
err = errors.WithStack(err)
return
}
return
}
// UserCards .
func (d *Dao) UserCards(c context.Context, mid, actID int64) (res []*model.CouponUserCard, err error) {
var rows *sql.Rows
if rows, err = d.db.Query(c, _userCardsSQL, mid, actID); err != nil {
err = errors.WithStack(err)
return
}
defer rows.Close()
for rows.Next() {
r := &model.CouponUserCard{}
if err = rows.Scan(&r.CardType, &r.State, &r.BatchToken, &r.CouponToken, &r.ActID); err != nil {
err = errors.WithStack(err)
res = nil
return
}
res = append(res, r)
}
err = rows.Err()
return
}
// AddUserCard .
func (d *Dao) AddUserCard(c context.Context, tx *sql.Tx, uc *model.CouponUserCard) (a int64, err error) {
var res xsql.Result
if res, err = tx.Exec(_addUserCardSQL, uc.MID, uc.CardType, uc.State, uc.BatchToken, uc.CouponToken, uc.ActID); err != nil {
err = errors.WithStack(err)
return
}
if a, err = res.RowsAffected(); err != nil {
err = errors.WithStack(err)
return
}
return
}
// UpdateUserCard .
func (d *Dao) UpdateUserCard(c context.Context, mid int64, state int8, couponToken string) (a int64, err error) {
var res xsql.Result
if res, err = d.db.Exec(c, _updateUserCardSQL, state, mid, couponToken); 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,100 @@
package dao
import (
"context"
"math/rand"
"testing"
"go-common/app/service/main/coupon/model"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoUserCard(t *testing.T) {
convey.Convey("UserCard", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(88895150)
actID = int64(1)
cardType = int8(1)
noMID = int64(-1)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
r, err := d.UserCard(c, mid, actID, cardType)
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)
})
r, err = d.UserCard(c, noMID, actID, cardType)
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 TestDaoUserCards(t *testing.T) {
convey.Convey("UserCards", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(88895150)
actID = int64(1)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
res, err := d.UserCards(c, mid, actID)
convCtx.Convey("Then err should be nil.res should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoAddUserCard(t *testing.T) {
convey.Convey("AddUserCard", t, func(convCtx convey.C) {
var (
c = context.Background()
tx, _ = d.BeginTran(context.Background())
uc = &model.CouponUserCard{MID: rand.Int63n(9999999)}
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
a, err := d.AddUserCard(c, tx, uc)
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.ShouldNotBeNil)
})
})
})
}
func TestDaoUpdateUserCard(t *testing.T) {
convey.Convey("UpdateUserCard", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(0)
state = int8(0)
couponToken = ""
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
a, err := d.UpdateUserCard(c, mid, state, couponToken)
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()
})
}