Create & Init Project...

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

View File

@@ -0,0 +1,95 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_test",
"go_library",
)
go_test(
name = "go_default_test",
srcs = [
"appeal_test.go",
"blocked_mc_test.go",
"blocked_redis_test.go",
"blocked_test.go",
"case_mc_test.go",
"case_redis_test.go",
"case_test.go",
"dao_test.go",
"databus_test.go",
"http_test.go",
"jury_test.go",
"manager_test.go",
"mc_test.go",
"memcache_test.go",
"mysql_test.go",
"opinion_test.go",
"redis_test.go",
],
embed = [":go_default_library"],
rundir = ".",
tags = ["automanaged"],
deps = [
"//app/interface/main/credit/conf:go_default_library",
"//app/interface/main/credit/model:go_default_library",
"//vendor/github.com/go-sql-driver/mysql: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 = [
"appeal.go",
"blocked.go",
"blocked_mc.go",
"blocked_redis.go",
"case.go",
"case_mc.go",
"case_redis.go",
"dao.go",
"databus.go",
"http.go",
"jury.go",
"manager.go",
"memcache.go",
"mysql.go",
"opinion.go",
"redis.go",
],
importpath = "go-common/app/interface/main/credit/dao",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/interface/main/credit/conf:go_default_library",
"//app/interface/main/credit/model:go_default_library",
"//library/cache/memcache:go_default_library",
"//library/cache/redis: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/queue/databus:go_default_library",
"//library/sync/errgroup:go_default_library",
"//library/time: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,64 @@
package dao
import (
"context"
"net/url"
"strconv"
"go-common/app/interface/main/credit/model"
"go-common/library/ecode"
"go-common/library/log"
"go-common/library/net/metadata"
"github.com/pkg/errors"
)
// AddAppeal add appeal.
func (d *Dao) AddAppeal(c context.Context, tid, btid, oid, mid, business int64, content, reason string) (err error) {
params := url.Values{}
params.Set("tid", strconv.FormatInt(tid, 10))
params.Set("oid", strconv.FormatInt(oid, 10))
params.Set("mid", strconv.FormatInt(mid, 10))
params.Set("business_mid", strconv.FormatInt(mid, 10))
params.Set("business_typeid", strconv.FormatInt(btid, 10))
params.Set("business", strconv.FormatInt(business, 10))
params.Set("business_content", content)
params.Set("description", reason)
var res struct {
Code int `json:"code"`
Data *struct {
ChallengeNo int64 `json:"challengeNo"`
} `json:"data"`
}
if err = d.client.Post(c, d.addAppealURL, metadata.String(c, metadata.RemoteIP), params, &res); err != nil {
err = errors.Wrapf(err, "AddAppeal url(%s) res(%v)", d.addAppealURL+"?"+params.Encode(), res)
return
}
if res.Code != 0 {
log.Warn("add appeal url(%s) mid(%d) res(%v)", d.addAppealURL+"?"+params.Encode(), mid, res)
err = ecode.Int(res.Code)
}
return
}
// AppealList appeal list .
func (d *Dao) AppealList(c context.Context, mid int64, business int) (as []*model.Appeal, err error) {
params := url.Values{}
params.Set("mid", strconv.FormatInt(mid, 10))
params.Set("business", strconv.Itoa(business))
var res struct {
Code int `json:"code"`
Data []*model.Appeal `json:"data"`
}
if err = d.client.Get(c, d.appealListURL, metadata.String(c, metadata.RemoteIP), params, &res); err != nil {
err = errors.Wrapf(err, "AppealList url(%s) res(%v)", d.appealListURL+"?"+params.Encode(), res)
return
}
if res.Code != 0 {
log.Warn("appeal list url(%s) mid(%d) res(%v)", d.appealListURL+"?"+params.Encode(), mid, res)
err = ecode.Int(res.Code)
return
}
as = res.Data
return
}

View File

@@ -0,0 +1,58 @@
package dao
import (
"context"
"testing"
gock "gopkg.in/h2non/gock.v1"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoAddAppeal(t *testing.T) {
convey.Convey("AddAppeal", t, func(convCtx convey.C) {
var (
c = context.Background()
tid = int64(0)
btid = int64(0)
oid = int64(0)
mid = int64(0)
business = int64(0)
content = ""
reason = ""
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
defer gock.OffAll()
httpMock("POST", d.addAppealURL).Reply(200).JSON(`{"code": 0}`)
err := d.AddAppeal(c, tid, btid, oid, mid, business, content, reason)
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoAppealList(t *testing.T) {
convey.Convey("AppealList", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(0)
business = int(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
defer gock.OffAll()
httpMock("GET", d.appealListURL).Reply(200).JSON(`{"code": 0,"data":[]}`)
as, err := d.AppealList(c, mid, business)
convCtx.Convey("Then err should be nil.as should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(as, convey.ShouldNotBeNil)
})
httpMock("GET", d.appealListURL).Reply(200).JSON(`{"code": 0}`)
as, err = d.AppealList(c, mid, business)
convCtx.Convey("Then err should be nil.as should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(as, convey.ShouldBeNil)
})
})
})
}

View File

@@ -0,0 +1,272 @@
package dao
import (
"context"
"fmt"
"strconv"
"strings"
"time"
"go-common/app/interface/main/credit/model"
"go-common/library/database/sql"
"go-common/library/log"
xtime "go-common/library/time"
"go-common/library/xstr"
"github.com/pkg/errors"
)
const (
_addBlockedInfoSQL = `INSERT INTO blocked_info(uid,origin_title,blocked_remark,origin_url,origin_content,origin_content_modify,origin_type,
punish_time,punish_type,blocked_days,publish_status,blocked_type,blocked_forever,reason_type,oper_id,moral_num,operator_name) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`
_addBatchBlockedInfoSQL = `INSERT INTO blocked_info(uid,origin_title,blocked_remark,origin_url,origin_content,origin_content_modify,origin_type,
punish_time,punish_type,blocked_days,publish_status,blocked_type,blocked_forever,reason_type,oper_id,moral_num,operator_name) VALUES %s`
_blockedCountSQL = `SELECT COUNT(*) FROM blocked_info WHERE uid=? AND punish_type IN (2,3) AND status = 0`
_blockedNumUserSQL = `SELECT COUNT(*) FROM blocked_info WHERE uid = ? AND status = 0`
_blkHistoryCountSQL = "SELECT COUNT(*) FROM blocked_info WHERE uid = ? AND ctime >= ? AND status = 0"
_blockedTotalSQL = "SELECT COUNT(*) AS num FROM blocked_info WHERE uid=? AND ctime >? AND status = 0"
_blockedInfosByMidSQL = `SELECT id,case_id,uid,origin_title,origin_url,origin_content,origin_content_modify,origin_type,punish_time,punish_type,blocked_days,publish_status,blocked_type,
reason_type,blocked_remark,ctime from blocked_info WHERE uid=? AND status = 0`
_blockedListSQL = `SELECT id,origin_type,blocked_type,publish_time FROM blocked_info WHERE publish_status = 1 %s %s AND status = 0 ORDER BY publish_time desc`
_blkHistorysSQL = `SELECT id,uid,blocked_days,blocked_forever,blocked_remark,moral_num,origin_content_modify,origin_title,origin_type,origin_url,punish_time,
punish_type,reason_type FROM blocked_info WHERE uid = ? AND ctime >= ? AND status = 0 ORDER BY id LIMIT ?,?`
_blockedInfoIDSQL = `SELECT id,uid,uname,origin_content,origin_content_modify,origin_type,punish_time,punish_type,moral_num,blocked_days,reason_type,blocked_forever,origin_title,
origin_url,blocked_type,blocked_remark,case_id,ctime,publish_status from blocked_info WHERE id=? AND status = 0`
_blockedInfoIDsSQL = `SELECT id,uid,blocked_days,blocked_forever,blocked_remark,moral_num,origin_content_modify,origin_title,origin_type,origin_url,punish_time,
punish_type,reason_type FROM blocked_info WHERE id IN (%s) AND status = 0`
_blockedInfosSQL = `SELECT id,uid,uname,origin_content_modify,origin_type,punish_time,punish_type,moral_num,blocked_days,reason_type,blocked_forever,origin_title,
origin_url,blocked_type,blocked_remark,case_id,ctime,publish_status FROM blocked_info WHERE id IN (%s) AND publish_status = 1 AND status = 0 ORDER BY publish_time desc`
)
// AddBlockedInfo add blocked info
func (d *Dao) AddBlockedInfo(c context.Context, r *model.BlockedInfo) (err error) {
if _, err = d.db.Exec(c, _addBlockedInfoSQL, r.UID, r.OriginTitle, r.BlockedRemark, r.OriginURL, r.OriginContent, r.OriginContent,
r.OriginType, r.PunishTime.Time(), r.PunishType, r.BlockedDays, r.PublishStatus, r.BlockedType, r.BlockedForever,
r.ReasonType, r.OID, r.MoralNum, r.OperatorName); err != nil {
err = errors.Wrap(err, "AddBlockedInfo")
}
return
}
// TxAddBlockedInfo add blocked info
func (d *Dao) TxAddBlockedInfo(tx *sql.Tx, rs []*model.BlockedInfo) (err error) {
l := len(rs)
valueStrings := make([]string, 0, l)
valueArgs := make([]interface{}, 0, l*17)
for _, v := range rs {
valueStrings = append(valueStrings, "(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)")
valueArgs = append(valueArgs, strconv.FormatInt(v.UID, 10))
valueArgs = append(valueArgs, v.OriginTitle)
valueArgs = append(valueArgs, v.BlockedRemark)
valueArgs = append(valueArgs, v.OriginURL)
valueArgs = append(valueArgs, v.OriginContent)
valueArgs = append(valueArgs, v.OriginContent)
valueArgs = append(valueArgs, strconv.FormatInt(v.OriginType, 10))
valueArgs = append(valueArgs, v.PunishTime.Time())
valueArgs = append(valueArgs, strconv.FormatInt(v.PunishType, 10))
valueArgs = append(valueArgs, strconv.FormatInt(v.BlockedDays, 10))
valueArgs = append(valueArgs, strconv.FormatInt(v.PublishStatus, 10))
valueArgs = append(valueArgs, strconv.FormatInt(v.BlockedType, 10))
valueArgs = append(valueArgs, strconv.FormatInt(v.BlockedForever, 10))
valueArgs = append(valueArgs, strconv.FormatInt(v.ReasonType, 10))
valueArgs = append(valueArgs, strconv.FormatInt(v.OID, 10))
valueArgs = append(valueArgs, strconv.FormatInt(v.MoralNum, 10))
valueArgs = append(valueArgs, v.OperatorName)
}
stmt := fmt.Sprintf(_addBatchBlockedInfoSQL, strings.Join(valueStrings, ","))
_, err = tx.Exec(stmt, valueArgs...)
if err != nil {
err = errors.Wrapf(err, "TxAddBlockedInfo tx.Exec() error(%+v)", err)
}
return
}
// BlockedCount get user blocked count.
func (d *Dao) BlockedCount(c context.Context, mid int64) (count int, err error) {
row := d.db.QueryRow(c, _blockedCountSQL, mid)
if err = row.Scan(&count); err != nil {
err = errors.Wrap(err, "BlockedCount scan fail")
}
return
}
// BlockedNumUser get blocked user number.
func (d *Dao) BlockedNumUser(c context.Context, mid int64) (count int, err error) {
row := d.db.QueryRow(c, _blockedNumUserSQL, mid)
if err = row.Scan(&count); err != nil {
if err == sql.ErrNoRows {
err = nil
return
}
err = errors.Wrap(err, "BlockedNumUser")
}
return
}
// BLKHistoryCount get blocked historys count.
func (d *Dao) BLKHistoryCount(c context.Context, ArgHis *model.ArgHistory) (count int64, err error) {
row := d.db.QueryRow(c, _blkHistoryCountSQL, ArgHis.MID, xtime.Time(ArgHis.STime))
if err = row.Scan(&count); err != nil {
if err == sql.ErrNoRows {
err = nil
return
}
err = errors.Wrap(err, "BLKHistoryCount")
}
return
}
// BlockTotalTime get block total by time.
func (d *Dao) BlockTotalTime(c context.Context, mid int64, ts time.Time) (total int64, err error) {
row := d.db.QueryRow(c, _blockedTotalSQL, mid, ts)
if err = row.Scan(&total); err != nil {
if err != sql.ErrNoRows {
log.Error("row.Scan() error(%v)", err)
return
}
err = nil
total = 0
}
return
}
// BlockedUserList get user blocked list.
func (d *Dao) BlockedUserList(c context.Context, mid int64) (res []*model.BlockedInfo, err error) {
rows, err := d.db.Query(c, _blockedInfosByMidSQL, mid)
if err != nil {
log.Error("d.getBlockedInfosByMidStmt.Query(mid %d) error(%v)", mid, err)
err = errors.Wrap(err, "BlockedUserList")
return
}
defer rows.Close()
for rows.Next() {
r := &model.BlockedInfo{}
if err = rows.Scan(&r.ID, &r.CaseID, &r.UID, &r.OriginTitle, &r.OriginURL, &r.OriginContent, &r.OriginContentModify, &r.OriginType, &r.PunishTime, &r.PunishType,
&r.BlockedDays, &r.PublishStatus, &r.BlockedType, &r.ReasonType, &r.BlockedRemark, &r.CTime); err != nil {
if err == sql.ErrNoRows {
err = nil
return
}
}
res = append(res, r)
}
err = rows.Err()
return
}
// BlockedList get blocked list.
func (d *Dao) BlockedList(c context.Context, otype, btype int8) (res []*model.BlockedInfo, err error) {
var ostr, bstr string
if otype != 0 {
ostr = fmt.Sprintf("AND origin_type=%d ", otype)
}
if btype >= 0 {
bstr = fmt.Sprintf("AND blocked_type=%d ", btype)
}
rows, err := d.db.Query(c, fmt.Sprintf(_blockedListSQL, ostr, bstr))
if err != nil {
err = errors.Wrap(err, "BlockedInfos")
return
}
defer rows.Close()
for rows.Next() {
r := &model.BlockedInfo{}
if err = rows.Scan(&r.ID, &r.OriginType, &r.BlockedType, &r.PublishTime); err != nil {
if err == sql.ErrNoRows {
err = nil
return
}
}
res = append(res, r)
}
err = rows.Err()
return
}
// BLKHistorys get blocked historys list.
func (d *Dao) BLKHistorys(c context.Context, ah *model.ArgHistory) (res []*model.BlockedInfo, err error) {
rows, err := d.db.Query(c, _blkHistorysSQL, ah.MID, xtime.Time(ah.STime), (ah.PN-1)*ah.PS, ah.PS)
if err != nil {
err = errors.Wrap(err, "BLKHistorys")
return
}
defer rows.Close()
for rows.Next() {
bi := new(model.BlockedInfo)
if err = rows.Scan(&bi.ID, &bi.UID, &bi.BlockedDays, &bi.BlockedForever, &bi.BlockedRemark, &bi.MoralNum, &bi.OriginContentModify, &bi.OriginTitle,
&bi.OriginType, &bi.OriginURL, &bi.PunishTime, &bi.PunishType, &bi.ReasonType); err != nil {
if err == sql.ErrNoRows {
err = nil
return
}
err = errors.Wrap(err, "BLKHistorys")
return
}
res = append(res, bi)
}
err = rows.Err()
return
}
// BlockedInfoByID get blocked info by id.
func (d *Dao) BlockedInfoByID(c context.Context, id int64) (r *model.BlockedInfo, err error) {
row := d.db.QueryRow(c, _blockedInfoIDSQL, id)
r = new(model.BlockedInfo)
if err = row.Scan(&r.ID, &r.UID, &r.Uname, &r.OriginContent, &r.OriginContentModify, &r.OriginType, &r.PunishTime, &r.PunishType, &r.MoralNum,
&r.BlockedDays, &r.ReasonType, &r.BlockedForever, &r.OriginTitle, &r.OriginURL, &r.BlockedType, &r.BlockedRemark, &r.CaseID, &r.CTime, &r.PublishStatus); err != nil {
if err == sql.ErrNoRows {
err = nil
r = nil
return
}
err = errors.Wrap(err, "BlockedInfoByID")
}
return
}
// BlockedInfoIDs get blocked info by ids
func (d *Dao) BlockedInfoIDs(c context.Context, ids []int64) (res map[int64]*model.BlockedInfo, err error) {
rows, err := d.db.Query(c, fmt.Sprintf(_blockedInfoIDsSQL, xstr.JoinInts(ids)))
if err != nil {
err = errors.Wrap(err, "BlockedInfoIDs")
return
}
defer rows.Close()
res = make(map[int64]*model.BlockedInfo, len(ids))
for rows.Next() {
bi := new(model.BlockedInfo)
if err = rows.Scan(&bi.ID, &bi.UID, &bi.BlockedDays, &bi.BlockedForever, &bi.BlockedRemark, &bi.MoralNum, &bi.OriginContentModify, &bi.OriginTitle,
&bi.OriginType, &bi.OriginURL, &bi.PunishTime, &bi.PunishType, &bi.ReasonType); err != nil {
if err == sql.ErrNoRows {
err = nil
return
}
err = errors.Wrap(err, "BlockedInfoIDs")
return
}
res[bi.ID] = bi
}
err = rows.Err()
return
}
// BlockedInfos get blocked infos. Queryed without mid or id, public default.
func (d *Dao) BlockedInfos(c context.Context, ids []int64) (res []*model.BlockedInfo, err error) {
rows, err := d.db.Query(c, fmt.Sprintf(_blockedInfosSQL, xstr.JoinInts(ids)))
if err != nil {
err = errors.Wrap(err, "BlockedInfos")
return
}
defer rows.Close()
for rows.Next() {
r := &model.BlockedInfo{}
if err = rows.Scan(&r.ID, &r.UID, &r.Uname, &r.OriginContentModify, &r.OriginType, &r.PunishTime, &r.PunishType, &r.MoralNum,
&r.BlockedDays, &r.ReasonType, &r.BlockedForever, &r.OriginTitle, &r.OriginURL, &r.BlockedType, &r.BlockedRemark, &r.CaseID, &r.CTime, &r.PublishStatus); err != nil {
log.Error("BlockedInfos err %v", err)
return
}
res = append(res, r)
}
err = rows.Err()
return
}

View File

@@ -0,0 +1,127 @@
package dao
import (
"context"
"fmt"
"strconv"
"go-common/app/interface/main/credit/model"
gmc "go-common/library/cache/memcache"
)
const (
_prefixBlockedUserList = "bul_%d"
_prefixBlockInfo = "blo_%d"
)
func userBlockedListKey(mid int64) string {
return fmt.Sprintf(_prefixBlockedUserList, mid)
}
func blockedInfoKey(id int64) string {
return fmt.Sprintf(_prefixBlockInfo, id)
}
// BlockedUserListCache get user blocked list.
func (d *Dao) BlockedUserListCache(c context.Context, mid int64) (ls []*model.BlockedInfo, err error) {
var (
reply *gmc.Item
conn = d.mc.Get(c)
)
defer conn.Close()
reply, err = conn.Get(userBlockedListKey(mid))
if err != nil {
if err == gmc.ErrNotFound {
err = nil
}
return
}
ls = make([]*model.BlockedInfo, 0)
err = conn.Scan(reply, &ls)
return
}
// SetBlockedUserListCache set user blocked list cache.
func (d *Dao) SetBlockedUserListCache(c context.Context, mid int64, ls []*model.BlockedInfo) (err error) {
var (
item = &gmc.Item{Key: userBlockedListKey(mid), Object: ls, Expiration: d.userExpire, Flags: gmc.FlagJSON}
conn = d.mc.Get(c)
)
defer conn.Close()
err = conn.Set(item)
return
}
// BlockedInfoCache get blocked info by blocked id.
func (d *Dao) BlockedInfoCache(c context.Context, id int64) (info *model.BlockedInfo, err error) {
var (
reply *gmc.Item
conn = d.mc.Get(c)
key = blockedInfoKey(id)
)
defer conn.Close()
reply, err = conn.Get(key)
if err != nil {
if err == gmc.ErrNotFound {
err = nil
}
return
}
info = &model.BlockedInfo{}
err = conn.Scan(reply, &info)
return
}
// SetBlockedInfoCache set user blocked list cache.
func (d *Dao) SetBlockedInfoCache(c context.Context, id int64, info *model.BlockedInfo) (err error) {
var (
item = &gmc.Item{Key: blockedInfoKey(id), Object: info, Expiration: d.minCommonExpire, Flags: gmc.FlagJSON}
conn = d.mc.Get(c)
)
defer conn.Close()
err = conn.Set(item)
return
}
// BlockedInfosCache get blocked infos by ids.
func (d *Dao) BlockedInfosCache(c context.Context, ids []int64) (infos []*model.BlockedInfo, miss []int64, err error) {
var (
rs map[string]*gmc.Item
conn = d.mc.Get(c)
)
defer conn.Close()
keys := make([]string, len(ids))
for _, id := range ids {
keys = append(keys, blockedInfoKey(id))
}
rs, err = conn.GetMulti(keys)
if err != nil {
if err == gmc.ErrNotFound {
err = nil
}
return
}
for _, id := range ids {
if r, ok := rs[strconv.FormatInt(id, 10)]; ok {
info := &model.BlockedInfo{}
conn.Scan(r, &info)
infos = append(infos, info)
} else {
miss = append(miss, id)
}
}
return
}
// SetBlockedInfosCache set user blocked list cache.
func (d *Dao) SetBlockedInfosCache(c context.Context, infos []*model.BlockedInfo) (err error) {
conn := d.mc.Get(c)
defer conn.Close()
for _, info := range infos {
item := &gmc.Item{Key: blockedInfoKey(info.ID), Object: info, Expiration: d.minCommonExpire, Flags: gmc.FlagJSON}
if err = conn.Set(item); err != nil {
return
}
}
return
}

View File

@@ -0,0 +1,133 @@
package dao
import (
"context"
"go-common/app/interface/main/credit/model"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaouserBlockedListKey(t *testing.T) {
convey.Convey("userBlockedListKey", t, func(convCtx convey.C) {
var (
mid = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
p1 := userBlockedListKey(mid)
convCtx.Convey("Then p1 should not be nil.", func(convCtx convey.C) {
convCtx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoblockedInfoKey(t *testing.T) {
convey.Convey("blockedInfoKey", t, func(convCtx convey.C) {
var (
id = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
p1 := blockedInfoKey(id)
convCtx.Convey("Then p1 should not be nil.", func(convCtx convey.C) {
convCtx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoBlockedUserListCache(t *testing.T) {
convey.Convey("BlockedUserListCache", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(-1)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
ls, err := d.BlockedUserListCache(c, mid)
convCtx.Convey("Then err should be nil.ls should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(len(ls), convey.ShouldBeGreaterThanOrEqualTo, 0)
})
})
})
}
func TestDaoSetBlockedUserListCache(t *testing.T) {
convey.Convey("SetBlockedUserListCache", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(0)
ls = []*model.BlockedInfo{}
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.SetBlockedUserListCache(c, mid, ls)
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoBlockedInfoCache(t *testing.T) {
convey.Convey("BlockedInfoCache", t, func(convCtx convey.C) {
var (
c = context.Background()
id = int64(-1)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
info, err := d.BlockedInfoCache(c, id)
convCtx.Convey("Then err should be nil.info should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(info, convey.ShouldBeNil)
})
})
})
}
func TestDaoSetBlockedInfoCache(t *testing.T) {
convey.Convey("SetBlockedInfoCache", t, func(convCtx convey.C) {
var (
c = context.Background()
id = int64(0)
info = &model.BlockedInfo{}
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.SetBlockedInfoCache(c, id, info)
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoBlockedInfosCache(t *testing.T) {
convey.Convey("BlockedInfosCache", t, func(convCtx convey.C) {
var (
c = context.Background()
ids = []int64{234}
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
infos, miss, err := d.BlockedInfosCache(c, ids)
convCtx.Convey("Then err should not be nil.infos,miss should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldNotBeNil)
convCtx.So(miss, convey.ShouldBeNil)
convCtx.So(infos, convey.ShouldBeNil)
})
})
})
}
func TestDaoSetBlockedInfosCache(t *testing.T) {
convey.Convey("SetBlockedInfosCache", t, func(convCtx convey.C) {
var (
c = context.Background()
infos = []*model.BlockedInfo{}
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.SetBlockedInfosCache(c, infos)
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
})
}

View File

@@ -0,0 +1,65 @@
package dao
import (
"context"
"fmt"
"go-common/app/interface/main/credit/model"
"go-common/library/cache/redis"
"go-common/library/log"
)
const (
_blockIdx = "bl_%d_%d"
)
func blockIndexKey(otype, btype int8) string {
return fmt.Sprintf(_blockIdx, otype, btype)
}
// BlockedIdxCache get block list idx.
func (d *Dao) BlockedIdxCache(c context.Context, otype, btype int8, start, end int) (ids []int64, err error) {
key := blockIndexKey(otype, btype)
conn := d.redis.Get(c)
if ids, err = redis.Int64s(conn.Do("ZREVRANGE", key, start, end)); err != nil {
log.Info("Redis.ZREVRANGE err(%v)", err)
}
conn.Close()
return
}
// ExpireBlockedIdx expire case index cache.
func (d *Dao) ExpireBlockedIdx(c context.Context, otype, btype int8) (ok bool, err error) {
conn := d.redis.Get(c)
defer conn.Close()
if ok, err = redis.Bool(conn.Do("EXPIRE", blockIndexKey(otype, btype), d.redisExpire)); err != nil {
log.Error("redis.bool err(%v)", err)
}
return
}
// LoadBlockedIdx laod blocked info index.
func (d *Dao) LoadBlockedIdx(c context.Context, otype, btype int8, infos []*model.BlockedInfo) (err error) {
key := blockIndexKey(otype, btype)
conn := d.redis.Get(c)
defer conn.Close()
for _, info := range infos {
if err = conn.Send("ZADD", key, info.PublishTime, info.ID); err != nil {
log.Error("ZADD err(%v)", err)
return
}
}
if err = conn.Send("EXPIRE", key, d.redisExpire); err != nil {
log.Error("EXPIRE err(%v)", err)
return
}
if err = conn.Flush(); err != nil {
return
}
for i := 0; i < len(infos)+1; i++ {
if _, err = conn.Receive(); err != nil {
return
}
}
return
}

View File

@@ -0,0 +1,77 @@
package dao
import (
"context"
"go-common/app/interface/main/credit/model"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoblockIndexKey(t *testing.T) {
convey.Convey("blockIndexKey", t, func(convCtx convey.C) {
var (
otype = int8(0)
btype = int8(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
p1 := blockIndexKey(otype, btype)
convCtx.Convey("Then p1 should not be nil.", func(convCtx convey.C) {
convCtx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoBlockedIdxCache(t *testing.T) {
convey.Convey("BlockedIdxCache", t, func(convCtx convey.C) {
var (
c = context.Background()
otype = int8(0)
btype = int8(0)
start = int(0)
end = int(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
ids, err := d.BlockedIdxCache(c, otype, btype, start, end)
convCtx.Convey("Then err should be nil.ids should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(ids, convey.ShouldBeNil)
})
})
})
}
func TestDaoExpireBlockedIdx(t *testing.T) {
convey.Convey("ExpireBlockedIdx", t, func(convCtx convey.C) {
var (
c = context.Background()
otype = int8(0)
btype = int8(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
ok, err := d.ExpireBlockedIdx(c, otype, btype)
convCtx.Convey("Then err should be nil.ok should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(ok, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoLoadBlockedIdx(t *testing.T) {
convey.Convey("LoadBlockedIdx", t, func(convCtx convey.C) {
var (
c = context.Background()
otype = int8(0)
btype = int8(0)
infos = []*model.BlockedInfo{}
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.LoadBlockedIdx(c, otype, btype, infos)
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
})
}

View File

@@ -0,0 +1,211 @@
package dao
import (
"context"
"go-common/app/interface/main/credit/model"
"testing"
"time"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoAddBlockedInfo(t *testing.T) {
convey.Convey("AddBlockedInfo", t, func(convCtx convey.C) {
var (
c = context.Background()
r = &model.BlockedInfo{}
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.AddBlockedInfo(c, r)
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoTxAddBlockedInfo(t *testing.T) {
convey.Convey("TxAddBlockedInfo", t, func(convCtx convey.C) {
var (
tx, _ = d.BeginTran(context.Background())
rs = []*model.BlockedInfo{}
r = &model.BlockedInfo{Uname: "test", UID: 1024}
)
rs = append(rs, r)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.TxAddBlockedInfo(tx, rs)
if err == nil {
if err = tx.Commit(); err != nil {
tx.Rollback()
}
} else {
tx.Rollback()
}
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoBlockedCount(t *testing.T) {
convey.Convey("BlockedCount", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
count, err := d.BlockedCount(c, mid)
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 TestDaoBlockedNumUser(t *testing.T) {
convey.Convey("BlockedNumUser", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
count, err := d.BlockedNumUser(c, mid)
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 TestDaoBLKHistoryCount(t *testing.T) {
convey.Convey("BLKHistoryCount", t, func(convCtx convey.C) {
var (
c = context.Background()
ArgHis = &model.ArgHistory{}
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
count, err := d.BLKHistoryCount(c, ArgHis)
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 TestDaoBlockTotalTime(t *testing.T) {
convey.Convey("BlockTotalTime", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(0)
ts = time.Now()
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
total, err := d.BlockTotalTime(c, mid, ts)
convCtx.Convey("Then err should be nil.total should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(total, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoBlockedUserList(t *testing.T) {
convey.Convey("BlockedUserList", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
res, err := d.BlockedUserList(c, mid)
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 TestDaoBlockedList(t *testing.T) {
convey.Convey("BlockedList", t, func(convCtx convey.C) {
var (
c = context.Background()
otype = int8(0)
btype = int8(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
res, err := d.BlockedList(c, otype, btype)
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 TestDaoBLKHistorys(t *testing.T) {
convey.Convey("BLKHistorys", t, func(convCtx convey.C) {
var (
c = context.Background()
ah = &model.ArgHistory{MID: 0}
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
res, err := d.BLKHistorys(c, ah)
convCtx.Convey("Then err should be nil.res should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(res, convey.ShouldBeNil)
})
})
})
}
func TestDaoBlockedInfoByID(t *testing.T) {
convey.Convey("BlockedInfoByID", t, func(convCtx convey.C) {
var (
c = context.Background()
id = int64(234)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
r, err := d.BlockedInfoByID(c, id)
convCtx.Convey("Then err should be nil.r should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(r, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoBlockedInfoIDs(t *testing.T) {
convey.Convey("BlockedInfoIDs", t, func(convCtx convey.C) {
var (
c = context.Background()
ids = []int64{1, 234, 27515668}
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
res, err := d.BlockedInfoIDs(c, ids)
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 TestDaoBlockedInfos(t *testing.T) {
convey.Convey("BlockedInfos", t, func(convCtx convey.C) {
var (
c = context.Background()
ids = []int64{243, 629}
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
res, err := d.BlockedInfos(c, ids)
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)
})
})
})
}

View File

@@ -0,0 +1,325 @@
package dao
import (
"context"
"fmt"
"strconv"
"strings"
"time"
model "go-common/app/interface/main/credit/model"
"go-common/library/database/sql"
"go-common/library/log"
"go-common/library/xstr"
"github.com/pkg/errors"
)
const (
_addBlockedCasesSQL = "INSERT INTO blocked_case(status,mid,operator,origin_content,punish_result,origin_title,origin_type,origin_url,blocked_days,reason_type,relation_id,oper_id,business_time) VALUES %s"
_insertVoteSQL = "INSERT INTO blocked_case_vote(mid,cid,expired) VALUES(?,?,?)"
_updateVoteSQL = "INSERT INTO blocked_case_vote(mid,cid,vote) VALUES(?,?,?) ON DUPLICATE KEY UPDATE vote=?"
_inBlockedCaseApplyLogSQL = "INSERT INTO blocked_case_apply_log(mid,case_id,apply_type,origin_reason,apply_reason) VALUES(?,?,?,?,?)"
_updateCaseVoteTotalSQL = "UPDATE blocked_case SET %s=%s+? WHERE id=?"
_getCaseByIDSQL = `SELECT id,mid,status,origin_content,punish_result,origin_title,origin_url,end_time,vote_rule,vote_break,vote_delete,origin_type,reason_type,judge_type,blocked_days,
put_total,start_time,end_time,operator,ctime,mtime,relation_id,case_type FROM blocked_case WHERE id=? AND status IN (1,3,4,6)`
_countCaseVoteSQL = "SELECT COUNT(*) FROM blocked_case_vote WHERE mid=? AND vote!=3"
_isVoteByMIDSQL = "SELECT id FROM blocked_case_vote WHERE mid=? AND cid=? AND vote=0"
_getVoteInfoSQL = "SELECT id,cid,mid,vote,expired,mtime FROM blocked_case_vote WHERE mid=? AND cid=?"
_loadMidVoteIDSQL = "SELECT v.cid,c.case_type FROM blocked_case_vote v INNER JOIN blocked_case c ON v.cid=c.id WHERE v.mid =? AND v.ctime >=? ORDER BY v.id DESC"
_getCaseByIDsSQL = `SELECT id,mid,status,origin_content,punish_result,origin_title,origin_url,end_time,vote_rule,vote_break,vote_delete,origin_type,reason_type,judge_type,blocked_days,
put_total,start_time,end_time,operator,ctime,mtime,relation_id,case_type FROM blocked_case WHERE id IN(%s) AND status IN (1,3,4,6)`
_caseRelationIDCountSQL = "SELECT COUNT(*) FROM blocked_case WHERE origin_type=? AND relation_id =?"
_caseInfoIDsSQL = `SELECT id,mid,status,origin_content,punish_result,origin_title,origin_url,end_time,vote_rule,vote_break,vote_delete,origin_type,reason_type,judge_type,blocked_days,
put_total,start_time,end_time,operator,ctime,mtime,relation_id,case_type FROM blocked_case WHERE id IN (%s)`
_caseVotesMIDSQL = "SELECT id,cid,mid,vote,expired,mtime FROM blocked_case_vote WHERE id IN (%s)"
_caseVoteIDMIDSQL = "SELECT id,cid FROM blocked_case_vote WHERE mid = ? ORDER BY mtime DESC LIMIT ?,?"
_caseVoteIDTopSQL = "SELECT id,cid FROM blocked_case_vote WHERE mid = ? ORDER BY mtime DESC LIMIT 100"
)
// AddBlockedCases batch add blocked cases.
func (d *Dao) AddBlockedCases(c context.Context, bc []*model.ArgJudgeCase) (err error) {
l := len(bc)
valueStrings := make([]string, 0, l)
valueArgs := make([]interface{}, 0, l*13)
for _, b := range bc {
valueStrings = append(valueStrings, "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
valueArgs = append(valueArgs, strconv.FormatInt(2, 10))
valueArgs = append(valueArgs, strconv.FormatInt(b.MID, 10))
valueArgs = append(valueArgs, b.Operator)
valueArgs = append(valueArgs, b.OContent)
valueArgs = append(valueArgs, strconv.FormatInt(int64(b.PunishResult), 10))
valueArgs = append(valueArgs, b.OTitle)
valueArgs = append(valueArgs, strconv.FormatInt(int64(b.OType), 10))
valueArgs = append(valueArgs, b.OURL)
valueArgs = append(valueArgs, strconv.FormatInt(int64(b.BlockedDays), 10))
valueArgs = append(valueArgs, strconv.FormatInt(int64(b.ReasonType), 10))
valueArgs = append(valueArgs, b.RelationID)
valueArgs = append(valueArgs, strconv.FormatInt(b.OperID, 10))
if b.BCTime != 0 {
valueArgs = append(valueArgs, b.BCTime)
} else {
valueArgs = append(valueArgs, "1979-12-31 16:00:00")
}
}
stmt := fmt.Sprintf(_addBlockedCasesSQL, strings.Join(valueStrings, ","))
_, err = d.db.Exec(c, stmt, valueArgs...)
if err != nil {
log.Error("AddBlockedCases: db.Exec(bc(%+v)) error(%v)", bc, err)
}
return
}
// InsVote insert user vote.
func (d *Dao) InsVote(c context.Context, mid int64, cid int64, t int64) (err error) {
if _, err = d.db.Exec(c, _insertVoteSQL, mid, cid, time.Now().Add(time.Duration(t)*time.Minute)); err != nil {
log.Error("InsVote: db.Exec(%d,%d) error(%v)", mid, cid, err)
}
return
}
// Setvote set user vote.
func (d *Dao) Setvote(c context.Context, mid, cid, vote int64) (err error) {
if _, err = d.db.Exec(c, _updateVoteSQL, mid, cid, vote, vote); err != nil {
log.Error("Setvote: db.Exec(%d,%d,%d) error(%v)", mid, cid, vote, err)
}
return
}
// SetVoteTx set vote info by tx.
func (d *Dao) SetVoteTx(tx *sql.Tx, mid, cid int64, vote int8) (affect int64, err error) {
row, err := tx.Exec(_updateVoteSQL, mid, cid, vote, vote)
if err != nil {
log.Error("SetVoteTx err(%v)", err)
return
}
return row.LastInsertId()
}
// AddCaseReasonApply add case reason apply log.
func (d *Dao) AddCaseReasonApply(c context.Context, mid, cid int64, applyType, originReason, applyReason int8) (err error) {
_, err = d.db.Exec(c, _inBlockedCaseApplyLogSQL, mid, cid, applyType, originReason, applyReason)
if err != nil {
log.Error("AddCaseReasonApply err(%v)", err)
return
}
return
}
// AddCaseVoteTotal add case vote total.
func (d *Dao) AddCaseVoteTotal(c context.Context, field string, cid int64, voteNum int8) (err error) {
sql := fmt.Sprintf(_updateCaseVoteTotalSQL, field, field)
if _, err = d.db.Exec(c, sql, voteNum, cid); err != nil {
log.Error("AddCaseVoteTotal: db.Exec(%d) error(%v)", cid, err)
}
return
}
// CaseInfo jury get case info.
func (d *Dao) CaseInfo(c context.Context, cid int64) (r *model.BlockedCase, err error) {
row := d.db.QueryRow(c, _getCaseByIDSQL, cid)
r = &model.BlockedCase{}
if err = row.Scan(&r.ID, &r.MID, &r.Status, &r.OriginContent, &r.PunishResult, &r.OriginTitle, &r.OriginURL, &r.EndTime, &r.VoteRule, &r.VoteBreak, &r.VoteDelete, &r.OriginType, &r.ReasonType, &r.JudgeType, &r.BlockedDays, &r.PutTotal, &r.StartTime, &r.EndTime, &r.Operator, &r.CTime, &r.MTime, &r.RelationID, &r.CaseType); err != nil {
if err == sql.ErrNoRows {
err = nil
r = nil
return
}
}
return
}
// CountCaseVote jury count case vote total.
func (d *Dao) CountCaseVote(c context.Context, mid int64) (r int64, err error) {
row := d.db.QueryRow(c, _countCaseVoteSQL, mid)
if err = row.Scan(&r); err != nil {
log.Error("row.Scan() error(%v)", err)
}
return
}
// IsVote jury user is vote.
func (d *Dao) IsVote(c context.Context, mid int64, cid int64) (r int64, err error) {
row := d.db.QueryRow(c, _isVoteByMIDSQL, mid, cid)
if err = row.Scan(&r); err != nil {
if err == sql.ErrNoRows {
r = 0
err = nil
} else {
log.Error("row.Scan() error(%v)", err)
}
}
return
}
// VoteInfo jury user get vote info.
func (d *Dao) VoteInfo(c context.Context, mid int64, cid int64) (r *model.VoteInfo, err error) {
row := d.db.QueryRow(c, _getVoteInfoSQL, mid, cid)
r = &model.VoteInfo{}
if err = row.Scan(&r.ID, &r.CID, &r.MID, &r.Vote, &r.Expired, &r.Mtime); err != nil {
if err == sql.ErrNoRows {
err = nil
r = nil
}
}
return
}
// LoadVoteIDsMid load user vote case ids.
func (d *Dao) LoadVoteIDsMid(c context.Context, mid int64, day int) (cases map[int64]*model.SimCase, err error) {
now := time.Now()
t := time.Date(now.Year(), now.Month(), now.Day()-day, 0, 0, 0, 0, now.Location())
rows, err := d.db.Query(c, _loadMidVoteIDSQL, mid, t)
if err != nil {
log.Error("d.db.Query(%d %v) error(%v)", mid, t, err)
return
}
defer rows.Close()
cases = make(map[int64]*model.SimCase)
for rows.Next() {
mcase := &model.SimCase{}
if err = rows.Scan(&mcase.ID, &mcase.CaseType); err != nil {
log.Error("rows.Scan error(%v)", err)
return
}
cases[mcase.ID] = mcase
}
return
}
// CaseVoteIDs get user's vote info by ids.
func (d *Dao) CaseVoteIDs(c context.Context, ids []int64) (mbc map[int64]*model.BlockedCase, err error) {
rows, err := d.db.Query(c, fmt.Sprintf(_getCaseByIDsSQL, xstr.JoinInts(ids)))
if err != nil {
err = errors.WithStack(err)
return
}
defer rows.Close()
mbc = make(map[int64]*model.BlockedCase, len(ids))
for rows.Next() {
r := new(model.BlockedCase)
if err = rows.Scan(&r.ID, &r.MID, &r.Status, &r.OriginContent, &r.PunishResult, &r.OriginTitle, &r.OriginURL, &r.EndTime, &r.VoteRule, &r.VoteBreak, &r.VoteDelete, &r.OriginType, &r.ReasonType, &r.JudgeType, &r.BlockedDays, &r.PutTotal, &r.StartTime, &r.EndTime, &r.Operator, &r.CTime, &r.MTime, &r.RelationID, &r.CaseType); err != nil {
if err == sql.ErrNoRows {
mbc = nil
err = nil
return
}
err = errors.WithStack(err)
return
}
mbc[r.ID] = r
}
err = rows.Err()
return
}
// CaseRelationIDCount get case relation_id count.
func (d *Dao) CaseRelationIDCount(c context.Context, tp int8, relationID string) (count int64, err error) {
row := d.db.QueryRow(c, _caseRelationIDCountSQL, tp, relationID)
if err = row.Scan(&count); err != nil {
log.Error("d.caseRelationIDCount err(%v)", err)
}
return
}
// CaseInfoIDs get case info by ids.
func (d *Dao) CaseInfoIDs(c context.Context, ids []int64) (cases map[int64]*model.BlockedCase, err error) {
rows, err := d.db.Query(c, fmt.Sprintf(_caseInfoIDsSQL, xstr.JoinInts(ids)))
if err != nil {
log.Error("d.CaseInfoIDs err(%v)", err)
return
}
defer rows.Close()
cases = make(map[int64]*model.BlockedCase, len(ids))
for rows.Next() {
ca := &model.BlockedCase{}
if err = rows.Scan(&ca.ID, &ca.MID, &ca.Status, &ca.OriginContent, &ca.PunishResult, &ca.OriginTitle, &ca.OriginURL, &ca.EndTime, &ca.VoteRule,
&ca.VoteBreak, &ca.VoteDelete, &ca.OriginType, &ca.ReasonType, &ca.JudgeType, &ca.BlockedDays, &ca.PutTotal, &ca.StartTime, &ca.EndTime,
&ca.Operator, &ca.CTime, &ca.MTime, &ca.RelationID, &ca.CaseType); err != nil {
log.Error("row.Scan err(%v)", err)
return
}
cases[ca.ID] = ca
}
return
}
// CaseVotesMID get user's vote case ids.
func (d *Dao) CaseVotesMID(c context.Context, ids []int64) (mvo map[int64]*model.VoteInfo, err error) {
rows, err := d.db.Query(c, fmt.Sprintf(_caseVotesMIDSQL, xstr.JoinInts(ids)))
if err != nil {
err = errors.WithStack(err)
return
}
defer rows.Close()
mvo = make(map[int64]*model.VoteInfo, len(ids))
for rows.Next() {
vo := new(model.VoteInfo)
if err = rows.Scan(&vo.ID, &vo.CID, &vo.MID, &vo.Vote, &vo.Expired, &vo.Mtime); err != nil {
if err == sql.ErrNoRows {
mvo = nil
err = nil
return
}
err = errors.WithStack(err)
return
}
mvo[vo.CID] = vo
}
err = rows.Err()
return
}
// CaseVoteIDMID get user's vote case ids and cids.
func (d *Dao) CaseVoteIDMID(c context.Context, mid, pn, ps int64) (vids []int64, cids []int64, err error) {
rows, err := d.db.Query(c, _caseVoteIDMIDSQL, mid, (pn-1)*ps, ps)
if err != nil {
err = errors.WithStack(err)
return
}
defer rows.Close()
for rows.Next() {
var vid, cid int64
if err = rows.Scan(&vid, &cid); err != nil {
if err == sql.ErrNoRows {
vids = nil
cids = nil
err = nil
return
}
err = errors.WithStack(err)
return
}
vids = append(vids, vid)
cids = append(cids, cid)
}
err = rows.Err()
return
}
// CaseVoteIDTop get user's vote case ids and cids by top 100.
func (d *Dao) CaseVoteIDTop(c context.Context, mid int64) (vids []int64, cids []int64, err error) {
rows, err := d.db.Query(c, _caseVoteIDTopSQL, mid)
if err != nil {
err = errors.WithStack(err)
return
}
defer rows.Close()
for rows.Next() {
var vid, cid int64
if err = rows.Scan(&vid, &cid); err != nil {
if err == sql.ErrNoRows {
vids = nil
cids = nil
err = nil
return
}
err = errors.WithStack(err)
return
}
vids = append(vids, vid)
cids = append(cids, cid)
}
err = rows.Err()
return
}

View File

@@ -0,0 +1,116 @@
package dao
import (
"context"
"fmt"
model "go-common/app/interface/main/credit/model"
gmc "go-common/library/cache/memcache"
)
const (
_prefixCaseInfo = "ca_in_%d"
_prefixVoteCaseInfo = "vc_in_%d_%d"
_caseVoteTop = "ca_vo_top_%d"
)
func caseInfoKey(cid int64) string {
return fmt.Sprintf(_prefixCaseInfo, cid)
}
func voteCaseInfoKey(mid int64, cid int64) string {
return fmt.Sprintf(_prefixVoteCaseInfo, mid, cid)
}
func caseVoteTopKey(mid int64) string {
return fmt.Sprintf(_caseVoteTop, mid)
}
// SetCaseInfoCache set case info.
func (d *Dao) SetCaseInfoCache(c context.Context, cid int64, bc *model.BlockedCase) (err error) {
var (
conn = d.mc.Get(c)
item = &gmc.Item{Key: caseInfoKey(cid), Object: bc, Expiration: d.minCommonExpire, Flags: gmc.FlagJSON}
)
defer conn.Close()
err = conn.Set(item)
return
}
// CaseInfoCache get case info cache
func (d *Dao) CaseInfoCache(c context.Context, cid int64) (bc *model.BlockedCase, err error) {
var (
reply *gmc.Item
conn = d.mc.Get(c)
)
defer conn.Close()
if reply, err = conn.Get(caseInfoKey(cid)); err != nil {
if err == gmc.ErrNotFound {
err = nil
}
return
}
bc = &model.BlockedCase{}
err = conn.Scan(reply, &bc)
return
}
// SetVoteInfoCache set vote case info.
func (d *Dao) SetVoteInfoCache(c context.Context, mid, cid int64, vi *model.VoteInfo) (err error) {
var (
conn = d.mc.Get(c)
item = &gmc.Item{Key: voteCaseInfoKey(mid, cid), Object: vi, Expiration: d.userExpire, Flags: gmc.FlagJSON}
)
defer conn.Close()
err = conn.Set(item)
return
}
// VoteInfoCache get vote case info cache
func (d *Dao) VoteInfoCache(c context.Context, mid, cid int64) (vi *model.VoteInfo, err error) {
var (
reply *gmc.Item
conn = d.mc.Get(c)
)
defer conn.Close()
reply, err = conn.Get(voteCaseInfoKey(mid, cid))
if err != nil {
if err == gmc.ErrNotFound {
err = nil
}
return
}
vi = &model.VoteInfo{}
err = conn.Scan(reply, &vi)
return
}
// CaseVoteTopCache get case votes by top 100.
func (d *Dao) CaseVoteTopCache(c context.Context, mid int64) (bs []*model.BlockedCase, err error) {
var (
reply *gmc.Item
conn = d.mc.Get(c)
)
defer conn.Close()
reply, err = conn.Get(caseVoteTopKey(mid))
if err != nil {
if err == gmc.ErrNotFound {
err = nil
}
return
}
bs = make([]*model.BlockedCase, 0)
err = conn.Scan(reply, &bs)
return
}
// SetCaseVoteTopCache set case votes by top 100.
func (d *Dao) SetCaseVoteTopCache(c context.Context, mid int64, bs []*model.BlockedCase) (err error) {
var (
conn = d.mc.Get(c)
item = &gmc.Item{Key: caseVoteTopKey(mid), Object: bs, Expiration: d.userExpire, Flags: gmc.FlagJSON}
)
defer conn.Close()
err = conn.Set(item)
return
}

View File

@@ -0,0 +1,150 @@
package dao
import (
"context"
"go-common/app/interface/main/credit/model"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaocaseInfoKey(t *testing.T) {
convey.Convey("caseInfoKey", t, func(convCtx convey.C) {
var (
cid = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
p1 := caseInfoKey(cid)
convCtx.Convey("Then p1 should not be nil.", func(convCtx convey.C) {
convCtx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaovoteCaseInfoKey(t *testing.T) {
convey.Convey("voteCaseInfoKey", t, func(convCtx convey.C) {
var (
mid = int64(0)
cid = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
p1 := voteCaseInfoKey(mid, cid)
convCtx.Convey("Then p1 should not be nil.", func(convCtx convey.C) {
convCtx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaocaseVoteTopKey(t *testing.T) {
convey.Convey("caseVoteTopKey", t, func(convCtx convey.C) {
var (
mid = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
p1 := caseVoteTopKey(mid)
convCtx.Convey("Then p1 should not be nil.", func(convCtx convey.C) {
convCtx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoSetCaseInfoCache(t *testing.T) {
convey.Convey("SetCaseInfoCache", t, func(convCtx convey.C) {
var (
c = context.Background()
cid = int64(0)
bc = &model.BlockedCase{}
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.SetCaseInfoCache(c, cid, bc)
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoCaseInfoCache(t *testing.T) {
convey.Convey("CaseInfoCache", t, func(convCtx convey.C) {
var (
c = context.Background()
cid = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
bc, err := d.CaseInfoCache(c, cid)
convCtx.Convey("Then err should be nil.bc should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(bc, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoSetVoteInfoCache(t *testing.T) {
convey.Convey("SetVoteInfoCache", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(0)
cid = int64(0)
vi = &model.VoteInfo{}
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.SetVoteInfoCache(c, mid, cid, vi)
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoVoteInfoCache(t *testing.T) {
convey.Convey("VoteInfoCache", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(0)
cid = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
vi, err := d.VoteInfoCache(c, mid, cid)
convCtx.Convey("Then err should be nil.vi should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(vi, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoCaseVoteTopCache(t *testing.T) {
convey.Convey("CaseVoteTopCache", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(-1)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
bs, err := d.CaseVoteTopCache(c, mid)
convCtx.Convey("Then err should be nil.bs should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(len(bs), convey.ShouldBeGreaterThanOrEqualTo, 0)
})
})
})
}
func TestDaoSetCaseVoteTopCache(t *testing.T) {
convey.Convey("SetCaseVoteTopCache", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(0)
bs = []*model.BlockedCase{}
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.SetCaseVoteTopCache(c, mid, bs)
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
})
}

View File

@@ -0,0 +1,152 @@
package dao
import (
"context"
"fmt"
"strconv"
model "go-common/app/interface/main/credit/model"
"go-common/library/cache/redis"
)
const (
_voteOpIdx = "vo_%d_%d"
_caseOpIdx = "caseop_"
)
func voteIndexKey(cid int64, otype int8) string {
return fmt.Sprintf(_voteOpIdx, otype, cid)
}
func caseIndexKey(cid int64) string {
return _caseOpIdx + strconv.FormatInt(cid, 10)
}
// VoteOpIdxCache get vote opinion index from cache.
func (d *Dao) VoteOpIdxCache(c context.Context, cid, start, end int64, otype int8) (ids []int64, err error) {
var (
key = voteIndexKey(cid, otype)
conn = d.redis.Get(c)
)
defer conn.Close()
ids, err = redis.Int64s(conn.Do("LRANGE", key, start, end))
return
}
// ExpireVoteIdx expire vote idx.
func (d *Dao) ExpireVoteIdx(c context.Context, cid int64, otype int8) (ok bool, err error) {
conn := d.redis.Get(c)
defer conn.Close()
ok, err = redis.Bool(conn.Do("EXPIRE", voteIndexKey(cid, otype), d.redisExpire))
return
}
// LenVoteIdx get lenth of vote index.
func (d *Dao) LenVoteIdx(c context.Context, cid int64, otype int8) (count int, err error) {
conn := d.redis.Get(c)
defer conn.Close()
count, err = redis.Int(conn.Do("LLEN", voteIndexKey(cid, otype)))
return
}
// CaseOpIdxCache get case opinion index from cache.
func (d *Dao) CaseOpIdxCache(c context.Context, cid, start, end int64) (ids []int64, err error) {
var (
key = caseIndexKey(cid)
conn = d.redis.Get(c)
)
defer conn.Close()
ids, err = redis.Int64s(conn.Do("ZREVRANGE", key, start, end))
return
}
// LenCaseIdx get lenth of vote index.
func (d *Dao) LenCaseIdx(c context.Context, cid int64) (count int, err error) {
conn := d.redis.Get(c)
defer conn.Close()
count, err = redis.Int(conn.Do("ZCARD", caseIndexKey(cid)))
return
}
// ExpireCaseIdx expire case index cache.
func (d *Dao) ExpireCaseIdx(c context.Context, cid int64) (ok bool, err error) {
conn := d.redis.Get(c)
defer conn.Close()
ok, err = redis.Bool(conn.Do("EXPIRE", caseIndexKey(cid), d.redisExpire))
return
}
// LoadVoteOpIdxs load vote opinion index into cache.
func (d *Dao) LoadVoteOpIdxs(c context.Context, cid int64, otype int8, idx []int64) (err error) {
var (
ok bool
key = voteIndexKey(cid, otype)
conn = d.redis.Get(c)
)
defer conn.Close()
if ok, err = redis.Bool(conn.Do("EXPIRE", key, d.redisExpire)); ok {
return
}
for _, id := range idx {
if err = conn.Send("LPUSH", key, id); err != nil {
return
}
}
if err = conn.Send("EXPIRE", key, d.redisExpire); err != nil {
return
}
if err = conn.Flush(); err != nil {
return
}
for i := 0; i < len(idx)+1; i++ {
_, err = conn.Receive()
}
return
}
// LoadCaseIdxs load case opinion index into redis.
func (d *Dao) LoadCaseIdxs(c context.Context, cid int64, ops []*model.Opinion) (err error) {
key := caseIndexKey(cid)
conn := d.redis.Get(c)
defer conn.Close()
for _, op := range ops {
if err = conn.Send("ZADD", key, op.Like-op.Hate, op.OpID); err != nil {
return
}
}
if err = conn.Send("EXPIRE", key, d.redisExpire); err != nil {
return
}
if err = conn.Flush(); err != nil {
return
}
for i := 0; i < len(ops)+1; i++ {
_, err = conn.Receive()
}
return
}
// DelCaseIdx DEL case opinion idx.
func (d *Dao) DelCaseIdx(c context.Context, cid int64) (err error) {
conn := d.redis.Get(c)
defer conn.Close()
_, err = conn.Do("DEL", caseIndexKey(cid))
return
}
// DelVoteIdx DEL case opinion idx.
func (d *Dao) DelVoteIdx(c context.Context, cid int64) (err error) {
conn := d.redis.Get(c)
defer conn.Close()
if err = conn.Send("DEL", voteIndexKey(cid, 1)); err != nil {
return
}
if err = conn.Send("DEL", voteIndexKey(cid, 2)); err != nil {
return
}
conn.Flush()
for i := 0; i < 2; i++ {
conn.Receive()
}
return
}

View File

@@ -0,0 +1,249 @@
package dao
import (
"context"
"go-common/app/interface/main/credit/model"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaovoteIndexKey(t *testing.T) {
convey.Convey("voteIndexKey", t, func(convCtx convey.C) {
var (
cid = int64(0)
otype = int8(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
p1 := voteIndexKey(cid, otype)
convCtx.Convey("Then p1 should not be nil.", func(convCtx convey.C) {
convCtx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaocaseIndexKey(t *testing.T) {
convey.Convey("caseIndexKey", t, func(convCtx convey.C) {
var (
cid = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
p1 := caseIndexKey(cid)
convCtx.Convey("Then p1 should not be nil.", func(convCtx convey.C) {
convCtx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoVoteOpIdxCache(t *testing.T) {
convey.Convey("VoteOpIdxCache", t, func(convCtx convey.C) {
var (
c = context.Background()
cid = int64(0)
start = int64(0)
end = int64(0)
otype = int8(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
ids, err := d.VoteOpIdxCache(c, cid, start, end, otype)
convCtx.Convey("Then err should be nil.ids should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(ids, convey.ShouldBeNil)
})
})
})
}
func TestDaoExpireVoteIdx(t *testing.T) {
convey.Convey("ExpireVoteIdx", t, func(convCtx convey.C) {
var (
c = context.Background()
cid = int64(0)
otype = int8(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
ok, err := d.ExpireVoteIdx(c, cid, otype)
convCtx.Convey("Then err should be nil.ok should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(ok, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoLenVoteIdx(t *testing.T) {
convey.Convey("LenVoteIdx", t, func(convCtx convey.C) {
var (
c = context.Background()
cid = int64(0)
otype = int8(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
count, err := d.LenVoteIdx(c, cid, otype)
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 TestDaoCaseOpIdxCache(t *testing.T) {
convey.Convey("CaseOpIdxCache", t, func(convCtx convey.C) {
var (
c = context.Background()
cid = int64(0)
start = int64(0)
end = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
ids, err := d.CaseOpIdxCache(c, cid, start, end)
convCtx.Convey("Then err should be nil.ids should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(ids, convey.ShouldBeNil)
})
})
})
}
func TestDaoLenCaseIdx(t *testing.T) {
convey.Convey("LenCaseIdx", t, func(convCtx convey.C) {
var (
c = context.Background()
cid = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
count, err := d.LenCaseIdx(c, cid)
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 TestDaoExpireCaseIdx(t *testing.T) {
convey.Convey("ExpireCaseIdx", t, func(convCtx convey.C) {
var (
c = context.Background()
cid = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
ok, err := d.ExpireCaseIdx(c, cid)
convCtx.Convey("Then err should be nil.ok should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(ok, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoLoadVoteOpIdxs(t *testing.T) {
convey.Convey("LoadVoteOpIdxs", t, func(convCtx convey.C) {
var (
c = context.Background()
cid = int64(0)
otype = int8(0)
idx = []int64{}
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.LoadVoteOpIdxs(c, cid, otype, idx)
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoLoadCaseIdxs(t *testing.T) {
convey.Convey("LoadCaseIdxs", t, func(convCtx convey.C) {
var (
c = context.Background()
cid = int64(0)
ops = []*model.Opinion{}
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.LoadCaseIdxs(c, cid, ops)
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoDelCaseIdx(t *testing.T) {
convey.Convey("DelCaseIdx", t, func(convCtx convey.C) {
var (
c = context.Background()
cid = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.DelCaseIdx(c, cid)
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoDelVoteIdx(t *testing.T) {
convey.Convey("DelVoteIdx", t, func(convCtx convey.C) {
var (
c = context.Background()
cid = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.DelVoteIdx(c, cid)
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
})
}
// TestVoteOpIdxCache .
func TestVoteOpIdxCache(t *testing.T) {
var (
idx = []int64{1, 2, 3, 4}
cid int64 = 639
c = context.TODO()
otype int8 = 1
)
convey.Convey("return someting", t, func(convCtx convey.C) {
d.LoadVoteOpIdxs(c, cid, otype, idx)
ids, err := d.VoteOpIdxCache(c, cid, 1, 3, otype)
convey.So(err, convey.ShouldBeNil)
convey.So(ids, convey.ShouldNotBeNil)
convey.Convey("get vote count", func(convCtx convey.C) {
count, err := d.LenVoteIdx(c, cid, otype)
convey.So(err, convey.ShouldBeNil)
convey.So(count, convey.ShouldEqual, 4)
})
})
}
// TestCaseOpIdxCache .
func TestCaseOpIdxCache(t *testing.T) {
var (
c = context.TODO()
cid int64 = 2
)
convey.Convey("return someting", t, func(ctx convey.C) {
ops, err := d.Opinions(c, []int64{631, 633})
convey.So(err, convey.ShouldBeNil)
convey.So(ops, convey.ShouldNotBeNil)
convey.Convey("gets case data from cache", func(ctx convey.C) {
d.LoadCaseIdxs(c, cid, ops)
ids, err := d.CaseOpIdxCache(c, cid, 0, 3)
convey.So(err, convey.ShouldBeNil)
convey.So(ids, convey.ShouldNotBeNil)
})
convey.Convey("count cid from case cache", func(ctx convey.C) {
count, err := d.LenCaseIdx(c, cid)
convey.So(err, convey.ShouldBeNil)
convey.So(count, convey.ShouldEqual, len(ops))
})
})
}

View File

@@ -0,0 +1,312 @@
package dao
import (
"context"
"go-common/app/interface/main/credit/model"
"math/rand"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoAddBlockedCases(t *testing.T) {
convey.Convey("AddBlockedCases", t, func(convCtx convey.C) {
var (
c = context.Background()
bc = []*model.ArgJudgeCase{}
b = &model.ArgJudgeCase{MID: 1}
)
bc = append(bc, b)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.AddBlockedCases(c, bc)
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoInsVote(t *testing.T) {
convey.Convey("InsVote", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = rand.Int63n(99999999)
cid = rand.Int63n(99999999)
no = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.InsVote(c, mid, cid, no)
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoSetvote(t *testing.T) {
convey.Convey("Setvote", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(0)
cid = int64(0)
vote = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.Setvote(c, mid, cid, vote)
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoSetVoteTx(t *testing.T) {
convey.Convey("SetVoteTx", t, func(convCtx convey.C) {
var (
tx, _ = d.BeginTran(context.Background())
mid = rand.Int63n(99999999)
cid = rand.Int63n(99999999)
vote = int8(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
affect, err := d.SetVoteTx(tx, mid, cid, vote)
if err == nil {
if err = tx.Commit(); err != nil {
tx.Rollback()
}
} else {
tx.Rollback()
}
convCtx.Convey("Then err should be nil.affect should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(affect, convey.ShouldBeGreaterThanOrEqualTo, 0)
})
})
})
}
func TestDaoAddCaseReasonApply(t *testing.T) {
convey.Convey("AddCaseReasonApply", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(0)
cid = int64(0)
applyType = int8(0)
originReason = int8(0)
applyReason = int8(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.AddCaseReasonApply(c, mid, cid, applyType, originReason, applyReason)
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoAddCaseVoteTotal(t *testing.T) {
convey.Convey("AddCaseVoteTotal", t, func(convCtx convey.C) {
var (
c = context.Background()
field = "vote_rule"
cid = int64(3)
voteNum = int8(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.AddCaseVoteTotal(c, field, cid, voteNum)
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoCaseInfo(t *testing.T) {
convey.Convey("CaseInfo", t, func(convCtx convey.C) {
var (
c = context.Background()
cid = int64(3)
cid1 = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
r, err := d.CaseInfo(c, cid)
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)
})
r1, err := d.CaseInfo(c, cid1)
convCtx.Convey("Then err should be nil.r should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(r1, convey.ShouldBeNil)
})
})
})
}
func TestDaoCountCaseVote(t *testing.T) {
convey.Convey("CountCaseVote", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
r, err := d.CountCaseVote(c, mid)
convCtx.Convey("Then err should be nil.r should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(r, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoIsVote(t *testing.T) {
convey.Convey("IsVote", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(0)
cid = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
r, err := d.IsVote(c, mid, cid)
convCtx.Convey("Then err should be nil.r should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(r, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoVoteInfo(t *testing.T) {
convey.Convey("VoteInfo", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(0)
cid = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
r, err := d.VoteInfo(c, mid, cid)
convCtx.Convey("Then err should be nil.r should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(r, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoLoadVoteIDsMid(t *testing.T) {
convey.Convey("LoadVoteIDsMid", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(0)
day = int(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
cases, err := d.LoadVoteIDsMid(c, mid, day)
convCtx.Convey("Then err should be nil.cases should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(cases, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoCaseVoteIDs(t *testing.T) {
convey.Convey("CaseVoteIDs", t, func(convCtx convey.C) {
var (
c = context.Background()
ids = []int64{3, 6}
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
mbc, err := d.CaseVoteIDs(c, ids)
convCtx.Convey("Then err should be nil.mbc should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(mbc, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoCaseRelationIDCount(t *testing.T) {
convey.Convey("CaseRelationIDCount", t, func(convCtx convey.C) {
var (
c = context.Background()
tp = int8(0)
relationID = ""
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
count, err := d.CaseRelationIDCount(c, tp, relationID)
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 TestDaoCaseInfoIDs(t *testing.T) {
convey.Convey("CaseInfoIDs", t, func(convCtx convey.C) {
var (
c = context.Background()
ids = []int64{3}
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
cases, err := d.CaseInfoIDs(c, ids)
convCtx.Convey("Then err should be nil.cases should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(cases, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoCaseVotesMID(t *testing.T) {
convey.Convey("CaseVotesMID", t, func(convCtx convey.C) {
var (
c = context.Background()
ids = []int64{1, 44}
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
mvo, err := d.CaseVotesMID(c, ids)
convCtx.Convey("Then err should be nil.mvo should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(mvo, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoCaseVoteIDMID(t *testing.T) {
convey.Convey("CaseVoteIDMID", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(111001692)
pn = int64(1)
ps = int64(1)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
vids, cids, err := d.CaseVoteIDMID(c, mid, pn, ps)
convCtx.Convey("Then err should be nil.vids,cids should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(cids, convey.ShouldNotBeNil)
convCtx.So(vids, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoCaseVoteIDTop(t *testing.T) {
convey.Convey("CaseVoteIDTop", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
vids, cids, err := d.CaseVoteIDTop(c, mid)
convCtx.Convey("Then err should be nil.vids,cids should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(cids, convey.ShouldNotBeNil)
convCtx.So(vids, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,110 @@
package dao
import (
"context"
"time"
"go-common/app/interface/main/credit/conf"
"go-common/library/cache/memcache"
"go-common/library/cache/redis"
"go-common/library/database/sql"
bm "go-common/library/net/http/blademaster"
"go-common/library/queue/databus"
)
const (
_sendMsgURI = "/api/notify/send.user.notify.do"
_getQSURI = "/laogai/question"
_replyCountURI = "/x/internal/v2/reply/mcount"
_sendMedalURI = "/x/internal/medal/grant"
_managersURI = "/x/admin/manager/users"
_managerTotalURI = "/x/admin/manager/users/total"
_addAppealURI = "/x/internal/workflow/appeal/add"
_appealDetailURI = "/x/internal/workflow/appeal/info"
_appealListURI = "/x/internal/workflow/appeal/list"
)
// Dao struct info of Dao.
type Dao struct {
// mysql
db *sql.DB
// memcache
mc *memcache.Pool
userExpire int32
minCommonExpire int32
commonExpire int32
// redis
redis *redis.Pool
redisExpire int64
// databus stat
dbusLabour *databus.Databus
// http
client *bm.Client
// conf
c *conf.Config
// message api
sendMsgURL string
// big data api
getQSURL string
// account.co api
sendMedalURL string
replyCountURL string
managersURL string
managerTotalURL string
// appeal
addAppealURL string
appealDetailURL string
appealListURL string
}
// New new a Dao and return.
func New(c *conf.Config) (d *Dao) {
d = &Dao{
// conf
c: c,
// db
db: sql.NewMySQL(c.Mysql),
// memcache
mc: memcache.NewPool(c.Memcache.Config),
userExpire: int32(time.Duration(c.Memcache.UserExpire) / time.Second),
minCommonExpire: int32(time.Duration(c.Memcache.MinCommonExpire) / time.Second),
commonExpire: int32(time.Duration(c.Memcache.CommonExpire) / time.Second),
// redis
redis: redis.NewPool(c.Redis.Config),
redisExpire: int64(time.Duration(c.Redis.Expire) / time.Second),
// databus
dbusLabour: databus.New(c.DataBus),
// http client
client: bm.NewClient(c.HTTPClient),
}
d.sendMsgURL = c.Host.MessageURI + _sendMsgURI
d.getQSURL = c.Host.BigDataURI + _getQSURI
d.sendMedalURL = c.Host.APICoURI + _sendMedalURI
d.replyCountURL = c.Host.APICoURI + _replyCountURI
d.managersURL = c.Host.ManagersURI + _managersURI
d.managerTotalURL = c.Host.ManagersURI + _managerTotalURI
d.addAppealURL = c.Host.APICoURI + _addAppealURI
d.appealDetailURL = c.Host.APICoURI + _appealDetailURI
d.appealListURL = c.Host.APICoURI + _appealListURI
return
}
// Ping ping health.
func (d *Dao) Ping(c context.Context) (err error) {
return d.pingMC(c)
}
// Close close connections of mc, redis, db.
func (d *Dao) Close() {
if d.mc != nil {
d.mc.Close()
}
if d.db != nil {
d.db.Close()
}
}
// BeginTran begin mysql transaction.
func (d *Dao) BeginTran(c context.Context) (*sql.Tx, error) {
return d.db.Begin(c)
}

View File

@@ -0,0 +1,84 @@
package dao
import (
"flag"
"os"
"strings"
"testing"
gock "gopkg.in/h2non/gock.v1"
"go-common/app/interface/main/credit/conf"
_ "github.com/go-sql-driver/mysql"
// . "github.com/smartystreets/goconvey/convey"
)
var d *Dao
// func CleanCache() {
// c := context.TODO()
// pool := redis.NewPool(conf.Conf.Redis.Config)
// pool.Get(c).Do("FLUSHDB")
// }
func TestMain(m *testing.M) {
if os.Getenv("DEPLOY_ENV") != "" {
flag.Set("app_id", "main.account-law.credit")
flag.Set("conf_appid", "main.account-law.credit")
flag.Set("conf_token", "aX4znxOXioonmhCtY5Piod6XLCHDPUKt")
flag.Set("tree_id", "5659")
flag.Set("conf_version", "docker-1")
flag.Set("deploy_env", "uat")
flag.Set("conf_env", "10")
flag.Set("conf_host", "config.bilibili.co")
flag.Set("conf_path", "/tmp")
flag.Set("region", "sh")
flag.Set("zone", "sh001")
} else {
flag.Set("conf", "../cmd/credit-test.toml")
}
flag.Parse()
if err := conf.Init(); err != nil {
panic(err)
}
d = New(conf.Conf)
d.client.SetTransport(gock.DefaultTransport)
os.Exit(m.Run())
}
func httpMock(method, url string) *gock.Request {
r := gock.New(url)
r.Method = strings.ToUpper(method)
return r
}
// func WithDao(f func(d *Dao)) func() {
// return func() {
// Reset(func() { CleanCache() })
// f(d)
// }
// }
// func WithMysql(f func(d *Dao)) func() {
// return func() {
// Reset(func() { CleanCache() })
// f(d)
// }
// }
// func WithCleanCache(f func()) func() {
// return func() {
// Reset(func() { CleanCache() })
// }
// }
// func httpMock(method, url string) *gock.Request {
// r := gock.New(url)
// r.Method = strings.ToUpper(method)
// return r
// }
// func ctx() context.Context {
// return context.Background()
// }

View File

@@ -0,0 +1,17 @@
package dao
import (
"context"
"strconv"
"go-common/library/log"
)
// PubLabour pub labour answer log msg into databus.
func (d *Dao) PubLabour(c context.Context, aid int64, msg interface{}) (err error) {
key := strconv.FormatInt(aid, 10)
if err = d.dbusLabour.Send(c, key, msg); err != nil {
log.Error("PubLabour.Pub(%s, %v) error (%v)", key, msg, err)
}
return
}

View File

@@ -0,0 +1,24 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoPubLabour(t *testing.T) {
convey.Convey("PubLabour", t, func(convCtx convey.C) {
var (
c = context.Background()
aid = int64(0)
msg = interface{}(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.PubLabour(c, aid, msg)
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
})
}

View File

@@ -0,0 +1,98 @@
package dao
import (
"context"
"fmt"
"net/url"
"strconv"
model "go-common/app/interface/main/credit/model"
"go-common/library/ecode"
"go-common/library/log"
"go-common/library/net/metadata"
"go-common/library/xstr"
"github.com/pkg/errors"
)
// SendSysMsg send msg.
func (dao *Dao) SendSysMsg(c context.Context, mid int64, title string, context string) (err error) {
params := url.Values{}
params.Set("mc", "2_1_13")
params.Set("title", title)
params.Set("data_type", "4")
params.Set("context", context)
params.Set("mid_list", fmt.Sprintf("%d", mid))
var res struct {
Code int `json:"code"`
Data *struct {
Status int8 `json:"status"`
Remark string `json:"remark"`
} `json:"data"`
}
if err = dao.client.Post(c, dao.sendMsgURL, metadata.String(c, metadata.RemoteIP), params, &res); err != nil {
log.Error("SendSysMsg(%s) error(%v)", dao.sendMsgURL+"?"+params.Encode(), err)
return
}
if res.Code != 0 {
log.Error("SendSysMsg(%s) error(%v)", dao.sendMsgURL+"?"+params.Encode(), res.Code)
err = ecode.Int(res.Code)
return
}
return
}
// GetQS get question from big data.
func (dao *Dao) GetQS(c context.Context, mid int64) (qs *model.AIQsID, err error) {
qs = &model.AIQsID{}
params := url.Values{}
params.Set("mid", strconv.FormatInt(mid, 10))
var res struct {
Code int `json:"code"`
Data *model.AIQsID `json:"data"`
}
if err = dao.client.Get(c, dao.getQSURL, metadata.String(c, metadata.RemoteIP), params, &res); err != nil {
log.Error("GetQS(%s) error(%v)", dao.getQSURL+"?"+params.Encode(), err)
return
}
if res.Code != 0 {
log.Error("GetQS(%s) error(%v)", dao.getQSURL+"?"+params.Encode(), res.Code)
err = ecode.Int(res.Code)
return
}
qs = res.Data
return
}
// ReplysCount get reply count.
func (dao *Dao) ReplysCount(c context.Context, oid []int64) (counts map[string]int64, err error) {
params := url.Values{}
params.Set("oid", xstr.JoinInts(oid))
params.Set("type", "6")
var res struct {
Data map[string]int64 `json:"data"`
}
if err = dao.client.Get(c, dao.replyCountURL, metadata.String(c, metadata.RemoteIP), params, &res); err != nil {
log.Error("ReplysCount(%s) err(%v)", dao.replyCountURL+"?"+params.Encode(), err)
return
}
counts = res.Data
return
}
// SendMedal send mdal.
func (dao *Dao) SendMedal(c context.Context, mid int64, nid int64) (err error) {
params := url.Values{}
params.Set("nid", strconv.FormatInt(nid, 10))
params.Set("mid", strconv.FormatInt(mid, 10))
var res struct {
Code int `json:"code"`
}
if err = dao.client.Post(c, dao.sendMedalURL, "", params, &res); err != nil {
return
}
if res.Code != 0 {
err = errors.WithStack(ecode.Int(res.Code))
}
return
}

View File

@@ -0,0 +1,45 @@
package dao
import (
"context"
"testing"
gock "gopkg.in/h2non/gock.v1"
"github.com/smartystreets/goconvey/convey"
)
// TestReplysCount .
func TestSendSysMsg(t *testing.T) {
convey.Convey("return someting", t, func(convCtx convey.C) {
defer gock.OffAll()
httpMock("POST", d.sendMsgURL).Reply(200).JSON(`{"code": 0}`)
err := d.SendSysMsg(context.Background(), 1, "test", "test")
convCtx.So(err, convey.ShouldBeNil)
})
}
func TestGetQS(t *testing.T) {
convey.Convey("return someting", t, func(convCtx convey.C) {
defer gock.OffAll()
httpMock("GET", d.getQSURL).Reply(200).JSON(`{"code": 0,"data":{}}`)
res, err := d.GetQS(context.Background(), 1)
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(res, convey.ShouldNotBeNil)
})
}
func TestReplysCount(t *testing.T) {
convey.Convey("return someting", t, func(convCtx convey.C) {
res, err := d.ReplysCount(context.Background(), []int64{2, 3, 4})
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(res, convey.ShouldNotBeNil)
})
}
func TestSendMedal(t *testing.T) {
convey.Convey("return someting", t, func(convCtx convey.C) {
defer gock.OffAll()
httpMock("POST", d.sendMedalURL).Reply(200).JSON(`{"code": 0}`)
err := d.SendMedal(context.Background(), 1, 1)
convCtx.So(err, convey.ShouldBeNil)
})
}

View File

@@ -0,0 +1,75 @@
package dao
import (
"context"
"fmt"
"time"
model "go-common/app/interface/main/credit/model"
"go-common/library/database/sql"
"go-common/library/log"
"go-common/library/xstr"
"github.com/pkg/errors"
)
const (
_updateJurySQL = "INSERT INTO blocked_jury(mid,status,expired) VALUES(?,?,?) ON DUPLICATE KEY UPDATE status=?,expired=?"
_updateVoteTotalSQL = "UPDATE blocked_jury SET vote_total=vote_total+1 WHERE mid=?"
_getJurySQL = "SELECT id,mid,status,expired,invalid_reason,vote_total,vote_radio,vote_right,vote_total,black FROM blocked_jury WHERE mid=?"
_juryInfosSQL = "SELECT mid,status,expired,invalid_reason,vote_total,vote_radio,vote_right,total,black FROM blocked_jury WHERE mid IN (%s)"
)
//JuryApply user jury apply.
func (d *Dao) JuryApply(c context.Context, mid int64, expired time.Time) (err error) {
if _, err = d.db.Exec(c, _updateJurySQL, mid, 1, expired, 1, expired); err != nil {
log.Error("JuryApply: db.Exec(%d,%d,%v) error(%v)", mid, 1, expired, err)
}
return
}
// AddUserVoteTotal add user vote total.
func (d *Dao) AddUserVoteTotal(c context.Context, mid int64) (err error) {
if _, err = d.db.Exec(c, _updateVoteTotalSQL, mid); err != nil {
log.Error("AddUserVoteTotal: db.Exec(%d) error(%v)", mid, err)
}
return
}
// JuryInfo get user's jury info
func (d *Dao) JuryInfo(c context.Context, mid int64) (r *model.BlockedJury, err error) {
row := d.db.QueryRow(c, _getJurySQL, mid)
r = &model.BlockedJury{}
if err = row.Scan(&r.ID, &r.MID, &r.Status, &r.Expired, &r.InvalidReason, &r.VoteTotal, &r.VoteRadio, &r.VoteRight, &r.CaseTotal, &r.Black); err != nil {
if err == sql.ErrNoRows {
err = nil
r = nil
}
}
return
}
// JuryInfos get user's applying jury info
func (d *Dao) JuryInfos(c context.Context, mids []int64) (mbj map[int64]*model.BlockedJury, err error) {
rows, err := d.db.Query(c, fmt.Sprintf(_juryInfosSQL, xstr.JoinInts(mids)))
if err != nil {
err = errors.Wrap(err, "JuryInfos")
return
}
mbj = make(map[int64]*model.BlockedJury, len(mids))
defer rows.Close()
for rows.Next() {
bj := new(model.BlockedJury)
if err = rows.Scan(&bj.MID, &bj.Status, &bj.Expired, &bj.InvalidReason, &bj.VoteTotal, &bj.VoteRadio, &bj.VoteRight, &bj.CaseTotal, &bj.Black); err != nil {
if err == sql.ErrNoRows {
err = nil
return
}
err = errors.Wrap(err, "JuryInfos")
return
}
mbj[bj.MID] = bj
}
err = rows.Err()
return
}

View File

@@ -0,0 +1,72 @@
package dao
import (
"context"
"testing"
"time"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoJuryApply(t *testing.T) {
convey.Convey("JuryApply", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(0)
expired = time.Now()
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.JuryApply(c, mid, expired)
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoAddUserVoteTotal(t *testing.T) {
convey.Convey("AddUserVoteTotal", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.AddUserVoteTotal(c, mid)
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoJuryInfo(t *testing.T) {
convey.Convey("JuryInfo", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
r, err := d.JuryInfo(c, mid)
convCtx.Convey("Then err should be nil.r should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(r, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoJuryInfos(t *testing.T) {
convey.Convey("JuryInfos", t, func(convCtx convey.C) {
var (
c = context.Background()
mids = []int64{111, 88889017}
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
mbj, err := d.JuryInfos(c, mids)
convCtx.Convey("Then err should be nil.mbj should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(mbj, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,101 @@
package dao
import (
"context"
"net/url"
"strconv"
"sync"
"go-common/app/interface/main/credit/model"
"go-common/library/log"
"go-common/library/sync/errgroup"
)
// Managers get manager users info.
func (d *Dao) Managers(c context.Context) (manMap map[string]int64, err error) {
var (
count, page int64
g errgroup.Group
l sync.RWMutex
)
if count, err = d.ManagerTotal(c); err != nil {
log.Error("d.ManagerTotal error(%v)", err)
return
}
if count <= 0 {
return
}
manMap = make(map[string]int64, count)
ps := int64(500)
pageNum := count / ps
if count%ps != 0 {
pageNum++
}
for page = 1; page <= pageNum; page++ {
tmpPage := page
g.Go(func() (err error) {
mi, err := d.Manager(c, tmpPage, ps)
if err != nil {
log.Error("d.Manager(%d,%d) error(%v) ", tmpPage, ps, err)
err = nil
return
}
for _, v := range mi {
l.Lock()
manMap[v.Uname] = v.OID
l.Unlock()
}
return
})
}
g.Wait()
return
}
// Manager get manager users.
func (d *Dao) Manager(c context.Context, pn, ps int64) (mi []*model.MangerInfo, err error) {
params := url.Values{}
params.Set("pn", strconv.FormatInt(pn, 10))
params.Set("ps", strconv.FormatInt(ps, 10))
var res struct {
Code int `json:"code"`
Data *struct {
Items []*model.MangerInfo `json:"items"`
} `json:"data"`
}
if err = d.client.Get(c, d.managersURL, "", params, &res); err != nil {
log.Error("Manager(%s) error(%v)", d.managersURL+"?"+params.Encode(), err)
return
}
if res.Code != 0 {
log.Warn("Manager(%s) code(%d) data(%+v)", d.managersURL+"?"+params.Encode(), res.Code, res.Data)
return
}
if res.Data != nil {
mi = res.Data.Items
}
return
}
// ManagerTotal get manager user total.
func (d *Dao) ManagerTotal(c context.Context) (count int64, err error) {
params := url.Values{}
var res struct {
Code int `json:"code"`
Data *struct {
Total int64 `json:"total"`
} `json:"data"`
}
if err = d.client.Get(c, d.managerTotalURL, "", params, &res); err != nil {
log.Error("ManagerTotal(%s) error(%v)", d.managerTotalURL+"?"+params.Encode(), err)
return
}
if res.Code != 0 {
log.Warn("ManagerTotal(%s) code(%d) data(%+v)", d.managerTotalURL+"?"+params.Encode(), res.Code, res.Data)
return
}
if res.Data != nil {
count = res.Data.Total
}
return
}

View File

@@ -0,0 +1,55 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoManagers(t *testing.T) {
convey.Convey("Managers", t, func(convCtx convey.C) {
var (
c = context.Background()
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
manMap, err := d.Managers(c)
convCtx.Convey("Then err should be nil.manMap should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(manMap, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoManager(t *testing.T) {
convey.Convey("Manager", t, func(convCtx convey.C) {
var (
c = context.Background()
pn = int64(0)
ps = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
mi, err := d.Manager(c, pn, ps)
convCtx.Convey("Then err should be nil.mi should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(mi, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoManagerTotal(t *testing.T) {
convey.Convey("ManagerTotal", t, func(convCtx convey.C) {
var (
c = context.Background()
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
count, err := d.ManagerTotal(c)
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)
})
})
})
}

View File

@@ -0,0 +1,30 @@
package dao
import (
"context"
"testing"
credit "go-common/app/interface/main/credit/model"
. "github.com/smartystreets/goconvey/convey"
)
// TestMcJury .
func TestMcJury(t *testing.T) {
var (
c = context.TODO()
op = &credit.Opinion{
Mid: 1,
OpID: 632,
Content: "aaaaa",
}
)
Convey("return someting", t, func() {
d.AddOpinionCache(c, op)
mop, miss, err := d.OpinionsCache(c, []int64{632, 631})
So(err, ShouldBeNil)
So(miss, ShouldNotBeNil)
So(mop, ShouldNotBeNil)
})
}

View File

@@ -0,0 +1,285 @@
package dao
import (
"context"
"fmt"
"strconv"
model "go-common/app/interface/main/credit/model"
gmc "go-common/library/cache/memcache"
"go-common/library/log"
)
const (
_noticeInfo = "notice" // key of creditInfo
_reasonList = "reason" // key of creditInfo
_opinion = "op_v2_" // user opinion prefix.
_questionids = "question" // key of creditInfo
_labourIsAnswer = "labour_%d" // key of labourIsAnswer
_juryInfo = "jy_" // key of jury info
)
func noticeKey() string {
return _noticeInfo
}
func reasonKey() string {
return _reasonList
}
// user opinion key.
func opinionKey(opid int64) string {
return _opinion + strconv.FormatInt(opid, 10)
}
func questionKey(mid int64) string {
return _questionids + strconv.FormatInt(mid, 10)
}
func labourKey(mid int64) string {
return fmt.Sprintf(_labourIsAnswer, mid)
}
// user jury info key.
func juryInfoKey(mid int64) string {
return _juryInfo + strconv.FormatInt(mid, 10)
}
func (d *Dao) pingMC(c context.Context) (err error) {
conn := d.mc.Get(c)
if err = conn.Set(&gmc.Item{Key: "ping", Value: []byte{1}, Expiration: d.commonExpire}); err != nil {
log.Error("conn.Store(set, ping, 1) error(%v)", err)
}
conn.Close()
return
}
// NoticeInfoCache get notice info cache.
func (d *Dao) NoticeInfoCache(c context.Context) (dt *model.Notice, err error) {
var conn = d.mc.Get(c)
defer conn.Close()
item, err := conn.Get(noticeKey())
if err != nil {
if err == gmc.ErrNotFound {
err = nil
}
return
}
dt = &model.Notice{}
err = conn.Scan(item, &dt)
return
}
// SetReasonListCache get notice info cache.
func (d *Dao) SetReasonListCache(c context.Context, dt []*model.Reason) (err error) {
var (
item = &gmc.Item{Key: reasonKey(), Object: dt, Expiration: d.minCommonExpire, Flags: gmc.FlagJSON}
conn = d.mc.Get(c)
)
defer conn.Close()
err = conn.Set(item)
return
}
// SetNoticeInfoCache get Notice info cache.
func (d *Dao) SetNoticeInfoCache(c context.Context, n *model.Notice) (err error) {
var (
item = &gmc.Item{Key: noticeKey(), Object: n, Expiration: d.minCommonExpire, Flags: gmc.FlagJSON}
conn = d.mc.Get(c)
)
defer conn.Close()
err = conn.Set(item)
return
}
// DelNoticeInfoCache delete notice info cache.
func (d *Dao) DelNoticeInfoCache(c context.Context, mid int64) (err error) {
conn := d.mc.Get(c)
defer conn.Close()
if err = conn.Delete(noticeKey()); err != nil {
if err == gmc.ErrNotFound {
err = nil
}
}
return
}
// ReasonListCache get Reason info cache.
func (d *Dao) ReasonListCache(c context.Context) (dt []*model.Reason, err error) {
conn := d.mc.Get(c)
defer conn.Close()
item, err := conn.Get(reasonKey())
if err != nil {
if err == gmc.ErrNotFound {
err = nil
}
return
}
dt = make([]*model.Reason, 0)
err = conn.Scan(item, &dt)
return
}
// DelReasonListCache delete reason info cache.
func (d *Dao) DelReasonListCache(c context.Context) (err error) {
conn := d.mc.Get(c)
defer conn.Close()
if err = conn.Delete(reasonKey()); err != nil {
if err == gmc.ErrNotFound {
err = nil
}
}
return
}
// AddOpinionCache add opinion cache.
func (d *Dao) AddOpinionCache(c context.Context, op *model.Opinion) (err error) {
var (
item = &gmc.Item{Key: opinionKey(op.OpID), Object: op, Expiration: d.commonExpire, Flags: gmc.FlagJSON}
conn = d.mc.Get(c)
)
defer conn.Close()
err = conn.Set(item)
return
}
// OpinionsCache get opids opinion detail.
func (d *Dao) OpinionsCache(c context.Context, opids []int64) (ops map[int64]*model.Opinion, miss []int64, err error) {
var (
keys []string
conn = d.mc.Get(c)
)
for _, id := range opids {
keys = append(keys, opinionKey(id))
}
defer conn.Close()
res, err := conn.GetMulti(keys)
if err != nil {
return
}
ops = make(map[int64]*model.Opinion, len(res))
for _, id := range opids {
if r, ok := res[opinionKey(id)]; ok {
op := &model.Opinion{}
if err = conn.Scan(r, &op); err != nil {
return
}
ops[op.OpID] = op
} else {
miss = append(miss, id)
}
}
return
}
// SetQsCache set labour questions cache.
func (d *Dao) SetQsCache(c context.Context, mid int64, qsid *model.QsCache) (err error) {
var (
item = &gmc.Item{Key: questionKey(mid), Object: qsid, Expiration: d.commonExpire, Flags: gmc.FlagJSON}
conn = d.mc.Get(c)
)
defer conn.Close()
err = conn.Set(item)
return
}
// GetQsCache get labour qestions info cache.
func (d *Dao) GetQsCache(c context.Context, mid int64) (qsid *model.QsCache, err error) {
var (
reply *gmc.Item
conn = d.mc.Get(c)
)
defer conn.Close()
reply, err = conn.Get(questionKey(mid))
if err != nil || reply == nil {
if err == gmc.ErrNotFound {
err = nil
}
return
}
qsid = &model.QsCache{}
err = conn.Scan(reply, &qsid)
return
}
// DelQsCache delete labour questions cache.
func (d *Dao) DelQsCache(c context.Context, mid int64) (err error) {
conn := d.mc.Get(c)
defer conn.Close()
if err = conn.Delete(questionKey(mid)); err != nil {
if err == gmc.ErrNotFound {
err = nil
}
}
return
}
// SetAnswerStateCache set labour answer state cache.
func (d *Dao) SetAnswerStateCache(c context.Context, mid int64, state int8) (err error) {
var (
conn = d.mc.Get(c)
item = &gmc.Item{Key: labourKey(mid), Object: state, Expiration: d.userExpire, Flags: gmc.FlagJSON}
)
defer conn.Close()
err = conn.Set(item)
return
}
// GetAnswerStateCache get labour answer state cache.
func (d *Dao) GetAnswerStateCache(c context.Context, mid int64) (state int8, found bool, err error) {
var (
reply *gmc.Item
conn = d.mc.Get(c)
)
defer conn.Close()
if reply, err = conn.Get(labourKey(mid)); err != nil {
if err == gmc.ErrNotFound {
err = nil
}
return
}
if err = conn.Scan(reply, &state); err != nil {
return
}
found = true
return
}
// JuryInfoCache .
func (d *Dao) JuryInfoCache(c context.Context, mid int64) (bj *model.BlockedJury, err error) {
conn := d.mc.Get(c)
defer conn.Close()
item, err := conn.Get(juryInfoKey(mid))
if err != nil {
if err == gmc.ErrNotFound {
err = nil
}
return
}
bj = &model.BlockedJury{}
err = conn.Scan(item, &bj)
return
}
// SetJuryInfoCache .
func (d *Dao) SetJuryInfoCache(c context.Context, mid int64, bj *model.BlockedJury) (err error) {
var (
conn = d.mc.Get(c)
item = &gmc.Item{Key: juryInfoKey(mid), Object: bj, Expiration: d.userExpire, Flags: gmc.FlagJSON}
)
defer conn.Close()
err = conn.Set(item)
return
}
// DelJuryInfoCache del jury cache info.
func (d *Dao) DelJuryInfoCache(c context.Context, mid int64) (err error) {
conn := d.mc.Get(c)
defer conn.Close()
if err = conn.Delete(juryInfoKey(mid)); err != nil {
if err == gmc.ErrNotFound {
err = nil
}
}
return
}

View File

@@ -0,0 +1,349 @@
package dao
import (
"context"
"go-common/app/interface/main/credit/model"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaonoticeKey(t *testing.T) {
convey.Convey("noticeKey", t, func(convCtx convey.C) {
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
p1 := noticeKey()
convCtx.Convey("Then p1 should not be nil.", func(convCtx convey.C) {
convCtx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoreasonKey(t *testing.T) {
convey.Convey("reasonKey", t, func(convCtx convey.C) {
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
p1 := reasonKey()
convCtx.Convey("Then p1 should not be nil.", func(convCtx convey.C) {
convCtx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoopinionKey(t *testing.T) {
convey.Convey("opinionKey", t, func(convCtx convey.C) {
var (
opid = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
p1 := opinionKey(opid)
convCtx.Convey("Then p1 should not be nil.", func(convCtx convey.C) {
convCtx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoquestionKey(t *testing.T) {
convey.Convey("questionKey", t, func(convCtx convey.C) {
var (
mid = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
p1 := questionKey(mid)
convCtx.Convey("Then p1 should not be nil.", func(convCtx convey.C) {
convCtx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaolabourKey(t *testing.T) {
convey.Convey("labourKey", t, func(convCtx convey.C) {
var (
mid = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
p1 := labourKey(mid)
convCtx.Convey("Then p1 should not be nil.", func(convCtx convey.C) {
convCtx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaojuryInfoKey(t *testing.T) {
convey.Convey("juryInfoKey", t, func(convCtx convey.C) {
var (
mid = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
p1 := juryInfoKey(mid)
convCtx.Convey("Then p1 should not be nil.", func(convCtx convey.C) {
convCtx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaopingMC(t *testing.T) {
convey.Convey("pingMC", t, func(convCtx convey.C) {
var (
c = context.Background()
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.pingMC(c)
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoNoticeInfoCache(t *testing.T) {
convey.Convey("NoticeInfoCache", t, func(convCtx convey.C) {
var (
c = context.Background()
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
dt, err := d.NoticeInfoCache(c)
convCtx.Convey("Then err should be nil.dt should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(dt, convey.ShouldBeNil)
})
})
})
}
func TestDaoSetReasonListCache(t *testing.T) {
convey.Convey("SetReasonListCache", t, func(convCtx convey.C) {
var (
c = context.Background()
dt = []*model.Reason{}
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.SetReasonListCache(c, dt)
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoSetNoticeInfoCache(t *testing.T) {
convey.Convey("SetNoticeInfoCache", t, func(convCtx convey.C) {
var (
c = context.Background()
n = &model.Notice{}
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.SetNoticeInfoCache(c, n)
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoDelNoticeInfoCache(t *testing.T) {
convey.Convey("DelNoticeInfoCache", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.DelNoticeInfoCache(c, mid)
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoReasonListCache(t *testing.T) {
convey.Convey("ReasonListCache", t, func(convCtx convey.C) {
var (
c = context.Background()
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
dt, err := d.ReasonListCache(c)
convCtx.Convey("Then err should be nil.dt should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(dt, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoDelReasonListCache(t *testing.T) {
convey.Convey("DelReasonListCache", t, func(convCtx convey.C) {
var (
c = context.Background()
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.DelReasonListCache(c)
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoAddOpinionCache(t *testing.T) {
convey.Convey("AddOpinionCache", t, func(convCtx convey.C) {
var (
c = context.Background()
op = &model.Opinion{}
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.AddOpinionCache(c, op)
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoOpinionsCache(t *testing.T) {
convey.Convey("OpinionsCache", t, func(convCtx convey.C) {
var (
c = context.Background()
opids = []int64{}
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
ops, miss, err := d.OpinionsCache(c, opids)
convCtx.Convey("Then err should be nil.ops should not be nil,miss should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(miss, convey.ShouldBeNil)
convCtx.So(ops, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoSetQsCache(t *testing.T) {
convey.Convey("SetQsCache", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(0)
qsid = &model.QsCache{}
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.SetQsCache(c, mid, qsid)
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoGetQsCache(t *testing.T) {
convey.Convey("GetQsCache", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
qsid, err := d.GetQsCache(c, mid)
convCtx.Convey("Then err should be nil.qsid should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(qsid, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoDelQsCache(t *testing.T) {
convey.Convey("DelQsCache", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.DelQsCache(c, mid)
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoSetAnswerStateCache(t *testing.T) {
convey.Convey("SetAnswerStateCache", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(0)
state = int8(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.SetAnswerStateCache(c, mid, state)
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoGetAnswerStateCache(t *testing.T) {
convey.Convey("GetAnswerStateCache", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
state, found, err := d.GetAnswerStateCache(c, mid)
convCtx.Convey("Then err should be nil.state,found should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(found, convey.ShouldNotBeNil)
convCtx.So(state, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoJuryInfoCache(t *testing.T) {
convey.Convey("JuryInfoCache", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
bj, err := d.JuryInfoCache(c, mid)
convCtx.Convey("Then err should be nil.bj should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(bj, convey.ShouldBeNil)
})
})
})
}
func TestDaoSetJuryInfoCache(t *testing.T) {
convey.Convey("SetJuryInfoCache", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(0)
bj = &model.BlockedJury{}
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.SetJuryInfoCache(c, mid, bj)
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoDelJuryInfoCache(t *testing.T) {
convey.Convey("DelJuryInfoCache", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.DelJuryInfoCache(c, mid)
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
})
}

View File

@@ -0,0 +1,354 @@
package dao
import (
"context"
"fmt"
"time"
model "go-common/app/interface/main/credit/model"
"go-common/library/database/sql"
"go-common/library/log"
ctime "go-common/library/time"
"go-common/library/xstr"
"github.com/pkg/errors"
)
const (
_insAnsLogSQL = "INSERT INTO blocked_labour_answer_log(mid,score,content,start_time) VALUES(?,?,?,?)"
_insQsSQL = "INSERT INTO blocked_labour_question(question,ans,av_id,status,source) VALUES(?,?,?,?,?)"
_updateQsSQL = "UPDATE blocked_labour_question SET ans=?,status=? WHERE id=?"
_delQsSQL = "UPDATE blocked_labour_question SET isdel=? WHERE id=?"
_selConfSQL = "SELECT config_key,content from blocked_config"
_selNoticeSQL = "SELECT id,content,url FROM blocked_notice WHERE status=0 ORDER BY id DESC LIMIT 1"
_selReasonSQL = "SELECT id,reason,content FROM blocked_reason WHERE status=0"
_selQuestionSQL = "SELECT id,question,ans FROM blocked_labour_question WHERE id IN(%s) AND status=2 ORDER BY find_in_set(id,'%s') "
_selAllQuestionSQL = "SELECT id,question,ans,av_id,status,source,ctime,mtime FROM blocked_labour_question WHERE id IN(%s) "
_isAnsweredSQL = "SELECT COUNT(*) FROM blocked_labour_answer_log WHERE mid=? AND score=100 AND mtime>=?"
_noAuditQuestionSQL = "SELECT id,av_id,question FROM blocked_labour_question WHERE status=2 ORDER BY id DESC LIMIT 20"
_auditQuestionSQL = "SELECT id,av_id,question FROM blocked_labour_question WHERE status=1 AND ans=0 ORDER BY id DESC LIMIT 20"
_selKPISQL = "SELECT k.mid,k.day,k.rate,k.rank,k.rank_per,k.rank_total,p.point,p.active_days,p.vote_total,p.opinion_likes,p.vote_real_total from blocked_kpi k inner join blocked_kpi_data p on k.mid=p.mid and k.day=p.day where k.mid = ?"
_announcementInfoSQL = `SELECT id,title,sub_title,publish_status,stick_status,content,url,ctime,mtime FROM blocked_publish WHERE id = ? AND publish_status = 1 AND status = 0`
_announcementListSQL = `SELECT id,title,sub_title,publish_status,stick_status,content,url,ptype,ctime,mtime FROM blocked_publish WHERE publish_status = 1 AND status = 0 AND show_time <= ? ORDER BY ctime desc`
_publishsSQL = "SELECT id,title,sub_title,stick_status,content,ctime FROM blocked_publish WHERE id IN (%s) AND publish_status = 1 AND status = 0"
_selNewKPISQL = "SELECT rate FROM blocked_kpi WHERE mid=? ORDER BY id DESC LIMIT 1"
)
// AddAnsLog add labour answer log.
func (d *Dao) AddAnsLog(c context.Context, mid int64, score int64, anstr string, stime ctime.Time) (affect int64, err error) {
result, err := d.db.Exec(c, _insAnsLogSQL, mid, score, anstr, stime)
if err != nil {
log.Error("AddAnsLog: db.Exec(mid:%d,score:%d,ans:%s) error(%v)", mid, score, anstr, err)
return
}
affect, err = result.LastInsertId()
return
}
// AddQs add labour question log.
func (d *Dao) AddQs(c context.Context, qs *model.LabourQs) (err error) {
if _, err = d.db.Exec(c, _insQsSQL, qs.Question, qs.Ans, qs.AvID, qs.Status, qs.Source); err != nil {
log.Error("AddQs: db.Exec(as:%v) error(%v)", qs, err)
}
return
}
// SetQs set labour question field.
func (d *Dao) SetQs(c context.Context, id int64, ans int64, status int64) (err error) {
if _, err = d.db.Exec(c, _updateQsSQL, ans, status, id); err != nil {
log.Error("setQs: db.Exec(ans:%d status:%d) error(%v)", ans, status, err)
}
return
}
// DelQs del labour question.
func (d *Dao) DelQs(c context.Context, id int64, isDel int64) (err error) {
if _, err = d.db.Exec(c, _delQsSQL, isDel, id); err != nil {
log.Error("setQs: db.Exec(id:%d isDel:%d) error(%v)", id, isDel, err)
}
return
}
// LoadConf load conf.
func (d *Dao) LoadConf(c context.Context) (cf map[string]string, err error) {
cf = make(map[string]string)
rows, err := d.db.Query(c, _selConfSQL)
if err != nil {
log.Error("d.loadConf err(%v)", err)
return
}
defer rows.Close()
var (
key string
value string
)
for rows.Next() {
if err = rows.Scan(&key, &value); err != nil {
log.Error("rows.Scan err(%v)", err)
return
}
cf[key] = value
}
err = rows.Err()
return
}
// Notice get notice
func (d *Dao) Notice(c context.Context) (n *model.Notice, err error) {
row := d.db.QueryRow(c, _selNoticeSQL)
if err != nil {
log.Error("Notice: d.QueryRow error(%v)", err)
return
}
n = &model.Notice{}
if err = row.Scan(&n.ID, &n.Content, &n.URL); err != nil {
log.Error("row.Scan() error(%v)", err)
}
return
}
// ReasonList get reason list
func (d *Dao) ReasonList(c context.Context) (res []*model.Reason, err error) {
rows, err := d.db.Query(c, _selReasonSQL)
if err != nil {
log.Error("reasonList: d.db.Query error(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
r := new(model.Reason)
if err = rows.Scan(&r.ID, &r.Reason, &r.Content); err != nil {
log.Error("row.Scan() error(%v)", err)
res = nil
return
}
res = append(res, r)
}
err = rows.Err()
return
}
// QsList get question list.
func (d *Dao) QsList(c context.Context, idStr string) (res []*model.LabourQs, err error) {
var rows *sql.Rows
if rows, err = d.db.Query(c, fmt.Sprintf(_selQuestionSQL, idStr, idStr)); err != nil {
log.Error("d.QuestionList.Query(%s) error(%v)", idStr, err)
return
}
defer rows.Close()
for rows.Next() {
r := new(model.LabourQs)
if err = rows.Scan(&r.ID, &r.Question, &r.Ans); err != nil {
log.Error("row.Scan() error(%v)", err)
res = nil
return
}
res = append(res, r)
}
err = rows.Err()
return
}
// QsAllList get question list.
func (d *Dao) QsAllList(c context.Context, idStr string) (mlab map[int64]*model.LabourQs, labs []*model.LabourQs, avIDs []int64, err error) {
var rows *sql.Rows
if rows, err = d.db.Query(c, fmt.Sprintf(_selAllQuestionSQL, idStr)); err != nil {
return
}
defer rows.Close()
mlab = make(map[int64]*model.LabourQs, 40)
for rows.Next() {
r := new(model.LabourQs)
if err = rows.Scan(&r.ID, &r.Question, &r.Ans, &r.AvID, &r.Status, &r.Source, &r.Ctime, &r.Mtime); err != nil {
if err == sql.ErrNoRows {
err = nil
}
mlab = nil
labs = nil
avIDs = nil
return
}
mlab[r.ID] = r
labs = append(labs, r)
if r.AvID != 0 {
avIDs = append(avIDs, r.AvID)
}
}
err = rows.Err()
return
}
// AnswerStatus get blocked user answer status.
func (d *Dao) AnswerStatus(c context.Context, mid int64, ts time.Time) (status bool, err error) {
row := d.db.QueryRow(c, _isAnsweredSQL, mid, ts)
var count int64
if err = row.Scan(&count); err != nil {
if err != sql.ErrNoRows {
err = errors.Wrap(err, "AnswerStatus")
return
}
count = 0
err = nil
}
status = count > 0
return
}
// LastNoAuditQuestion get new no audit question data.
func (d *Dao) LastNoAuditQuestion(c context.Context) (res []*model.LabourQs, avIDs []int64, err error) {
rows, err := d.db.Query(c, _noAuditQuestionSQL)
if err != nil {
log.Error("d.db.Query err(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
labourQs := &model.LabourQs{}
if err = rows.Scan(&labourQs.ID, &labourQs.AvID, &labourQs.Question); err != nil {
if err == sql.ErrNoRows {
err = nil
} else {
log.Error("rows.Scan err(%v)", err)
}
res = []*model.LabourQs{}
avIDs = []int64{}
return
}
res = append(res, labourQs)
if labourQs.AvID != 0 {
avIDs = append(avIDs, labourQs.AvID)
}
}
err = rows.Err()
return
}
// LastAuditQuestion get new audit question data.
func (d *Dao) LastAuditQuestion(c context.Context) (res []*model.LabourQs, avIDs []int64, err error) {
rows, err := d.db.Query(c, _auditQuestionSQL)
if err != nil {
log.Error("d.db.Query err(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
labourQs := &model.LabourQs{}
if err = rows.Scan(&labourQs.ID, &labourQs.AvID, &labourQs.Question); err != nil {
if err == sql.ErrNoRows {
err = nil
} else {
log.Error("rows.Scan err(%v)", err)
}
res = []*model.LabourQs{}
avIDs = []int64{}
return
}
res = append(res, labourQs)
if labourQs.AvID != 0 {
avIDs = append(avIDs, labourQs.AvID)
}
}
err = rows.Err()
return
}
// KPIList get kpi list.
func (d *Dao) KPIList(c context.Context, mid int64) (res []*model.KPIData, err error) {
var rows *sql.Rows
if rows, err = d.db.Query(c, _selKPISQL, mid); err != nil {
log.Error("KpiList: d.db.Query error(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
r := new(model.KPIData)
if err = rows.Scan(&r.Mid, &r.Day, &r.Rate, &r.RankPer, &r.RankPer, &r.RankTotal, &r.Point, &r.ActiveDays, &r.VoteTotal, &r.OpinionLikes, &r.VoteRealTotal); err != nil {
log.Error("row.Scan() error(%v)", err)
res = nil
return
}
res = append(res, r)
}
err = rows.Err()
return
}
// AnnouncementInfo get announcement detail.
func (d *Dao) AnnouncementInfo(c context.Context, aid int64) (r *model.BlockedAnnouncement, err error) {
row := d.db.QueryRow(c, _announcementInfoSQL, aid)
if err = row.Scan(&r.ID, &r.Title, &r.SubTitle, &r.Content, &r.PublishStatus, &r.StickStatus, &r.URL, &r.Ptype, &r.CTime, &r.MTime); err != nil {
if err == sql.ErrNoRows {
err = nil
return
}
err = errors.Wrap(err, "AnnouncementInfo")
}
return
}
// AnnouncementList get accnoucement list.
func (d *Dao) AnnouncementList(c context.Context) (res []*model.BlockedAnnouncement, err error) {
rows, err := d.db.Query(c, _announcementListSQL, time.Now())
if err != nil {
err = errors.Wrap(err, "AnnouncementList")
return
}
defer rows.Close()
for rows.Next() {
r := new(model.BlockedAnnouncement)
if err = rows.Scan(&r.ID, &r.Title, &r.SubTitle, &r.PublishStatus, &r.StickStatus, &r.Content, &r.URL, &r.Ptype, &r.CTime, &r.MTime); err != nil {
if err == sql.ErrNoRows {
err = nil
return
}
err = errors.Wrap(err, "AnnouncementList")
return
}
res = append(res, r)
}
err = rows.Err()
return
}
// BatchPublishs get publish info list.
func (d *Dao) BatchPublishs(c context.Context, ids []int64) (res map[int64]*model.BlockedAnnouncement, err error) {
rows, err := d.db.Query(c, fmt.Sprintf(_publishsSQL, xstr.JoinInts(ids)))
if err != nil {
err = errors.Wrap(err, "BatchPublishs")
return
}
res = make(map[int64]*model.BlockedAnnouncement)
defer rows.Close()
for rows.Next() {
r := new(model.BlockedAnnouncement)
if err = rows.Scan(&r.ID, &r.Title, &r.SubTitle, &r.StickStatus, &r.Content, &r.CTime); err != nil {
if err == sql.ErrNoRows {
err = nil
return
}
err = errors.Wrap(err, "BatchPublishs")
return
}
res[r.ID] = r
}
err = rows.Err()
return
}
// NewKPI return user newest KPI rate.
func (d *Dao) NewKPI(c context.Context, mid int64) (rate int8, err error) {
row := d.db.QueryRow(c, _selNewKPISQL, mid)
if err != nil {
log.Error("NewKPI: d.QueryRow error(%v)", err)
return
}
if err = row.Scan(&rate); err != nil {
if err == sql.ErrNoRows {
rate = model.KPILevelC
err = nil
return
}
log.Error("row.Scan() error(%v)", err)
}
return
}

View File

@@ -0,0 +1,250 @@
package dao
import (
"context"
"math/rand"
"testing"
"time"
model "go-common/app/interface/main/credit/model"
"github.com/smartystreets/goconvey/convey"
)
// TestDao_LoadConf .
func TestDao_LoadConf(t *testing.T) {
var c = context.Background()
convey.Convey("return someting", t, func(convCtx convey.C) {
v, err := d.LoadConf(c)
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(v, convey.ShouldNotBeNil)
})
}
// TestJuryOpinion .
func TestJuryOpinion(t *testing.T) {
var (
c = context.Background()
)
convey.Convey("return someting", t, func(convCtx convey.C) {
tx, err := d.BeginTran(c)
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(tx, convey.ShouldNotBeNil)
d.SetVoteTx(tx, 21432418, 383, 1)
d.AddOpinionTx(tx, 383, 632, 11, "aaa", 1, 1, 1)
tx.Commit()
_, err = d.AddHates(c, []int64{632})
convCtx.So(err, convey.ShouldBeNil)
_, err = d.AddLikes(c, []int64{632})
convCtx.So(err, convey.ShouldBeNil)
ops, err := d.Opinions(c, []int64{632})
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(ops, convey.ShouldBeNil)
})
}
// TestDao_IsVote .
func TestDao_IsVote(t *testing.T) {
var (
err error
c = context.Background()
res int64
)
convey.Convey("return someting", t, func(convCtx convey.C) {
res, err = d.IsVote(c, 2528, 631)
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(res, convey.ShouldNotBeNil)
})
}
// TestDao_CaseInfo .
func TestDao_CaseInfo(t *testing.T) {
var (
err error
c = context.Background()
res = &model.BlockedCase{}
)
convey.Convey("return someting", t, func(convCtx convey.C) {
res, err = d.CaseInfo(c, -1)
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(res, convey.ShouldBeNil)
})
}
// TestDao_VoteInfo .
func TestDao_VoteInfo(t *testing.T) {
var (
err error
c = context.Background()
res = &model.VoteInfo{}
)
convey.Convey("return someting", t, func(convCtx convey.C) {
res, err = d.VoteInfo(c, 2528, 631)
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(res, convey.ShouldNotBeNil)
})
}
// TestDao_ApplyJuryInfo .
func TestDao_ApplyJuryInfo(t *testing.T) {
var (
err error
c = context.Background()
res = &model.BlockedJury{}
)
convey.Convey("return someting", t, func(convCtx convey.C) {
res, err = d.JuryInfo(c, 2528)
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(res, convey.ShouldNotBeNil)
})
}
// TestDao_JuryInfo .
func TestDao_JuryInfo(t *testing.T) {
var (
err error
c = context.Background()
res = &model.BlockedJury{}
)
convey.Convey("return someting", t, func(convCtx convey.C) {
res, err = d.JuryInfo(c, 0)
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(res, convey.ShouldNotBeNil)
})
}
// TestDao_Setvote .
func TestDao_Setvote(t *testing.T) {
var (
err error
c = context.Background()
)
convey.Convey("return someting", t, func(convCtx convey.C) {
err = d.Setvote(c, 2528, 631, 1)
convCtx.So(err, convey.ShouldBeNil)
})
}
// TestDao_InsVote .
func TestDao_InsVote(t *testing.T) {
var (
err error
c = context.Background()
)
convey.Convey("return someting", t, func(convCtx convey.C) {
err = d.InsVote(c, rand.Int63n(9999999), rand.Int63n(9999999), 1)
convCtx.So(err, convey.ShouldBeNil)
})
}
func TestDao_AddUserVoteTotal(t *testing.T) {
var (
err error
c = context.Background()
)
convey.Convey("return someting", t, func(convCtx convey.C) {
err = d.AddUserVoteTotal(c, 2528)
convCtx.So(err, convey.ShouldBeNil)
})
}
func TestDao_AddCaseVoteTotal(t *testing.T) {
var (
err error
c = context.Background()
)
convey.Convey("return someting", t, func(convCtx convey.C) {
err = d.AddCaseVoteTotal(c, "put_total", 631, 1)
convCtx.So(err, convey.ShouldBeNil)
})
}
func TestDao_JuryApply(t *testing.T) {
var (
err error
c = context.Background()
)
convey.Convey("return someting", t, func(convCtx convey.C) {
err = d.JuryApply(c, 2528, time.Now().AddDate(0, 0, 30))
convCtx.So(err, convey.ShouldBeNil)
})
}
func TestOpinionIdx(t *testing.T) {
convey.Convey("return someting", t, func(convCtx convey.C) {
res, err := d.OpinionIdx(context.Background(), -1)
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(res, convey.ShouldBeNil)
})
}
func TestDao_addQs(t *testing.T) {
var qs = &model.LabourQs{}
qs.Question = "test"
qs.Ans = 1
qs.AvID = 123
qs.Status = 1
convey.Convey("return someting", t, func(convCtx convey.C) {
err := d.AddQs(context.Background(), qs)
convCtx.So(err, convey.ShouldBeNil)
})
}
func TestDao_setQs(t *testing.T) {
convey.Convey("return someting", t, func(convCtx convey.C) {
err := d.SetQs(context.Background(), 1, 2, 2)
convCtx.So(err, convey.ShouldBeNil)
})
}
func TestDao_delQs(t *testing.T) {
convey.Convey("return someting", t, func(convCtx convey.C) {
err := d.DelQs(context.Background(), 1, 1)
convCtx.So(err, convey.ShouldBeNil)
})
}
func TestDao_AddBlockedCases(t *testing.T) {
var (
err error
c = context.Background()
bc []*model.ArgJudgeCase
b = &model.ArgJudgeCase{}
)
b.MID = 1
b.Operator = "a"
b.OContent = "oc"
b.PunishResult = 1
b.OTitle = "ot"
b.OType = 1
b.OURL = "ou"
b.BlockedDays = 1
b.ReasonType = 1
b.RelationID = "1-1"
bc = append(bc, b)
b = &model.ArgJudgeCase{}
b.MID = 1
b.Operator = "a"
b.OContent = "oc"
b.PunishResult = 1
b.OTitle = "ot"
b.OType = 1
b.OURL = "ou"
b.BlockedDays = 1
b.ReasonType = 1
b.RelationID = "1-1"
bc = append(bc, b)
convey.Convey("return someting", t, func(convCtx convey.C) {
err = d.AddBlockedCases(c, bc)
convCtx.So(err, convey.ShouldBeNil)
})
}
func TestDao_NewKPI(t *testing.T) {
convey.Convey("should return err be nil & map be nil", t, func(convCtx convey.C) {
rate, err := d.NewKPI(context.Background(), 4)
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(rate, convey.ShouldBeGreaterThanOrEqualTo, 0)
t.Logf("rate:%d", rate)
})
}

View File

@@ -0,0 +1,131 @@
package dao
import (
"context"
"fmt"
"go-common/app/interface/main/credit/model"
"go-common/library/database/sql"
"go-common/library/log"
"go-common/library/xstr"
)
const (
_addOpinionSQL = "INSERT INTO blocked_opinion(vid,cid,content,attr,mid,vote,state) VALUE(?,?,?,?,?,?,?)"
_addLikesSQL = "UPDATE blocked_opinion SET likes=likes+1 where vid in(%s)"
_addHatesSQL = "UPDATE blocked_opinion SET hates=hates+1 where vid in(%s)"
_delOpinionSQL = "UPDATE blocked_opinion SET state = 1 WHERE vid = ?"
_selOpinionIdxSQL = "SELECT vid,likes,hates,vote FROM blocked_opinion WHERE cid = ? AND state = 0 ORDER BY likes DESC"
_selOpinionsSQL = "SELECT vid,content,attr,hates,likes,mid,vote FROM blocked_opinion WHERE vid IN(%s) AND state = 0"
_opContentMidSQL = "SELECT content FROM blocked_opinion WHERE mid = ? AND state = 0 ORDER BY id DESC LIMIT 1"
)
// AddOpinionTx add user opinion by transaction.
func (d *Dao) AddOpinionTx(tx *sql.Tx, cid, opid, mid int64, content string, attr, vote, state int8) (affect int64, err error) {
row, err := tx.Exec(_addOpinionSQL, opid, cid, content, attr, mid, vote, state)
if err != nil {
log.Error("add opinion err(%v)", err)
return
}
return row.RowsAffected()
}
// AddLikes add user like opinions.
func (d *Dao) AddLikes(c context.Context, ids []int64) (affect int64, err error) {
rows, err := d.db.Exec(c, fmt.Sprintf(_addLikesSQL, xstr.JoinInts(ids)))
if err != nil {
log.Error("d.AddLikes err(%v) ids(%v)", err, ids)
return
}
return rows.RowsAffected()
}
// AddHates add user like opinions.
func (d *Dao) AddHates(c context.Context, ids []int64) (affect int64, err error) {
rows, err := d.db.Exec(c, fmt.Sprintf(_addHatesSQL, xstr.JoinInts(ids)))
if err != nil {
log.Error("d.AddHates err(%v) ids(%v)", err, ids)
return
}
return rows.RowsAffected()
}
// DelOpinion del opinion.
func (d *Dao) DelOpinion(c context.Context, opid int64) (err error) {
if _, err = d.db.Exec(c, _delOpinionSQL, opid); err != nil {
log.Error("d.Delopinion err(%v)", err)
}
return
}
// OpinionIdx get opinion index.
func (d *Dao) OpinionIdx(c context.Context, cid int64) (ops []*model.Opinion, err error) {
rows, err := d.db.Query(c, _selOpinionIdxSQL, cid)
if err != nil {
log.Error("OpinionIdx err(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
op := &model.Opinion{}
if err = rows.Scan(&op.OpID, &op.Like, &op.Hate, &op.Vote); err != nil {
log.Error("row.Scan err(%v)", err)
return
}
ops = append(ops, op)
}
return
}
// OpinionCaseIdx get opinion case index.
func (d *Dao) OpinionCaseIdx(c context.Context, cid int64) (ops []*model.Opinion, err error) {
rows, err := d.db.Query(c, _selOpinionIdxSQL, cid)
if err != nil {
log.Error("OpinionIdx err(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
op := &model.Opinion{}
if err = rows.Scan(&op.OpID, &op.Like, &op.Hate, &op.Vote); err != nil {
log.Error("row.Scan err(%v)", err)
return
}
if op.Like-op.Hate > -5 {
ops = append(ops, op)
}
}
return
}
// Opinions get opinions.
func (d *Dao) Opinions(c context.Context, opids []int64) (ops []*model.Opinion, err error) {
rows, err := d.db.Query(c, fmt.Sprintf(_selOpinionsSQL, xstr.JoinInts(opids)))
if err != nil {
log.Error("d.Opinions vids(%v) err(%v)", err, opids)
return
}
defer rows.Close()
for rows.Next() {
op := &model.Opinion{}
if err = rows.Scan(&op.OpID, &op.Content, &op.Attr, &op.Hate, &op.Like, &op.Mid, &op.Vote); err != nil {
log.Error("row.Scan err(%v)", err)
}
ops = append(ops, op)
}
return
}
// OpContentMid get opinion content.
func (d *Dao) OpContentMid(c context.Context, mid int64) (content string, err error) {
row := d.db.QueryRow(c, _opContentMidSQL, mid)
if err = row.Scan(&content); err != nil {
if err != sql.ErrNoRows {
log.Error("row.Scan() error(%v)", err)
return
}
content = ""
err = nil
}
return
}

View File

@@ -0,0 +1,148 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoAddOpinionTx(t *testing.T) {
convey.Convey("AddOpinionTx", t, func(convCtx convey.C) {
var (
tx, _ = d.BeginTran(context.Background())
cid = int64(0)
opid = int64(0)
mid = int64(0)
content = ""
attr = int8(0)
vote = int8(0)
state = int8(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
affect, err := d.AddOpinionTx(tx, cid, opid, mid, content, attr, vote, state)
if err == nil {
if err = tx.Commit(); err != nil {
tx.Rollback()
}
} else {
tx.Rollback()
}
convCtx.Convey("Then err should be nil.affect should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(affect, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoAddLikes(t *testing.T) {
convey.Convey("AddLikes", t, func(convCtx convey.C) {
var (
c = context.Background()
ids = []int64{53, 55}
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
affect, err := d.AddLikes(c, ids)
convCtx.Convey("Then err should be nil.affect should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(affect, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoAddHates(t *testing.T) {
convey.Convey("AddHates", t, func(convCtx convey.C) {
var (
c = context.Background()
ids = []int64{53, 55}
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
affect, err := d.AddHates(c, ids)
convCtx.Convey("Then err should be nil.affect should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(affect, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoDelOpinion(t *testing.T) {
convey.Convey("DelOpinion", t, func(convCtx convey.C) {
var (
c = context.Background()
opid = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.DelOpinion(c, opid)
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoOpinionIdx(t *testing.T) {
convey.Convey("OpinionIdx", t, func(convCtx convey.C) {
var (
c = context.Background()
cid = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
ops, err := d.OpinionIdx(c, cid)
convCtx.Convey("Then err should be nil.ops should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(ops, convey.ShouldBeNil)
})
})
})
}
func TestDaoOpinionCaseIdx(t *testing.T) {
convey.Convey("OpinionCaseIdx", t, func(convCtx convey.C) {
var (
c = context.Background()
cid = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
ops, err := d.OpinionCaseIdx(c, cid)
convCtx.Convey("Then err should be nil.ops should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(ops, convey.ShouldBeNil)
})
})
})
}
func TestDaoOpinions(t *testing.T) {
convey.Convey("Opinions", t, func(convCtx convey.C) {
var (
c = context.Background()
opids = []int64{55, 207}
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
ops, err := d.Opinions(c, opids)
convCtx.Convey("Then err should be nil.ops should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(ops, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoOpContentMid(t *testing.T) {
convey.Convey("OpContentMid", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
content, err := d.OpContentMid(c, mid)
convCtx.Convey("Then err should be nil.content should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(content, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,172 @@
package dao
import (
"context"
"encoding/json"
"fmt"
"strconv"
"time"
model "go-common/app/interface/main/credit/model"
"go-common/library/cache/redis"
"go-common/library/log"
"github.com/pkg/errors"
)
const (
_caseObtainMIDIdx = "c_o_v2_%d"
_caseVoteCIDMIDIdx = "c_v_c_m_v2_%d_%s"
_grantCaseKey = "gr_ca_li_v2"
)
func caseObtainMIDKey(mid int64) string {
return fmt.Sprintf(_caseObtainMIDIdx, mid)
}
func caseVoteCIDMIDKey(mid int64) string {
return fmt.Sprintf(_caseVoteCIDMIDIdx, mid, time.Now().Format("2006_01_02"))
}
// CaseObtainMID get voted cids by MID.
func (d *Dao) CaseObtainMID(c context.Context, mid int64, isToday bool) (cases map[int64]*model.SimCase, err error) {
conn := d.redis.Get(c)
defer conn.Close()
var _setKey string
if isToday {
_setKey = caseVoteCIDMIDKey(mid)
} else {
_setKey = caseObtainMIDKey(mid)
}
var ms []string
if ms, err = redis.Strings(conn.Do("SMEMBERS", _setKey)); err != nil {
if err != redis.ErrNil {
return
}
err = nil
}
cases = make(map[int64]*model.SimCase)
for _, s := range ms {
if s == "" {
continue
}
sc := &model.SimCase{}
if err = json.Unmarshal([]byte(s), sc); err != nil {
err = errors.WithStack(err)
return
}
cases[sc.ID] = sc
}
return
}
// IsExpiredObtainMID voted cids by MID of key is expired.
func (d *Dao) IsExpiredObtainMID(c context.Context, mid int64, isToday bool) (ok bool, err error) {
conn := d.redis.Get(c)
defer conn.Close()
var _setKey string
if isToday {
_setKey = caseVoteCIDMIDKey(mid)
} else {
_setKey = caseObtainMIDKey(mid)
}
ok, err = redis.Bool(conn.Do("EXPIRE", _setKey, d.redisExpire))
return
}
// GrantCases get granting case cids.
func (d *Dao) GrantCases(c context.Context) (mcases map[int64]*model.SimCase, err error) {
conn := d.redis.Get(c)
defer conn.Close()
var ms map[string]string
if ms, err = redis.StringMap(conn.Do("HGETALL", _grantCaseKey)); err != nil {
if err != redis.ErrNil {
return
}
err = nil
}
mcases = make(map[int64]*model.SimCase)
for m, s := range ms {
if s == "" {
continue
}
cid, err := strconv.ParseInt(m, 10, 64)
if err != nil {
log.Error("strconv.ParseInt(%s) error(%v)", m, err)
err = nil
continue
}
cc := &model.SimCase{}
if err = json.Unmarshal([]byte(s), cc); err != nil {
log.Error("json.Unmarshal(%s) error(%v)", s, err)
err = nil
continue
}
mcases[cid] = cc
}
return
}
// LoadVoteCaseMID load mid vote cases.
func (d *Dao) LoadVoteCaseMID(c context.Context, mid int64, mcases map[int64]*model.SimCase, isToday bool) (err error) {
conn := d.redis.Get(c)
defer conn.Close()
var _setKey string
if isToday {
_setKey = caseVoteCIDMIDKey(mid)
} else {
_setKey = caseObtainMIDKey(mid)
}
args := redis.Args{}.Add(_setKey)
for _, mcase := range mcases {
var mcStr []byte
if mcStr, err = json.Marshal(mcase); err != nil {
err = errors.WithStack(err)
return
}
args = args.Add(string(mcStr))
}
if err = conn.Send("SADD", args...); err != nil {
return
}
if err = conn.Send("EXPIRE", _setKey, d.redisExpire); err != nil {
return
}
if err = conn.Flush(); err != nil {
return
}
for i := 0; i < 2; i++ {
_, err = conn.Receive()
}
return
}
// SetVoteCaseMID set vote case by mid on today.
func (d *Dao) SetVoteCaseMID(c context.Context, mid int64, sc *model.SimCase) (err error) {
conn := d.redis.Get(c)
defer conn.Close()
var scStr []byte
if scStr, err = json.Marshal(sc); err != nil {
err = errors.WithStack(err)
return
}
if err = conn.Send("SADD", caseObtainMIDKey(mid), string(scStr)); err != nil {
return
}
if err = conn.Send("SADD", caseVoteCIDMIDKey(mid), string(scStr)); err != nil {
return
}
if err = conn.Send("EXPIRE", caseObtainMIDKey(mid), d.redisExpire); err != nil {
return
}
if err = conn.Send("EXPIRE", caseVoteCIDMIDKey(mid), d.redisExpire); err != nil {
return
}
if err = conn.Flush(); err != nil {
return
}
for i := 0; i < 4; i++ {
_, err = conn.Receive()
}
return
}

View File

@@ -0,0 +1,119 @@
package dao
import (
"context"
"go-common/app/interface/main/credit/model"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaocaseObtainMIDKey(t *testing.T) {
convey.Convey("caseObtainMIDKey", t, func(convCtx convey.C) {
var (
mid = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
p1 := caseObtainMIDKey(mid)
convCtx.Convey("Then p1 should not be nil.", func(convCtx convey.C) {
convCtx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaocaseVoteCIDMIDKey(t *testing.T) {
convey.Convey("caseVoteCIDMIDKey", t, func(convCtx convey.C) {
var (
mid = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
p1 := caseVoteCIDMIDKey(mid)
convCtx.Convey("Then p1 should not be nil.", func(convCtx convey.C) {
convCtx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoCaseObtainMID(t *testing.T) {
convey.Convey("CaseObtainMID", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(0)
isToday bool
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
cases, err := d.CaseObtainMID(c, mid, isToday)
convCtx.Convey("Then err should be nil.cases should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(cases, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoIsExpiredObtainMID(t *testing.T) {
convey.Convey("IsExpiredObtainMID", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(0)
isToday bool
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
ok, err := d.IsExpiredObtainMID(c, mid, isToday)
convCtx.Convey("Then err should be nil.ok should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(ok, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoGrantCases(t *testing.T) {
convey.Convey("GrantCases", t, func(convCtx convey.C) {
var (
c = context.Background()
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
mcases, err := d.GrantCases(c)
convCtx.Convey("Then err should be nil.mcases should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(mcases, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoLoadVoteCaseMID(t *testing.T) {
convey.Convey("LoadVoteCaseMID", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(0)
mcases map[int64]*model.SimCase
isToday bool
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.LoadVoteCaseMID(c, mid, mcases, isToday)
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoSetVoteCaseMID(t *testing.T) {
convey.Convey("SetVoteCaseMID", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(0)
sc = &model.SimCase{}
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.SetVoteCaseMID(c, mid, sc)
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
})
}