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,103 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_test",
"go_library",
)
go_test(
name = "go_default_test",
srcs = [
"activity_test.go",
"authority_test.go",
"banner_test.go",
"blacklist_test.go",
"block_test.go",
"cheat_test.go",
"credit_test.go",
"dao_test.go",
"expense_info_test.go",
"notice_test.go",
"offlineactivity_test.go",
"special_award_test.go",
"tag_test.go",
"trade_test.go",
"up_tag_income_test.go",
"up_test.go",
"upload_test.go",
],
embed = [":go_default_library"],
rundir = ".",
tags = ["automanaged"],
deps = [
"//app/admin/main/growup/conf:go_default_library",
"//app/admin/main/growup/dao/shell:go_default_library",
"//app/admin/main/growup/model:go_default_library",
"//app/admin/main/growup/model/offlineactivity:go_default_library",
"//library/time:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
],
)
go_library(
name = "go_default_library",
srcs = [
"activity.go",
"authority.go",
"banner.go",
"blacklist.go",
"block.go",
"cheat.go",
"credit.go",
"dao.go",
"expense_info.go",
"notice.go",
"offlineactivity.go",
"special_award.go",
"tag.go",
"trade.go",
"up.go",
"up_tag_income.go",
"upload.go",
],
importpath = "go-common/app/admin/main/growup/dao",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/admin/main/growup/conf:go_default_library",
"//app/admin/main/growup/dao/shell:go_default_library",
"//app/admin/main/growup/model:go_default_library",
"//app/admin/main/growup/model/offlineactivity:go_default_library",
"//app/admin/main/up/util:go_default_library",
"//library/database/orm:go_default_library",
"//library/database/sql:go_default_library",
"//library/ecode:go_default_library",
"//library/log:go_default_library",
"//library/net/http/blademaster:go_default_library",
"//library/net/trace:go_default_library",
"//library/time:go_default_library",
"//library/xstr:go_default_library",
"//vendor/github.com/jinzhu/gorm:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [
":package-srcs",
"//app/admin/main/growup/dao/income:all-srcs",
"//app/admin/main/growup/dao/message:all-srcs",
"//app/admin/main/growup/dao/resource:all-srcs",
"//app/admin/main/growup/dao/shell:all-srcs",
],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

View File

@@ -0,0 +1,187 @@
package dao
import (
"context"
"fmt"
"go-common/app/admin/main/growup/model"
"go-common/library/database/sql"
"go-common/library/log"
"go-common/library/xstr"
)
const (
_activityByNameSQL = "SELECT id FROM creative_activity WHERE name = ?"
_activityCountSQL = "SELECT count(*) FROM creative_activity %s"
_activitisSQL = "SELECT id,name,signed_start,signed_end,sign_up,sign_up_start,sign_up_end,object,upload_start,upload_end,win_type,require_items,require_value,statistics_start,statistics_end,bonus_type,bonus_time,progress_frequency,update_page,progress_start,progress_end,progress_sync,bonus_query,bonus_query_start,bonus_query_end,background,win_desc,unwin_desc,details FROM creative_activity %s LIMIT ?,?"
_activityBonusSQL = "SELECT activity_id,ranking,bonus_money FROM activity_bonus WHERE activity_id IN (%s)"
_upActivityStateCountSQL = "SELECT count(*) FROM up_activity WHERE activity_id = ? AND state IN (%s)"
_upActivitySQL = "SELECT mid,nickname,sign_up_time,bonus,ranking,state FROM up_activity WHERE activity_id = ? AND state != 0 AND is_deleted = 0 LIMIT ?,?"
_upActivitySuccessSQL = "SELECT mid,nickname,aids,aid_num,bonus,success_time,state FROM up_activity WHERE activity_id = ? AND state IN (2,3) %s AND is_deleted = 0 LIMIT ?,?"
_txInsertActivitySQL = "INSERT INTO creative_activity(name,creator,signed_start,signed_end,sign_up,sign_up_start,sign_up_end,object,upload_start,upload_end,win_type,require_items,require_value,statistics_start,statistics_end,bonus_type,bonus_time,progress_frequency,update_page,progress_start,progress_end,progress_sync,bonus_query,bonus_query_start,bonus_query_end,background,win_desc,unwin_desc,details) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) %s"
_txInsertBonusRankSQL = "INSERT INTO activity_bonus(activity_id,ranking,bonus_money) VALUES %s ON DUPLICATE KEY UPDATE activity_id=VALUES(activity_id),ranking=VALUES(ranking),bonus_money=VALUES(bonus_money)"
_updateUpActivityStateSQL = "UPDATE up_activity SET state = ? WHERE activity_id = ? AND mid IN (%s) AND state = ?"
)
// GetActivityByName get activity by name
func (d *Dao) GetActivityByName(c context.Context, name string) (id int64, err error) {
err = d.rddb.QueryRow(c, _activityByNameSQL, name).Scan(&id)
return
}
// ActivityCount get activity count by query
func (d *Dao) ActivityCount(c context.Context, query string) (count int, err error) {
err = d.rddb.QueryRow(c, fmt.Sprintf(_activityCountSQL, query)).Scan(&count)
return
}
// GetActivities get activity by query
func (d *Dao) GetActivities(c context.Context, query string, from, limit int) (acs []*model.CActivity, err error) {
acs = make([]*model.CActivity, 0)
rows, err := d.rddb.Query(c, fmt.Sprintf(_activitisSQL, query), from, limit)
if err != nil {
log.Error("GetActivities d.db.Query error(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
ac := &model.CActivity{}
err = rows.Scan(&ac.ID, &ac.Name, &ac.SignedStart, &ac.SignedEnd, &ac.SignUp, &ac.SignUpStart, &ac.SignUpEnd, &ac.Object, &ac.UploadStart, &ac.UploadEnd, &ac.WinType, &ac.RequireItems, &ac.RequireValue, &ac.StatisticsStart, &ac.StatisticsEnd, &ac.BonusType, &ac.BonusTime, &ac.ProgressFrequency, &ac.UpdatePage, &ac.ProgressStart, &ac.ProgressEnd, &ac.ProgressSync, &ac.BonusQuery, &ac.BonusQuerStart, &ac.BonusQueryEnd, &ac.Background, &ac.WinDesc, &ac.UnwinDesc, &ac.Details)
if err != nil {
log.Error("GetActivities row.Scan error(%v)", err)
return
}
acs = append(acs, ac)
}
err = rows.Err()
return
}
// TxGetActivityByName get activity by name
func (d *Dao) TxGetActivityByName(tx *sql.Tx, name string) (id int64, err error) {
err = tx.QueryRow(_activityByNameSQL, name).Scan(&id)
return
}
// TxInsertActivity tx insert into creative_activity
func (d *Dao) TxInsertActivity(tx *sql.Tx, ac *model.CActivity, update string) (rows int64, err error) {
res, err := tx.Exec(fmt.Sprintf(_txInsertActivitySQL, update), ac.Name, ac.Creator, ac.SignedStart, ac.SignedEnd, ac.SignUp, ac.SignUpStart, ac.SignUpEnd, ac.Object, ac.UploadStart, ac.UploadEnd, ac.WinType, ac.RequireItems, ac.RequireValue, ac.StatisticsStart, ac.StatisticsEnd, ac.BonusType, ac.BonusTime, ac.ProgressFrequency, ac.UpdatePage, ac.ProgressStart, ac.ProgressEnd, ac.ProgressSync, ac.BonusQuery, ac.BonusQuerStart, ac.BonusQueryEnd, ac.Background, ac.WinDesc, ac.UnwinDesc, ac.Details)
if err != nil {
return
}
return res.RowsAffected()
}
// GetActivityBonus get activity_bonus by id
func (d *Dao) GetActivityBonus(c context.Context, ids []int64) (brs []*model.BonusRank, err error) {
brs = make([]*model.BonusRank, 0)
rows, err := d.rddb.Query(c, fmt.Sprintf(_activityBonusSQL, xstr.JoinInts(ids)))
if err != nil {
log.Error("GetActivityBonus d.db.Query error(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
br := &model.BonusRank{}
err = rows.Scan(&br.ID, &br.Rank, &br.Money)
if err != nil {
log.Error("GetActivityBonus row.Scan error(%v)", err)
return
}
brs = append(brs, br)
}
err = rows.Err()
return
}
// TxInsertActivityBonusBatch tx insert into activity_bonus
func (d *Dao) TxInsertActivityBonusBatch(tx *sql.Tx, vals string) (rows int64, err error) {
if vals == "" {
return
}
res, err := tx.Exec(fmt.Sprintf(_txInsertBonusRankSQL, vals))
if err != nil {
return
}
return res.RowsAffected()
}
// UpActivityStateCount get up activity state count
func (d *Dao) UpActivityStateCount(c context.Context, id int64, states []int64) (count int, err error) {
err = d.rddb.QueryRow(c, fmt.Sprintf(_upActivityStateCountSQL, xstr.JoinInts(states)), id).Scan(&count)
return
}
// ListUpActivity list up_activity where state != 0
func (d *Dao) ListUpActivity(c context.Context, id int64, from, limit int) (ups []*model.UpActivity, err error) {
ups = make([]*model.UpActivity, 0)
rows, err := d.rddb.Query(c, _upActivitySQL, id, from, limit)
if err != nil {
log.Error("ListUpActivity d.db.Query error(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
up := &model.UpActivity{}
err = rows.Scan(&up.MID, &up.Nickname, &up.SignUpTime, &up.Bonus, &up.Rank, &up.State)
if err != nil {
log.Error("ListUpActivity row.Scan error(%v)", err)
return
}
ups = append(ups, up)
}
err = rows.Err()
return
}
// ListUpActivitySuccess list up_activity where state != 0
func (d *Dao) ListUpActivitySuccess(c context.Context, id, mid int64, from, limit int) (ups []*model.UpActivity, err error) {
ups = make([]*model.UpActivity, 0)
query := ""
if mid != 0 {
query = fmt.Sprintf("AND mid = %d", mid)
}
rows, err := d.rddb.Query(c, fmt.Sprintf(_upActivitySuccessSQL, query), id, from, limit)
if err != nil {
log.Error("ListUpActivitySuccess d.db.Query error(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
up := &model.UpActivity{}
err = rows.Scan(&up.MID, &up.Nickname, &up.AIDs, &up.AIDNum, &up.Bonus, &up.SuccessTime, &up.State)
if err != nil {
log.Error("ListUpActivitySuccess row.Scan error(%v)", err)
return
}
ups = append(ups, up)
}
err = rows.Err()
return
}
// UpdateUpActivityState update up state
func (d *Dao) UpdateUpActivityState(c context.Context, activityID int64, mids []int64, oldState, newState int) (rows int64, err error) {
if oldState == newState {
return
}
res, err := d.rddb.Exec(c, fmt.Sprintf(_updateUpActivityStateSQL, xstr.JoinInts(mids)), newState, activityID, oldState)
if err != nil {
return
}
return res.RowsAffected()
}
// TxUpdateUpActivityState tx update up state
func (d *Dao) TxUpdateUpActivityState(tx *sql.Tx, activityID int64, mids []int64, oldState, newState int) (rows int64, err error) {
if oldState == newState {
return
}
res, err := tx.Exec(fmt.Sprintf(_updateUpActivityStateSQL, xstr.JoinInts(mids)), newState, activityID, oldState)
if err != nil {
return
}
return res.RowsAffected()
}

View File

@@ -0,0 +1,228 @@
package dao
import (
"context"
"go-common/app/admin/main/growup/model"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoGetActivityByName(t *testing.T) {
convey.Convey("GetActivityByName", t, func(ctx convey.C) {
var (
c = context.Background()
name = "test"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
Exec(c, "INSERT INTO creative_activity(name) VALUES('test')")
_, err := d.GetActivityByName(c, name)
ctx.Convey("Then err should be nil.id should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoActivityCount(t *testing.T) {
convey.Convey("ActivityCount", t, func(ctx convey.C) {
var (
c = context.Background()
query = ""
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
count, err := d.ActivityCount(c, query)
ctx.Convey("Then err should be nil.count should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(count, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoGetActivities(t *testing.T) {
convey.Convey("GetActivities", t, func(ctx convey.C) {
var (
c = context.Background()
query = ""
from = int(0)
limit = int(10)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
acs, err := d.GetActivities(c, query, from, limit)
ctx.Convey("Then err should be nil.acs should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(acs, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoTxGetActivityByName(t *testing.T) {
convey.Convey("TxGetActivityByName", t, func(ctx convey.C) {
var (
tx, _ = d.BeginTran(context.Background())
name = "test"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
defer tx.Commit()
id, err := d.TxGetActivityByName(tx, name)
ctx.Convey("Then err should be nil.id should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(id, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoTxInsertActivity(t *testing.T) {
convey.Convey("TxInsertActivity", t, func(ctx convey.C) {
var (
tx, _ = d.BeginTran(context.Background())
ac = &model.CActivity{
Name: "test1",
}
update = ""
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
defer tx.Commit()
Exec(context.Background(), "DELETE FROM creative_activity WHERE name = 'test1'")
rows, err := d.TxInsertActivity(tx, ac, update)
ctx.Convey("Then err should be nil.rows should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rows, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoGetActivityBonus(t *testing.T) {
convey.Convey("GetActivityBonus", t, func(ctx convey.C) {
var (
c = context.Background()
ids = []int64{111}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
Exec(c, "INSERT INTO activity_bonus(activity_id,ranking,bonus_money) VALUES(111, 1, 1)")
_, err := d.GetActivityBonus(c, ids)
ctx.Convey("Then err should be nil.brs should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoTxInsertActivityBonusBatch(t *testing.T) {
convey.Convey("TxInsertActivityBonusBatch", t, func(ctx convey.C) {
var (
c = context.Background()
tx, _ = d.BeginTran(c)
vals = "(1112, 10, 10)"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
defer tx.Commit()
rows, err := d.TxInsertActivityBonusBatch(tx, vals)
ctx.Convey("Then err should be nil.rows should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rows, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoUpActivityStateCount(t *testing.T) {
convey.Convey("UpActivityStateCount", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(111)
states = []int64{1, 2, 3}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
Exec(c, "INSERT INTO up_activity(activity_id, mid, state) VALUES(111, 1001, 2) ON DUPLICATE KEY UPDATE state = 2")
count, err := d.UpActivityStateCount(c, id, states)
ctx.Convey("Then err should be nil.count should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(count, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoListUpActivity(t *testing.T) {
convey.Convey("ListUpActivity", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(111)
from = int(0)
limit = int(10)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
ups, err := d.ListUpActivity(c, id, from, limit)
ctx.Convey("Then err should be nil.ups should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(ups, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoListUpActivitySuccess(t *testing.T) {
convey.Convey("ListUpActivitySuccess", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(111)
mid = int64(1001)
from = int(0)
limit = int(10)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
ups, err := d.ListUpActivitySuccess(c, id, mid, from, limit)
ctx.Convey("Then err should be nil.ups should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(ups, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoUpdateUpActivityState(t *testing.T) {
convey.Convey("UpdateUpActivityState", t, func(ctx convey.C) {
var (
c = context.Background()
activityID = int64(111)
mids = []int64{1001}
oldState = int(2)
newState = int(3)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
Exec(c, "INSERT INTO up_activity(activity_id, mid, state) VALUES(111, 1001, 2) ON DUPLICATE KEY UPDATE state = 2")
rows, err := d.UpdateUpActivityState(c, activityID, mids, oldState, newState)
ctx.Convey("Then err should be nil.rows should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rows, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoTxUpdateUpActivityState(t *testing.T) {
convey.Convey("TxUpdateUpActivityState", t, func(ctx convey.C) {
var (
c = context.Background()
tx, _ = d.BeginTran(c)
activityID = int64(111)
mids = []int64{1001}
oldState = int(2)
newState = int(3)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
defer tx.Commit()
Exec(c, "INSERT INTO up_activity(activity_id, mid, state) VALUES(111, 1001, 2) ON DUPLICATE KEY UPDATE state = 2")
rows, err := d.TxUpdateUpActivityState(tx, activityID, mids, oldState, newState)
ctx.Convey("Then err should be nil.rows should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rows, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,290 @@
package dao
import (
"strings"
"time"
"go-common/app/admin/main/growup/model"
"go-common/library/ecode"
xtime "go-common/library/time"
"github.com/jinzhu/gorm"
)
// const for db table name
const (
// table user
TableUser = "authority_user"
// table taskgroup
TableGroup = "authority_task_group"
// table taskrole
TableRole = "authority_task_role"
// table privilege
TablePrivilege = "authority_privilege"
)
func queryAddIsDeleted(query string) string {
if len(query) != 0 {
query += " AND is_deleted = 0"
} else {
query = "is_deleted = 0"
}
return query
}
// GetAuthorityUsersInfo get users info by query
func (d *Dao) GetAuthorityUsersInfo(query, members string) (users []*model.User, err error) {
query = queryAddIsDeleted(query)
err = d.db.Table(TableUser).Select(members).Where(query).Find(&users).Error
return
}
// ListAuthorityUsers find all authority users from db
func (d *Dao) ListAuthorityUsers(query string, from, limit int, sort string) (users []*model.User, total int, err error) {
query = queryAddIsDeleted(query)
err = d.db.Table(TableUser).Where(query).Count(&total).Error
if err != nil {
return
}
if strings.HasPrefix(sort, "-") {
sort = strings.TrimPrefix(sort, "-")
sort = sort + " " + "desc"
}
err = d.db.Table(TableUser).Order(sort).Offset(from).Where(query).Limit(limit).Find(&users).Error
return
}
// AddAuthorityUser add one user to authority-manage
func (d *Dao) AddAuthorityUser(user *model.User) (err error) {
var u model.User
err = d.db.Table(TableUser).Where("username = ?", user.Username).Find(&u).Error
if err == gorm.ErrRecordNotFound {
err = d.db.Table(TableUser).Create(user).Error
return
}
if err != nil {
return
}
if u.IsDeleted == 1 {
update := map[string]interface{}{
"nickname": user.Nickname,
"atime": xtime.Time(time.Now().Unix()),
"is_deleted": 0,
}
err = d.db.Table(TableUser).Where("username = ?", user.Username).Updates(update).Error
} else {
err = ecode.GrowupAuthorityExist
}
return
}
// UpdateAuthorityUser update user to db
func (d *Dao) UpdateAuthorityUser(id int64, update map[string]interface{}) (err error) {
return d.db.Table(TableUser).Where("id = ? AND is_deleted = 0", id).Updates(update).Error
}
// DeleteAuthorityUser modify user's is_delete = 1
func (d *Dao) DeleteAuthorityUser(id int64) (err error) {
update := map[string]interface{}{
"task_group": "",
"task_role": "",
"is_deleted": 1,
}
return d.db.Table(TableUser).Where("id = ? AND is_deleted = 0", id).Updates(update).Error
}
// ListAuthorityTaskGroups find all authority task groups from db
func (d *Dao) ListAuthorityTaskGroups(query string, from, limit int, sort string) (groups []*model.TaskGroup, total int, err error) {
query = queryAddIsDeleted(query)
err = d.db.Table(TableGroup).Where(query).Count(&total).Error
if err != nil {
return
}
if strings.HasPrefix(sort, "-") {
sort = strings.TrimPrefix(sort, "-")
sort = sort + " " + "desc"
}
err = d.db.Table(TableGroup).Order(sort).Offset(from).Where(query).Limit(limit).Find(&groups).Error
return
}
// GetAuthorityTaskGroup get authority task group
func (d *Dao) GetAuthorityTaskGroup(query string) (group model.TaskGroup, err error) {
query = queryAddIsDeleted(query)
err = d.db.Table(TableGroup).Where(query).Find(&group).Error
return
}
// AddAuthorityTaskGroup add new task group
func (d *Dao) AddAuthorityTaskGroup(taskGroup *model.TaskGroup) (err error) {
var group model.TaskGroup
err = d.db.Table(TableGroup).Where("name = ?", taskGroup.Name).Find(&group).Error
if err == gorm.ErrRecordNotFound {
err = d.db.Table(TableGroup).Create(taskGroup).Error
return
}
if err != nil {
return
}
if group.IsDeleted == 1 {
update := map[string]interface{}{
"desc": taskGroup.Desc,
"atime": xtime.Time(time.Now().Unix()),
"is_deleted": 0,
}
err = d.db.Table(TableGroup).Where("name = ?", taskGroup.Name).Updates(update).Error
} else {
return ecode.GrowupAuthorityExist
}
return
}
// UpdateAuthorityTaskGroup update task group info to db
func (d *Dao) UpdateAuthorityTaskGroup(id int64, update map[string]interface{}) (err error) {
return d.db.Table(TableGroup).Where("id = ? AND is_deleted = 0", id).Updates(update).Error
}
// DeleteAuthorityTaskGroup modify task group's is_deleted = 1
func (d *Dao) DeleteAuthorityTaskGroup(id int64) (err error) {
return d.db.Table(TableGroup).Where("id = ? AND is_deleted = 0", id).Updates(map[string]interface{}{"is_deleted": 1}).Error
}
// GetAuthorityTaskGroups get task groups id and name
func (d *Dao) GetAuthorityTaskGroups(query string) (groups []*model.Group, err error) {
query = queryAddIsDeleted(query)
err = d.db.Table(TableGroup).Where(query).Scan(&groups).Error
return
}
// GetAuthorityTaskGroupName get task group name
func (d *Dao) GetAuthorityTaskGroupName(groupID int64) (name string, err error) {
var group model.Group
err = d.db.Table(TableGroup).Where("id = ? AND is_deleted = 0", groupID).Scan(&group).Error
if err != nil {
return
}
name = group.Name
return
}
// GetAuthorityTaskGroupPrivileges get task group privileges
func (d *Dao) GetAuthorityTaskGroupPrivileges(groupID int64) (privileges string, err error) {
var group model.TaskGroup
err = d.db.Table(TableGroup).Where("id = ? AND is_deleted = 0", groupID).Scan(&group).Error
if err != nil {
return
}
privileges = group.Privileges
return
}
// GetAuthorityTaskGroupNames get task group names from ids(not use)
func (d *Dao) GetAuthorityTaskGroupNames(groupIDs []string) (names []string, err error) {
err = d.db.Table(TableGroup).Where("id in (?) AND is_deleted = 0", groupIDs).Pluck("name", &names).Error
return
}
// ListAuthorityTaskRoles find all authority task roles from db
func (d *Dao) ListAuthorityTaskRoles(query string, from, limit int, sort string) (roles []*model.TaskRole, total int, err error) {
query = queryAddIsDeleted(query)
err = d.db.Table(TableRole).Where(query).Count(&total).Error
if err != nil {
return
}
if strings.HasPrefix(sort, "-") {
sort = strings.TrimPrefix(sort, "-")
sort = sort + " " + "desc"
}
err = d.db.Table(TableRole).Order(sort).Offset(from).Where(query).Limit(limit).Find(&roles).Error
return
}
// AddAuthorityTaskRole add task role to db
func (d *Dao) AddAuthorityTaskRole(taskRole *model.TaskRole) (err error) {
var role model.TaskRole
err = d.db.Table(TableRole).Where("name = ?", taskRole.Name).Find(&role).Error
if err == gorm.ErrRecordNotFound {
err = d.db.Table(TableRole).Create(taskRole).Error
return
}
if err != nil {
return
}
if role.IsDeleted == 1 {
update := map[string]interface{}{
"desc": taskRole.Desc,
"group_id": taskRole.GroupID,
"atime": xtime.Time(time.Now().Unix()),
"is_deleted": 0,
}
err = d.db.Table(TableRole).Where("name = ?", taskRole.Name).Updates(update).Error
} else {
err = ecode.GrowupAuthorityExist
}
return
}
// UpdateAuthorityTaskRole update task role to db
func (d *Dao) UpdateAuthorityTaskRole(id int64, update map[string]interface{}) (err error) {
return d.db.Table(TableRole).Where("id = ? AND is_deleted = 0", id).Updates(update).Error
}
// DeleteAuthorityTaskRole modify task role's is_deleted = 1
func (d *Dao) DeleteAuthorityTaskRole(id int64) (err error) {
return d.db.Table(TableRole).Where("id = ? AND is_deleted = 0", id).Updates(map[string]interface{}{"is_deleted": 1}).Error
}
// GetAuthorityTaskRoles get task roles id and name
func (d *Dao) GetAuthorityTaskRoles(query string) (roles []*model.Role, err error) {
query = queryAddIsDeleted(query)
err = d.db.Table(TableRole).Where(query).Scan(&roles).Error
return
}
// GetAuthorityTaskRolePrivileges get task role's privileges
func (d *Dao) GetAuthorityTaskRolePrivileges(roleID int64) (privileges string, err error) {
var role model.TaskRole
err = d.db.Table(TableRole).Where("id = ? AND is_deleted = 0", roleID).Scan(&role).Error
if err != nil {
return
}
privileges = role.Privileges
return
}
// AddPrivilege add privilege to db
func (d *Dao) AddPrivilege(privilege *model.Privilege) (err error) {
var p model.Privilege
err = d.db.Table(TablePrivilege).Where("name = ?", privilege.Name).Find(&p).Error
if err == gorm.ErrRecordNotFound {
err = d.db.Table(TablePrivilege).Create(privilege).Error
return
}
if err != nil {
return
}
if p.IsDeleted == 1 {
update := map[string]interface{}{
"name": privilege.Name,
"level": privilege.Level,
"father_id": privilege.FatherID,
"is_deleted": 0,
}
err = d.db.Table(TablePrivilege).Where("name = ?", privilege.Name).Updates(update).Error
} else {
err = ecode.GrowupAuthorityExist
}
return
}
// UpdatePrivilege update privilege to db
func (d *Dao) UpdatePrivilege(id int64, update map[string]interface{}) (err error) {
return d.db.Table(TablePrivilege).Where("id = ? AND is_deleted = 0", id).Updates(update).Error
}
// GetLevelPrivileges get sprivileges by query
func (d *Dao) GetLevelPrivileges(query string) (p []*model.SPrivilege, err error) {
query = queryAddIsDeleted(query)
err = d.db.Table(TablePrivilege).Select("id, name, level, is_router").Where(query).Scan(&p).Error
return
}

View File

@@ -0,0 +1,265 @@
package dao
import (
"context"
"testing"
"time"
"go-common/app/admin/main/growup/model"
xtime "go-common/library/time"
. "github.com/smartystreets/goconvey/convey"
)
func TestDao_AddAuthorityTaskGroup(t *testing.T) {
Convey("", t, func() {
now := xtime.Time(time.Now().Unix())
user := &model.SUser{
Name: "admin",
}
sUser := []*model.SUser{user}
group := &model.TaskGroup{
Name: "test-dao",
Desc: "test",
Privileges: "test",
ATime: now,
Users: sUser,
IsDeleted: 0,
}
Exec(context.Background(), "DELETE FROM authority_task_group WHERE name = 'test-dao'")
err := d.AddAuthorityTaskGroup(group)
So(err, ShouldBeNil)
group.Desc = "test1"
Exec(context.Background(), "UPDATE authority_task_group SET is_deleted = 1 WHERE name = 'test-dao'")
err = d.AddAuthorityTaskGroup(group)
So(err, ShouldBeNil)
})
}
func TestDao_AddAuthorityTaskRole(t *testing.T) {
Convey("", t, func() {
now := xtime.Time(time.Now().Unix())
user := &model.SUser{
Name: "admin",
}
users := []*model.SUser{user}
role := &model.TaskRole{
Name: "test-dao",
Desc: "test",
GroupID: 1,
Privileges: "test",
ATime: now,
GroupName: "test",
Users: users,
}
Exec(context.Background(), "DELETE FROM authority_task_role WHERE name = 'test-dao'")
err := d.AddAuthorityTaskRole(role)
So(err, ShouldBeNil)
Exec(context.Background(), "UPDATE authority_task_role SET is_deleted = 1 WHERE name = 'test-dao'")
role.Desc = "test1"
err = d.AddAuthorityTaskRole(role)
So(err, ShouldBeNil)
})
}
func TestDao_AddAuthorityUser(t *testing.T) {
Convey("", t, func() {
now := xtime.Time(time.Now().Unix())
group := &model.Group{
Name: "TEST_GROUP",
}
role := &model.Role{
Name: "test_role",
}
user := &model.User{
Username: "test-dao",
Nickname: "test",
TaskGroup: "test",
TaskRole: "test",
ATime: now,
IsDeleted: 0,
Groups: []*model.Group{group},
Roles: []*model.Role{role},
}
Exec(context.Background(), "DELETE FROM authority_user WHERE username = 'test-dao'")
err := d.AddAuthorityUser(user)
So(err, ShouldBeNil)
Exec(context.Background(), "UPDATE authority_user SET is_deleted = 1 WHERE username = 'test-dao'")
user.Nickname = "test1"
err = d.AddAuthorityUser(user)
So(err, ShouldBeNil)
})
}
func TestDao_AddPrivilege(t *testing.T) {
Convey("", t, func() {
privilege := &model.Privilege{
Name: "test-dao",
Level: 1,
FatherID: 2,
IsRouter: 1,
IsDeleted: 0,
}
Exec(context.Background(), "DELETE FROM authority_privilege WHERE name = 'test-dao'")
err := d.AddPrivilege(privilege)
So(err, ShouldBeNil)
Exec(context.Background(), "UPDATE authority_privilege SET is_deleted = 1 WHERE name = 'test-dao'")
privilege.IsRouter = 0
err = d.AddPrivilege(privilege)
So(err, ShouldBeNil)
})
}
func TestDao_DeleteAuthorityTaskGroup(t *testing.T) {
Convey("", t, func() {
Exec(context.Background(), "INSERT INTO authority_task_group(id) VALUES(9999)")
err := d.DeleteAuthorityTaskGroup(9999)
So(err, ShouldBeNil)
})
}
func TestDao_DeleteAuthorityTaskRole(t *testing.T) {
Convey("", t, func() {
Exec(context.Background(), "INSERT INTO authority_task_role(id) VALUES(9999)")
err := d.DeleteAuthorityTaskRole(9999)
So(err, ShouldBeNil)
})
}
func TestDao_DeleteAuthorityUser(t *testing.T) {
Convey("", t, func() {
Exec(context.Background(), "INSERT INTO authority_user(id) VALUES(9999)")
err := d.DeleteAuthorityUser(1)
So(err, ShouldBeNil)
})
}
func TestDao_GetAuthorityTaskGroupName(t *testing.T) {
Convey("", t, func() {
Exec(context.Background(), "UPDATE authority_task_group SET is_deleted = 0 WHERE id = 1")
_, err := d.GetAuthorityTaskGroupName(1)
So(err, ShouldBeNil)
})
}
func TestDao_GetAuthorityTaskGroupNames(t *testing.T) {
Convey("", t, func() {
_, err := d.GetAuthorityTaskGroupNames([]string{"1"})
So(err, ShouldBeNil)
})
}
func TestDao_GetAuthorityTaskGroup(t *testing.T) {
Convey("", t, func() {
_, err := d.GetAuthorityTaskGroup("id > 0")
So(err, ShouldBeNil)
})
}
func TestDao_GetAuthorityTaskGroupPrivileges(t *testing.T) {
Convey("", t, func() {
Exec(context.Background(), "insert into authority_task_group(id,name,privileges) values(1001, '12131','1,2,3,4,5,6,7')")
_, err := d.GetAuthorityTaskGroupPrivileges(1001)
So(err, ShouldBeNil)
})
}
func TestDao_GetAuthorityTaskGroups(t *testing.T) {
Convey("", t, func() {
_, err := d.GetAuthorityTaskGroups("")
So(err, ShouldBeNil)
})
}
func TestDao_GetAuthorityTaskRolePrivileges(t *testing.T) {
Convey("", t, func() {
Exec(context.Background(), "insert into authority_task_role(id,name,group_id,privileges) values(1000, '12312',1001, '1,2,3,4,5,6,7')")
_, err := d.GetAuthorityTaskRolePrivileges(1000)
So(err, ShouldBeNil)
})
}
func TestDao_GetAuthorityTaskRoles(t *testing.T) {
Convey("", t, func() {
_, err := d.GetAuthorityTaskRoles("")
So(err, ShouldBeNil)
})
}
func TestDao_GetAuthorityUsersInfo(t *testing.T) {
Convey("", t, func() {
_, err := d.GetAuthorityUsersInfo("", "id")
So(err, ShouldBeNil)
})
}
func TestDao_GetLevelPrivileges(t *testing.T) {
Convey("", t, func() {
_, err := d.GetLevelPrivileges("")
So(err, ShouldBeNil)
})
}
func TestDao_ListAuthorityTaskGroups(t *testing.T) {
Convey("", t, func() {
_, _, err := d.ListAuthorityTaskGroups("", 0, 0, "-id")
So(err, ShouldBeNil)
})
}
func TestDao_ListAuthorityTaskRoles(t *testing.T) {
Convey("", t, func() {
_, _, err := d.ListAuthorityTaskRoles("", 0, 0, "-id")
So(err, ShouldBeNil)
})
}
func TestDao_ListAuthorityUsers(t *testing.T) {
Convey("", t, func() {
_, _, err := d.ListAuthorityUsers("", 0, 0, "-id")
So(err, ShouldBeNil)
})
}
func TestDao_UpdateAuthorityTaskGroup(t *testing.T) {
Convey("", t, func() {
updates := map[string]interface{}{
"desc": "test11",
}
Exec(context.Background(), "UPDATE authority_task_group SET desc = 'aaa' WHERE id = 1")
err := d.UpdateAuthorityTaskGroup(1, updates)
So(err, ShouldBeNil)
})
}
func TestDao_UpdateAuthorityTaskRole(t *testing.T) {
Convey("", t, func() {
updates := map[string]interface{}{
"desc": "test",
}
Exec(context.Background(), "UPDATE authority_task_role SET desc = 'aaa' WHERE id = 1")
err := d.UpdateAuthorityTaskRole(1, updates)
So(err, ShouldBeNil)
})
}
func TestDao_UpdateAuthorityUser(t *testing.T) {
Convey("", t, func() {
updates := map[string]interface{}{
"username": "test",
}
err := d.UpdateAuthorityUser(1, updates)
So(err, ShouldBeNil)
})
}
func TestDao_UpdatePrivilege(t *testing.T) {
Convey("", t, func() {
updates := map[string]interface{}{
"name": "test",
}
err := d.UpdatePrivilege(1, updates)
So(err, ShouldBeNil)
})
}

View File

@@ -0,0 +1,108 @@
package dao
import (
"context"
"database/sql"
"go-common/app/admin/main/growup/model"
"go-common/library/log"
"go-common/library/time"
)
const (
_insertBannerSQL = "INSERT INTO banner(image,link,start_at,end_at) VALUES(?,?,?,?)"
_bannersSQL = "SELECT id,image,link,start_at,end_at FROM banner WHERE id > ? ORDER BY id LIMIT ?"
_totalBannerCountSQL = "SELECT count(*) FROM banner"
// start_at > end_at(insert) or end_at < start_at(insert)
_bannerSQL = "SELECT id FROM banner WHERE end_at > ? AND NOT ((start_at > ?) OR (end_at < ?))"
_editBannerSQL = "SELECT id FROM banner WHERE id != ? AND end_at > ? AND NOT ((start_at > ?) OR (end_at < ?))"
_updateBannerSQL = "UPDATE banner SET image=?,link=?,start_at=?,end_at=? WHERE id=?"
_updateEndAtSQL = "UPDATE banner SET end_at=? WHERE id=?"
)
// TotalBannerCount get total banner count
func (d *Dao) TotalBannerCount(c context.Context) (count int64, err error) {
row := d.rddb.QueryRow(c, _totalBannerCountSQL)
if err = row.Scan(&count); err != nil {
log.Error("d.rddb.TotalBannerCount error(%v)", err)
}
return
}
// DupEditBanner find duplicate banner id where end_at >= start_at(edit)
func (d *Dao) DupEditBanner(c context.Context, startAt, endAt, now, id int64) (dup int64, err error) {
row := d.rddb.QueryRow(c, _editBannerSQL, id, time.Time(now), time.Time(endAt), time.Time(startAt))
if err = row.Scan(&dup); err != nil {
if err == sql.ErrNoRows {
err = nil
} else {
log.Error("d.rddb.DupEditBanner error(%v)", err)
}
}
return
}
// DupBanner find duplicate banner id that end_at > start_at(insert)
func (d *Dao) DupBanner(c context.Context, startAt, endAt, now int64) (dup int64, err error) {
row := d.rddb.QueryRow(c, _bannerSQL, time.Time(now), time.Time(endAt), time.Time(startAt))
if err = row.Scan(&dup); err != nil {
if err == sql.ErrNoRows {
err = nil
} else {
log.Error("d.rddb.DupBanner error(%v)", err)
}
}
return
}
// InsertBanner insert banner
func (d *Dao) InsertBanner(c context.Context, image, link string, startAt, endAt int64) (rows int64, err error) {
res, err := d.rddb.Exec(c, _insertBannerSQL, image, link, time.Time(startAt), time.Time(endAt))
if err != nil {
log.Error("d.db.Exec insert banner error(%v)", err)
return
}
return res.RowsAffected()
}
// Banners get banners
func (d *Dao) Banners(c context.Context, offset, limit int64) (bs []*model.Banner, err error) {
rows, err := d.rddb.Query(c, _bannersSQL, offset, limit)
if err != nil {
log.Error("d.db.query banners error(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
b := &model.Banner{}
err = rows.Scan(&b.ID, &b.Image, &b.Link, &b.StartAt, &b.EndAt)
if err != nil {
log.Error("rows scan error(%v)", err)
return
}
bs = append(bs, b)
}
return
}
// UpdateBanner update banner
func (d *Dao) UpdateBanner(c context.Context, image, link string, startAt, endAt, id int64) (rows int64, err error) {
res, err := d.rddb.Exec(c, _updateBannerSQL, image, link, time.Time(startAt), time.Time(endAt), id)
if err != nil {
log.Error("d.db.Exec update banner error(%v)", err)
return
}
return res.RowsAffected()
}
// UpdateBannerEndAt update banner end at
func (d *Dao) UpdateBannerEndAt(c context.Context, endAt, id int64) (rows int64, err error) {
res, err := d.rddb.Exec(c, _updateEndAtSQL, time.Time(endAt), id)
if err != nil {
log.Error("d.db.Exec update banner end_at error(%v)", err)
return
}
return res.RowsAffected()
}

View File

@@ -0,0 +1,132 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoTotalBannerCount(t *testing.T) {
convey.Convey("TotalBannerCount", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
count, err := d.TotalBannerCount(c)
ctx.Convey("Then err should be nil.count should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(count, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoDupEditBanner(t *testing.T) {
convey.Convey("DupEditBanner", t, func(ctx convey.C) {
var (
c = context.Background()
startAt = int64(0)
endAt = int64(0)
now = int64(0)
id = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
dup, err := d.DupEditBanner(c, startAt, endAt, now, id)
ctx.Convey("Then err should be nil.dup should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(dup, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoDupBanner(t *testing.T) {
convey.Convey("DupBanner", t, func(ctx convey.C) {
var (
c = context.Background()
startAt = int64(0)
endAt = int64(0)
now = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
dup, err := d.DupBanner(c, startAt, endAt, now)
ctx.Convey("Then err should be nil.dup should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(dup, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoInsertBanner(t *testing.T) {
convey.Convey("InsertBanner", t, func(ctx convey.C) {
var (
c = context.Background()
image = ""
link = ""
startAt = int64(0)
endAt = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
rows, err := d.InsertBanner(c, image, link, startAt, endAt)
ctx.Convey("Then err should be nil.rows should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rows, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoBanners(t *testing.T) {
convey.Convey("Banners", t, func(ctx convey.C) {
var (
c = context.Background()
offset = int64(0)
limit = int64(10)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
_, err := d.Banners(c, offset, limit)
ctx.Convey("Then err should be nil.bs should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoUpdateBanner(t *testing.T) {
convey.Convey("UpdateBanner", t, func(ctx convey.C) {
var (
c = context.Background()
image = ""
link = ""
startAt = int64(0)
endAt = int64(0)
id = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
rows, err := d.UpdateBanner(c, image, link, startAt, endAt, id)
ctx.Convey("Then err should be nil.rows should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rows, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoUpdateBannerEndAt(t *testing.T) {
convey.Convey("UpdateBannerEndAt", t, func(ctx convey.C) {
var (
c = context.Background()
endAt = int64(0)
id = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
rows, err := d.UpdateBannerEndAt(c, endAt, id)
ctx.Convey("Then err should be nil.rows should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rows, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,32 @@
package dao
import (
"strings"
"go-common/app/admin/main/growup/model"
)
// ListBlacklist find blacklist by query
func (d *Dao) ListBlacklist(query string, from, limit int, sort string) (list []*model.Blacklist, total int, err error) {
err = d.db.Table("av_black_list").Where(query).Count(&total).Error
if err != nil {
return
}
if strings.HasPrefix(sort, "-") {
sort = strings.TrimPrefix(sort, "-")
sort = sort + " " + "desc"
}
err = d.db.Table("av_black_list").Order(sort).Offset(from).Where(query).Limit(limit).Find(&list).Error
return
}
// GetAvIncomeStatis get av total income
func (d *Dao) GetAvIncomeStatis(query string) (avIncome []*model.AvIncomeStatis, err error) {
err = d.db.Table("av_income_statis").Where(query).Find(&avIncome).Error
return
}
// UpdateBlacklist update blacklist
func (d *Dao) UpdateBlacklist(avID int64, ctype int, update map[string]interface{}) (err error) {
return d.db.Table("av_black_list").Where("av_id = ? AND ctype = ? AND is_delete = 0", avID, ctype).Updates(update).Error
}

View File

@@ -0,0 +1,63 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoListBlacklist(t *testing.T) {
convey.Convey("ListBlacklist", t, func(ctx convey.C) {
var (
query = "id > 0"
from = int(0)
limit = int(0)
sort = "-id"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
Exec(context.Background(), "INSERT INTO av_black_list(av_id, mid, ctype) VALUES(1993, 1001, 0)")
list, total, err := d.ListBlacklist(query, from, limit, sort)
ctx.Convey("Then err should be nil.list,total should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(total, convey.ShouldNotBeNil)
ctx.So(list, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoGetAvIncomeStatis(t *testing.T) {
convey.Convey("GetAvIncomeStatis", t, func(ctx convey.C) {
var (
query = "id > 0"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
Exec(context.Background(), "INSERT INTO av_income_statis(av_id, total_income) VALUE(1000, 100)")
avIncome, err := d.GetAvIncomeStatis(query)
ctx.Convey("Then err should be nil.avIncome should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(avIncome, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoUpdateBlacklist(t *testing.T) {
convey.Convey("UpdateBlacklist", t, func(ctx convey.C) {
var (
avID = int64(1993)
ctype = int(0)
update = make(map[string]interface{})
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
Exec(context.Background(), "DELETE FROM av_black_list WHERE av_id = 1993")
Exec(context.Background(), "INSERT INTO av_black_list(av_id, mid, ctype) VALUES(1993, 1001, 0) ON DUPLICATE KEY UPDATE ctype = 0")
update["ctype"] = 1
err := d.UpdateBlacklist(avID, ctype, update)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}

View File

@@ -0,0 +1,107 @@
package dao
import (
"context"
"database/sql"
"fmt"
"go-common/app/admin/main/growup/model"
"go-common/library/log"
xtime "go-common/library/time"
)
const (
// insert
_inBlockedSQL = "INSERT INTO up_blocked (mid,nickname,original_archive_count,category_id,fans,apply_at,is_deleted) VALUES (?,?,?,?,?,?,0) ON DUPLICATE KEY UPDATE mid=?,nickname=?,original_archive_count=?,category_id=?,fans=?,apply_at=?,is_deleted=0"
// select
_upInfoVideoSQL = "SELECT apply_at FROM up_info_video WHERE mid=?"
_blockedCountSQL = "SELECT count(*) FROM up_blocked WHERE %s"
_blockedSQL = "SELECT mid,nickname,original_archive_count,category_id,fans,apply_at FROM up_blocked WHERE %s"
_isBlockedSQL = "SELECT mid FROM up_blocked WHERE mid=? AND is_deleted=0"
// update
_upBlockedStateSQL = "UPDATE up_blocked SET is_deleted=? WHERE mid=?"
)
// ApplyAt query apply_at from up_info_video by mid
func (d *Dao) ApplyAt(c context.Context, mid int64) (applyAt xtime.Time, err error) {
row := d.rddb.QueryRow(c, _upInfoVideoSQL, mid)
if err = row.Scan(&applyAt); err != nil {
if err == sql.ErrNoRows {
err = nil
} else {
log.Error("row.Scan error(%v)", err)
}
}
return
}
// InsertBlocked insert block up to blacklist
func (d *Dao) InsertBlocked(c context.Context, v *model.Blocked) (rows int64, err error) {
res, err := d.rddb.Exec(c, _inBlockedSQL, v.MID, v.Nickname, v.OriginalArchiveCount, v.MainCategory, v.Fans, v.ApplyAt, v.MID, v.Nickname, v.OriginalArchiveCount, v.MainCategory, v.Fans, v.ApplyAt)
if err != nil {
log.Error("db.inBlockedStmt.Exec(%s) error(%v)", _inBlockedSQL, err)
return
}
return res.RowsAffected()
}
// UpdateBlockedState update blocked is_deleted
func (d *Dao) UpdateBlockedState(c context.Context, mid int64, del int) (rows int64, err error) {
res, err := d.rddb.Exec(c, _upBlockedStateSQL, del, mid)
if err != nil {
log.Error("db.upBlockedState.Exec(%s) error(%v)", _upBlockedStateSQL, err)
return
}
return res.RowsAffected()
}
// DelFromBlocked del blocked
func (d *Dao) DelFromBlocked(c context.Context, mid int64) (rows int64, err error) {
return d.UpdateBlockedState(c, mid, 1)
}
// BlockCount get blocked count
func (d *Dao) BlockCount(c context.Context, query string) (count int, err error) {
row := d.rddb.QueryRow(c, fmt.Sprintf(_blockedCountSQL, query))
if err = row.Scan(&count); err != nil {
if err == sql.ErrNoRows {
err = nil
} else {
log.Error("rows.Scan error(%v)", err)
}
}
return
}
// QueryFromBlocked query blocked user in black list
func (d *Dao) QueryFromBlocked(c context.Context, query string) (ups []*model.Blocked, err error) {
rows, err := d.rddb.Query(c, fmt.Sprintf(_blockedSQL, query))
if err != nil {
return
}
defer rows.Close()
for rows.Next() {
v := &model.Blocked{}
err = rows.Scan(&v.MID, &v.Nickname, &v.OriginalArchiveCount, &v.MainCategory, &v.Fans, &v.ApplyAt)
if err != nil {
log.Error("rows.Scan error(%v)", err)
return
}
ups = append(ups, v)
}
return
}
// Blocked check user is blocked
func (d *Dao) Blocked(c context.Context, mid int64) (id int64, err error) {
row := d.rddb.QueryRow(c, _isBlockedSQL, mid)
if err = row.Scan(&id); err != nil {
if err == sql.ErrNoRows {
err = nil
} else {
log.Error("row Scan error(%v)", err)
}
}
return
}

View File

@@ -0,0 +1,67 @@
package dao
import (
"context"
"testing"
"time"
"go-common/app/admin/main/growup/model"
xtime "go-common/library/time"
. "github.com/smartystreets/goconvey/convey"
)
func Test_BlockSql(t *testing.T) {
Convey("query apply_at from up_info_video by mid", t, WithMysql(func(d *Dao) {
mid := int64(1011)
_, err := d.ApplyAt(context.Background(), mid)
So(err, ShouldBeNil)
}))
Convey("insert block up to blacklist", t, WithMysql(func(d *Dao) {
v := &model.Blocked{MID: int64(1011), Nickname: "hello", OriginalArchiveCount: 10, MainCategory: 1, Fans: 100, ApplyAt: xtime.Time(time.Now().Unix())}
_, err := d.InsertBlocked(context.Background(), v)
So(err, ShouldBeNil)
}))
Convey("update blocked is_deleted", t, WithMysql(func(d *Dao) {
var (
mid int64 = 1011
del = 1
)
_, err := d.UpdateBlockedState(context.Background(), mid, del)
So(err, ShouldBeNil)
}))
Convey("del blocked", t, WithMysql(func(d *Dao) {
var (
mid int64 = 1011
)
_, err := d.DelFromBlocked(context.Background(), mid)
So(err, ShouldBeNil)
}))
Convey("get blocked count", t, WithMysql(func(d *Dao) {
var (
query = "1 = 1"
)
_, err := d.BlockCount(context.Background(), query)
So(err, ShouldBeNil)
}))
Convey("query blocked user in black list", t, WithMysql(func(d *Dao) {
var (
query = "1 = 1"
)
_, err := d.QueryFromBlocked(context.Background(), query)
So(err, ShouldBeNil)
}))
Convey("check user is blocked", t, WithMysql(func(d *Dao) {
var (
mid int64 = 1011
)
_, err := d.Blocked(context.Background(), mid)
So(err, ShouldBeNil)
}))
}

View File

@@ -0,0 +1,215 @@
package dao
import (
"context"
"fmt"
"net/url"
"strconv"
"go-common/library/database/sql"
"go-common/library/log"
"go-common/library/xstr"
"go-common/app/admin/main/growup/model"
)
const (
// select
_upSpySQL = "SELECT mid,signed_at,nickname,fans,cheat_fans,play_count,cheat_play_count,account_state FROM up_spy_statistics %s LIMIT ?, ?"
_avSpySQL = "SELECT archive_id,mid,nickname,upload_time,total_income,cheat_play_count,cheat_favorite,cheat_coin,deducted FROM archive_spy_statistics %s LIMIT ?,?"
// select count(*)
_upSpyCountSQL = "SELECT count(*) FROM up_spy_statistics"
_avSpyCountSQL = "SELECT count(*) FROM archive_spy_statistics %s"
// update
_updateUpState = "UPDATE up_spy_statistics SET account_state=? WHERE mid=?"
_updateAvState = "UPDATE archive_spy_statistics SET deducted=? WHERE archive_id IN (%s)"
// cheat fans
_cheatFansSQL = "SELECT mid,nickname,real_fans,cheat_fans,signed_at,deduct_at FROM cheat_fans_info WHERE is_deleted = 0 LIMIT ?,?"
_cheatFansCountSQL = "SELECT count(*) FROM cheat_fans_info WHERE is_deleted = 0"
_delCheatUpSQL = "UPDATE cheat_fans_info SET is_deleted = 1 WHERE mid = ?"
_insertCheatFansSQL = "INSERT INTO cheat_fans_info(mid, nickname, signed_at, real_fans, cheat_fans, deduct_at) VALUES %s ON DUPLICATE KEY UPDATE mid = values(mid), nickname = values(nickname), signed_at = values(signed_at), real_fans = values(real_fans), cheat_fans = values(cheat_fans), deduct_at = values(deduct_at), is_deleted = 0"
)
// TxUpdateUpSpyState tx update up_spy_state
func (d *Dao) TxUpdateUpSpyState(tx *sql.Tx, state int, mid int64) (rows int64, err error) {
res, err := tx.Exec(_updateUpState, state, mid)
if err != nil {
log.Error("d.db.TxUpdateUpSpyState error(%v)", err)
return
}
return res.RowsAffected()
}
// TxUpdateAvSpyState tx update av_spy_state
func (d *Dao) TxUpdateAvSpyState(tx *sql.Tx, state int, archives []int64) (rows int64, err error) {
if len(archives) == 0 {
return
}
res, err := tx.Exec(fmt.Sprintf(_updateAvState, xstr.JoinInts(archives)), state)
if err != nil {
log.Error("d.db.TxUpdateAvSpyState error(%v)", err)
return
}
return res.RowsAffected()
}
// UpSpyCount get up spy count
func (d *Dao) UpSpyCount(c context.Context) (count int, err error) {
row := d.rddb.QueryRow(c, _upSpyCountSQL)
if err = row.Scan(&count); err != nil {
log.Error("d.rddb.UpSpyCount error(%v)", err)
}
return
}
// UpSpies get up spy.
func (d *Dao) UpSpies(c context.Context, query string, offset, limit int) (spies []*model.UpSpy, err error) {
rows, err := d.rddb.Query(c, fmt.Sprintf(_upSpySQL, query), offset, limit)
if err != nil {
log.Error("d.db.Query UpSpies error(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
spy := &model.UpSpy{}
if err = rows.Scan(&spy.MID, &spy.SignedAt, &spy.Nickname, &spy.Fans, &spy.CheatFans, &spy.PlayCount, &spy.CheatPlayCount, &spy.AccountState); err != nil {
log.Error("dao.UpSpies scan error(%v)", err)
return
}
spies = append(spies, spy)
}
return
}
// ArchiveSpyCount get archive count
func (d *Dao) ArchiveSpyCount(c context.Context, query string) (count int, err error) {
row := d.rddb.QueryRow(c, fmt.Sprintf(_avSpyCountSQL, query))
if err = row.Scan(&count); err != nil {
log.Error("dao.GetArchiveSpy count error(%v)", err)
}
return
}
// ArchiveSpies get av spy.
func (d *Dao) ArchiveSpies(c context.Context, query string, offset, limit int) (spies []*model.ArchiveSpy, err error) {
rows, err := d.rddb.Query(c, fmt.Sprintf(_avSpySQL, query), offset, limit)
if err != nil {
log.Error("dao.GetArchiveSpy query error(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
spy := &model.ArchiveSpy{}
if err = rows.Scan(&spy.ArchiveID, &spy.MID, &spy.Nickname, &spy.UploadTime, &spy.TotalIncome, &spy.CheatPlayCount, &spy.CheatFavorite, &spy.CheatCoin, &spy.Deducted); err != nil {
log.Error("dao.GetArchiveSpy scan error(%v)", err)
return
}
spies = append(spies, spy)
}
return
}
// CheatFansCount get cheat fans count.
func (d *Dao) CheatFansCount(c context.Context) (count int64, err error) {
row := d.rddb.QueryRow(c, _cheatFansCountSQL)
if err = row.Scan(&count); err != nil {
log.Error("dao.CheatFansInfo count error(%v)", err)
}
return
}
// CheatFans get cheat fans info.
func (d *Dao) CheatFans(c context.Context, from, limit int64) (fans []*model.CheatFans, err error) {
rows, err := d.rddb.Query(c, _cheatFansSQL, from, limit)
if err != nil {
log.Error("dao.CheatFansInfo query error(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
fan := &model.CheatFans{}
if err = rows.Scan(&fan.MID, &fan.Nickname, &fan.RealFans, &fan.CheatFans, &fan.SignedAt, &fan.DeductAt); err != nil {
log.Error("dao.CheatFansInfo scan error(%v)", err)
return
}
fans = append(fans, fan)
}
err = rows.Err()
return
}
// DelCheatUp update cheat_fans_info.
func (d *Dao) DelCheatUp(c context.Context, mid int64) (rows int64, err error) {
res, err := d.rddb.Exec(c, _delCheatUpSQL, mid)
if err != nil {
log.Error("dao.UpdateCheatFans error(%v)", err)
return
}
return res.RowsAffected()
}
// InsertCheatFansInfo insert into cheat_fans_info.
func (d *Dao) InsertCheatFansInfo(c context.Context, values string) (rows int64, err error) {
res, err := d.rddb.Exec(c, fmt.Sprintf(_insertCheatFansSQL, values))
if err != nil {
log.Error("dao.InsertCheatFansInfo error(%v)", err)
return
}
return res.RowsAffected()
}
const (
_realFansCount = "/x/internal/relation/stat"
_cheatFansCount = "/x/internal/v1/spy/stat"
)
// GetUpRealFansCount get up real fans count
func (d *Dao) GetUpRealFansCount(c context.Context, host string, mid int64) (count int, err error) {
params := url.Values{}
params.Set("mid", strconv.FormatInt(mid, 10))
var res struct {
Code int `json:"code"`
Data struct {
FansCount int `json:"follower"`
} `json:"data"`
}
if err = d.client.Get(c, host+_realFansCount, "", params, &res); err != nil {
log.Error("dao.GetUpRealFansCount get cheat count error(%v)", err)
return
}
if res.Code != 0 {
err = fmt.Errorf("get real fans count error code: %d", res.Code)
return
}
count = res.Data.FansCount
return
}
// GetUpCheatFansCount get up cheat fan count.
func (d *Dao) GetUpCheatFansCount(c context.Context, host string, mid int64) (count int, err error) {
params := url.Values{}
params.Set("mid", strconv.FormatInt(mid, 10))
var res struct {
Code int `json:"code"`
Data []*model.CheatCount `json:"data"`
}
if err = d.client.Get(c, host+_cheatFansCount, "", params, &res); err != nil {
log.Error("dao.GetUpCheatFansCount get cheat count error(%v)", err)
return
}
if res.Code != 0 {
log.Error("growup-job GetUpCheatFansCount code != 0. res.Code(%d) | params(%s) error(%v)", res.Code, params.Encode(), err)
err = fmt.Errorf("get cheat fans count error code: %d", res.Code)
return
}
for _, v := range res.Data {
if v.EventID == "异常粉丝量" {
count = v.Quantity
}
}
return
}

View File

@@ -0,0 +1,209 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoTxUpdateUpSpyState(t *testing.T) {
convey.Convey("TxUpdateUpSpyState", t, func(ctx convey.C) {
var (
tx, _ = d.BeginTran(context.Background())
state = int(3)
mid = int64(1001)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
defer tx.Commit()
d.Exec(context.Background(), "INSERT INTO up_spy_statistics(mid, account_state) VALUES(1001, 4) ON DUPLICATE KEY UPDATE account_state = 4")
rows, err := d.TxUpdateUpSpyState(tx, state, mid)
ctx.Convey("Then err should be nil.rows should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rows, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoTxUpdateAvSpyState(t *testing.T) {
convey.Convey("TxUpdateAvSpyState", t, func(ctx convey.C) {
var (
tx, _ = d.BeginTran(context.Background())
state = int(5)
archives = []int64{1000}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
defer tx.Commit()
d.Exec(context.Background(), "INSERT INTO archive_spy_statistics(archive_id, deducted) VALUES(1000, 5)")
rows, err := d.TxUpdateAvSpyState(tx, state, archives)
ctx.Convey("Then err should be nil.rows should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rows, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoUpSpyCount(t *testing.T) {
convey.Convey("UpSpyCount", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
count, err := d.UpSpyCount(c)
ctx.Convey("Then err should be nil.count should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(count, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoUpSpies(t *testing.T) {
convey.Convey("UpSpies", t, func(ctx convey.C) {
var (
c = context.Background()
query = "WHERE"
offset = int(0)
limit = int(10)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
_, err := d.UpSpies(c, query, offset, limit)
ctx.Convey("Then err should be nil.spies should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoArchiveSpyCount(t *testing.T) {
convey.Convey("ArchiveSpyCount", t, func(ctx convey.C) {
var (
c = context.Background()
query = ""
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
count, err := d.ArchiveSpyCount(c, query)
ctx.Convey("Then err should be nil.count should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(count, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoArchiveSpies(t *testing.T) {
convey.Convey("ArchiveSpies", t, func(ctx convey.C) {
var (
c = context.Background()
query = ""
offset = int(0)
limit = int(10)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
spies, err := d.ArchiveSpies(c, query, offset, limit)
ctx.Convey("Then err should be nil.spies should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(spies, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoCheatFansCount(t *testing.T) {
convey.Convey("CheatFansCount", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
count, err := d.CheatFansCount(c)
ctx.Convey("Then err should be nil.count should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(count, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoCheatFans(t *testing.T) {
convey.Convey("CheatFans", t, func(ctx convey.C) {
var (
c = context.Background()
from = int64(0)
limit = int64(100)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
fans, err := d.CheatFans(c, from, limit)
ctx.Convey("Then err should be nil.fans should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(fans, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoDelCheatUp(t *testing.T) {
convey.Convey("DelCheatUp", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(1000)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
d.Exec(c, "INSERT INTO cheat_fans_info(mid, is_deleted) values(1000, 0) ON DUPLICATE KEY UPDATE is_deleted = 0")
rows, err := d.DelCheatUp(c, mid)
ctx.Convey("Then err should be nil.rows should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rows, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoInsertCheatFansInfo(t *testing.T) {
convey.Convey("InsertCheatFansInfo", t, func(ctx convey.C) {
var (
c = context.Background()
values = "(123, 'tt', '2018-09-01', 100, 100, '2018-09-01')"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
rows, err := d.InsertCheatFansInfo(c, values)
ctx.Convey("Then err should be nil.rows should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rows, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoGetUpRealFansCount(t *testing.T) {
convey.Convey("GetUpRealFansCount", t, func(ctx convey.C) {
var (
c = context.Background()
host = ""
mid = int64(100)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
_, err := d.GetUpRealFansCount(c, host, mid)
ctx.Convey("Then err should be nil.count should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoGetUpCheatFansCount(t *testing.T) {
convey.Convey("GetUpCheatFansCount", t, func(ctx convey.C) {
var (
c = context.Background()
host = ""
mid = int64(100)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
_, err := d.GetUpCheatFansCount(c, host, mid)
ctx.Convey("Then err should be nil.count should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,152 @@
package dao
import (
"context"
"fmt"
"go-common/app/admin/main/growup/model"
"go-common/library/database/sql"
"go-common/library/log"
"go-common/library/xstr"
)
const (
// credit score record
_inCreditRecordSQL = "INSERT INTO credit_score_record (mid,operate_at,operator,reason,deducted,remaining) VALUES(?,?,?,?,?,?)"
_creditRecordsSQL = "SELECT id,mid,operate_at,operator,reason,deducted,remaining,is_deleted FROM credit_score_record WHERE mid=?"
_creditRecordSQL = "SELECT deducted FROM credit_score_record WHERE id=? AND is_deleted=0"
// credit score
_inCreditScoreSQL = "INSERT INTO credit_score (mid) VALUES %s ON DUPLICATE KEY UPDATE mid=VALUES(mid)"
_creditScoreSQL = "SELECT score FROM credit_score WHERE mid=?"
_creditScoresSQL = "SELECT mid,score FROM credit_score WHERE mid IN (%s)"
// update credit score
_upCreditScoreSQL = "UPDATE credit_score SET score=? WHERE mid=?"
_reCreditScoreSQL = "UPDATE credit_score SET score=score+%d WHERE mid=?"
)
// InsertCreditRecord insert credit record
func (d *Dao) InsertCreditRecord(c context.Context, cr *model.CreditRecord) (rows int64, err error) {
res, err := d.rddb.Exec(c, _inCreditRecordSQL, cr.MID, cr.OperateAt, cr.Operator, cr.Reason, cr.Deducted, cr.Remaining)
if err != nil {
log.Error("db.inCreditRecordSQL.Exec(%s) error(%v)", _inCreditRecordSQL, err)
return
}
return res.RowsAffected()
}
// TxInsertCreditRecord tx insert credit record
func (d *Dao) TxInsertCreditRecord(tx *sql.Tx, cr *model.CreditRecord) (rows int64, err error) {
res, err := tx.Exec(_inCreditRecordSQL, cr.MID, cr.OperateAt, cr.Operator, cr.Reason, cr.Deducted, cr.Remaining)
if err != nil {
log.Error("tx.inCreditRecordSQL.Exec(%s) error(%v)", _inCreditRecordSQL, err)
return
}
return res.RowsAffected()
}
// CreditRecords get credit records by mid
func (d *Dao) CreditRecords(c context.Context, mid int64) (crs []*model.CreditRecord, err error) {
rows, err := d.rddb.Query(c, _creditRecordsSQL, mid)
if err != nil {
return
}
defer rows.Close()
for rows.Next() {
cr := &model.CreditRecord{}
err = rows.Scan(&cr.ID, &cr.MID, &cr.OperateAt, &cr.Operator, &cr.Reason, &cr.Deducted, &cr.Remaining, &cr.IsDeleted)
if err != nil {
log.Error("rows Scan error(%v)", err)
return
}
crs = append(crs, cr)
}
return
}
// DeductedScore get deducted credit score from credit_score_record by id
func (d *Dao) DeductedScore(c context.Context, id int64) (deducted int, err error) {
row := d.rddb.QueryRow(c, _creditRecordSQL, id)
if err = row.Scan(&deducted); err != nil {
if err == sql.ErrNoRows {
err = nil
} else {
log.Error("row.Scan error(%v)", err)
}
}
return
}
// InsertCreditScore insert credit score
func (d *Dao) InsertCreditScore(c context.Context, values string) (rows int64, err error) {
res, err := d.rddb.Exec(c, fmt.Sprintf(_inCreditScoreSQL, values))
if err != nil {
log.Error("db.inCreditScoreSQL.Exec(%s) error(%v)", _inCreditScoreSQL, err)
return
}
return res.RowsAffected()
}
// UpdateCreditScore update credit score
func (d *Dao) UpdateCreditScore(c context.Context, mid int64, score int) (rows int64, err error) {
res, err := d.rddb.Exec(c, _upCreditScoreSQL, score, mid)
if err != nil {
log.Error("db.upCreditScoreSQL.Exec(%s) error(%v)", _inCreditScoreSQL, err)
return
}
return res.RowsAffected()
}
// TxUpdateCreditScore update credit score
func (d *Dao) TxUpdateCreditScore(tx *sql.Tx, mid int64, score int) (rows int64, err error) {
res, err := tx.Exec(_upCreditScoreSQL, score, mid)
if err != nil {
log.Error("tx.upCreditScoreSQL.Exec(%s) error(%v)", _inCreditScoreSQL, err)
return
}
return res.RowsAffected()
}
// CreditScore credit score by mid
func (d *Dao) CreditScore(c context.Context, mid int64) (score int, err error) {
row := d.rddb.QueryRow(c, _creditScoreSQL, mid)
if err = row.Scan(&score); err != nil {
if err == sql.ErrNoRows {
err = nil
} else {
log.Error("row.Scan error(%v)", err)
}
}
return
}
// CreditScores scores map[mid]score
func (d *Dao) CreditScores(c context.Context, mids []int64) (scores map[int64]int, err error) {
scores = make(map[int64]int)
rows, err := d.rddb.Query(c, fmt.Sprintf(_creditScoresSQL, xstr.JoinInts(mids)))
if err != nil {
return
}
defer rows.Close()
for rows.Next() {
var mid int64
var score int
err = rows.Scan(&mid, &score)
if err != nil {
log.Error("rows Scan error(%v)", err)
return
}
scores[mid] = score
}
return
}
// TxRecoverCreditScore recover credit score
func (d *Dao) TxRecoverCreditScore(tx *sql.Tx, deducted int, mid int64) (rows int64, err error) {
res, err := tx.Exec(fmt.Sprintf(_reCreditScoreSQL, deducted), mid)
if err != nil {
return
}
return res.RowsAffected()
}

View File

@@ -0,0 +1,176 @@
package dao
import (
"context"
"go-common/app/admin/main/growup/model"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoInsertCreditRecord(t *testing.T) {
convey.Convey("InsertCreditRecord", t, func(ctx convey.C) {
var (
c = context.Background()
cr = &model.CreditRecord{}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
rows, err := d.InsertCreditRecord(c, cr)
ctx.Convey("Then err should be nil.rows should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rows, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoTxInsertCreditRecord(t *testing.T) {
convey.Convey("TxInsertCreditRecord", t, func(ctx convey.C) {
var (
tx, _ = d.BeginTran(context.Background())
cr = &model.CreditRecord{}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
defer tx.Commit()
rows, err := d.TxInsertCreditRecord(tx, cr)
ctx.Convey("Then err should be nil.rows should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rows, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoCreditRecords(t *testing.T) {
convey.Convey("CreditRecords", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
crs, err := d.CreditRecords(c, mid)
ctx.Convey("Then err should be nil.crs should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(crs, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoDeductedScore(t *testing.T) {
convey.Convey("DeductedScore", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
deducted, err := d.DeductedScore(c, id)
ctx.Convey("Then err should be nil.deducted should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(deducted, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoInsertCreditScore(t *testing.T) {
convey.Convey("InsertCreditScore", t, func(ctx convey.C) {
var (
c = context.Background()
values = "(100)"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
d.Exec(c, "DELETE FROM credit_score WHERE mid = 100")
rows, err := d.InsertCreditScore(c, values)
ctx.Convey("Then err should be nil.rows should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rows, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoUpdateCreditScore(t *testing.T) {
convey.Convey("UpdateCreditScore", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(0)
score = int(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
rows, err := d.UpdateCreditScore(c, mid, score)
ctx.Convey("Then err should be nil.rows should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rows, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoTxUpdateCreditScore(t *testing.T) {
convey.Convey("TxUpdateCreditScore", t, func(ctx convey.C) {
var (
tx, _ = d.BeginTran(context.Background())
mid = int64(0)
score = int(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
defer tx.Commit()
rows, err := d.TxUpdateCreditScore(tx, mid, score)
ctx.Convey("Then err should be nil.rows should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rows, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoCreditScore(t *testing.T) {
convey.Convey("CreditScore", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
score, err := d.CreditScore(c, mid)
ctx.Convey("Then err should be nil.score should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(score, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoCreditScores(t *testing.T) {
convey.Convey("CreditScores", t, func(ctx convey.C) {
var (
c = context.Background()
mids = []int64{1}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
scores, err := d.CreditScores(c, mids)
ctx.Convey("Then err should be nil.scores should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(scores, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoTxRecoverCreditScore(t *testing.T) {
convey.Convey("TxRecoverCreditScore", t, func(ctx convey.C) {
var (
tx, _ = d.BeginTran(context.Background())
deducted = int(0)
mid = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
defer tx.Commit()
rows, err := d.TxRecoverCreditScore(tx, deducted, mid)
ctx.Convey("Then err should be nil.rows should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rows, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,97 @@
package dao
import (
"context"
"go-common/app/admin/main/growup/conf"
"go-common/library/database/orm"
"go-common/library/database/sql"
"go-common/library/log"
httpx "go-common/library/net/http/blademaster"
"github.com/jinzhu/gorm"
)
// Dao dao
type Dao struct {
c *conf.Config
db *gorm.DB
rddb *sql.DB
client *httpx.Client
VideoURL string
ColumnURL string
}
// New fn
func New(c *conf.Config) (d *Dao) {
d = &Dao{
c: c,
db: orm.NewMySQL(c.ORM.Growup),
rddb: sql.NewMySQL(c.ORM.Allowance),
client: httpx.NewClient(c.HTTPClient),
VideoURL: c.Host.VideoType + "/videoup/types",
ColumnURL: c.Host.ColumnType + "/x/article/categories",
}
d.initORM()
return
}
func (d *Dao) initORM() {
d.db.LogMode(true)
}
// Ping check conn of db
func (d *Dao) Ping(c context.Context) (err error) {
if d.db != nil {
err = d.db.DB().PingContext(c)
}
return
}
// Close close conn of db
func (d *Dao) Close() {
if d.db != nil {
d.db.Close()
}
}
// BeginTran begin tran
func (d *Dao) BeginTran(c context.Context) (tx *sql.Tx, err error) {
return d.rddb.Begin(c)
}
// Exec do exec
func (d *Dao) Exec(c context.Context, sql string) (rows int64, err error) {
res, err := d.rddb.Exec(c, sql)
if err != nil {
return
}
return res.RowsAffected()
}
// DoInTx .
func (d *Dao) DoInTx(c context.Context, txFunc func(*sql.Tx) error) (err error) {
tx, err := d.rddb.Begin(c)
if err != nil {
log.Error("d.rddb.Begin err(%v)", err)
return
}
defer func() {
if err != nil {
if err1 := tx.Rollback(); err1 != nil {
log.Error("tx.Rollback err(%v)", err1)
}
return
}
}()
err = txFunc(tx)
if err != nil {
return
}
if err = tx.Commit(); err != nil {
log.Error("tx.Commit err(%v)", err)
}
return
}

View File

@@ -0,0 +1,57 @@
package dao
import (
"context"
"flag"
"os"
"testing"
"go-common/app/admin/main/growup/conf"
. "github.com/smartystreets/goconvey/convey"
)
var (
d *Dao
)
func CleanMysql() {
}
func TestMain(m *testing.M) {
if os.Getenv("DEPLOY_ENV") != "" {
flag.Set("app_id", "mobile.studio.growup-admin")
flag.Set("conf_token", "ac1fd397cbc33eb60541e8734844bdd5")
flag.Set("tree_id", "13583")
flag.Set("conf_version", "docker-1")
flag.Set("deploy_env", "uat")
flag.Set("conf_host", "config.bilibili.co")
flag.Set("conf_path", "/tmp")
flag.Set("region", "sh")
flag.Set("zone", "sh001")
} else {
flag.Set("conf", "../cmd/growup-admin.toml")
}
flag.Parse()
if err := conf.Init(); err != nil {
panic(err)
}
d = New(conf.Conf)
os.Exit(m.Run())
}
func WithMysql(f func(d *Dao)) func() {
return func() {
Reset(func() { CleanMysql() })
f(d)
}
}
// Exec do exec
func Exec(c context.Context, sql string) (rows int64, err error) {
res, err := d.rddb.Exec(c, sql)
if err != nil {
return
}
return res.RowsAffected()
}

View File

@@ -0,0 +1,86 @@
package dao
import (
"context"
"fmt"
"time"
"go-common/app/admin/main/growup/model"
"go-common/library/log"
)
const (
// select
_getAllDayExpenseSQL = "SELECT day_expense, up_count, av_count, up_avg_expense, av_avg_expense, total_expense, date FROM expense_daily_info WHERE date >= ? AND ctype = ? ORDER BY date DESC limit ?,?"
_getAllMonthExpenseSQL = "SELECT month_expense, up_count, av_count, up_avg_expense, av_avg_expense, total_expense, date, month FROM expense_monthly_info WHERE month <= ? AND month >=? AND ctype = ? ORDER BY month DESC LIMIT ?,?"
_getDayTotalExpenseSQL = "SELECT total_expense FROM expense_daily_info WHERE date = ? AND ctype = ?"
_getLatelyExpenseDateSQL = "SELECT date FROM expense_%s_info WHERE ctype = ? ORDER BY date DESC LIMIT 1"
// count(*)
_expenseDayCountSQL = "SELECT count(*) FROM expense_daily_info WHERE date >= ? AND ctype = ?"
_expenseMonthCountSQL = "SELECT count(*) FROM expense_monthly_info WHERE month <= ? AND month >= ? AND ctype = ?"
)
// GetDayExpenseCount get expense_daily_info count
func (d *Dao) GetDayExpenseCount(c context.Context, beginDate time.Time, ctype int) (total int, err error) {
err = d.rddb.QueryRow(c, _expenseDayCountSQL, beginDate, ctype).Scan(&total)
return
}
// GetAllDayExpenseInfo get year all day expense.
func (d *Dao) GetAllDayExpenseInfo(c context.Context, beginDate time.Time, ctype, from, limit int) (infos []*model.BudgetDayStatistics, err error) {
rows, err := d.rddb.Query(c, _getAllDayExpenseSQL, beginDate, ctype, from, limit)
if err != nil {
log.Error("dao.GetAllDayExpenseInfo query error(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
a := &model.BudgetDayStatistics{}
if err = rows.Scan(&a.DayExpense, &a.UpCount, &a.AvCount, &a.UpAvgExpense, &a.AvAvgExpense, &a.TotalExpense, &a.Date); err != nil {
log.Error("dao.GetAllDayExpenseInfo scan error(%v)", err)
return
}
infos = append(infos, a)
}
err = rows.Err()
return
}
// GetDayTotalExpenseInfo get one day total_expense.
func (d *Dao) GetDayTotalExpenseInfo(c context.Context, date time.Time, ctype int) (totalExpense int64, err error) {
err = d.rddb.QueryRow(c, _getDayTotalExpenseSQL, date, ctype).Scan(&totalExpense)
return
}
// GetMonthExpenseCount get expense month count
func (d *Dao) GetMonthExpenseCount(c context.Context, month, beginMonth string, ctype int) (total int, err error) {
err = d.rddb.QueryRow(c, _expenseMonthCountSQL, month, beginMonth, ctype).Scan(&total)
return
}
// GetAllMonthExpenseInfo get all month expense.
func (d *Dao) GetAllMonthExpenseInfo(c context.Context, month, beginMonth string, ctype, from, limit int) (infos []*model.BudgetMonthStatistics, err error) {
rows, err := d.rddb.Query(c, _getAllMonthExpenseSQL, month, beginMonth, ctype, from, limit)
if err != nil {
log.Error("dao.GetAllMonthExpenseInfo query error(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
a := &model.BudgetMonthStatistics{}
if err = rows.Scan(&a.MonthExpense, &a.UpCount, &a.AvCount, &a.UpAvgExpense, &a.AvAvgExpense, &a.TotalExpense, &a.Date, &a.Month); err != nil {
log.Error("dao.GetAllMonthExpenseInfo scan error(%v)", err)
return
}
infos = append(infos, a)
}
err = rows.Err()
return
}
// GetLatelyExpenseDate get lately date.
func (d *Dao) GetLatelyExpenseDate(c context.Context, table string, ctype int) (date time.Time, err error) {
err = d.rddb.QueryRow(c, fmt.Sprintf(_getLatelyExpenseDateSQL, table), ctype).Scan(&date)
return
}

View File

@@ -0,0 +1,118 @@
package dao
import (
"context"
"fmt"
"testing"
"time"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoGetDayExpenseCount(t *testing.T) {
convey.Convey("GetDayExpenseCount", t, func(ctx convey.C) {
var (
c = context.Background()
beginDate = time.Now()
ctype = int(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
total, err := d.GetDayExpenseCount(c, beginDate, ctype)
ctx.Convey("Then err should be nil.total should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(total, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoGetAllDayExpenseInfo(t *testing.T) {
convey.Convey("GetAllDayExpenseInfo", t, func(ctx convey.C) {
var (
c = context.Background()
beginDate, _ = time.ParseInLocation("2018-06-01", "2018-01-01", time.Local)
ctype = int(0)
from = int(0)
limit = int(10)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
Exec(c, "INSERT INTO expense_daily_info(up_acount, date) VALUES(100, '2018-01-01')")
_, err := d.GetAllDayExpenseInfo(c, beginDate, ctype, from, limit)
ctx.Convey("Then err should be nil.infos should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoGetDayTotalExpenseInfo(t *testing.T) {
convey.Convey("GetDayTotalExpenseInfo", t, func(ctx convey.C) {
var (
c = context.Background()
date = time.Date(2018, 9, 1, 0, 0, 0, 0, time.Local)
ctype = int(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
Exec(c, fmt.Sprintf("INSERT INTO expense_daily_info(date, total_expense) VALUES('%s', 100)", date.Format("2006-01-02")))
_, err := d.GetDayTotalExpenseInfo(c, date, ctype)
ctx.Convey("Then err should be nil.totalExpense should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoGetMonthExpenseCount(t *testing.T) {
convey.Convey("GetMonthExpenseCount", t, func(ctx convey.C) {
var (
c = context.Background()
month = "2019-01-01"
beginMonth = "2018-01-01"
ctype = int(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
total, err := d.GetMonthExpenseCount(c, month, beginMonth, ctype)
ctx.Convey("Then err should be nil.total should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(total, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoGetAllMonthExpenseInfo(t *testing.T) {
convey.Convey("GetAllMonthExpenseInfo", t, func(ctx convey.C) {
var (
c = context.Background()
month = "2019-01"
beginMonth = "2018-01"
ctype = int(0)
from = int(0)
limit = int(10)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
Exec(c, fmt.Sprintf("INSERT INTO expense_monthly_info(date, total_expense) VALUES('2018-02', 100)"))
_, err := d.GetAllMonthExpenseInfo(c, month, beginMonth, ctype, from, limit)
ctx.Convey("Then err should be nil.infos should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoGetLatelyExpenseDate(t *testing.T) {
convey.Convey("GetLatelyExpenseDate", t, func(ctx convey.C) {
var (
c = context.Background()
table = "daily"
ctype = int(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
date, err := d.GetLatelyExpenseDate(c, table, ctype)
ctx.Convey("Then err should be nil.date should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(date, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,75 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_test",
"go_library",
)
go_test(
name = "go_default_test",
srcs = [
"av_breach_test.go",
"av_income_test.go",
"bgm_test.go",
"blacklist_test.go",
"charge_test.go",
"dao_test.go",
"lottery_test.go",
"up_account_test.go",
"up_category_info_test.go",
"up_income_test.go",
"up_info_video_test.go",
"up_withdraw_test.go",
],
embed = [":go_default_library"],
rundir = ".",
tags = ["automanaged"],
deps = [
"//app/admin/main/growup/conf:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
],
)
go_library(
name = "go_default_library",
srcs = [
"av_breach.go",
"av_income.go",
"bgm.go",
"blacklist.go",
"charge.go",
"dao.go",
"lottery.go",
"up_account.go",
"up_category_info.go",
"up_income.go",
"up_info_video.go",
"up_withdraw.go",
],
importpath = "go-common/app/admin/main/growup/dao/income",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/admin/main/growup/conf:go_default_library",
"//app/admin/main/growup/model/income:go_default_library",
"//library/database/sql:go_default_library",
"//library/log:go_default_library",
"//library/time:go_default_library",
"//library/xstr: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,105 @@
package income
import (
"context"
"fmt"
model "go-common/app/admin/main/growup/model/income"
"go-common/library/database/sql"
"go-common/library/log"
"go-common/library/xstr"
)
const (
// insert
_inAvBreachSQL = "INSERT INTO av_breach_record(av_id,mid,cdate,money,ctype,reason,upload_time) VALUES %s"
// select
_avBreachByMIDsSQL = "SELECT av_id, mid, cdate, money FROM av_breach_record WHERE mid in (%s) AND ctype in (%s)"
_breachSQL = "SELECT av_id,mid,cdate,money,ctype,reason,upload_time FROM av_breach_record WHERE %s"
_breachCountSQL = "SELECT count(*) FROM av_breach_record WHERE %s"
// update
_upAvBreachPreSQL = "UPDATE av_breach_pre SET state = 2 WHERE aid IN (%s) AND ctype = 0 AND cdate <= '%s'"
)
// BreachCount breach count
func (d *Dao) BreachCount(c context.Context, query string) (total int, err error) {
err = d.db.QueryRow(c, fmt.Sprintf(_breachCountSQL, query)).Scan(&total)
if err == sql.ErrNoRows {
err = nil
}
return
}
// ListArchiveBreach list av_breach_record by query
func (d *Dao) ListArchiveBreach(c context.Context, query string) (breachs []*model.AvBreach, err error) {
breachs = make([]*model.AvBreach, 0)
rows, err := d.db.Query(c, fmt.Sprintf(_breachSQL, query))
if err != nil {
log.Error("ListArchiveBreach d.db.Query error(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
b := &model.AvBreach{}
err = rows.Scan(&b.AvID, &b.MID, &b.CDate, &b.Money, &b.CType, &b.Reason, &b.UploadTime)
if err != nil {
log.Error("ListArchiveBreach rows.Scan error(%v)", err)
return
}
breachs = append(breachs, b)
}
err = rows.Err()
return
}
// TxInsertAvBreach insert av_breach_record
func (d *Dao) TxInsertAvBreach(tx *sql.Tx, val string) (rows int64, err error) {
if val == "" {
return
}
res, err := tx.Exec(fmt.Sprintf(_inAvBreachSQL, val))
if err != nil {
return
}
return res.RowsAffected()
}
// GetAvBreachByMIDs get av_breach_record by mids
func (d *Dao) GetAvBreachByMIDs(c context.Context, mids []int64, types []int64) (breachs []*model.AvBreach, err error) {
if len(mids) == 0 {
return
}
rows, err := d.db.Query(c, fmt.Sprintf(_avBreachByMIDsSQL, xstr.JoinInts(mids), xstr.JoinInts(types)))
if err != nil {
log.Error("GetAvBreachByMIDs d.db.Query error(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
b := &model.AvBreach{}
err = rows.Scan(&b.AvID, &b.MID, &b.CDate, &b.Money)
if err != nil {
log.Error("GetAvBreachByMIDs rows scan error(%v)", err)
return
}
breachs = append(breachs, b)
}
err = rows.Err()
return
}
// TxUpdateBreachPre update av_breach_pre state = 2
func (d *Dao) TxUpdateBreachPre(tx *sql.Tx, aids []int64, cdate string) (rows int64, err error) {
if len(aids) == 0 {
return
}
res, err := tx.Exec(fmt.Sprintf(_upAvBreachPreSQL, xstr.JoinInts(aids), cdate))
if err != nil {
return
}
return res.RowsAffected()
}

View File

@@ -0,0 +1,94 @@
package income
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestIncomeBreachCount(t *testing.T) {
convey.Convey("BreachCount", t, func(ctx convey.C) {
var (
c = context.Background()
query = "id > 0"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
total, err := d.BreachCount(c, query)
ctx.Convey("Then err should be nil.total should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(total, convey.ShouldNotBeNil)
})
})
})
}
func TestIncomeListArchiveBreach(t *testing.T) {
convey.Convey("ListArchiveBreach", t, func(ctx convey.C) {
var (
c = context.Background()
query = "id > 0"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
breachs, err := d.ListArchiveBreach(c, query)
ctx.Convey("Then err should be nil.breachs should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(breachs, convey.ShouldNotBeNil)
})
})
})
}
func TestIncomeTxInsertAvBreach(t *testing.T) {
convey.Convey("TxInsertAvBreach", t, func(ctx convey.C) {
var (
tx, _ = d.BeginTran(context.Background())
val = "(520,1100,'2018-01-01',10,0,'aa','2018-01-01')"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
defer tx.Commit()
Exec(context.Background(), "DELETE FROM av_breach_record WHERE av_id = 520")
rows, err := d.TxInsertAvBreach(tx, val)
ctx.Convey("Then err should be nil.rows should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rows, convey.ShouldNotBeNil)
})
})
})
}
func TestIncomeGetAvBreachByMIDs(t *testing.T) {
convey.Convey("GetAvBreachByMIDs", t, func(ctx convey.C) {
var (
c = context.Background()
mids = []int64{1000}
types = []int64{1}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
Exec(c, "INSERT INTO av_breach_record(mid, ctype) VALUES(1000, 1)")
breachs, err := d.GetAvBreachByMIDs(c, mids, types)
ctx.Convey("Then err should be nil.breachs should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(breachs, convey.ShouldNotBeNil)
})
})
})
}
func TestIncomeTxUpdateBreachPre(t *testing.T) {
convey.Convey("TxUpdateBreachPre", t, func(ctx convey.C) {
var (
tx, _ = d.BeginTran(context.Background())
aids = []int64{1001}
cdate = "2018-06-01"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
defer tx.Commit()
rows, err := d.TxUpdateBreachPre(tx, aids, cdate)
ctx.Convey("Then err should be nil.rows should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rows, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,119 @@
package income
import (
"context"
"fmt"
model "go-common/app/admin/main/growup/model/income"
"go-common/library/log"
)
var (
_video = 0
_column = 2
_bgm = 3
_lottery = 5
)
const (
// select
_avIncomeStatisTableSQL = "SELECT avs,money_section,money_tips,income,category_id,cdate FROM %s WHERE %s LIMIT ?,?"
_avIncomeSQL = "SELECT id,av_id,mid,tag_id,is_original,upload_time,total_income,income,tax_money,date FROM av_income WHERE id > ? AND %s date >= ? AND date <= ? ORDER BY id LIMIT ?"
_columnIncomeSQL = "SELECT id,aid,mid,tag_id,upload_time,total_income,income,tax_money,date FROM column_income WHERE id > ? AND date >= ? AND date <= ? AND %s is_deleted = 0 ORDER BY id LIMIT ?"
)
// GetArchiveStatis get av/column income statis from table and query
func (d *Dao) GetArchiveStatis(c context.Context, table, query string, from, limit int) (avs []*model.ArchiveStatis, err error) {
avs = make([]*model.ArchiveStatis, 0)
if table == "" || query == "" {
return nil, fmt.Errorf("error args table(%s), query(%s)", table, query)
}
rows, err := d.db.Query(c, fmt.Sprintf(_avIncomeStatisTableSQL, table, query), from, limit)
if err != nil {
log.Error("GetArchiveStatis d.db.Query error(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
list := &model.ArchiveStatis{}
err = rows.Scan(&list.Avs, &list.MoneySection, &list.MoneyTips, &list.Income, &list.CategroyID, &list.CDate)
if err != nil {
log.Error("GetArchiveStatis rows scan error(%v)", err)
return
}
avs = append(avs, list)
}
err = rows.Err()
return
}
// GetArchiveIncome get archive income by query
func (d *Dao) GetArchiveIncome(c context.Context, id int64, query string, from, to string, limit int, typ int) (archs []*model.ArchiveIncome, err error) {
switch typ {
case _video:
return d.GetAvIncome(c, id, query, from, to, limit, typ)
case _column:
return d.GetColumnIncome(c, id, query, from, to, limit, typ)
case _bgm:
return d.GetBgmIncome(c, id, query, from, to, limit, typ)
case _lottery:
return d.GetLotteryIncome(c, id, query, from, to, limit, typ)
}
err = fmt.Errorf("get archive type error(%d)", typ)
return
}
// GetAvIncome get av income by query
func (d *Dao) GetAvIncome(c context.Context, id int64, query string, from, to string, limit int, typ int) (avs []*model.ArchiveIncome, err error) {
avs = make([]*model.ArchiveIncome, 0)
if query != "" {
query += " AND"
}
rows, err := d.db.Query(c, fmt.Sprintf(_avIncomeSQL, query), id, from, to, limit)
if err != nil {
log.Error("GetAvIncome d.db.Query error(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
list := &model.ArchiveIncome{}
err = rows.Scan(&list.ID, &list.AvID, &list.MID, &list.TagID, &list.IsOriginal, &list.UploadTime, &list.TotalIncome, &list.Income, &list.TaxMoney, &list.Date)
if err != nil {
log.Error("GetAvIncome rows scan error(%v)", err)
return
}
list.Type = typ
avs = append(avs, list)
}
err = rows.Err()
return
}
// GetColumnIncome get column income by query
func (d *Dao) GetColumnIncome(c context.Context, id int64, query string, from, to string, limit int, typ int) (columns []*model.ArchiveIncome, err error) {
columns = make([]*model.ArchiveIncome, 0)
if query != "" {
query += " AND"
}
rows, err := d.db.Query(c, fmt.Sprintf(_columnIncomeSQL, query), id, from, to, limit)
if err != nil {
log.Error("GetColumnIncome d.db.Query error(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
list := &model.ArchiveIncome{}
err = rows.Scan(&list.ID, &list.AvID, &list.MID, &list.TagID, &list.UploadTime, &list.TotalIncome, &list.Income, &list.TaxMoney, &list.Date)
if err != nil {
log.Error("GetColumnIncome rows scan error(%v)", err)
return
}
list.Type = typ
columns = append(columns, list)
}
err = rows.Err()
return
}

View File

@@ -0,0 +1,152 @@
package income
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestIncomeGetArchiveStatis(t *testing.T) {
convey.Convey("GetArchiveStatis", t, func(ctx convey.C) {
var (
c = context.Background()
table = "av_income_daily_statis"
query = "id > 0"
from = int(0)
limit = int(10)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
Exec(c, "INSERT INTO av_income_daily_statis(avs,money_section,money_tips,income,category_id,cdate) VALUES(10, 1, '0-3',1, '2018-01-01')")
avs, err := d.GetArchiveStatis(c, table, query, from, limit)
ctx.Convey("Then err should be nil.avs should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(avs, convey.ShouldNotBeNil)
})
})
})
}
func TestIncomeGetArchiveIncome(t *testing.T) {
convey.Convey("GetArchiveIncome av", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(0)
query = "id > 0"
from = "2018-01-01"
to = "2019-01-01"
limit = int(100)
typ = int(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
Exec(c, "INSERT INTO av_income(av_id,mid,date) VALUES(1001, 1000, '2018-05-01')")
archs, err := d.GetArchiveIncome(c, id, query, from, to, limit, typ)
ctx.Convey("Then err should be nil.archs should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(archs, convey.ShouldNotBeNil)
})
})
})
convey.Convey("GetArchiveIncome column", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(0)
query = "id > 0"
from = "2018-01-01"
to = "2019-01-01"
limit = int(100)
typ = int(2)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
Exec(c, "INSERT INTO column_income(aid,mid,date) VALUES(1002, 1000, '2018-05-01')")
archs, err := d.GetArchiveIncome(c, id, query, from, to, limit, typ)
ctx.Convey("Then err should be nil.archs should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(archs, convey.ShouldNotBeNil)
})
})
})
convey.Convey("GetArchiveIncome bgm", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(0)
query = "id > 0"
from = "2018-01-01"
to = "2019-01-01"
limit = int(100)
typ = int(3)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
Exec(c, "INSERT INTO bgm_income(sid,mid,date) VALUES(1003, 1000, '2018-05-01')")
archs, err := d.GetArchiveIncome(c, id, query, from, to, limit, typ)
ctx.Convey("Then err should be nil.archs should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(archs, convey.ShouldNotBeNil)
})
})
})
convey.Convey("GetArchiveIncome error type", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(0)
query = "id > 0"
from = "2018-01-01"
to = "2019-01-01"
limit = int(100)
typ = int(4)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
_, err := d.GetArchiveIncome(c, id, query, from, to, limit, typ)
ctx.Convey("Then err should be nil.archs should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldNotBeNil)
})
})
})
}
func TestIncomeGetAvIncome(t *testing.T) {
convey.Convey("GetAvIncome", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(0)
query = "id > 0"
from = "2018-01-01"
to = "2019-01-01"
limit = int(100)
typ = int(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
Exec(c, "INSERT INTO av_income(av_id,mid,date) VALUES(1001, 1000, '2018-05-01')")
avs, err := d.GetAvIncome(c, id, query, from, to, limit, typ)
ctx.Convey("Then err should be nil.avs should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(avs, convey.ShouldNotBeNil)
})
})
})
}
func TestIncomeGetColumnIncome(t *testing.T) {
convey.Convey("GetColumnIncome", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(0)
query = "id > 0"
from = "2018-01-01"
to = "2019-01-01"
limit = int(100)
typ = int(2)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
Exec(c, "INSERT INTO column_income(aid,mid,date) VALUES(1002, 1000, '2018-05-01')")
columns, err := d.GetColumnIncome(c, id, query, from, to, limit, typ)
ctx.Convey("Then err should be nil.columns should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(columns, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,65 @@
package income
import (
"context"
"fmt"
model "go-common/app/admin/main/growup/model/income"
"go-common/library/log"
)
const (
// select
_getAvByBgmIncome = "SELECT aid FROM bgm_income WHERE sid = ? AND date >= ? AND date <= ?"
_bgmIncomeSQL = "SELECT id,sid,mid,join_at,total_income,income,tax_money,date FROM bgm_income WHERE id > ? AND date >= ? AND date <= ? AND %s is_deleted = 0 ORDER BY id LIMIT ?"
)
// GetAvByBgm get av_id by bgm id
func (d *Dao) GetAvByBgm(c context.Context, sid int64, from, to string) (avs map[int64]struct{}, err error) {
avs = make(map[int64]struct{})
rows, err := d.db.Query(c, _getAvByBgmIncome, sid, from, to)
if err != nil {
log.Error("GetAvByBgm d.db.Query error(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
var avID int64
err = rows.Scan(&avID)
if err != nil {
log.Error("GetAvByBgm rows scan error(%v)", err)
return
}
avs[avID] = struct{}{}
}
err = rows.Err()
return
}
// GetBgmIncome get bgm income by query
func (d *Dao) GetBgmIncome(c context.Context, id int64, query string, from, to string, limit int, typ int) (bgms []*model.ArchiveIncome, err error) {
bgms = make([]*model.ArchiveIncome, 0)
if query != "" {
query += " AND"
}
rows, err := d.db.Query(c, fmt.Sprintf(_bgmIncomeSQL, query), id, from, to, limit)
if err != nil {
log.Error("GetBgmIncome d.db.Query error(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
list := &model.ArchiveIncome{}
err = rows.Scan(&list.ID, &list.AvID, &list.MID, &list.UploadTime, &list.TotalIncome, &list.Income, &list.TaxMoney, &list.Date)
if err != nil {
log.Error("GetBgmIncome rows scan error(%v)", err)
return
}
list.Type = typ
bgms = append(bgms, list)
}
err = rows.Err()
return
}

View File

@@ -0,0 +1,48 @@
package income
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestIncomeGetAvByBgm(t *testing.T) {
convey.Convey("GetAvByBgm", t, func(ctx convey.C) {
var (
c = context.Background()
sid = int64(1003)
from = "2018-01-01"
to = "2019-01-03"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
Exec(c, "INSERT INTO bgm_income(sid,mid,date) VALUES(1003, 1000, '2018-05-01')")
avs, err := d.GetAvByBgm(c, sid, from, to)
ctx.Convey("Then err should be nil.avs should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(avs, convey.ShouldNotBeNil)
})
})
})
}
func TestIncomeGetBgmIncome(t *testing.T) {
convey.Convey("GetBgmIncome", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(0)
query = ""
from = "2018-01-02"
to = "2018-01-03"
limit = int(10)
typ = int(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
bgms, err := d.GetBgmIncome(c, id, query, from, to, limit, typ)
ctx.Convey("Then err should be nil.bgms should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(bgms, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,77 @@
package income
import (
"context"
"fmt"
"go-common/library/database/sql"
"go-common/library/log"
"go-common/library/xstr"
)
const (
// select
_blackListByMIDSQL = "SELECT av_id FROM av_black_list WHERE mid = ? AND ctype = ? AND is_delete = 0"
_blackListByAvIDSQL = "SELECT av_id FROM av_black_list WHERE av_id in (%s) AND ctype = ? AND is_delete = 0"
// insert
_inBlackListSQL = "INSERT INTO av_black_list(av_id,mid,ctype,reason,nickname,has_signed,is_delete) VALUES %s ON DUPLICATE KEY UPDATE reason=VALUES(reason),nickname=VALUES(nickname),has_signed=VALUES(has_signed),is_delete=VALUES(is_delete)"
)
// ListAvBlackList list av_blakc_list by av_id
func (d *Dao) ListAvBlackList(c context.Context, avID []int64, ctype int) (avb map[int64]struct{}, err error) {
avb = make(map[int64]struct{})
rows, err := d.db.Query(c, fmt.Sprintf(_blackListByAvIDSQL, xstr.JoinInts(avID)), ctype)
if err != nil {
log.Error("ListAvBlackList d.db.Query error(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
var id int64
err = rows.Scan(&id)
if err != nil {
log.Error("ListAvBlackList rows scan error(%v)", err)
return
}
avb[id] = struct{}{}
}
err = rows.Err()
return
}
// GetAvBlackListByMID list av_blakc_list by av_id
func (d *Dao) GetAvBlackListByMID(c context.Context, mid int64, typ int) (avb map[int64]struct{}, err error) {
avb = make(map[int64]struct{})
rows, err := d.db.Query(c, _blackListByMIDSQL, mid, typ)
if err != nil {
log.Error("GetAvBlackListByMID d.db.Query error(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
var avID int64
err = rows.Scan(&avID)
if err != nil {
log.Error("GetAvBlackListByMID rows scan error(%v)", err)
return
}
avb[avID] = struct{}{}
}
err = rows.Err()
return
}
// TxInsertAvBlackList insert val into av_black_list
func (d *Dao) TxInsertAvBlackList(tx *sql.Tx, val string) (rows int64, err error) {
if val == "" {
return
}
res, err := tx.Exec(fmt.Sprintf(_inBlackListSQL, val))
if err != nil {
log.Error("TxInsertAvBlackList tx.Exec error(%v)", err)
return
}
return res.RowsAffected()
}

View File

@@ -0,0 +1,60 @@
package income
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestIncomeListAvBlackList(t *testing.T) {
convey.Convey("ListAvBlackList", t, func(ctx convey.C) {
var (
c = context.Background()
avID = []int64{19930812}
ctype = int(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
Exec(c, "INSERT INTO av_black_list(av_id, mid) VALUES(19930812,19930812)")
avb, err := d.ListAvBlackList(c, avID, ctype)
ctx.Convey("Then err should be nil.avb should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(avb, convey.ShouldNotBeNil)
})
})
})
}
func TestIncomeGetAvBlackListByMID(t *testing.T) {
convey.Convey("GetAvBlackListByMID", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(19930812)
typ = int(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
Exec(c, "INSERT INTO av_black_list(av_id, mid) VALUES(1002,19930812)")
avb, err := d.GetAvBlackListByMID(c, mid, typ)
ctx.Convey("Then err should be nil.avb should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(avb, convey.ShouldNotBeNil)
})
})
})
}
func TestIncomeTxInsertAvBlackList(t *testing.T) {
convey.Convey("TxInsertAvBlackList", t, func(ctx convey.C) {
var (
tx, _ = d.BeginTran(context.Background())
val = "(1001,1000,0,'test','szy',1,0)"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
rows, err := d.TxInsertAvBlackList(tx, val)
ctx.Convey("Then err should be nil.rows should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rows, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,149 @@
package income
import (
"context"
"fmt"
model "go-common/app/admin/main/growup/model/income"
"go-common/library/database/sql"
"go-common/library/log"
xtime "go-common/library/time"
)
const (
// select
_avDailyChargeSQL = "SELECT av_id,mid,tag_id,upload_time,inc_charge,date FROM av_daily_charge_%02d WHERE av_id = ? LIMIT 31"
_cmDailyChargeSQL = "SELECT aid,mid,tag_id,upload_time,inc_charge,date FROM column_daily_charge WHERE aid = ?"
_bgmDailyChargeSQL = "SELECT sid,aid,mid,join_at,inc_charge,date FROM bgm_daily_charge WHERE sid = ?"
_upChargeRatioSQL = "SELECT mid, ratio FROM up_charge_ratio LIMIT ?, ?"
_archiveChargeStatisTableSQL = "SELECT avs,money_section,money_tips,charge,category_id,cdate FROM %s WHERE %s LIMIT ?,?"
_archiveTotalChargeSQL = "SELECT total_charge FROM %s WHERE %s LIMIT 1"
)
// GetAvDailyCharge get av_daily_charge by month
func (d *Dao) GetAvDailyCharge(c context.Context, month int, avID int64) (avs []*model.ArchiveCharge, err error) {
if month < 1 || month > 12 {
return nil, fmt.Errorf("error args month(%d)", month)
}
rows, err := d.db.Query(c, fmt.Sprintf(_avDailyChargeSQL, month), avID)
if err != nil {
log.Error("GetAvDailyCharge d.db.Query error(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
list := &model.ArchiveCharge{}
err = rows.Scan(&list.AID, &list.MID, &list.CategoryID, &list.UploadTime, &list.Charge, &list.Date)
if err != nil {
log.Error("GetAvDailyCharge rows scan error(%v)", err)
return
}
avs = append(avs, list)
}
err = rows.Err()
return
}
// GetColumnCharges get column daily charge
func (d *Dao) GetColumnCharges(c context.Context, aid int64) (cms []*model.ArchiveCharge, err error) {
cms = make([]*model.ArchiveCharge, 0)
rows, err := d.db.Query(c, _cmDailyChargeSQL, aid)
if err != nil {
log.Error("GetColumnCharge d.db.Query error(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
var uploadTime int64
cm := &model.ArchiveCharge{}
err = rows.Scan(&cm.AID, &cm.MID, &cm.CategoryID, &uploadTime, &cm.Charge, &cm.Date)
if err != nil {
log.Error("GetColumnCharge rows scan error(%v)", err)
return
}
cm.UploadTime = xtime.Time(uploadTime)
cms = append(cms, cm)
}
err = rows.Err()
return
}
// GetBgmCharges get bgm daily charge
func (d *Dao) GetBgmCharges(c context.Context, aid int64) (bgms []*model.ArchiveCharge, err error) {
bgms = make([]*model.ArchiveCharge, 0)
rows, err := d.db.Query(c, _bgmDailyChargeSQL, aid)
if err != nil {
log.Error("GetBgmCharge d.db.Query error(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
bgm := &model.ArchiveCharge{}
err = rows.Scan(&bgm.AID, &bgm.AvID, &bgm.MID, &bgm.UploadTime, &bgm.Charge, &bgm.Date)
if err != nil {
log.Error("GetBgmCharge rows scan error(%v)", err)
return
}
bgms = append(bgms, bgm)
}
err = rows.Err()
return
}
// GetArchiveChargeStatis get archive charge statis from table and query
func (d *Dao) GetArchiveChargeStatis(c context.Context, table, query string, from, limit int) (archs []*model.ArchiveChargeStatis, err error) {
archs = make([]*model.ArchiveChargeStatis, 0)
if table == "" || query == "" {
return nil, fmt.Errorf("error args table(%s), query(%s)", table, query)
}
rows, err := d.db.Query(c, fmt.Sprintf(_archiveChargeStatisTableSQL, table, query), from, limit)
if err != nil {
log.Error("GetArchiveChargeStatis d.db.Query error(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
list := &model.ArchiveChargeStatis{}
err = rows.Scan(&list.Avs, &list.MoneySection, &list.MoneyTips, &list.Charge, &list.CategroyID, &list.CDate)
if err != nil {
log.Error("GetArchiveChargeStatis rows scan error(%v)", err)
return
}
archs = append(archs, list)
}
err = rows.Err()
return
}
// GetTotalCharge get total charge by table and aid
func (d *Dao) GetTotalCharge(c context.Context, table, query string) (total int64, err error) {
err = d.db.QueryRow(c, fmt.Sprintf(_archiveTotalChargeSQL, table, query)).Scan(&total)
if err == sql.ErrNoRows {
err = nil
}
return
}
// UpRatio get up charge ratio
func (d *Dao) UpRatio(c context.Context, from, limit int64) (ratio map[int64]int64, err error) {
ratio = make(map[int64]int64)
rows, err := d.db.Query(c, _upChargeRatioSQL, from, limit)
if err != nil {
log.Error("d.db.Query error(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
var mid, charge int64
err = rows.Scan(&mid, &charge)
if err != nil {
log.Error("rows scan error(%v)", err)
return
}
ratio[mid] = charge
}
err = rows.Err()
return
}

View File

@@ -0,0 +1,111 @@
package income
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestIncomeGetAvDailyCharge(t *testing.T) {
convey.Convey("GetAvDailyCharge", t, func(ctx convey.C) {
var (
c = context.Background()
month = int(1)
avID = int64(1001)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
Exec(c, "INSERT INTO av_daily_charge_01(av_id, date) VALUES(1001, '2018-01-01')")
_, err := d.GetAvDailyCharge(c, month, avID)
ctx.Convey("Then err should be nil.avs should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
convey.Convey("GetAvDailyCharge month error", t, func(ctx convey.C) {
var (
c = context.Background()
month = int(13)
avID = int64(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
_, err := d.GetAvDailyCharge(c, month, avID)
ctx.Convey("Then err should be nil.avs should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldNotBeNil)
})
})
})
}
func TestIncomeGetColumnCharges(t *testing.T) {
convey.Convey("GetColumnCharges", t, func(ctx convey.C) {
var (
c = context.Background()
aid = int64(1002)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
Exec(c, "INSERT INTO column_daily_charge(aid, date) VALUES(1002, '2018-01-01')")
cms, err := d.GetColumnCharges(c, aid)
ctx.Convey("Then err should be nil.cms should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(cms, convey.ShouldNotBeNil)
})
})
})
}
func TestIncomeGetBgmCharges(t *testing.T) {
convey.Convey("GetBgmCharges", t, func(ctx convey.C) {
var (
c = context.Background()
aid = int64(1003)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
Exec(c, "INSERT INTO bgm_daily_charge(sid, date) VALUES(1003, '2018-01-01')")
bgms, err := d.GetBgmCharges(c, aid)
ctx.Convey("Then err should be nil.bgms should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(bgms, convey.ShouldNotBeNil)
})
})
})
}
func TestIncomeGetArchiveChargeStatis(t *testing.T) {
convey.Convey("GetArchiveChargeStatis", t, func(ctx convey.C) {
var (
c = context.Background()
table = "av_charge_daily_statis"
query = "cdate = '2018-01-01'"
from = int(0)
limit = int(10)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
Exec(c, "INSERT INTO av_charge_daily_statis(avs, cdate) VALUES(10, '2018-01-01')")
archs, err := d.GetArchiveChargeStatis(c, table, query, from, limit)
ctx.Convey("Then err should be nil.archs should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(archs, convey.ShouldNotBeNil)
})
})
})
}
func TestIncomeGetTotalCharge(t *testing.T) {
convey.Convey("GetTotalCharge", t, func(ctx convey.C) {
var (
c = context.Background()
table = "av_charge_statis"
query = "av_id = 1001"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
Exec(c, "INSERT INTO av_charge_statis(av_id, total_income) VALUES(1001, 10)")
total, err := d.GetTotalCharge(c, table, query)
ctx.Convey("Then err should be nil.total should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(total, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,40 @@
package income
import (
"context"
"go-common/app/admin/main/growup/conf"
"go-common/library/database/sql"
)
// Dao dao
type Dao struct {
c *conf.Config
db *sql.DB
}
// New fn
func New(c *conf.Config) (d *Dao) {
d = &Dao{
c: c,
db: sql.NewMySQL(c.ORM.Allowance),
}
return d
}
// Ping ping health.
func (d *Dao) Ping(c context.Context) (err error) {
return d.db.Ping(c)
}
// Close close connections of mc, redis, db.
func (d *Dao) Close() {
if d.db != nil {
d.db.Close()
}
}
// BeginTran begin transcation
func (d *Dao) BeginTran(c context.Context) (tx *sql.Tx, err error) {
return d.db.Begin(c)
}

View File

@@ -0,0 +1,55 @@
package income
import (
"context"
"flag"
"go-common/app/admin/main/growup/conf"
"os"
"testing"
. "github.com/smartystreets/goconvey/convey"
)
var (
d *Dao
)
func CleanMysql() {
}
func TestMain(m *testing.M) {
if os.Getenv("DEPLOY_ENV") != "" {
flag.Set("app_id", "mobile.studio.growup-admin")
flag.Set("conf_token", "ac1fd397cbc33eb60541e8734844bdd5")
flag.Set("tree_id", "13583")
flag.Set("conf_version", "docker-1")
flag.Set("deploy_env", "uat")
flag.Set("conf_host", "config.bilibili.co")
flag.Set("conf_path", "/tmp")
flag.Set("region", "sh")
flag.Set("zone", "sh001")
} else {
flag.Set("conf", "../../cmd/growup-admin.toml")
}
flag.Parse()
if err := conf.Init(); err != nil {
panic(err)
}
d = New(conf.Conf)
os.Exit(m.Run())
}
func WithMysql(f func(d *Dao)) func() {
return func() {
Reset(func() { CleanMysql() })
f(d)
}
}
func Exec(c context.Context, sql string) (rows int64, err error) {
res, err := d.db.Exec(c, sql)
if err != nil {
return
}
return res.RowsAffected()
}

View File

@@ -0,0 +1,41 @@
package income
import (
"context"
"fmt"
model "go-common/app/admin/main/growup/model/income"
"go-common/library/log"
)
const (
// select
_lotteryIncomeSQL = "SELECT id,av_id,mid,tag_id,upload_time,total_income,income,tax_money,date FROM lottery_av_income WHERE id > ? AND %s date >= ? AND date <= ? ORDER BY id LIMIT ?"
)
// GetLotteryIncome get lottery income by query
func (d *Dao) GetLotteryIncome(c context.Context, id int64, query string, from, to string, limit int, typ int) (avs []*model.ArchiveIncome, err error) {
avs = make([]*model.ArchiveIncome, 0)
if query != "" {
query += " AND"
}
rows, err := d.db.Query(c, fmt.Sprintf(_lotteryIncomeSQL, query), id, from, to, limit)
if err != nil {
log.Error("GetLotteryIncome d.db.Query error(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
list := &model.ArchiveIncome{}
err = rows.Scan(&list.ID, &list.AvID, &list.MID, &list.TagID, &list.UploadTime, &list.TotalIncome, &list.Income, &list.TaxMoney, &list.Date)
if err != nil {
log.Error("GetLotteryIncome rows scan error(%v)", err)
return
}
list.Type = typ
avs = append(avs, list)
}
err = rows.Err()
return
}

View File

@@ -0,0 +1,30 @@
package income
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestIncomeGetLotteryIncome(t *testing.T) {
convey.Convey("GetLotteryIncome", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(0)
query = ""
from = "2018-01-01"
to = "2019-01-01"
limit = int(2000)
typ = int(5)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
Exec(c, "INSERT INTO lottery_av_income(av_id, mid, income, date) VALUES(10010, 1001, 100, '2018-11-11') ONDUPLICATE KEY UPDATE date = '2018-11-11'")
avs, err := d.GetLotteryIncome(c, id, query, from, to, limit, typ)
ctx.Convey("Then err should be nil.avs should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(avs, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,68 @@
package income
import (
"context"
"fmt"
model "go-common/app/admin/main/growup/model/income"
"go-common/library/database/sql"
"go-common/library/log"
)
const (
// count
_upAccountCountSQL = "SELECT count(*) FROM up_account WHERE %s is_deleted = ?"
// select
_upAccountSQL = "SELECT mid,total_income,total_unwithdraw_income,total_withdraw_income,withdraw_date_version,last_withdraw_time,mtime FROM up_account WHERE %s is_deleted = ? LIMIT ?,?"
_upAccountByMIDSQL = "SELECT mid,total_income,total_unwithdraw_income,withdraw_date_version,version FROM up_account WHERE mid = ? AND is_deleted = 0"
// update
_breachUpAccountSQL = "UPDATE up_account SET total_income = ?, total_unwithdraw_income = ?, version = ? WHERE mid = ? AND version = ? AND is_deleted = 0"
)
// UpAccountCount get up_account count
func (d *Dao) UpAccountCount(c context.Context, query string, isDeleted int) (total int64, err error) {
err = d.db.QueryRow(c, fmt.Sprintf(_upAccountCountSQL, query), isDeleted).Scan(&total)
if err == sql.ErrNoRows {
err = nil
}
return
}
// ListUpAccount list up account bu query
func (d *Dao) ListUpAccount(c context.Context, query string, isDeleted, from, limit int) (ups []*model.UpAccount, err error) {
ups = make([]*model.UpAccount, 0)
rows, err := d.db.Query(c, fmt.Sprintf(_upAccountSQL, query), isDeleted, from, limit)
if err != nil {
log.Error("ListUpAccount d.db.Query error(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
up := &model.UpAccount{}
err = rows.Scan(&up.MID, &up.TotalIncome, &up.TotalUnwithdrawIncome, &up.TotalWithdrawIncome, &up.WithdrawDateVersion, &up.LastWithdrawTime, &up.MTime)
if err != nil {
log.Error("ListUpAccount rows scan error(%v)", err)
return
}
ups = append(ups, up)
}
err = rows.Err()
return
}
// GetUpAccount get up_account by mid
func (d *Dao) GetUpAccount(c context.Context, mid int64) (up *model.UpAccount, err error) {
up = &model.UpAccount{}
err = d.db.QueryRow(c, _upAccountByMIDSQL, mid).Scan(&up.MID, &up.TotalIncome, &up.TotalUnwithdrawIncome, &up.WithdrawDateVersion, &up.Version)
return
}
// TxBreachUpAccount breach up_account
func (d *Dao) TxBreachUpAccount(tx *sql.Tx, total, unwithdraw, mid, newVersion, oldVersion int64) (rows int64, err error) {
res, err := tx.Exec(_breachUpAccountSQL, total, unwithdraw, newVersion, mid, oldVersion)
if err != nil {
return
}
return res.RowsAffected()
}

View File

@@ -0,0 +1,81 @@
package income
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestIncomeUpAccountCount(t *testing.T) {
convey.Convey("UpAccountCount", t, func(ctx convey.C) {
var (
c = context.Background()
query = ""
isDeleted = int(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
total, err := d.UpAccountCount(c, query, isDeleted)
ctx.Convey("Then err should be nil.total should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(total, convey.ShouldNotBeNil)
})
})
})
}
func TestIncomeListUpAccount(t *testing.T) {
convey.Convey("ListUpAccount", t, func(ctx convey.C) {
var (
c = context.Background()
query = ""
isDeleted = int(0)
from = int(0)
limit = int(100)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
ups, err := d.ListUpAccount(c, query, isDeleted, from, limit)
ctx.Convey("Then err should be nil.ups should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(ups, convey.ShouldNotBeNil)
})
})
})
}
func TestIncomeGetUpAccount(t *testing.T) {
convey.Convey("GetUpAccount", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(1001)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
Exec(c, "INSERT INTO up_account(mid) VALUES(1001)")
up, err := d.GetUpAccount(c, mid)
ctx.Convey("Then err should be nil.up should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(up, convey.ShouldNotBeNil)
})
})
})
}
func TestIncomeTxBreachUpAccount(t *testing.T) {
convey.Convey("TxBreachUpAccount", t, func(ctx convey.C) {
var (
tx, _ = d.BeginTran(context.Background())
total = int64(0)
unwithdraw = int64(0)
mid = int64(1001)
newVersion = int64(0)
oldVersion = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
rows, err := d.TxBreachUpAccount(tx, total, unwithdraw, mid, newVersion, oldVersion)
ctx.Convey("Then err should be nil.rows should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rows, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,41 @@
package income
import (
"context"
"fmt"
"go-common/library/log"
"go-common/library/xstr"
)
const (
// select
_upInfoSQL = "SELECT mid, nick_name FROM up_category_info WHERE mid in (%s) AND is_deleted = 0"
)
// ListUpInfo list up_category_info by mids
func (d *Dao) ListUpInfo(c context.Context, mids []int64) (upInfo map[int64]string, err error) {
upInfo = make(map[int64]string)
if len(mids) == 0 {
return
}
rows, err := d.db.Query(c, fmt.Sprintf(_upInfoSQL, xstr.JoinInts(mids)))
if err != nil {
log.Error("ListUpInfo d.db.Query error(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
var mid int64
var nickname string
err = rows.Scan(&mid, &nickname)
if err != nil {
log.Error("ListUpInfo rows scan error(%v)", err)
return
}
upInfo[mid] = nickname
}
err = rows.Err()
return
}

View File

@@ -0,0 +1,18 @@
package income
import (
"context"
"testing"
. "github.com/smartystreets/goconvey/convey"
)
func Test_ListUpInfo(t *testing.T) {
Convey("ListUpInfo by mids", t, WithMysql(func(d *Dao) {
var (
mids = []int64{1, 2}
)
_, err := d.ListUpInfo(context.Background(), mids)
So(err, ShouldBeNil)
}))
}

View File

@@ -0,0 +1,103 @@
package income
import (
"context"
"fmt"
model "go-common/app/admin/main/growup/model/income"
"go-common/library/log"
)
const (
// select
_upIncomeTableSQL = "SELECT id,mid,%s,date FROM %s WHERE id > ? AND %s LIMIT ?"
_upIncomeTableSortSQL = "SELECT mid,av_count,column_count,bgm_count,%s,date FROM %s WHERE %s ORDER BY date desc,%s desc LIMIT ?,? "
_upIncomeCountSQL = "SELECT count(*) FROM %s WHERE %s"
_upDailyStatisSQL = "SELECT ups,income,cdate FROM %s WHERE cdate >= '%s' AND cdate <= '%s'"
)
// UpIncomeCount count
func (d *Dao) UpIncomeCount(c context.Context, table, query string) (count int, err error) {
if table == "" || query == "" {
return 0, fmt.Errorf("error args table(%s), query(%s)", table, query)
}
err = d.db.QueryRow(c, fmt.Sprintf(_upIncomeCountSQL, table, query)).Scan(&count)
return
}
// GetUpIncome get up_income_(weekly/monthly) from table and query
func (d *Dao) GetUpIncome(c context.Context, table, incomeType, query string, id int64, limit int) (upIncome []*model.UpIncome, err error) {
upIncome = make([]*model.UpIncome, 0)
if table == "" || query == "" {
return nil, fmt.Errorf("error args table(%s), query(%s)", table, query)
}
rows, err := d.db.Query(c, fmt.Sprintf(_upIncomeTableSQL, incomeType, table, query), id, limit)
if err != nil {
log.Error("GetUpIncome d.db.Query error(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
list := &model.UpIncome{}
err = rows.Scan(&list.ID, &list.MID, &list.Income, &list.Date)
if err != nil {
log.Error("GetUpIncome rows scan error(%v)", err)
return
}
upIncome = append(upIncome, list)
}
err = rows.Err()
return
}
// GetUpIncomeBySort get up_income by query
func (d *Dao) GetUpIncomeBySort(c context.Context, table, typeField, sort, query string, from, limit int) (upIncome []*model.UpIncome, err error) {
upIncome = make([]*model.UpIncome, 0)
if table == "" || query == "" || typeField == "" {
return nil, fmt.Errorf("error args table(%s), typeField(%s),query(%s)", table, typeField, query)
}
rows, err := d.db.Query(c, fmt.Sprintf(_upIncomeTableSortSQL, typeField, table, query, sort), from, limit)
if err != nil {
log.Error("GetUpIncomeBySort d.db.Query error(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
up := &model.UpIncome{}
err = rows.Scan(&up.MID, &up.AvCount, &up.ColumnCount, &up.BgmCount, &up.Income, &up.TaxMoney, &up.BaseIncome, &up.TotalIncome, &up.Date)
if err != nil {
log.Error("GetUpIncome rows scan error(%v)", err)
return
}
upIncome = append(upIncome, up)
}
err = rows.Err()
return
}
// GetUpDailyStatis get up income daily statis
func (d *Dao) GetUpDailyStatis(c context.Context, table, fromTime, toTime string) (s []*model.UpDailyStatis, err error) {
if table == "" {
return nil, fmt.Errorf("error args table(%s)", table)
}
s = make([]*model.UpDailyStatis, 0)
rows, err := d.db.Query(c, fmt.Sprintf(_upDailyStatisSQL, table, fromTime, toTime))
if err != nil {
log.Error("GetUpDailyStatis d.db.Query error(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
list := &model.UpDailyStatis{}
err = rows.Scan(&list.Ups, &list.Income, &list.Date)
if err != nil {
log.Error("GetUpIncome rows scan error(%v)", err)
return
}
s = append(s, list)
}
err = rows.Err()
return
}

View File

@@ -0,0 +1,135 @@
package income
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestIncomeUpIncomeCount(t *testing.T) {
convey.Convey("UpIncomeCount", t, func(ctx convey.C) {
var (
c = context.Background()
table = "up_income"
query = "id > 0"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
Exec(c, "INSERT INTO up_income(mid, income, date) VALUS(1993, 10, '2018-01-01')")
count, err := d.UpIncomeCount(c, table, query)
ctx.Convey("Then err should be nil.count should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(count, convey.ShouldNotBeNil)
})
})
})
convey.Convey("UpIncomeCount table error", t, func(ctx convey.C) {
var (
c = context.Background()
table = ""
query = ""
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
_, err := d.UpIncomeCount(c, table, query)
ctx.Convey("Then err should be nil.count should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldNotBeNil)
})
})
})
}
func TestIncomeGetUpIncome(t *testing.T) {
convey.Convey("GetUpIncome", t, func(ctx convey.C) {
var (
c = context.Background()
table = "up_income"
incomeType = "av_income"
query = "is_deleted = 0"
id = int64(0)
limit = int(10)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
upIncome, err := d.GetUpIncome(c, table, incomeType, query, id, limit)
ctx.Convey("Then err should be nil.upIncome should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(upIncome, convey.ShouldNotBeNil)
})
})
})
convey.Convey("GetUpIncome query == nil", t, func(ctx convey.C) {
var (
c = context.Background()
table = "up_income"
incomeType = "av_income"
query = ""
id = int64(0)
limit = int(10)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
_, err := d.GetUpIncome(c, table, incomeType, query, id, limit)
ctx.Convey("Then err should be nil.upIncome should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldNotBeNil)
})
})
})
}
func TestIncomeGetUpIncomeBySort(t *testing.T) {
convey.Convey("GetUpIncomeBySort", t, func(ctx convey.C) {
var (
c = context.Background()
table = "up_income"
typeField = "av_income,av_tax,av_base_income,av_total_income"
sort = "id"
query = "id > 0"
from = int(0)
limit = int(10)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
upIncome, err := d.GetUpIncomeBySort(c, table, typeField, sort, query, from, limit)
ctx.Convey("Then err should be nil.upIncome should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(upIncome, convey.ShouldNotBeNil)
})
})
})
convey.Convey("GetUpIncomeBySort table == nil", t, func(ctx convey.C) {
var (
c = context.Background()
table = ""
typeField = "av_income"
sort = "id"
query = "id > 0"
from = int(0)
limit = int(10)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
_, err := d.GetUpIncomeBySort(c, table, typeField, sort, query, from, limit)
ctx.Convey("Then err should be nil.upIncome should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldNotBeNil)
})
})
})
}
func TestIncomeGetUpDailyStatis(t *testing.T) {
convey.Convey("GetUpDailyStatis", t, func(ctx convey.C) {
var (
c = context.Background()
table = "up_income_daily_statis"
fromTime = "2018-01-01"
toTime = "2018-01-10"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
Exec(c, "INSERT INTO up_income_daily_statis(ups, cdate) VALUES(10, '2018-01-02')")
s, err := d.GetUpDailyStatis(c, table, fromTime, toTime)
ctx.Convey("Then err should be nil.s should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(s, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,62 @@
package income
import (
"context"
"fmt"
"go-common/library/database/sql"
"go-common/library/log"
"go-common/library/xstr"
)
const (
// select
_upInfoNicknameSQL = "SELECT mid, nickname FROM up_info_video WHERE mid in (%s)"
_upInfoNicknameByMIDSQL = "SELECT nickname FROM %s WHERE mid = ? AND account_state = 3 AND is_deleted = 0"
// update
_updateUpInfoScoreSQL = "UPDATE %s set credit_score = credit_score + ? WHERE mid = ? AND is_deleted = 0"
)
// GetUpInfoNickname get nickname
func (d *Dao) GetUpInfoNickname(c context.Context, mids []int64) (upInfo map[int64]string, err error) {
upInfo = make(map[int64]string)
if len(mids) == 0 {
return
}
rows, err := d.db.Query(c, fmt.Sprintf(_upInfoNicknameSQL, xstr.JoinInts(mids)))
if err != nil {
log.Error("GetUpInfoNickname d.db.Query error(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
var mid int64
var nickname string
err = rows.Scan(&mid, &nickname)
if err != nil {
log.Error("GetUpInfoNickname rows scan error(%v)", err)
return
}
upInfo[mid] = nickname
}
err = rows.Err()
return
}
// GetUpInfoNicknameByMID get nickname by mid
func (d *Dao) GetUpInfoNicknameByMID(c context.Context, mid int64, table string) (nickname string, err error) {
err = d.db.QueryRow(c, fmt.Sprintf(_upInfoNicknameByMIDSQL, table), mid).Scan(&nickname)
if err == sql.ErrNoRows {
return "", nil
}
return
}
// TxUpdateUpInfoScore update up_info_video credit score
func (d *Dao) TxUpdateUpInfoScore(tx *sql.Tx, table string, score int, mid int64) (rows int64, err error) {
res, err := tx.Exec(fmt.Sprintf(_updateUpInfoScoreSQL, table), score, mid)
if err != nil {
return
}
return res.RowsAffected()
}

View File

@@ -0,0 +1,61 @@
package income
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestIncomeGetUpInfoNickname(t *testing.T) {
convey.Convey("GetUpInfoNickname", t, func(ctx convey.C) {
var (
c = context.Background()
mids = []int64{1993}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
Exec(c, "INSERT INTO up_info_video(mid, account_state) VALUES(1993, 3)")
upInfo, err := d.GetUpInfoNickname(c, mids)
ctx.Convey("Then err should be nil.upInfo should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(upInfo, convey.ShouldNotBeNil)
})
})
})
}
func TestIncomeGetUpInfoNicknameByMID(t *testing.T) {
convey.Convey("GetUpInfoNicknameByMID", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(1993)
table = "up_info_video"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
nickname, err := d.GetUpInfoNicknameByMID(c, mid, table)
ctx.Convey("Then err should be nil.nickname should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(nickname, convey.ShouldNotBeNil)
})
})
})
}
func TestIncomeTxUpdateUpInfoScore(t *testing.T) {
convey.Convey("TxUpdateUpInfoScore", t, func(ctx convey.C) {
var (
tx, _ = d.BeginTran(context.Background())
table = "up_info_video"
score = int(5)
mid = int64(1993)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
defer tx.Commit()
rows, err := d.TxUpdateUpInfoScore(tx, table, score, mid)
ctx.Convey("Then err should be nil.rows should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rows, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,37 @@
package income
import (
"context"
"fmt"
model "go-common/app/admin/main/growup/model/income"
"go-common/library/log"
)
const (
// select
_upWithdrawSQL = "SELECT id, mid, withdraw_income, date_version, mtime FROM up_income_withdraw WHERE id > ? AND state = 2 AND %s is_deleted = 0 LIMIT ?"
)
// ListUpWithdraw list up_income_withdraw by query
func (d *Dao) ListUpWithdraw(c context.Context, id int64, query string, limit int) (upWithdraw []*model.UpIncomeWithdraw, err error) {
upWithdraw = make([]*model.UpIncomeWithdraw, 0)
rows, err := d.db.Query(c, fmt.Sprintf(_upWithdrawSQL, query), id, limit)
if err != nil {
log.Error("GetUpWithdraw d.db.Query error(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
w := &model.UpIncomeWithdraw{}
err = rows.Scan(&w.ID, &w.MID, &w.WithdrawIncome, &w.DateVersion, &w.MTime)
if err != nil {
log.Error("GetUpWithdraw rows scan error(%v)", err)
return
}
upWithdraw = append(upWithdraw, w)
}
err = rows.Err()
return
}

View File

@@ -0,0 +1,15 @@
package income
import (
"context"
"testing"
. "github.com/smartystreets/goconvey/convey"
)
func Test_GetUpWithdraw(t *testing.T) {
Convey("GetUpWithdraw", t, WithMysql(func(d *Dao) {
_, err := d.ListUpWithdraw(context.Background(), 0, "", 10)
So(err, ShouldBeNil)
}))
}

View File

@@ -0,0 +1,52 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
"go_test",
)
go_library(
name = "go_default_library",
srcs = [
"dao.go",
"send.go",
],
importpath = "go-common/app/admin/main/growup/dao/message",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/admin/main/growup/conf:go_default_library",
"//library/log:go_default_library",
"//library/net/http/blademaster:go_default_library",
"//library/xstr:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)
go_test(
name = "go_default_test",
srcs = [
"dao_test.go",
"send_test.go",
],
embed = [":go_default_library"],
tags = ["automanaged"],
deps = [
"//app/admin/main/growup/conf:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
],
)

View File

@@ -0,0 +1,24 @@
package message
import (
"go-common/app/admin/main/growup/conf"
xhttp "go-common/library/net/http/blademaster"
)
// Dao is message dao
type Dao struct {
c *conf.Config
uri, creativeURL string
client *xhttp.Client
}
// New a message dao
func New(c *conf.Config) (d *Dao) {
d = &Dao{
c: c,
client: xhttp.NewClient(c.HTTPClient),
uri: c.Host.Message + "/api/notify/send.user.notify.do",
creativeURL: c.Host.Creative + "/x/internal/creative/join/growup/account",
}
return
}

View File

@@ -0,0 +1,34 @@
package message
import (
"flag"
"go-common/app/admin/main/growup/conf"
"os"
"testing"
)
var (
d *Dao
)
func TestMain(m *testing.M) {
if os.Getenv("DEPLOY_ENV") != "" {
flag.Set("app_id", "mobile.studio.growup-admin")
flag.Set("conf_token", "ac1fd397cbc33eb60541e8734844bdd5")
flag.Set("tree_id", "13583")
flag.Set("conf_version", "docker-1")
flag.Set("deploy_env", "uat")
flag.Set("conf_host", "config.bilibili.co")
flag.Set("conf_path", "/tmp")
flag.Set("region", "sh")
flag.Set("zone", "sh001")
} else {
flag.Set("conf", "../../cmd/growup-admin.toml")
}
flag.Parse()
if err := conf.Init(); err != nil {
panic(err)
}
d = New(conf.Conf)
os.Exit(m.Run())
}

View File

@@ -0,0 +1,66 @@
package message
import (
"context"
"fmt"
"net/url"
"strconv"
"strings"
"go-common/library/log"
"go-common/library/xstr"
)
// Send message to upper
func (d *Dao) Send(c context.Context, mc, title, msg string, mids []int64, ts int64) (err error) {
params := url.Values{}
source := strings.Split(mc, "_")
params.Set("type", "json")
params.Set("source", source[0])
params.Set("data_type", "4")
params.Set("mc", mc)
params.Set("title", title)
params.Set("context", msg)
var midList string
for _, mid := range mids {
midList += strconv.FormatInt(mid, 10)
midList += ","
}
midList = strings.TrimSuffix(midList, ",")
params.Set("mid_list", midList)
var res struct {
Code int `json:"code"`
}
log.Info("params:%v", params)
if err = d.client.Post(c, d.uri, "", params, &res); err != nil {
log.Error("growup-admin message url(%s) error(%v)", d.uri+"?"+params.Encode(), err)
return
}
log.Info("message res code:%d", res.Code)
if res.Code != 0 {
log.Error("growup-admin message url(%s) error(%v)", d.uri+"?"+params.Encode(), err)
err = fmt.Errorf("message send failed")
}
return
}
// NotifyTask notify task finish
func (d *Dao) NotifyTask(c context.Context, mids []int64) (err error) {
params := url.Values{}
params.Set("mids", xstr.JoinInts(mids))
var res struct {
Code int `json:"code"`
}
log.Info("creative notify task params:%v", params)
if err = d.client.Post(c, d.creativeURL, "", params, &res); err != nil {
log.Error("growup-admin creative notify task url(%s) error(%v)", d.creativeURL+"?"+params.Encode(), err)
return
}
log.Info("creative notify task res code:%d", res.Code)
if res.Code != 0 {
log.Error("growup-admin creative notify task url(%s) error(%v)", d.creativeURL+"?"+params.Encode(), err)
err = fmt.Errorf("creative notify task send failed")
}
return
}

View File

@@ -0,0 +1,43 @@
package message
import (
"context"
"testing"
"time"
"github.com/smartystreets/goconvey/convey"
)
func TestMessageSend(t *testing.T) {
convey.Convey("Send", t, func(ctx convey.C) {
var (
c = context.Background()
mc = "1_14_2"
title = "test"
msg = "test"
mids = []int64{253550886}
ts = time.Now().Unix()
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.Send(c, mc, title, msg, mids, ts)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestMessageNotifyTask(t *testing.T) {
convey.Convey("NotifyTask", t, func(ctx convey.C) {
var (
c = context.Background()
mids = []int64{2316310}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.NotifyTask(c, mids)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,64 @@
package dao
import (
"context"
"fmt"
"go-common/app/admin/main/growup/model"
"go-common/library/log"
)
const (
_inNoticeSQL = "INSERT INTO notice(title,type,platform,link,status) VALUES (?,?,?,?,?)"
_noticesSQL = "SELECT id,title,type,platform,link,status FROM notice WHERE id > ? %s LIMIT ?"
_noticeCountSQL = "SELECT count(*) FROM notice WHERE id > 0 %s"
_updateNoticeSQL = "UPDATE notice SET %s WHERE id=?"
)
// InsertNotice insert notice
func (d *Dao) InsertNotice(c context.Context, notice *model.Notice) (rows int64, err error) {
res, err := d.rddb.Exec(c, _inNoticeSQL, notice.Title, notice.Type, notice.Platform, notice.Link, notice.Status)
if err != nil {
log.Error("d.db.Exec insert notice error(%v)", err)
return
}
return res.RowsAffected()
}
// NoticeCount get notice count
func (d *Dao) NoticeCount(c context.Context, query string) (count int, err error) {
row := d.rddb.QueryRow(c, fmt.Sprintf(_noticeCountSQL, query))
if err = row.Scan(&count); err != nil {
log.Error("d.db.notice count error(%v)", err)
}
return
}
// Notices get notices
func (d *Dao) Notices(c context.Context, query string, offset int, limit int) (notices []*model.Notice, err error) {
rows, err := d.rddb.Query(c, fmt.Sprintf(_noticesSQL, query), offset, limit)
if err != nil {
log.Error("d.db.Query notice error(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
n := &model.Notice{}
err = rows.Scan(&n.ID, &n.Title, &n.Type, &n.Platform, &n.Link, &n.Status)
if err != nil {
log.Error("rows scan error(%v)", err)
return
}
notices = append(notices, n)
}
return
}
// UpdateNotice update notice
func (d *Dao) UpdateNotice(c context.Context, kv string, id int64) (rows int64, err error) {
res, err := d.rddb.Exec(c, fmt.Sprintf(_updateNoticeSQL, kv), id)
if err != nil {
return
}
return res.RowsAffected()
}

View File

@@ -0,0 +1,47 @@
package dao
import (
"context"
"testing"
"go-common/app/admin/main/growup/model"
. "github.com/smartystreets/goconvey/convey"
)
func Test_NoticeSql(t *testing.T) {
Convey("growup-admin", t, WithMysql(func(d *Dao) {
var (
a = &model.Notice{Title: "title", Type: 1, Platform: 1, Link: "www.bilibili.com", Status: 1}
)
_, err := d.InsertNotice(context.Background(), a)
So(err, ShouldBeNil)
}))
Convey("growup-admin", t, WithMysql(func(d *Dao) {
var (
query = ""
)
_, err := d.NoticeCount(context.Background(), query)
So(err, ShouldBeNil)
}))
Convey("growup-admin", t, WithMysql(func(d *Dao) {
var (
query = ""
from, limit = 0, 1000
)
res, err := d.Notices(context.Background(), query, from, limit)
So(err, ShouldBeNil)
So(len(res), ShouldBeGreaterThan, 0)
}))
Convey("growup-admin", t, WithMysql(func(d *Dao) {
var (
kv = "is_deleted = 1"
id int64 = 1
)
_, err := d.UpdateNotice(context.Background(), kv, id)
So(err, ShouldBeNil)
}))
}

View File

@@ -0,0 +1,285 @@
package dao
import (
"context"
"fmt"
"github.com/jinzhu/gorm"
"go-common/app/admin/main/growup/dao/shell"
"go-common/app/admin/main/growup/model/offlineactivity"
"go-common/app/admin/main/up/util"
"go-common/library/log"
"strconv"
"strings"
)
func generateDelimiter(delimiter string) func(r rune) bool {
return func(r rune) bool {
for _, v := range delimiter {
if v == r {
return true
}
}
return false
}
}
const (
trimSet = "\r\n "
)
func strlistToInt64List(list []string, trimSet string) (result []int64) {
for _, v := range list {
mid, e := strconv.ParseInt(strings.Trim(v, trimSet), 10, 64)
if e != nil {
continue
}
result = append(result, mid)
}
return
}
func trimString(strlist []string, trimset string) (result []string) {
for _, v := range strlist {
var trimed = strings.Trim(v, trimSet)
if trimed == "" {
continue
}
result = append(result, trimed)
}
return
}
//ParseMidsFromString parse []int64 from string
func ParseMidsFromString(str string) (result []int64) {
var midstrlist = trimString(strings.FieldsFunc(str, generateDelimiter(",\r\n")), trimSet)
result = util.Unique(strlistToInt64List(midstrlist, trimSet))
return
}
//OfflineActivityAddActivity add acitvity
func (d *Dao) OfflineActivityAddActivity(ctx context.Context, arg *offlineactivity.AddActivityArg) (err error) {
var activityInfo = offlineactivity.OfflineActivityInfo{
Title: arg.Title,
Link: arg.Link,
BonusType: arg.BonusType,
Memo: arg.Memo,
State: int8(offlineactivity.ActivityStateInit),
Creator: arg.Creator,
}
var bonusList = arg.BonusList
var hasBonus = false
for _, bonus := range bonusList {
if bonus.TotalMoney <= 0 {
err = fmt.Errorf("bonus money < 0, money=%f", bonus.TotalMoney)
log.Error(err.Error())
return
}
bonus.MidList = ParseMidsFromString(bonus.Mids)
bonus.MemberCount = int64(len(bonus.MidList))
if bonus.MemberCount == 0 {
log.Warn("no mid for this bonus, bonusmoney=%.2f", bonus.TotalMoney)
continue
}
hasBonus = true
log.Info("bonus info:money=%.2f, membercount=%d", bonus.TotalMoney/1000, bonus.MemberCount)
}
// 如果一个bonus都没有则什么也不做
if !hasBonus {
log.Error("no bonus")
err = fmt.Errorf("no bonus info")
return
}
if err = d.db.Create(&activityInfo).Error; err != nil {
log.Error("err insert offline activity, err=%s", err)
return
}
var tx = d.db.Begin()
defer func() {
if r := recover(); r != nil || err != nil {
tx.Rollback()
activityInfo.State = int8(offlineactivity.ActivityStateCreateFail)
if err = d.db.Select("state").Save(&activityInfo).Error; err != nil {
log.Error("err update offline activity, err=%s", err)
return
}
}
}()
// create
for _, bonus := range bonusList {
if bonus.MemberCount <= 0 {
continue
}
// 插入OfflineActivityBonus
//if activityInfo.BonusType == offlineactivity.BonusTypeMoney {
bonusMoney := offlineactivity.GetMoneyForDb(bonus.TotalMoney)
//}
var bonusInfo = offlineactivity.OfflineActivityBonus{
TotalMoney: bonusMoney,
MemberCount: uint32(bonus.MemberCount),
State: int8(offlineactivity.BonusStateInit),
ActivityID: activityInfo.ID,
}
if err = tx.Create(&bonusInfo).Error; err != nil {
log.Error("err insert offline activity bonus, err=%s", err)
return
}
// 插入OfflineActivityResult
var insertSchema []string
var vals []interface{}
var dbmoney = bonusInfo.TotalMoney / int64(bonusInfo.MemberCount)
for _, mid := range bonus.MidList {
insertSchema = append(insertSchema, "(?,?,?,?,?)")
vals = append(vals, activityInfo.ID, bonusInfo.ID, activityInfo.BonusType, mid, dbmoney)
}
var insertPre = "insert into offline_activity_result (activity_id, bonus_id, bonus_type, mid, bonus_money) values "
var insertSQL = insertPre + strings.Join(insertSchema, ",")
if err = tx.Table(offlineactivity.TableOfflineActivityResult).Exec(insertSQL, vals...).Error; err != nil {
log.Error("err insert offline activity result, err=%s", err)
return
}
}
activityInfo.State = int8(offlineactivity.ActivityStateSending)
if arg.BonusType == int8(offlineactivity.BonusTypeThing) {
activityInfo.State = int8(offlineactivity.ActivityStateSucess)
}
if err = tx.Select("state").Save(&activityInfo).Error; err != nil {
log.Error("err update offline activity, err=%s", err)
return
}
return tx.Commit().Error
}
//ShellCallbackUpdate shell callback
func (d *Dao) ShellCallbackUpdate(ctx context.Context, result *shell.OrderCallbackJSON, msgid string) (orderInfo offlineactivity.OfflineActivityShellOrder, err error) {
// 找到order info, 写入结果
var stateResult = offlineactivity.ActivityStateWaitResult
if result.IsSuccess() {
stateResult = offlineactivity.ActivityStateSucess
} else if result.IsFail() {
stateResult = offlineactivity.ActivityStateFail
}
if err = d.db.Where("order_id=?", result.ThirdOrderNo).Find(&orderInfo).Error; err != nil {
log.Error("order id=%s, find order id fail, err=%s", result.ThirdOrderNo, err)
return
}
var tx = d.db.Begin()
defer func() {
if r := recover(); r != nil || err != nil {
tx.Rollback()
}
}()
if err = tx.Table(offlineactivity.TableOfflineActivityShellOrder).
Where("id=?", orderInfo.ID).
Update("order_status", result.Status).
Error; err != nil {
log.Error("order id=%s, update order fail, err=%s", result.ThirdOrderNo, err)
return
}
if err = tx.Table(offlineactivity.TableOfflineActivityResult).
Where("id=?", orderInfo.ResultID).
Update("state", stateResult).
Error; err != nil {
log.Error("order id=%s, update result fail, err=%s", result.ThirdOrderNo, err)
return
}
log.Info("order id=%s, shell callback, success, mid=%s, status=%s", result.ThirdOrderNo, result.Mid, result.Status)
err = tx.Commit().Error
return
}
//OfflineActivityGetUpBonusResult Up主所有Activity一起统计
func (d *Dao) OfflineActivityGetUpBonusResult(ctx context.Context, needCount bool, limit, offset int, query string, args ...interface{}) (upResult []*offlineactivity.OfflineActivityResult, totalCount int, err error) {
// 查询所有的 result for mid
// 区分已结算、未结算
// 已结算= 成功, 未结算= 初始、发送、等待
if needCount {
if err = d.db.Table(offlineactivity.TableOfflineActivityResult).Where(query, args...).Count(&totalCount).Error; err != nil {
log.Error("fail to get from db, err=%s", err)
return
}
}
if err = d.db.Where(query, args...).Limit(limit).Offset(offset).Find(&upResult).Error; err != nil {
log.Error("fail to get from db, err=%s", err)
return
}
return
}
//OfflineActivityGetUpBonusResultSelect select by selection
func (d *Dao) OfflineActivityGetUpBonusResultSelect(ctx context.Context, selectQuery string, query string, args ...interface{}) (upResult []*offlineactivity.OfflineActivityResult, err error) {
if err = d.db.Where(query, args...).Select(selectQuery).Find(&upResult).Error; err != nil {
log.Error("fail to get from db, err=%s", err)
return
}
return
}
//OfflineActivityGetUpBonusByActivityResult 根据Activity来分别统计
func (d *Dao) OfflineActivityGetUpBonusByActivityResult(ctx context.Context, limit, offset int, mid int64) (upResult []*offlineactivity.OfflineActivityResult, totalCount int, err error) {
// 查询所有的 result for mid
// 区分已结算、未结算
// 已结算= 成功, 未结算= 初始、发送、等待
var actividyIds []struct {
ActivityID int64 `gorm:"column:activity_id"`
}
if err = d.db.Table(offlineactivity.TableOfflineActivityResult).Select("count(distinct(activity_id))").Where("mid=?", mid).Count(&totalCount).Error; err != nil {
log.Error("fail to get from db, err=%s", err)
return
}
if err = d.db.Table(offlineactivity.TableOfflineActivityResult).Select("distinct(activity_id)").Where("mid=?", mid).Offset(offset).Limit(limit).Find(&actividyIds).Error; err != nil {
log.Error("fail to get from db, err=%s", err)
return
}
//totalCount = len(actividyIds)
var ids []int64
for i := 0; i < len(actividyIds); i++ {
ids = append(ids, actividyIds[i].ActivityID)
}
if err = d.db.Where("mid=? and activity_id in(?)", mid, ids).Find(&upResult).Error; err != nil {
log.Error("fail to get from db, err=%s", err)
return
}
return
}
//OfflineActivityGetDB get gorm db
func (d *Dao) OfflineActivityGetDB() *gorm.DB {
return d.db
}
//UpdateActivityState 更新Activity的状态根据每一个付款记录的状态
func (d *Dao) UpdateActivityState(ctx context.Context, activityID int64) (affectedRow int64, err error) {
// 找到所有result中state最小的一个
// 更新到activity的状态
var record offlineactivity.OfflineActivityResult
if err = d.db.Model(&record).Select("min(state) as state").Where("activity_id=?", activityID).Find(&record).Error; err != nil {
log.Error("fail to get from db, err=%s", err)
return
}
var db = d.db.Table(offlineactivity.TableOfflineActivityInfo).
Where("id=? and state<10 and state<?", activityID, record.State).
Update("state", record.State)
if err = db.Error; err != nil {
log.Error("fail to get from db, err=%s", err)
return
}
affectedRow = db.RowsAffected
if affectedRow > 0 {
log.Info("update activity state, id=%d, newstate=%d", activityID, record.State)
} else {
log.Info("no need to update activity, id=%d, newstate=%d", activityID, record.State)
}
return
}

View File

@@ -0,0 +1,195 @@
package dao
import (
"context"
"go-common/app/admin/main/growup/dao/shell"
"go-common/app/admin/main/growup/model/offlineactivity"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaogenerateDelimiter(t *testing.T) {
convey.Convey("generateDelimiter", t, func(ctx convey.C) {
var (
delimiter = "test"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := generateDelimiter(delimiter)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaostrlistToInt64List(t *testing.T) {
convey.Convey("strlistToInt64List", t, func(ctx convey.C) {
var (
list = []string{"11", "22 ", "vv ", "33 "}
trimSet = " "
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
result := strlistToInt64List(list, trimSet)
ctx.Convey("Then result should not be nil.", func(ctx convey.C) {
ctx.So(result, convey.ShouldNotBeNil)
})
})
})
}
func TestDaotrimString(t *testing.T) {
convey.Convey("trimString", t, func(ctx convey.C) {
var (
strlist = []string{"11", "22 ", "vv ", "33 "}
trimset = " "
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
result := trimString(strlist, trimset)
ctx.Convey("Then result should not be nil.", func(ctx convey.C) {
ctx.So(result, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoParseMidsFromString(t *testing.T) {
convey.Convey("ParseMidsFromString", t, func(ctx convey.C) {
var (
str = "123"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
result := ParseMidsFromString(str)
ctx.Convey("Then result should not be nil.", func(ctx convey.C) {
ctx.So(result, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoOfflineActivityAddActivity(t *testing.T) {
convey.Convey("OfflineActivityAddActivity", t, func(ctx convey.C) {
var (
c = context.Background()
arg = &offlineactivity.AddActivityArg{
Title: "test",
BonusType: 0,
Memo: "memo test",
Link: "http://12345.com",
BonusList: []*offlineactivity.BonusInfo{{TotalMoney: 100, Mids: "1,2,3,"}},
}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.OfflineActivityAddActivity(c, arg)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoShellCallbackUpdate(t *testing.T) {
convey.Convey("ShellCallbackUpdate", t, func(ctx convey.C) {
var (
c = context.Background()
result = &shell.OrderCallbackJSON{
ThirdOrderNo: "1001",
Status: "SUCCESS",
}
msgid = ""
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
Exec(c, "INSERT INTO offline_activity_shell_order(id, result_id, order_id, order_status) VALUES(1000, '1001', '1001', 'SUCCESS')")
orderInfo, err := d.ShellCallbackUpdate(c, result, msgid)
ctx.Convey("Then err should be nil.orderInfo should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(orderInfo, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoOfflineActivityGetUpBonusResult(t *testing.T) {
convey.Convey("OfflineActivityGetUpBonusResult", t, func(ctx convey.C) {
var (
c = context.Background()
needCount bool
limit = int(10)
offset = int(1)
query = "id>?"
args = "0"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
upResult, totalCount, err := d.OfflineActivityGetUpBonusResult(c, needCount, limit, offset, query, args)
ctx.Convey("Then err should be nil.upResult,totalCount should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(totalCount, convey.ShouldNotBeNil)
ctx.So(upResult, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoOfflineActivityGetUpBonusResultSelect(t *testing.T) {
convey.Convey("OfflineActivityGetUpBonusResultSelect", t, func(ctx convey.C) {
var (
c = context.Background()
selectQuery = "activity_id"
query = "id>?"
args = "0"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
upResult, err := d.OfflineActivityGetUpBonusResultSelect(c, selectQuery, query, args)
ctx.Convey("Then err should be nil.upResult should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(upResult, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoOfflineActivityGetUpBonusByActivityResult(t *testing.T) {
convey.Convey("OfflineActivityGetUpBonusByActivityResult", t, func(ctx convey.C) {
var (
c = context.Background()
limit = int(10)
offset = int(0)
mid = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
upResult, totalCount, err := d.OfflineActivityGetUpBonusByActivityResult(c, limit, offset, mid)
ctx.Convey("Then err should be nil.upResult,totalCount should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(totalCount, convey.ShouldNotBeNil)
ctx.So(upResult, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoOfflineActivityGetDB(t *testing.T) {
convey.Convey("OfflineActivityGetDB", t, func(ctx convey.C) {
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := d.OfflineActivityGetDB()
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoUpdateActivityState(t *testing.T) {
convey.Convey("UpdateActivityState", t, func(ctx convey.C) {
var (
c = context.Background()
activityID = int64(10)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
affectedRow, err := d.UpdateActivityState(c, activityID)
ctx.Convey("Then err should be nil.affectedRow should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(affectedRow, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,64 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
"go_test",
)
go_library(
name = "go_default_library",
srcs = [
"account.go",
"article_category.go",
"resource.go",
"video_category.go",
"vip.go",
],
importpath = "go-common/app/admin/main/growup/dao/resource",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/admin/main/growup/conf:go_default_library",
"//app/admin/main/growup/model:go_default_library",
"//app/admin/main/growup/util:go_default_library",
"//app/service/main/account/api:go_default_library",
"//app/service/main/vip/model:go_default_library",
"//app/service/main/vip/rpc/client:go_default_library",
"//library/ecode:go_default_library",
"//library/log:go_default_library",
"//library/net/http/blademaster:go_default_library",
"//vendor/github.com/pkg/errors:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)
go_test(
name = "go_default_test",
srcs = [
"account_test.go",
"article_category_test.go",
"resource_test.go",
"video_category_test.go",
"vip_test.go",
],
embed = [":go_default_library"],
tags = ["automanaged"],
deps = [
"//app/admin/main/growup/conf:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
],
)

View File

@@ -0,0 +1,56 @@
package resource
import (
"context"
accgrpc "go-common/app/service/main/account/api"
"go-common/library/ecode"
"go-common/library/log"
)
// MidByNickname .
func MidByNickname(c context.Context, name string) (mid int64, err error) {
reply, err := accCli.InfosByName3(c, &accgrpc.NamesReq{Names: []string{name}})
if err != nil || reply == nil {
log.Error("accCli.InfosByName3 name(%s) err(%v)", name, err)
err = ecode.CreativeAccServiceErr
return
}
if reply.Infos != nil {
for k := range reply.Infos {
mid = k
}
}
return
}
// NamesByMIDs .
func NamesByMIDs(c context.Context, mids []int64) (res map[int64]string, err error) {
reply, err := accCli.Infos3(c, &accgrpc.MidsReq{Mids: mids})
if err != nil || reply == nil {
log.Error("accCli.NamesByMIDs mids(%v) err(%v)", mids, err)
err = ecode.CreativeAccServiceErr
return
}
if reply.Infos != nil {
res = make(map[int64]string, len(reply.Infos))
for mid, info := range reply.Infos {
res[mid] = info.Name
}
}
return
}
// NameByMID .
func NameByMID(c context.Context, mid int64) (nickname string, err error) {
reply, err := accCli.Info3(c, &accgrpc.MidReq{Mid: mid})
if err != nil || reply == nil {
log.Error("accCli.Info3 mid(%d) err(%v)", mid, err)
err = ecode.CreativeAccServiceErr
return
}
if reply.Info != nil {
nickname = reply.Info.Name
}
return
}

View File

@@ -0,0 +1,56 @@
package resource
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestResourceMidByNickname(t *testing.T) {
convey.Convey("MidByNickname", t, func(ctx convey.C) {
var (
c = context.Background()
name = "name"
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
mid, err := MidByNickname(c, name)
ctx.Convey("Then err should be nil.mid should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(mid, convey.ShouldNotBeNil)
})
})
})
}
func TestResourceNamesByMIDs(t *testing.T) {
convey.Convey("NamesByMIDs", t, func(ctx convey.C) {
var (
c = context.Background()
mids = []int64{1, 2}
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
res, err := NamesByMIDs(c, mids)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestResourceNameByMID(t *testing.T) {
convey.Convey("NameByMID", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(1)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
nickname, err := NameByMID(c, mid)
ctx.Convey("Then err should be nil.nickname should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(nickname, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,51 @@
package resource
import (
"context"
"go-common/library/ecode"
"go-common/library/log"
)
// ColumnInfo column category
type columnInfo struct {
ID int64 `json:"id"`
PID int64 `json:"parent_id"`
Name string `json:"name"`
}
// ColumnCategory get column types.
func columnCategory(c context.Context) (data []*columnInfo, err error) {
var res struct {
Code int `json:"code"`
Message string `json:"message"`
Data []*columnInfo `json:"data"`
}
url := articleCategoryURL
if err = client.Get(c, url, "", nil, &res); err != nil {
log.Error("resource.columnCategory GET error(%v) | uri(%s)", err, url)
return
}
if res.Code != 0 {
log.Error("resource.columnCategory code != 0. res.Code(%d) | uri(%s) res(%v)", res.Code, url, res)
err = ecode.GrowupGetTypeError
return
}
data = res.Data
return
}
// ColumnCategoryNameToID .
func ColumnCategoryNameToID(c context.Context) (categories map[string]int64, err error) {
data, err := columnCategory(c)
if err != nil {
return
}
categories = make(map[string]int64, len(data))
for _, v := range data {
if v.PID == 0 {
categories[v.Name] = v.ID
}
}
return
}

View File

@@ -0,0 +1,38 @@
package resource
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestResourcecolumnCategory(t *testing.T) {
convey.Convey("columnCategory", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
data, err := columnCategory(c)
ctx.Convey("Then err should be nil.data should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(data, convey.ShouldNotBeNil)
})
})
})
}
func TestResourceColumnCategoryNameToID(t *testing.T) {
convey.Convey("ColumnCategoryNameToID", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
categories, err := ColumnCategoryNameToID(c)
ctx.Convey("Then err should be nil.categories should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(categories, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,30 @@
package resource
import (
"go-common/app/admin/main/growup/conf"
accgrpc "go-common/app/service/main/account/api"
vip "go-common/app/service/main/vip/rpc/client"
httpx "go-common/library/net/http/blademaster"
"github.com/pkg/errors"
)
var (
vipRPC *vip.Service
client *httpx.Client
accCli accgrpc.AccountClient
videoCategoryURL string
articleCategoryURL string
)
// Init .
func Init(c *conf.Config) {
var err error
vipRPC = vip.New(c.VipRPC)
client = httpx.NewClient(c.HTTPClient)
videoCategoryURL = c.Host.VideoType + "/videoup/types"
articleCategoryURL = c.Host.ColumnType + "/x/article/categories"
if accCli, err = accgrpc.NewClient(c.Account); err != nil {
panic(errors.WithMessage(err, "Failed to dial account service"))
}
}

View File

@@ -0,0 +1,31 @@
package resource
import (
"flag"
"os"
"testing"
"go-common/app/admin/main/growup/conf"
)
func TestMain(m *testing.M) {
if os.Getenv("DEPLOY_ENV") != "" {
flag.Set("app_id", "mobile.studio.growup-admin")
flag.Set("conf_token", "ac1fd397cbc33eb60541e8734844bdd5")
flag.Set("tree_id", "13583")
flag.Set("conf_version", "docker-1")
flag.Set("deploy_env", "uat")
flag.Set("conf_host", "config.bilibili.co")
flag.Set("conf_path", "/tmp")
flag.Set("region", "sh")
flag.Set("zone", "sh001")
} else {
flag.Set("conf", "../../cmd/growup-admin.toml")
}
flag.Parse()
if err := conf.Init(); err != nil {
panic(err)
}
Init(conf.Conf)
os.Exit(m.Run())
}

View File

@@ -0,0 +1,65 @@
package resource
import (
"context"
"go-common/library/ecode"
"go-common/library/log"
)
// videoInfo video category
type videoInfo struct {
ID int64 `json:"id"`
PID int64 `json:"pid"`
Name string `json:"name"`
}
func videoCategory(c context.Context) (data map[int16]videoInfo, err error) {
var res struct {
Code int `json:"code"`
Message string `json:"message"`
Data map[int16]videoInfo `json:"data"`
}
url := videoCategoryURL
if err = client.Get(c, url, "", nil, &res); err != nil {
log.Error("resource.videoCategory GET error(%v) | uri(%s)", err, url)
return
}
if res.Code != 0 {
log.Error("resource.videoCategory code != 0. res.Code(%d) | uri(%s) res(%v)", res.Code, url, res)
err = ecode.GrowupGetTypeError
return
}
data = res.Data
return
}
// VideoCategoryIDToName .
func VideoCategoryIDToName(c context.Context) (res map[int64]string, err error) {
data, err := videoCategory(c)
if err != nil {
return
}
res = make(map[int64]string, len(data))
for _, v := range data {
if v.PID == 0 {
res[v.ID] = v.Name
}
}
return
}
// VideoCategoryNameToID .
func VideoCategoryNameToID(c context.Context) (res map[string]int64, err error) {
data, err := videoCategory(c)
if err != nil {
return
}
res = make(map[string]int64, len(data))
for _, v := range data {
if v.PID == 0 {
res[v.Name] = v.ID
}
}
return
}

View File

@@ -0,0 +1,53 @@
package resource
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestResourcevideoCategory(t *testing.T) {
convey.Convey("videoCategory", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
data, err := videoCategory(c)
ctx.Convey("Then err should be nil.data should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(data, convey.ShouldNotBeNil)
})
})
})
}
func TestResourceVideoCategoryIDToName(t *testing.T) {
convey.Convey("VideoCategoryIDToName", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
res, err := VideoCategoryIDToName(c)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestResourceVideoCategoryNameToID(t *testing.T) {
convey.Convey("VideoCategoryNameToID", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
res, err := VideoCategoryNameToID(c)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,36 @@
package resource
import (
"context"
"go-common/app/admin/main/growup/model"
"go-common/app/admin/main/growup/util"
vip "go-common/app/service/main/vip/model"
"go-common/library/log"
)
const _panelType = "incentive"
// VipProducts returns <vipProductID, goodsInfo> pairs
func VipProducts(c context.Context) (r map[string]*model.GoodsInfo, err error) {
res, err := vipRPC.VipPanelInfo5(c, &vip.ArgPanel{PanelType: _panelType})
if err != nil {
log.Error("VipPanelInfo5 err(%v)", err)
return
}
r = make(map[string]*model.GoodsInfo, len(res.Vps))
for _, v := range res.Vps {
r[v.PdID] = &model.GoodsInfo{
// vip商品唯一标识
ProductID: v.PdID,
// vip商品名称
ProductName: v.PdName,
// 大会员实时价格 = 激励兑换商品的实时成本价; 单位元转换为单位分
OriginPrice: int64(util.MulWithRound(v.DPrice, float64(100), 0)),
// vip会员时长
Month: v.Month,
}
}
return
}

View File

@@ -0,0 +1,23 @@
package resource
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestResourceVipProducts(t *testing.T) {
convey.Convey("VipProducts", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
r, err := VipProducts(c)
ctx.Convey("Then err should be nil.r should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(r, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,52 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
"go_test",
)
go_library(
name = "go_default_library",
srcs = [
"shellrequest.go",
"sign.go",
],
importpath = "go-common/app/admin/main/growup/dao/shell",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/admin/main/growup/conf:go_default_library",
"//library/log:go_default_library",
"//library/net/http/blademaster:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)
go_test(
name = "go_default_test",
srcs = [
"shellrequest_test.go",
"sign_test.go",
],
embed = [":go_default_library"],
tags = ["automanaged"],
deps = [
"//app/admin/main/growup/conf:go_default_library",
"//library/net/http/blademaster:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
],
)

View File

@@ -0,0 +1,242 @@
package shell
import (
"bytes"
"context"
"encoding/json"
"fmt"
"go-common/app/admin/main/growup/conf"
"go-common/library/log"
"go-common/library/net/http/blademaster"
"net/http"
)
//SignInterface set signature
type SignInterface interface {
SetSign(sign string)
SetCustomerID(customerID string)
SetSignType(signType string)
}
//OrderInfo order info
type OrderInfo struct {
Brokerage string `json:"brokerage"`
Mid int64 `json:"mid"`
ThirdCoin string `json:"thirdCoin"`
ThirdCtime string `json:"thirdCtime"`
ThirdOrderNo string `json:"thirdOrderNo"`
}
//OrderRequest shell order request
type OrderRequest struct {
CustomerID string `json:"customerId"`
ProductName string `json:"productName"`
Data []OrderInfo `json:"data"`
NotifyURL string `json:"notifyUrl"`
Rate string `json:"rate"`
SignType string `json:"signType"`
Timestamp string `json:"timestamp"`
Sign string `json:"sign,omitempty"`
}
//SetSign set sign
func (o *OrderRequest) SetSign(sign string) {
o.Sign = sign
}
//SetCustomerID set customId
func (o *OrderRequest) SetCustomerID(customerID string) {
o.CustomerID = customerID
}
//SetSignType set signtype
func (o *OrderRequest) SetSignType(signType string) {
o.SignType = signType
}
//OrderResponse shell order response
type OrderResponse struct {
Errno int `json:"errno"`
Msg string `json:"msg"`
}
const (
//CallbackStatusCreate 创建中状态
CallbackStatusCreate = "CREATE"
//CallbackStatusSuccess 成功
CallbackStatusSuccess = "SUCCESS"
//CallbackStatusFail 失败
CallbackStatusFail = "FAIL"
)
//OrderCallbackJSON MsgContent in OrderCallbackParam
type OrderCallbackJSON struct {
CustomerID string `json:"customerId"`
Status string `json:"status"`
ThirdOrderNo string `json:"thirdOrderNo"`
Mid string `json:"mid"`
Ext json.RawMessage `json:"ext"`
Timestamp string `json:"timestamp"`
SignType string `json:"signType"`
Sign string `json:"sign"`
}
//IsSuccess success
func (o *OrderCallbackJSON) IsSuccess() bool {
return o.Status == CallbackStatusSuccess
}
//IsFail fail
func (o *OrderCallbackJSON) IsFail() bool {
return o.Status == CallbackStatusFail
}
//IsCreate creating
func (o *OrderCallbackJSON) IsCreate() bool {
return o.Status == CallbackStatusCreate
}
//OrderCallbackParam call back url param
type OrderCallbackParam struct {
MsgID string `form:"msgId"`
MsgContent string `form:"msgContent"`
}
//OrderCheckRequest request
type OrderCheckRequest struct {
Sign string `json:"sign,omitempty"`
SignType string `json:"signType"`
CustomerID string `json:"customerId"`
Timestamp int64 `json:"timestamp"`
ThirdOrderNos string `json:"thirdOrderNos"`
}
//SetSign set sign
func (o *OrderCheckRequest) SetSign(sign string) {
o.Sign = sign
}
//SetCustomerID set customer id
func (o *OrderCheckRequest) SetCustomerID(customerID string) {
o.CustomerID = customerID
}
//SetSignType set sign type, always "MD5"
func (o *OrderCheckRequest) SetSignType(signType string) {
o.SignType = signType
}
//OrderStatusData call back data
type OrderStatusData struct {
ThirdOrderNo string `json:"thirdOrderNo"`
Status string `json:"status"`
Mid string `json:"mid"`
}
//IsSuccess is successful
func (o *OrderStatusData) IsSuccess() bool {
return o.Status == CallbackStatusSuccess
}
//OrderCheckResponse response
type OrderCheckResponse struct {
Errno int `json:"errno"`
Msg string `json:"msg"`
Orders []OrderStatusData `json:"data"`
}
//Client shell client
type Client struct {
conf conf.ShellConfig
CustomID string
Token string
HTTPClient *blademaster.Client
isDebug bool
}
//New client
func New(conf *conf.ShellConfig, httpClient *blademaster.Client) *Client {
return &Client{
CustomID: conf.CustomID,
Token: conf.Token,
HTTPClient: httpClient,
conf: *conf,
}
}
//SetDebug set debug
func (s *Client) SetDebug(isDebug bool) {
s.isDebug = isDebug
}
//SendOrderRequest send order rquest
func (s *Client) SendOrderRequest(ctx context.Context, req *OrderRequest) (res *OrderResponse, err error) {
var host = s.conf.PayHost
if host == "" {
host = "pay.bilibili.co"
}
var url = "http://" + host + "/bk-int/brokerage/rechargeBrokerage"
res = &OrderResponse{}
err = s.SendShellRequest(ctx, url, req, res)
if err != nil {
log.Error("send order request fail, err=%s", err)
}
return
}
//SendCheckOrderRequest send check order request
func (s *Client) SendCheckOrderRequest(ctx context.Context, req *OrderCheckRequest) (res *OrderCheckResponse, err error) {
var host = s.conf.PayHost
if host == "" {
host = "pay.bilibili.co"
}
var url = "http://" + host + "/bk-int/brokerage/queryRechargeBrokerage"
res = &OrderCheckResponse{}
err = s.SendShellRequest(ctx, url, req, res)
if err != nil {
log.Error("send check order request fail, err=%s", err)
}
return
}
//SendShellRequest send request
func (s *Client) SendShellRequest(ctx context.Context, url string, req interface{}, res interface{}) (err error) {
r, ok := req.(SignInterface)
if !ok {
err = fmt.Errorf("cast fail, req is not SignInterface")
return
}
r.SetSignType("MD5")
r.SetCustomerID(s.CustomID)
sign, err := Sign(r, s.Token)
if err != nil {
return
}
r.SetSign(sign)
jsonStr, err := json.Marshal(r)
if s.isDebug {
log.Info("send request, url=%s, req=%s", url, jsonStr)
}
if err != nil {
return
}
if err != nil {
return
}
var buffer = bytes.NewBuffer(jsonStr)
httpreq, _ := http.NewRequest("POST", url, buffer)
httpreq.Header.Set("Content-Type", "application/json")
bs, err := s.HTTPClient.Raw(ctx, httpreq)
if s.isDebug {
log.Info("req=%s, response=%s", jsonStr, bs)
}
if err != nil {
log.Error("get response err, err=%s, response=%s", err, string(bs))
return
}
if err = json.Unmarshal(bs, res); err != nil {
log.Error("json decode err, response=%s", string(bs))
}
return
}

View File

@@ -0,0 +1,208 @@
package shell
import (
"context"
"flag"
"os"
"testing"
"go-common/app/admin/main/growup/conf"
"go-common/library/net/http/blademaster"
"github.com/smartystreets/goconvey/convey"
)
var (
client *Client
)
func TestMain(m *testing.M) {
if os.Getenv("DEPLOY_ENV") != "" {
flag.Set("app_id", "mobile.studio.growup-admin")
flag.Set("conf_token", "ac1fd397cbc33eb60541e8734844bdd5")
flag.Set("tree_id", "13583")
flag.Set("conf_version", "docker-1")
flag.Set("deploy_env", "uat")
flag.Set("conf_host", "config.bilibili.co")
flag.Set("conf_path", "/tmp")
flag.Set("region", "sh")
flag.Set("zone", "sh001")
} else {
flag.Set("conf", "../../cmd/growup-admin.toml")
}
flag.Parse()
if err := conf.Init(); err != nil {
panic(err)
}
client = New(conf.Conf.ShellConf, blademaster.NewClient(conf.Conf.HTTPClient))
os.Exit(m.Run())
}
func TestShellSetSign(t *testing.T) {
convey.Convey("SetSign", t, func(ctx convey.C) {
var (
sign = "abc"
o = OrderRequest{}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
o.SetSign(sign)
ctx.Convey("No return values", func(ctx convey.C) {
})
})
})
}
func TestShellSetCustomerID(t *testing.T) {
convey.Convey("SetCustomerID", t, func(ctx convey.C) {
var (
customerID = "111"
o = OrderRequest{}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
o.SetCustomerID(customerID)
ctx.Convey("No return values", func(ctx convey.C) {
})
})
})
}
func TestShellSetSignType(t *testing.T) {
convey.Convey("SetSignType", t, func(ctx convey.C) {
var (
signType = "111"
o = OrderRequest{}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
o.SetSignType(signType)
ctx.Convey("No return values", func(ctx convey.C) {
})
})
})
}
func TestShellIsSuccess(t *testing.T) {
convey.Convey("IsSuccess", t, func(ctx convey.C) {
var (
o = OrderCallbackJSON{}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := o.IsSuccess()
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestShellIsFail(t *testing.T) {
convey.Convey("IsFail", t, func(ctx convey.C) {
var (
o = OrderCallbackJSON{}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := o.IsFail()
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestShellIsCreate(t *testing.T) {
convey.Convey("IsCreate", t, func(ctx convey.C) {
var (
o = OrderCallbackJSON{}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := o.IsCreate()
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestShellNew(t *testing.T) {
convey.Convey("New", t, func(ctx convey.C) {
var (
conf = &conf.ShellConfig{}
httpClient = &blademaster.Client{}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := New(conf, httpClient)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestShellSetDebug(t *testing.T) {
convey.Convey("SetDebug", t, func(ctx convey.C) {
var (
isDebug = true
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
client.SetDebug(isDebug)
ctx.Convey("No return values", func(ctx convey.C) {
})
})
})
}
func TestShellSendOrderRequest(t *testing.T) {
convey.Convey("SendOrderRequest", t, func(ctx convey.C) {
var (
c = context.Background()
req = &OrderRequest{
CustomerID: "1001",
ProductName: "test",
NotifyURL: "test",
Rate: "1",
SignType: "test",
Timestamp: "test",
Sign: "test",
}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := client.SendOrderRequest(c, req)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestShellSendCheckOrderRequest(t *testing.T) {
convey.Convey("SendCheckOrderRequest", t, func(ctx convey.C) {
var (
c = context.Background()
req = &OrderCheckRequest{}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := client.SendCheckOrderRequest(c, req)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestShellSendShellRequest(t *testing.T) {
convey.Convey("SendShellRequest", t, func(ctx convey.C) {
var (
c = context.Background()
url = "localhost:8080"
req = interface{}(0)
res = interface{}(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := client.SendShellRequest(c, url, req, res)
ctx.Convey("Then err should be not nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,264 @@
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package shell implements calculate signature for shell(pay system) query parameters.
//
// As a simple example:
//
// type Options struct {
// Query string `json:"q"`
// ShowAll bool `json:"all"`
// Page int `json:"page,omitempty"`
// }
// use json tags
//
package shell
import (
"bytes"
"crypto/md5"
"fmt"
"io"
"net/url"
"reflect"
"sort"
"strconv"
"strings"
"time"
)
var timeType = reflect.TypeOf(time.Time{})
//var encoderType = reflect.TypeOf(new(Encoder)).Elem()
// Encoder is an interface implemented by any type that wishes to encode
// itself into URL values in a non-standard way.
type Encoder interface {
EncodeValues(key string, v *url.Values) error
}
//Sign sign for shell request
func Sign(v interface{}, token string) (sign string, err error) {
var param string
param, err = Encode(v)
if err != nil {
return
}
var final = param + "&token=" + token
var h = md5.New()
io.WriteString(h, final)
var result = h.Sum(nil)
sign = fmt.Sprintf("%x", result)
return
}
// Encode encode with dictinary ascending order
func Encode(v interface{}) (res string, err error) {
val := reflect.ValueOf(v)
for val.Kind() == reflect.Ptr {
if val.IsNil() {
return "", nil
}
val = val.Elem()
}
if v == nil {
return "", nil
}
if val.Kind() != reflect.Struct {
return "", fmt.Errorf("query: Values() expects struct input. Got %v", val.Kind())
}
res, err = encodeValue(val, tagOptions{}, 0)
return
}
// encodeValue populates the values parameter from the struct fields in val.
// Embedded structs are followed recursively (using the rules defined in the
// Values function documentation) breadth-first.
func encodeValue(val reflect.Value, opts tagOptions, deep int) (res string, err error) {
typ := val.Type()
switch typ.Kind() {
case reflect.Struct:
return encodeStruct(val, deep+1)
case reflect.Slice, reflect.Array:
return encodeSlice(val, opts, deep+1)
default:
res = valueString(val, opts)
}
return
}
func encodeSlice(val reflect.Value, opts tagOptions, deep int) (res string, err error) {
var del byte = ','
if opts.Contains("comma") {
del = ','
} else if opts.Contains("space") {
del = ' '
} else if opts.Contains("semicolon") {
del = ';'
}
s := new(bytes.Buffer)
first := true
for i := 0; i < val.Len(); i++ {
if first {
first = false
} else {
s.WriteByte(del)
}
var r string
r, err = encodeValue(val.Index(i), opts, deep)
if err != nil {
return
}
s.WriteString(r)
}
return "[" + s.String() + "]", nil
}
func encodeStruct(val reflect.Value, deep int) (res string, err error) {
var values = make(url.Values)
typ := val.Type()
for i := 0; i < typ.NumField(); i++ {
sf := typ.Field(i)
if sf.PkgPath != "" && !sf.Anonymous { // unexported
continue
}
sv := val.Field(i)
tag := sf.Tag.Get("json")
if tag == "-" {
continue
}
name, opts := parseTag(tag)
if opts.Contains("omitempty") && isEmptyValue(sv) {
continue
}
for sv.Kind() == reflect.Ptr {
if sv.IsNil() {
break
}
sv = sv.Elem()
}
var r string
r, err = encodeValue(sv, opts, deep)
if err != nil {
return
}
values.Add(name, r)
}
if deep > 1 {
res = "{" + encode(values) + "}"
} else {
res = encode(values)
}
return res, nil
}
// valueString returns the string representation of a value.
func valueString(v reflect.Value, opts tagOptions) string {
for v.Kind() == reflect.Ptr {
if v.IsNil() {
return ""
}
v = v.Elem()
}
if v.Kind() == reflect.Bool && opts.Contains("int") {
if v.Bool() {
return "1"
}
return "0"
}
if v.Type() == timeType {
t := v.Interface().(time.Time)
if opts.Contains("unix") {
return strconv.FormatInt(t.Unix(), 10)
}
return t.Format(time.RFC3339)
}
return fmt.Sprint(v.Interface())
}
// tagOptions is the string following a comma in a struct field's "url" tag, or
// the empty string. It does not include the leading comma.
type tagOptions []string
// parseTag splits a struct field's url tag into its name and comma-separated
// options.
func parseTag(tag string) (string, tagOptions) {
s := strings.Split(tag, ",")
return s[0], s[1:]
}
// Contains checks whether the tagOptions contains the specified option.
func (o tagOptions) Contains(option string) bool {
for _, s := range o {
if s == option {
return true
}
}
return false
}
func encode(v url.Values) string {
if v == nil {
return ""
}
var buf bytes.Buffer
keys := make([]string, 0, len(v))
for k := range v {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
vs := v[k]
prefix := escape(k) + "="
for _, v := range vs {
if buf.Len() > 0 {
buf.WriteByte('&')
}
buf.WriteString(prefix)
buf.WriteString(escape(v))
}
}
return buf.String()
}
func escape(s string) string {
return s
}
// isEmptyValue checks if a value should be considered empty for the purposes
// of omitting fields with the "omitempty" option.
func isEmptyValue(v reflect.Value) bool {
switch v.Kind() {
case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
return v.Len() == 0
case reflect.Bool:
return !v.Bool()
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return v.Int() == 0
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return v.Uint() == 0
case reflect.Float32, reflect.Float64:
return v.Float() == 0
case reflect.Interface, reflect.Ptr:
return v.IsNil()
}
if v.Type() == timeType {
return v.Interface().(time.Time).IsZero()
}
return false
}

View File

@@ -0,0 +1,42 @@
package shell
import (
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoSign(t *testing.T) {
convey.Convey("Sign", t, func(ctx convey.C) {
var (
v struct {
Name string
}
token = "abc"
)
v.Name = "aaa"
ctx.Convey("When everything goes positive", func(ctx convey.C) {
_, err := Sign(v, token)
ctx.Convey("Then err should be nil.id should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoEncode(t *testing.T) {
convey.Convey("Encode", t, func(ctx convey.C) {
var (
v struct {
Name string
}
)
v.Name = "aaa"
ctx.Convey("When everything goes positive", func(ctx convey.C) {
_, err := Encode(v)
ctx.Convey("Then err should be nil.id should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}

View File

@@ -0,0 +1,481 @@
package dao
import (
"context"
"fmt"
"go-common/app/admin/main/growup/model"
"go-common/library/database/sql"
"go-common/library/log"
"go-common/library/xstr"
)
const (
_addAwardSQL = `INSERT INTO special_award
(award_id,award_name,cycle_start,cycle_end,announce_date,display_status,total_quota,total_bonus,open_status,open_time,created_by)
VALUES (%d,'%s','%s','%s','%s',?,?,?,1,'%s','%s')`
_updateAwardSQL = "UPDATE special_award SET %s WHERE award_id=?"
_queryAwardSQL = `SELECT id,award_id,award_name,cycle_start,cycle_end,announce_date,display_status,total_quota,total_bonus,open_status,open_time,created_by,ctime FROM special_award`
_pageListAwardSQL = _queryAwardSQL + " ORDER BY id LIMIT ?,?"
_selectAwardSQL = _queryAwardSQL + " WHERE award_id=?"
_selectAwardForUpdateSQL = _queryAwardSQL + " WHERE award_id=? FOR UPDATE"
_listDivisionSQL = "SELECT award_id,division_id,division_name,tag_id FROM special_award_division WHERE %s AND is_deleted=0"
_listPrizeSQL = "SELECT award_id,prize_id,bonus,quota FROM special_award_prize WHERE award_id = ? AND is_deleted=0"
_listWinnerSQL = "SELECT mid,division_id,prize_id,tag_id FROM special_award_winner WHERE award_id = ? AND is_deleted=0 %s"
_listRecordSQL = "SELECT award_id,mid,tag_id FROM special_award_record WHERE award_id = ? AND is_deleted=0 %s"
_listResourceSQL = "SELECT resource_type,resource_index,content FROM special_award_resource WHERE award_id=? AND is_deleted=0"
_groupCountWinnerSQL = "SELECT award_id, count(distinct mid) from special_award_winner where %s AND is_deleted=0 GROUP BY award_id"
_countWinnerSQL = "SELECT COUNT(mid) from special_award_winner WHERE award_id = ? %s AND is_deleted=0"
_countAwardSQL = "SELECT COUNT(distinct award_id) from special_award"
)
// AddAward tx
func AddAward(tx *sql.Tx, awardID int64, awardName, cycleStart, cycleEnd, announceDate, openTime string,
displayStatus, totalWinner, totalBonus int, creater string) (int64, error) {
res, err := tx.Exec(fmt.Sprintf(_addAwardSQL, awardID, awardName, cycleStart, cycleEnd, announceDate, openTime, creater),
displayStatus, totalWinner, totalBonus)
if err != nil {
log.Error("dao#AddAward, tx.Exec err(%v)", err)
return 0, err
}
return res.RowsAffected()
}
// Award query
func (d *Dao) Award(c context.Context, awardID int64) (data *model.Award, err error) {
data = &model.Award{}
err = d.rddb.QueryRow(c, _selectAwardSQL, awardID).Scan(
&data.ID, &data.AwardID, &data.AwardName, &data.CycleStart, &data.CycleEnd, &data.AnnounceDate,
&data.DisplayStatus, &data.TotalQuota, &data.TotalBonus,
&data.OpenStatus, &data.OpenTime, &data.CreatedBy, &data.CTime)
if err != nil {
if err == sql.ErrNoRows {
data = nil
err = nil
return
}
log.Error("dao.Award, d.rddb.QueryRow err(%v)", err)
}
return
}
// SelectAwardForUpdate tx
func SelectAwardForUpdate(tx *sql.Tx, awardID int64) (award *model.Award, err error) {
award = &model.Award{}
err = tx.QueryRow(_selectAwardForUpdateSQL, awardID).Scan(
&award.ID, &award.AwardID, &award.AwardName, &award.CycleStart, &award.CycleEnd, &award.AnnounceDate,
&award.DisplayStatus, &award.TotalQuota, &award.TotalBonus,
&award.OpenStatus, &award.OpenTime, &award.CreatedBy, &award.CTime)
if err != nil {
if err == sql.ErrNoRows {
err = nil
award = nil
return
}
log.Error("dao.SelectAwardForUpdate awardID{%d} err(%v)", awardID, err)
}
return
}
// UpdateAward tx
func UpdateAward(tx *sql.Tx, awardID int64, values string) (int64, error) {
if values == "" {
return 0, nil
}
res, err := tx.Exec(fmt.Sprintf(_updateAwardSQL, values), awardID)
if err != nil {
log.Error("dao#UpdateAward, tx.Exec err(%v)", err)
return 0, err
}
return res.RowsAffected()
}
// Award tx query
func Award(tx *sql.Tx, awardID int64) (data *model.Award, err error) {
data = &model.Award{}
err = tx.QueryRow(_selectAwardSQL, awardID).Scan(&data.ID,
&data.AwardID, &data.AwardName, &data.CycleStart, &data.CycleEnd, &data.AnnounceDate,
&data.DisplayStatus, &data.TotalQuota, &data.TotalBonus,
&data.OpenStatus, &data.OpenTime, &data.CreatedBy, &data.CTime)
if err != nil {
if err == sql.ErrNoRows {
data = nil
err = nil
return
}
log.Error("dao.Award, tx.QueryRow err(%v)", err)
}
return
}
// ListAwardsDivision tx
func ListAwardsDivision(tx *sql.Tx, where string) (res []*model.AwardDivision, err error) {
res = make([]*model.AwardDivision, 0)
rows, err := tx.Query(fmt.Sprintf(_listDivisionSQL, where))
if err != nil {
log.Error("dao.ListAwardsDivision tx.Query where{%s} err(%v)", where, err)
return
}
defer rows.Close()
for rows.Next() {
data := &model.AwardDivision{}
if err = rows.Scan(&data.AwardID, &data.DivisionID, &data.DivisionName, &data.TagID); err != nil {
log.Error("dao.ListAwardsDivision rows.Scan where{%s} err(%v)", where, err)
return
}
res = append(res, data)
}
err = rows.Err()
return
}
// ListDivision tx
func ListDivision(tx *sql.Tx, awardID int64) (res []*model.AwardDivision, err error) {
return ListAwardsDivision(tx, fmt.Sprintf("award_id=%d", awardID))
}
// DivisionInfo tx query divisionID-to-divisionModel k-v pairs
func DivisionInfo(tx *sql.Tx, awardID int64) (res map[int64]*model.AwardDivision, err error) {
res = make(map[int64]*model.AwardDivision)
rows, err := tx.Query(fmt.Sprintf(_listDivisionSQL, fmt.Sprintf("award_id=%d", awardID)))
if err != nil {
log.Error("dao.DivisionInfo tx.Query awardID{%d} err(%v)", awardID, err)
return
}
defer rows.Close()
for rows.Next() {
data := &model.AwardDivision{}
if err = rows.Scan(&data.AwardID, &data.DivisionID, &data.DivisionName, &data.TagID); err != nil {
log.Error("dao.DivisionInfo rows.Scan awardID{%d} err(%v)", awardID, err)
return
}
res[data.DivisionID] = data
}
err = rows.Err()
return
}
// ListPrize tx
func ListPrize(tx *sql.Tx, awardID int64) (res []*model.AwardPrize, err error) {
res = make([]*model.AwardPrize, 0)
rows, err := tx.Query(_listPrizeSQL, awardID)
if err != nil {
log.Error("dao.ListPrize, tx.Query err(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
data := &model.AwardPrize{}
if err = rows.Scan(&data.AwardID, &data.PrizeID, &data.Bonus, &data.Quota); err != nil {
log.Error("dao.ListPrize, rows.Scan err(%v)", err)
return
}
res = append(res, data)
}
err = rows.Err()
return
}
// ListResource tx resource_type->resource_index->resource_content
func ListResource(tx *sql.Tx, awardID int64) (res map[int]map[int]string, err error) {
res = make(map[int]map[int]string)
rows, err := tx.Query(_listResourceSQL, awardID)
if err != nil {
log.Error("dao.ListResource, tx.Query err(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
var tp, index int
var content string
if err = rows.Scan(&tp, &index, &content); err != nil {
log.Error("dao.ListPrize, rows.Scan err(%v)", err)
return
}
if _, ok := res[tp]; !ok {
res[tp] = make(map[int]string)
}
res[tp][index] = content
}
err = rows.Err()
return
}
// PrizeInfo tx query prizeID-to-prizeModel k-v pairs
func PrizeInfo(tx *sql.Tx, awardID int64) (res map[int64]*model.AwardPrize, err error) {
res = make(map[int64]*model.AwardPrize)
rows, err := tx.Query(_listPrizeSQL, awardID)
if err != nil {
log.Error("dao.PrizeInfo, tx.Query err(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
data := &model.AwardPrize{}
if err = rows.Scan(&data.AwardID, &data.PrizeID, &data.Bonus, &data.Quota); err != nil {
log.Error("dao.PrizeInfo, rows.Scan err(%v)", err)
return
}
res[data.PrizeID] = data
}
err = rows.Err()
return
}
// CountAward tx
func CountAward(tx *sql.Tx) (total int64, err error) {
err = tx.QueryRow(_countAwardSQL).Scan(&total)
if err != nil {
log.Error("dao.CountAward, tx.Query err(%v)", err)
}
return
}
// CountAwardWinner tx
func CountAwardWinner(tx *sql.Tx, awardID int64, where string) (total int64, err error) {
err = tx.QueryRow(fmt.Sprintf(_countWinnerSQL, where), awardID).Scan(&total)
if err != nil {
log.Error("dao.CountAwardWinner, awardID(%d), where(%s) err(%v)", awardID, where, err)
}
return
}
// GroupCountAwardWinner tx query awardID-to-winnerCount k-v pairs
func GroupCountAwardWinner(tx *sql.Tx, where string) (res map[int64]int, err error) {
res = make(map[int64]int)
rows, err := tx.Query(fmt.Sprintf(_groupCountWinnerSQL, where))
if err != nil {
log.Error("dao.GroupCountAwardWinner, tx.Query err(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
var awardID int64
var winnerC int
if err = rows.Scan(&awardID, &winnerC); err != nil {
log.Error("dao.GroupCountAwardWinner, rows.Scan err(%v)", err)
return
}
res[awardID] = winnerC
}
return
}
// AwardWinnerAll tx query winnerModel list
func AwardWinnerAll(tx *sql.Tx, awardID int64) (res []*model.AwardWinner, err error) {
res = make([]*model.AwardWinner, 0)
rows, err := tx.Query(fmt.Sprintf(_listWinnerSQL, ""), awardID)
if err != nil {
log.Error("dao.AwardWinnerAll, tx.Query err(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
data := &model.AwardWinner{}
if err = rows.Scan(&data.MID, &data.DivisionID, &data.PrizeID, &data.TagID); err != nil {
log.Error("dao.AwardWinnerAll, rows.Scan err(%v)", err)
return
}
res = append(res, data)
}
err = rows.Err()
return
}
// AwardDivisionInfo .
func (d *Dao) AwardDivisionInfo(c context.Context, awardID int64) (res map[int64]*model.AwardDivision, err error) {
res = make(map[int64]*model.AwardDivision)
rows, err := d.rddb.Query(c, fmt.Sprintf(_listDivisionSQL, fmt.Sprintf("award_id=%d", awardID)))
if err != nil {
log.Error("dao.DivisionInfo tx.Query awardID{%d} err(%v)", awardID, err)
return
}
defer rows.Close()
for rows.Next() {
data := &model.AwardDivision{}
if err = rows.Scan(&data.AwardID, &data.DivisionID, &data.DivisionName, &data.TagID); err != nil {
log.Error("dao.DivisionInfo rows.Scan awardID{%d} err(%v)", awardID, err)
return
}
res[data.DivisionID] = data
}
err = rows.Err()
return
}
// ListAwardRecord .
func (d *Dao) ListAwardRecord(c context.Context, awardID int64, where string) (res []*model.AwardRecord, err error) {
res = make([]*model.AwardRecord, 0)
rows, err := d.rddb.Query(c, fmt.Sprintf(_listRecordSQL, where), awardID)
if err != nil {
log.Error("dao.ListAwardRecord, db.Query awardID(%d) where(%s) err(%v)", awardID, where, err)
return
}
defer rows.Close()
for rows.Next() {
data := &model.AwardRecord{}
if err = rows.Scan(&data.AwardID, &data.MID, &data.TagID); err != nil {
log.Error("dao.ListAwardRecord, rows.Scan awardID(%d) where(%s) err(%v)", awardID, where, err)
return
}
res = append(res, data)
}
err = rows.Err()
return
}
// QueryAwardWinner tx query mid-to-winnerModel k-v pairs
func QueryAwardWinner(tx *sql.Tx, awardID int64, where string) (res map[int64]*model.AwardWinner, err error) {
res = make(map[int64]*model.AwardWinner)
str := fmt.Sprintf(_listWinnerSQL, where)
rows, err := tx.Query(str, awardID)
if err != nil {
log.Error("dao.QueryAwardWinner, tx.Query awardID(%d) sql(%s) err(%v)", awardID, str, err)
return
}
defer rows.Close()
for rows.Next() {
data := &model.AwardWinner{}
if err = rows.Scan(&data.MID, &data.DivisionID, &data.PrizeID, &data.TagID); err != nil {
log.Error("dao.QueryAwardWinner, rows.Scan awardID(%d) sql(%s) err(%v)", awardID, str, err)
return
}
res[data.MID] = data
}
err = rows.Err()
return
}
// ListAward .
func (d *Dao) ListAward(c context.Context) (res []*model.Award, err error) {
res = make([]*model.Award, 0)
rows, err := d.rddb.Query(c, _queryAwardSQL)
if err != nil {
log.Error("dao.ListAward, db.Query err(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
data := &model.Award{}
if err = rows.Scan(
&data.ID,
&data.AwardID, &data.AwardName, &data.CycleStart, &data.CycleEnd, &data.AnnounceDate,
&data.DisplayStatus, &data.TotalQuota, &data.TotalBonus,
&data.OpenStatus, &data.OpenTime, &data.CreatedBy, &data.CTime); err != nil {
log.Error("dao.ListAward, rows.Scan err(%v)", err)
return
}
res = append(res, data)
}
err = rows.Err()
return
}
// ListAward tx
func ListAward(tx *sql.Tx, from, limit int) (res []*model.Award, err error) {
res = make([]*model.Award, 0)
rows, err := tx.Query(_pageListAwardSQL, from, limit)
if err != nil {
log.Error("dao.ListAward, db.Query err(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
data := &model.Award{}
if err = rows.Scan(&data.ID,
&data.AwardID, &data.AwardName, &data.CycleStart, &data.CycleEnd, &data.AnnounceDate,
&data.DisplayStatus, &data.TotalQuota, &data.TotalBonus,
&data.OpenStatus, &data.OpenTime, &data.CreatedBy, &data.CTime); err != nil {
log.Error("dao.ListAward, rows.Scan err(%v)", err)
return
}
res = append(res, data)
}
err = rows.Err()
return
}
// DelWinner tx
func DelWinner(tx *sql.Tx, awardID int64, where string) (rows int64, err error) {
w := fmt.Sprintf("award_id=%d %s", awardID, where)
return delDataTemplate(tx, "special_award_winner", w, "dao#DelWinner")
}
// DelWinnerAll tx
func DelWinnerAll(tx *sql.Tx, awardID int64) (int64, error) {
where := fmt.Sprintf("award_id=%d", awardID)
return delDataTemplate(tx, "special_award_winner", where, "dao#DelWinnerAll")
}
// DelDivisionAll tx
func DelDivisionAll(tx *sql.Tx, awardID int64) (int64, error) {
where := fmt.Sprintf("award_id=%d", awardID)
return delDataTemplate(tx, "special_award_division", where, "dao#DelDivisionAll")
}
// DelDivisionsExclude tx
func DelDivisionsExclude(tx *sql.Tx, awardID int64, divisionIDs []int64) (int64, error) {
where := fmt.Sprintf("award_id=%d AND division_id NOT IN (%s)", awardID, xstr.JoinInts(divisionIDs))
return delDataTemplate(tx, "special_award_division", where, "dao#DelDivisionsExclude")
}
// DelPrizeAll tx
func DelPrizeAll(tx *sql.Tx, awardID int64) (int64, error) {
where := fmt.Sprintf("award_id=%d", awardID)
return delDataTemplate(tx, "special_award_prize", where, "dao#DelPrizeAll")
}
// DelPrizesExclude tx
func DelPrizesExclude(tx *sql.Tx, awardID int64, prizeIDs []int64) (int64, error) {
where := fmt.Sprintf("award_id=%d AND prize_id NOT IN (%s)", awardID, xstr.JoinInts(prizeIDs))
return delDataTemplate(tx, "special_award_prize", where, "dao#DelPrizesExclude")
}
// DelResources tx
func DelResources(tx *sql.Tx, where string) (int64, error) {
return delDataTemplate(tx, "special_award_resource", where, "dao#DelResource")
}
// SaveWinners tx
func SaveWinners(tx *sql.Tx, fields, values string) (rows int64, err error) {
rows, err = saveDataTemplate(tx, "special_award_winner", fields, values, "dao#SaveWinners")
return
}
// SaveDivisions tx
func SaveDivisions(tx *sql.Tx, fields, values string) (rows int64, err error) {
rows, err = saveDataTemplate(tx, "special_award_division", fields, values, "dao#SaveDivision")
return
}
// SaveResource tx
func SaveResource(tx *sql.Tx, fields, values string) (rows int64, err error) {
rows, err = saveDataTemplate(tx, "special_award_resource", fields, values, "dao#SaveResource")
return
}
// SavePrizes tx
func SavePrizes(tx *sql.Tx, fields, values string) (rows int64, err error) {
rows, err = saveDataTemplate(tx, "special_award_prize", fields, values, "dao#SavePrizes")
return
}
func saveDataTemplate(tx *sql.Tx, tableName, fields, values, funcName string) (rows int64, err error) {
str := fmt.Sprintf("INSERT INTO %s(%s) VALUES %s", tableName, fields, values)
res, err := tx.Exec(str)
if err != nil {
log.Error("%s exec(%s) err(%v)", funcName, str, err)
return
}
return res.RowsAffected()
}
func delDataTemplate(tx *sql.Tx, tableName, where, funcName string) (rows int64, err error) {
str := fmt.Sprintf("UPDATE %s SET is_deleted = 1 WHERE %s", tableName, where)
res, err := tx.Exec(str)
if err != nil {
log.Error("%s exec(%s) err(%v)", funcName, str, err)
return
}
return res.RowsAffected()
}

View File

@@ -0,0 +1,534 @@
package dao
import (
"context"
"fmt"
"testing"
"time"
"github.com/smartystreets/goconvey/convey"
)
var awardID = time.Now().Unix()
func TestDaoAddAward(t *testing.T) {
convey.Convey("AddAward", t, func(ctx convey.C) {
var (
tx, _ = d.BeginTran(context.TODO())
awardName = string(time.Now().Unix())
cycleStart = time.Now().Format("2006-01-02 15:04:05")
cycleEnd = time.Now().Format("2006-01-02 15:04:05")
announceDate = time.Now().Format("2006-01-02")
openTime = time.Now().Format("2006-01-02 15:04:00")
displayStatus = int(1)
totalWinner = int(0)
totalBonus = int(0)
createdBy = "test"
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
defer tx.Commit()
p1, err := AddAward(tx, awardID, awardName, cycleStart, cycleEnd, announceDate, openTime, displayStatus, totalWinner, totalBonus, createdBy)
ctx.Convey("Then err should be nil.p1 should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoAward(t *testing.T) {
convey.Convey("Award", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
data, err := d.Award(c, awardID)
ctx.Convey("Then err should be nil.data should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(data, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoSelectAwardForUpdate(t *testing.T) {
convey.Convey("SelectAwardForUpdate", t, func(ctx convey.C) {
var (
tx, _ = d.BeginTran(context.TODO())
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
defer tx.Commit()
award, err := SelectAwardForUpdate(tx, awardID)
ctx.Convey("Then err should be nil.award should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(award, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoUpdateAward(t *testing.T) {
convey.Convey("UpdateAward", t, func(ctx convey.C) {
var (
tx, _ = d.BeginTran(context.TODO())
values = ""
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
defer tx.Commit()
p1, err := UpdateAward(tx, awardID, values)
ctx.Convey("Then err should be nil.p1 should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoTxAward(t *testing.T) {
convey.Convey("Award", t, func(ctx convey.C) {
var (
tx, _ = d.BeginTran(context.TODO())
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
defer tx.Commit()
data, err := Award(tx, awardID)
ctx.Convey("Then err should be nil.data should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(data, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoListAwardsDivision(t *testing.T) {
convey.Convey("ListAwardsDivision", t, func(ctx convey.C) {
var (
tx, _ = d.BeginTran(context.TODO())
where = fmt.Sprintf("award_id=%d", awardID)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
defer tx.Commit()
res, err := ListAwardsDivision(tx, where)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoListDivision(t *testing.T) {
convey.Convey("ListDivision", t, func(ctx convey.C) {
var (
tx, _ = d.BeginTran(context.TODO())
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
defer tx.Commit()
res, err := ListDivision(tx, awardID)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoTxDivisionInfo(t *testing.T) {
convey.Convey("DivisionInfo", t, func(ctx convey.C) {
var (
tx, _ = d.BeginTran(context.TODO())
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
defer tx.Commit()
res, err := DivisionInfo(tx, awardID)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoDivisionInfo(t *testing.T) {
convey.Convey("DivisionInfo", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
res, err := d.AwardDivisionInfo(c, awardID)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoListPrize(t *testing.T) {
convey.Convey("ListPrize", t, func(ctx convey.C) {
var (
tx, _ = d.BeginTran(context.TODO())
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
defer tx.Commit()
res, err := ListPrize(tx, awardID)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoListResource(t *testing.T) {
convey.Convey("ListResource", t, func(ctx convey.C) {
var (
tx, _ = d.BeginTran(context.TODO())
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
defer tx.Commit()
res, err := ListResource(tx, awardID)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoPrizeInfo(t *testing.T) {
convey.Convey("PrizeInfo", t, func(ctx convey.C) {
var (
tx, _ = d.BeginTran(context.TODO())
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
defer tx.Commit()
res, err := PrizeInfo(tx, awardID)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoCountAward(t *testing.T) {
convey.Convey("CountAward", t, func(ctx convey.C) {
var (
tx, _ = d.BeginTran(context.TODO())
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
defer tx.Commit()
total, err := CountAward(tx)
ctx.Convey("Then err should be nil.total should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(total, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoCountAwardWinner(t *testing.T) {
convey.Convey("CountAwardWinner", t, func(ctx convey.C) {
var (
tx, _ = d.BeginTran(context.TODO())
where = ""
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
defer tx.Commit()
total, err := CountAwardWinner(tx, awardID, where)
ctx.Convey("Then err should be nil.total should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(total, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoGroupCountAwardWinner(t *testing.T) {
convey.Convey("GroupCountAwardWinner", t, func(ctx convey.C) {
var (
tx, _ = d.BeginTran(context.TODO())
where = fmt.Sprintf("award_id=%d", awardID)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
defer tx.Commit()
res, err := GroupCountAwardWinner(tx, where)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoAwardWinnerAll(t *testing.T) {
convey.Convey("AwardWinnerAll", t, func(ctx convey.C) {
var (
tx, _ = d.BeginTran(context.TODO())
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
defer tx.Commit()
res, err := AwardWinnerAll(tx, awardID)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoListAwardRecord(t *testing.T) {
convey.Convey("ListAwardRecord", t, func(ctx convey.C) {
var (
c = context.Background()
where = ""
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
res, err := d.ListAwardRecord(c, awardID, where)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoQueryAwardWinner(t *testing.T) {
convey.Convey("QueryAwardWinner", t, func(ctx convey.C) {
var (
tx, _ = d.BeginTran(context.TODO())
where = ""
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
defer tx.Commit()
res, err := QueryAwardWinner(tx, awardID, where)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoListAward(t *testing.T) {
convey.Convey("ListAward", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
res, err := d.ListAward(c)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoTxListAward(t *testing.T) {
convey.Convey("ListAward", t, func(ctx convey.C) {
var (
tx, _ = d.BeginTran(context.TODO())
from = int(1)
limit = int(20)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
defer tx.Commit()
res, err := ListAward(tx, from, limit)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoDelDivisionAll(t *testing.T) {
convey.Convey("DelDivisionAll", t, func(ctx convey.C) {
var (
tx, _ = d.BeginTran(context.TODO())
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
defer tx.Commit()
p1, err := DelDivisionAll(tx, awardID)
ctx.Convey("Then err should be nil.p1 should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoDelWinner(t *testing.T) {
convey.Convey("DelWinner", t, func(ctx convey.C) {
var (
tx, _ = d.BeginTran(context.TODO())
where = ""
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
defer tx.Commit()
rows, err := DelWinner(tx, awardID, where)
ctx.Convey("Then err should be nil.rows should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rows, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoDelWinnerAll(t *testing.T) {
convey.Convey("DelWinnerAll", t, func(ctx convey.C) {
var (
tx, _ = d.BeginTran(context.TODO())
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
defer tx.Commit()
p1, err := DelWinnerAll(tx, awardID)
ctx.Convey("Then err should be nil.p1 should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoDelDivisionsExclude(t *testing.T) {
convey.Convey("DelDivisionsExclude", t, func(ctx convey.C) {
var (
tx, _ = d.BeginTran(context.TODO())
divisionIDs = []int64{1, 2}
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
defer tx.Commit()
p1, err := DelDivisionsExclude(tx, awardID, divisionIDs)
ctx.Convey("Then err should be nil.p1 should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoDelPrizeAll(t *testing.T) {
convey.Convey("DelPrizeAll", t, func(ctx convey.C) {
var (
tx, _ = d.BeginTran(context.TODO())
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
defer tx.Commit()
p1, err := DelPrizeAll(tx, awardID)
ctx.Convey("Then err should be nil.p1 should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoDelPrizesExclude(t *testing.T) {
convey.Convey("DelPrizesExclude", t, func(ctx convey.C) {
var (
tx, _ = d.BeginTran(context.TODO())
prizeIDs = []int64{1, 2}
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
defer tx.Commit()
p1, err := DelPrizesExclude(tx, awardID, prizeIDs)
ctx.Convey("Then err should be nil.p1 should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoDelResources(t *testing.T) {
convey.Convey("DelResources", t, func(ctx convey.C) {
var (
tx, _ = d.BeginTran(context.TODO())
where = fmt.Sprintf("award_id=%d", awardID)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
defer tx.Commit()
p1, err := DelResources(tx, where)
ctx.Convey("Then err should be nil.p1 should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoSaveWinners(t *testing.T) {
convey.Convey("SaveWinners", t, func(ctx convey.C) {
var (
tx, _ = d.BeginTran(context.TODO())
fields = "award_id,mid,division_id,prize_id,tag_id"
values = fmt.Sprintf("(%d,1,1,1,1)", awardID)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
defer tx.Commit()
rows, err := SaveWinners(tx, fields, values)
ctx.Convey("Then err should be nil.rows should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rows, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoSaveDivisions(t *testing.T) {
convey.Convey("SaveDivisions", t, func(ctx convey.C) {
var (
tx, _ = d.BeginTran(context.TODO())
fields = "award_id,division_id,division_name,tag_id"
values = fmt.Sprintf("(%d,1,'test-division-name',1)", awardID)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
defer tx.Commit()
rows, err := SaveDivisions(tx, fields, values)
ctx.Convey("Then err should be nil.rows should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rows, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoSaveResource(t *testing.T) {
convey.Convey("SaveResource", t, func(ctx convey.C) {
var (
tx, _ = d.BeginTran(context.TODO())
fields = "award_id,resource_type,resource_index,content"
values = fmt.Sprintf("(%d,1,1,'test-content')", awardID)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
defer tx.Commit()
rows, err := SaveResource(tx, fields, values)
ctx.Convey("Then err should be nil.rows should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rows, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoSavePrizes(t *testing.T) {
convey.Convey("SavePrizes", t, func(ctx convey.C) {
var (
tx, _ = d.BeginTran(context.TODO())
fields = "award_id,prize_id,bonus,quota"
values = fmt.Sprintf("(%d,1,100,100)", awardID)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
defer tx.Commit()
rows, err := SavePrizes(tx, fields, values)
ctx.Convey("Then err should be nil.rows should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rows, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,191 @@
package dao
import (
"context"
"fmt"
"go-common/app/admin/main/growup/model"
"go-common/library/database/sql"
"go-common/library/log"
)
const (
// insert
_insertTagSQL = "INSERT INTO tag_info(tag,category_id,business_id,start_at,end_at,creator,ratio,activity_id,icon,dimension,adjust_type,upload_start_time,upload_end_time) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)"
// insert tag_up_info
_inTagUpInfoSQL = "INSERT INTO tag_up_info(tag_id,mid,is_deleted) VALUES (?,?,?) ON DUPLICATE KEY UPDATE is_deleted=VALUES(is_deleted)"
// update
_updateTagInfoSQL = "UPDATE tag_info SET tag=?,category_id=?,business_id=?,start_at=?,end_at=?,ratio=?,activity_id=?,icon=?,dimension=?,adjust_type=?,upload_start_time=?,upload_end_time=? WHERE id = ?"
_updatetagStateSQL = "UPDATE tag_info SET is_deleted = ? WHERE id = ?"
_updateTagComSQL = "UPDATE tag_info SET is_common = ? WHERE id = ?"
_updateTagActivitySQL = "UPDATE tag_info set activity_id = ? WHERE id = ?"
// count(*)
_tagCntSQL = "SELECT count(*) FROM tag_info %s"
_tagUpMIDSQL = "SELECT mid FROM tag_up_info WHERE tag_id = ? AND is_deleted = ?"
// select
_tagInfoSQL = "SELECT id, tag, category_id, business_id, start_at, end_at, ctime, creator, ratio, adjust_type, is_common, activity_id, icon, is_deleted FROM tag_info WHERE id = ?"
_tagInfoByNameSQL = "SELECT id FROM tag_info WHERE tag = ? AND dimension = ? AND category_id = ? AND business_id = ?"
_tagInfosSQL = "SELECT id, tag, dimension, category_id, business_id, total_income, start_at, end_at, ctime, creator, ratio, adjust_type, is_common, is_deleted, activity_id, icon, upload_start_time, upload_end_time, ups FROM tag_info %s LIMIT ?,?"
_getNicknameSQL = "SELECT nick_name FROM up_category_info WHERE mid = ? AND is_deleted = 0"
)
// UpdateTagState mode tag is_deleted.
func (d *Dao) UpdateTagState(c context.Context, tagID int, isDeleted int) (rows int64, err error) {
res, err := d.rddb.Exec(c, _updatetagStateSQL, isDeleted, tagID)
if err != nil {
log.Error("dao.UpdateTagState error(%v)", err)
return
}
return res.RowsAffected()
}
// TxInsertTagUpInfo insert tag mid into tag_up_info
func (d *Dao) TxInsertTagUpInfo(tx *sql.Tx, tagID, mid int64, isDeleted int) (rows int64, err error) {
res, err := tx.Exec(_inTagUpInfoSQL, tagID, mid, isDeleted)
if err != nil {
return
}
return res.RowsAffected()
}
// InsertTagUpInfo insert tag mid into tag_up_info
func (d *Dao) InsertTagUpInfo(c context.Context, tagID, mid int64, isDeleted int) (rows int64, err error) {
res, err := d.rddb.Exec(c, _inTagUpInfoSQL, tagID, mid, isDeleted)
if err != nil {
return
}
return res.RowsAffected()
}
// UpdateTagCom update tag is_common
func (d *Dao) UpdateTagCom(c context.Context, tagID int, isCommon int) (rows int64, err error) {
res, err := d.rddb.Exec(c, _updateTagComSQL, isCommon, tagID)
if err != nil {
log.Error("d.rddb.Exec error(%v)", err)
return
}
return res.RowsAffected()
}
// InsertTag insert tag_info.
func (d *Dao) InsertTag(c context.Context, tag *model.TagInfo) (rows int64, err error) {
res, err := d.rddb.Exec(c, _insertTagSQL, tag.Tag, tag.Category, tag.Business, tag.StartTime, tag.EndTime, tag.Creator, tag.Ratio, tag.ActivityID, tag.Icon, tag.Dimension, tag.AdjustType, tag.UploadStartTime, tag.UploadEndTime)
if err != nil {
return
}
return res.RowsAffected()
}
// TxInsertTag insert tag_info.
func (d *Dao) TxInsertTag(tx *sql.Tx, tag *model.TagInfo) (rows int64, err error) {
res, err := tx.Exec(_insertTagSQL, tag.Tag, tag.Category, tag.Business, tag.StartTime, tag.EndTime, tag.Creator, tag.Ratio, tag.ActivityID, tag.Icon, tag.Dimension, tag.AdjustType, tag.UploadStartTime, tag.UploadEndTime)
if err != nil {
return
}
return res.RowsAffected()
}
// UpdateTagInfo update tag_info.
func (d *Dao) UpdateTagInfo(c context.Context, t *model.TagInfo) (rows int64, err error) {
res, err := d.rddb.Exec(c, _updateTagInfoSQL, t.Tag, t.Category, t.Business, t.StartTime, t.EndTime, t.Ratio, t.ActivityID, t.Icon, t.Dimension, t.AdjustType, t.UploadStartTime, t.UploadEndTime, t.ID)
if err != nil {
log.Error("growup-admin dao.UpdateTag error(%v)", err)
return
}
return res.RowsAffected()
}
// GetTagInfo get tag info by tag id.
func (d *Dao) GetTagInfo(c context.Context, tagID int) (info *model.TagInfo, err error) {
info = new(model.TagInfo)
row := d.rddb.QueryRow(c, _tagInfoSQL, tagID)
err = row.Scan(&info.ID, &info.Tag, &info.Category, &info.Business, &info.StartTime, &info.EndTime, &info.CreateTime, &info.Creator, &info.Ratio, &info.AdjustType, &info.IsCommon, &info.ActivityID, &info.Icon, &info.IsDeleted)
return
}
// GetTagInfoByName get tag info by tag name.
func (d *Dao) GetTagInfoByName(c context.Context, tag string, dimension, category, business int) (id int64, err error) {
row := d.rddb.QueryRow(c, _tagInfoByNameSQL, tag, dimension, category, business)
err = row.Scan(&id)
return
}
// TxGetTagInfoByName get tag info by tag name.
func (d *Dao) TxGetTagInfoByName(tx *sql.Tx, tag string, dimension, category, business int) (id int64, err error) {
row := tx.QueryRow(_tagInfoByNameSQL, tag, dimension, category, business)
err = row.Scan(&id)
return
}
// TagsCount get tag count
func (d *Dao) TagsCount(c context.Context, query string) (count int, err error) {
err = d.rddb.QueryRow(c, fmt.Sprintf(_tagCntSQL, query)).Scan(&count)
return
}
// GetTagInfos get tag_infos by query
func (d *Dao) GetTagInfos(c context.Context, query string, from, limit int) (tagInfos []*model.TagInfo, err error) {
tagInfos = make([]*model.TagInfo, 0)
rows, err := d.rddb.Query(c, fmt.Sprintf(_tagInfosSQL, query), from, limit)
if err != nil {
log.Error("d.rddb.Query query error(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
a := &model.TagInfo{}
if err = rows.Scan(&a.ID, &a.Tag, &a.Dimension, &a.Category, &a.Business, &a.TotalIncome, &a.StartTime, &a.EndTime, &a.CreateTime, &a.Creator, &a.Ratio, &a.AdjustType, &a.IsCommon, &a.IsDeleted, &a.ActivityID, &a.Icon, &a.UploadStartTime, &a.UploadEndTime, &a.UpCount); err != nil {
log.Error("row.Scan error (%v)", err)
return
}
tagInfos = append(tagInfos, a)
}
return
}
// GetNickname get nickname
func (d *Dao) GetNickname(c context.Context, mid int64) (nickname string, err error) {
err = d.rddb.QueryRow(c, _getNicknameSQL, mid).Scan(&nickname)
if err != nil {
if err == sql.ErrNoRows {
err = nil
return
}
log.Error("d.rddb.QueryRow.Scan error(%v)", err)
}
return
}
// GetTagUpInfoMID get all tag_up_info mids
func (d *Dao) GetTagUpInfoMID(c context.Context, tagID int64, isDeleted int) (mids map[int64]int, err error) {
mids = make(map[int64]int)
rows, err := d.rddb.Query(c, _tagUpMIDSQL, tagID, isDeleted)
if err != nil {
log.Error("d.rddb.Query query error(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
var mid int64
if err = rows.Scan(&mid); err != nil {
log.Error("row.Scan error (%v)", err)
return
}
mids[mid] = 1
}
return
}
// UpdateTagActivity update tag activity_id.
func (d *Dao) UpdateTagActivity(c context.Context, tagID, activityID int64) (rows int64, err error) {
res, err := d.rddb.Exec(c, _updateTagActivitySQL, activityID, tagID)
if err != nil {
log.Error("dao.UpdateTagActivity error(%v)", err)
return
}
return res.RowsAffected()
}

View File

@@ -0,0 +1,290 @@
package dao
import (
"context"
"go-common/app/admin/main/growup/model"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoUpdateTagState(t *testing.T) {
convey.Convey("UpdateTagState", t, func(ctx convey.C) {
var (
c = context.Background()
tagID = int(100)
isDeleted = int(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
d.Exec(c, "INSERT INTO tag_info(id, is_deleted) VALUES(100, 1) ON DUPLICATE KEY UPDATE is_deleted = 1")
rows, err := d.UpdateTagState(c, tagID, isDeleted)
ctx.Convey("Then err should be nil.rows should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rows, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoTxInsertTagUpInfo(t *testing.T) {
convey.Convey("TxInsertTagUpInfo", t, func(ctx convey.C) {
var (
tx, _ = d.BeginTran(context.Background())
tagID = int64(100)
mid = int64(1000)
isDeleted = int(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
defer tx.Commit()
d.Exec(context.Background(), "DELETE FROM tag_up_info WHERE tag_id = 100")
rows, err := d.TxInsertTagUpInfo(tx, tagID, mid, isDeleted)
ctx.Convey("Then err should be nil.rows should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rows, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoInsertTagUpInfo(t *testing.T) {
convey.Convey("InsertTagUpInfo", t, func(ctx convey.C) {
var (
c = context.Background()
tagID = int64(100)
mid = int64(1000)
isDeleted = int(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
d.Exec(c, "DELETE FROM tag_up_info WHERE tag_id = 100")
rows, err := d.InsertTagUpInfo(c, tagID, mid, isDeleted)
ctx.Convey("Then err should be nil.rows should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rows, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoUpdateTagCom(t *testing.T) {
convey.Convey("UpdateTagCom", t, func(ctx convey.C) {
var (
c = context.Background()
tagID = int(100)
isCommon = int(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
d.Exec(c, "INSERT INTO tag_info(id, is_common) VALUES(100, 0) ON DUPLICATE KEY UPDATE is_common = 1")
rows, err := d.UpdateTagCom(c, tagID, isCommon)
ctx.Convey("Then err should be nil.rows should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rows, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoInsertTag(t *testing.T) {
convey.Convey("InsertTag", t, func(ctx convey.C) {
var (
c = context.Background()
tag = &model.TagInfo{
Tag: "tt",
Category: 1,
Business: 3,
}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
d.Exec(c, "DELETE FROM tag_info WHERE tag = 'tt'")
rows, err := d.InsertTag(c, tag)
ctx.Convey("Then err should be nil.rows should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rows, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoTxInsertTag(t *testing.T) {
convey.Convey("TxInsertTag", t, func(ctx convey.C) {
var (
tx, _ = d.BeginTran(context.Background())
tag = &model.TagInfo{
Tag: "tt",
Category: 1,
Business: 3,
}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
defer tx.Commit()
d.Exec(context.Background(), "DELETE FROM tag_info WHERE tag = 'tt'")
rows, err := d.TxInsertTag(tx, tag)
ctx.Convey("Then err should be nil.rows should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rows, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoUpdateTagInfo(t *testing.T) {
convey.Convey("UpdateTagInfo", t, func(ctx convey.C) {
var (
c = context.Background()
no = &model.TagInfo{
Tag: "tt",
Category: 1,
Business: 3,
}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
rows, err := d.UpdateTagInfo(c, no)
ctx.Convey("Then err should be nil.rows should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rows, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoGetTagInfo(t *testing.T) {
convey.Convey("GetTagInfo", t, func(ctx convey.C) {
var (
c = context.Background()
tagID = int(101)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
d.Exec(c, "INSERT INTO tag_info(id, tag) VALUES(101, 'kkkkk')")
info, err := d.GetTagInfo(c, tagID)
ctx.Convey("Then err should be nil.info should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(info, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoGetTagInfoByName(t *testing.T) {
convey.Convey("GetTagInfoByName", t, func(ctx convey.C) {
var (
c = context.Background()
tag = "ppp"
dimension = int(0)
category = int(0)
business = int(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
d.Exec(c, "INSERT INTO tag_info(id, tag) VALUES(102, 'ppp')")
id, err := d.GetTagInfoByName(c, tag, dimension, category, business)
ctx.Convey("Then err should be nil.id should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(id, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoTxGetTagInfoByName(t *testing.T) {
convey.Convey("TxGetTagInfoByName", t, func(ctx convey.C) {
var (
tx, _ = d.BeginTran(context.Background())
tag = "ppp"
dimension = int(0)
category = int(0)
business = int(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
defer tx.Commit()
id, err := d.TxGetTagInfoByName(tx, tag, dimension, category, business)
ctx.Convey("Then err should be nil.id should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(id, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoTagsCount(t *testing.T) {
convey.Convey("TagsCount", t, func(ctx convey.C) {
var (
c = context.Background()
query = ""
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
count, err := d.TagsCount(c, query)
ctx.Convey("Then err should be nil.count should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(count, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoGetTagInfos(t *testing.T) {
convey.Convey("GetTagInfos", t, func(ctx convey.C) {
var (
c = context.Background()
query = ""
from = int(0)
limit = int(10)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
tagInfos, err := d.GetTagInfos(c, query, from, limit)
ctx.Convey("Then err should be nil.tagInfos should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(tagInfos, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoGetNickname(t *testing.T) {
convey.Convey("GetNickname", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(100)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
d.Exec(c, "INSERT INTO up_category_info(mid, nick_name) VALUES(100, 'tt')")
nickname, err := d.GetNickname(c, mid)
ctx.Convey("Then err should be nil.nickname should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(nickname, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoGetTagUpInfoMID(t *testing.T) {
convey.Convey("GetTagUpInfoMID", t, func(ctx convey.C) {
var (
c = context.Background()
tagID = int64(100)
isDeleted = int(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
mids, err := d.GetTagUpInfoMID(c, tagID, isDeleted)
ctx.Convey("Then err should be nil.mids should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(mids, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoUpdateTagActivity(t *testing.T) {
convey.Convey("UpdateTagActivity", t, func(ctx convey.C) {
var (
c = context.Background()
tagID = int64(102)
activityID = int64(100)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
d.Exec(c, "INSERT INTO tag_info(id, activity_id) VALUES(102, 100) ON DUPLICATE KEY UPDATE activity_id = 100")
rows, err := d.UpdateTagActivity(c, tagID, activityID)
ctx.Convey("Then err should be nil.rows should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rows, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,115 @@
package dao
import (
"context"
"fmt"
"go-common/app/admin/main/growup/model"
"go-common/library/database/sql"
"go-common/library/log"
"go-common/library/xstr"
)
// TradeDao . r/w
type TradeDao interface {
AddGoods(c context.Context, fields string, values string) (int64, error)
UpdateGoods(c context.Context, set string, where string, IDs []int64) (int64, error)
GoodsCount(c context.Context, where string) (int64, error)
GoodsList(c context.Context, where string, from, limit int) ([]*model.GoodsInfo, error)
OrderList(c context.Context, where string, from, limit int) ([]*model.OrderInfo, error)
OrderCount(c context.Context, where string) (int64, error)
}
const (
_addGoodsSQL = "INSERT INTO creative_goods(%s) VALUES %s"
_updateGoodsSQL = "UPDATE creative_goods SET %s WHERE id in (%s)"
_listGoodsSQL = "SELECT id,goods_type,ex_product_id,ex_resource_id,is_display,display_on_time,discount FROM creative_goods WHERE %s ORDER By id DESC LIMIT ?,?"
_listOrderSQL = "SELECT mid, order_no, order_time, goods_id, goods_type, goods_name, goods_price, goods_cost FROM creative_order WHERE %s ORDER BY order_time DESC LIMIT ?,?"
_countOrderSQL = "SELECT count(id) FROM creative_order WHERE %s"
_countGoodsSQL = "SELECT count(id) FROM creative_goods WHERE %s"
)
// AddGoods .
func (d *Dao) AddGoods(c context.Context, fields string, values string) (int64, error) {
rows, err := d.rddb.Exec(c, fmt.Sprintf(_addGoodsSQL, fields, values))
if err != nil {
log.Error("d.AddGoods db.Exec err(%v)", err)
return 0, err
}
return rows.RowsAffected()
}
// UpdateGoods .
func (d *Dao) UpdateGoods(c context.Context, set string, where string, IDs []int64) (int64, error) {
s := _updateGoodsSQL
if where != "" {
s = s + " AND " + where
}
rows, err := d.rddb.Exec(c, fmt.Sprintf(s, set, xstr.JoinInts(IDs)))
if err != nil {
log.Error("d.UpdateGoods db.Exec err(%v)", err)
return 0, err
}
return rows.RowsAffected()
}
// GoodsList .
func (d *Dao) GoodsList(c context.Context, where string, from, limit int) (res []*model.GoodsInfo, err error) {
res = make([]*model.GoodsInfo, 0)
rows, err := d.rddb.Query(c, fmt.Sprintf(_listGoodsSQL, where), from, limit)
if err != nil {
log.Error("d.GoodsList db.Query err(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
m := new(model.GoodsInfo)
if err = rows.Scan(&m.ID, &m.GoodsType, &m.ProductID, &m.ResourceID, &m.IsDisplay, &m.DisplayOnTime, &m.Discount); err != nil {
log.Error("d.GoodsList rows.Scan err(%v)", err)
return nil, err
}
res = append(res, m)
}
err = rows.Err()
return
}
// GoodsCount .
func (d *Dao) GoodsCount(c context.Context, where string) (total int64, err error) {
err = d.rddb.QueryRow(c, fmt.Sprintf(_countGoodsSQL, where)).Scan(&total)
if err == sql.ErrNoRows {
err = nil
}
return
}
// OrderCount .
func (d *Dao) OrderCount(c context.Context, where string) (total int64, err error) {
err = d.rddb.QueryRow(c, fmt.Sprintf(_countOrderSQL, where)).Scan(&total)
if err == sql.ErrNoRows {
err = nil
}
return
}
// OrderList .
func (d *Dao) OrderList(c context.Context, where string, from, limit int) (res []*model.OrderInfo, err error) {
res = make([]*model.OrderInfo, 0)
rows, err := d.rddb.Query(c, fmt.Sprintf(_listOrderSQL, where), from, limit)
if err != nil {
log.Error("d.OrderList db.Query err(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
v := new(model.OrderInfo)
if err = rows.Scan(&v.MID, &v.OrderNo, &v.OrderTime, &v.GoodsID, &v.GoodsType, &v.GoodsName, &v.GoodsPrice, &v.GoodsCost); err != nil {
log.Error("d.OrderList rows.Scan err(%v)", err)
return
}
res = append(res, v)
}
err = rows.Err()
return
}

View File

@@ -0,0 +1,113 @@
package dao
import (
"context"
"fmt"
"testing"
"time"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoAddGoods(t *testing.T) {
convey.Convey("AddGoods", t, func(ctx convey.C) {
var (
c = context.Background()
fields = "ex_product_id, ex_resource_id, goods_type, is_display, discount"
values = fmt.Sprintf("('%s', 1, 1, 1, 100)", time.Now().Format("2006-01-02 15:04:05"))
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1, err := d.AddGoods(c, fields, values)
ctx.Convey("Then err should be nil.p1 should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoUpdateGoods(t *testing.T) {
convey.Convey("UpdateGoods", t, func(ctx convey.C) {
var (
c = context.Background()
set = "is_display=1"
where = "is_deleted=0"
IDs = []int64{1}
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
p1, err := d.UpdateGoods(c, set, where, IDs)
ctx.Convey("Then err should be nil.p1 should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoGoodsList(t *testing.T) {
convey.Convey("GoodsList", t, func(ctx convey.C) {
var (
c = context.Background()
where = "is_deleted=0"
from = int(0)
limit = int(0)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
res, err := d.GoodsList(c, where, from, limit)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoGoodsCount(t *testing.T) {
convey.Convey("GoodsCount", t, func(ctx convey.C) {
var (
c = context.Background()
where = "is_deleted=0"
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
total, err := d.GoodsCount(c, where)
ctx.Convey("Then err should be nil.total should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(total, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoOrderCount(t *testing.T) {
convey.Convey("OrderCount", t, func(ctx convey.C) {
var (
c = context.Background()
where = "is_deleted=0"
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
total, err := d.OrderCount(c, where)
ctx.Convey("Then err should be nil.total should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(total, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoOrderList(t *testing.T) {
convey.Convey("OrderList", t, func(ctx convey.C) {
var (
c = context.Background()
where = "is_deleted=0"
from = int(0)
limit = int(0)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
res, err := d.OrderList(c, where, from, limit)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,389 @@
package dao
import (
"context"
"fmt"
"go-common/app/admin/main/growup/model"
"go-common/library/database/sql"
"go-common/library/log"
"go-common/library/time"
"go-common/library/xstr"
)
const (
// insert
_inUpsSQL = "INSERT INTO up_info_video (mid,nickname,account_type,original_archive_count,category_id,fans,account_state,sign_type,reason,is_deleted) VALUES (?,?,?,?,?,?,?,?,?,0) ON DUPLICATE KEY UPDATE nickname=?,account_type=?,original_archive_count=?,category_id=?,fans=?,account_state=?,sign_type=?,reason=?,is_deleted=0"
_inUpColumnSQL = "INSERT INTO up_info_column (mid,nickname,category_id,fans,account_type,account_state,sign_type,is_deleted) VALUES (?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE nickname=VALUES(nickname),account_type=VALUES(account_type),account_state=VALUES(account_state),category_id=VALUES(category_id),sign_type=VALUES(sign_type),is_deleted=VALUES(is_deleted)"
_inUpBgmSQL = "INSERT INTO up_info_bgm(mid,nickname,bgms,play_count,apply_count,fans,account_state,account_type,sign_type,is_deleted) VALUES(?,?,?,?,?,?,?,?,?,0) ON DUPLICATE KEY UPDATE nickname=VALUES(nickname),bgms=VALUES(bgms),play_count=VALUES(play_count),apply_count=VALUES(apply_count),fans=VALUES(fans),account_state=VALUES(account_state),account_type=VALUES(account_type),sign_type=VALUES(sign_type),is_deleted=VALUES(is_deleted)"
_inWhitelistSQL = "INSERT INTO up_white_list(mid,type) VALUES(?,?) ON DUPLICATE KEY UPDATE type=VALUES(type)"
// select
_upsCateInfoSQL = "SELECT nick_name,main_category_id FROM up_category_info WHERE mid=?"
_upsStatInfoSQL = "SELECT fans,avs FROM up_base_statistics WHERE mid=?"
_upsCountSQL = "SELECT count(*) FROM %s WHERE %s "
_upsInfoSQL = "SELECT mid,nickname,account_type,original_archive_count,category_id,fans,account_state,sign_type,reason,apply_at,signed_at,reject_at,forbid_at,quit_at,dismiss_at,expired_in,ctime,mtime,is_deleted,credit_score,total_play_count,avs FROM up_info_video WHERE %s"
_upsColumnInfoSQL = "SELECT mid,nickname,account_type,article_count,category_id,fans,account_state,sign_type,total_view_count,apply_at,signed_at,reject_at,forbid_at,quit_at,dismiss_at,expired_in FROM up_info_column WHERE %s"
_upsBgmInfoSQL = "SELECT mid,nickname,bgms,play_count,apply_count,fans,account_state,signed_at,forbid_at,quit_at,dismiss_at,expired_in FROM up_info_bgm WHERE %s"
_upInfoSQL = "SELECT mid,nickname,fans,signed_at FROM up_info_video WHERE mid=? AND account_state=? AND is_deleted=0"
_upInfoStateSQL = "SELECT mid FROM %s WHERE account_state = ? AND mid in (%s) AND is_deleted = 0"
_upStateSQL = "SELECT account_state FROM %s WHERE mid = ? AND is_deleted = 0 LIMIT 1"
_pendingsSQL = "SELECT mid FROM %s WHERE mid IN (%s) AND account_state=2 AND is_deleted=0"
_unusualSQL = "SELECT mid FROM %s WHERE mid IN (%s) AND account_state IN (5, 6, 7) AND is_deleted = 0"
_bgmCountSQL = "SELECT count(distinct sid) FROM background_music WHERE mid=?"
// update
_rejectUpsSQL = "UPDATE %s SET account_state=?,reason=?,reject_at=?,expired_in=? WHERE mid IN (%s) AND is_deleted=0"
_passUpsSQL = "UPDATE %s SET account_state=?,signed_at=? WHERE mid IN (%s) AND is_deleted = 0"
_dismissUpSQL = "UPDATE %s SET account_state=?,reason=?,dismiss_at=?,quit_at=? WHERE mid=? AND account_state=? AND is_deleted=0"
_forbidUpSQL = "UPDATE %s SET account_state=?,reason=?,forbid_at=?,expired_in=? WHERE mid=? AND account_state=? AND is_deleted=0"
_updateAccStateSQL = "UPDATE %s SET account_state=? WHERE mid = ?"
_updateUpInfoDelSQL = "UPDATE %s SET is_deleted=? WHERE mid=?"
_delUpAccountSQL = "UPDATE up_account SET is_deleted=1 WHERE mid=?"
_updateUpAccountSQL = "UPDATE up_account SET is_deleted = ?, withdraw_date_version = '%s' WHERE mid = ?"
_delCreditRecordSQL = "UPDATE credit_score_record SET is_deleted=1 WHERE id=?"
)
// InsertWhitelist insert white mid
func (d *Dao) InsertWhitelist(c context.Context, mid int64, typ int) (rows int64, err error) {
res, err := d.rddb.Exec(c, _inWhitelistSQL, mid, typ)
if err != nil {
log.Error("db.inWhitelist.Exec(%s) error(%v)", _inWhitelistSQL, err)
return
}
return res.RowsAffected()
}
// Pendings get mids for account_state=2
func (d *Dao) Pendings(c context.Context, mids []int64, table string) (ms []int64, err error) {
rows, err := d.rddb.Query(c, fmt.Sprintf(_pendingsSQL, table, xstr.JoinInts(mids)))
if err != nil {
return
}
defer rows.Close()
for rows.Next() {
var mid int64
err = rows.Scan(&mid)
if err != nil {
return
}
ms = append(ms, mid)
}
return
}
// UnusualUps get mids for account_state=5,6,7
func (d *Dao) UnusualUps(c context.Context, mids []int64, table string) (ms []int64, err error) {
ms = make([]int64, 0)
rows, err := d.rddb.Query(c, fmt.Sprintf(_unusualSQL, table, xstr.JoinInts(mids)))
if err != nil {
return
}
defer rows.Close()
for rows.Next() {
var mid int64
err = rows.Scan(&mid)
if err != nil {
return
}
ms = append(ms, mid)
}
return
}
// InsertUpVideo add upinfo video
func (d *Dao) InsertUpVideo(c context.Context, v *model.UpInfo) (rows int64, err error) {
res, err := d.rddb.Exec(c, _inUpsSQL, v.MID, v.Nickname, v.AccountType, v.OriginalArchiveCount, v.MainCategory, v.Fans, v.AccountState, v.SignType, v.Reason, v.Nickname, v.AccountType, v.OriginalArchiveCount, v.MainCategory, v.Fans, v.AccountState, v.SignType, v.Reason)
if err != nil {
log.Error("db.inUpsStmt.Exec(%s) error(%v)", _inUpsSQL, err)
return
}
return res.RowsAffected()
}
// InsertUpColumn insert up column
func (d *Dao) InsertUpColumn(c context.Context, up *model.UpInfo) (rows int64, err error) {
res, err := d.rddb.Exec(c, _inUpColumnSQL, up.MID, up.Nickname, up.MainCategory, up.Fans, up.AccountType, up.AccountState, up.SignType, 0)
if err != nil {
log.Error("db.inUpsStmt.Exec(%s) error(%v)", _inUpColumnSQL, err)
return
}
return res.RowsAffected()
}
// InsertBgmUpInfo insert up bgm
func (d *Dao) InsertBgmUpInfo(c context.Context, m *model.UpInfo) (rows int64, err error) {
res, err := d.rddb.Exec(c, _inUpBgmSQL, m.MID, m.Nickname, m.BGMs, m.BgmPlayCount, m.BgmApplyCount, m.Fans, m.AccountState, m.AccountType, m.SignType)
if err != nil {
log.Error("db.inUpsStmt.Exec(%s) error(%v)", _inUpBgmSQL, err)
return
}
return res.RowsAffected()
}
// CategoryInfo return nickname & categoryID
func (d *Dao) CategoryInfo(c context.Context, mid int64) (nickname string, categoryID int, err error) {
row := d.rddb.QueryRow(c, _upsCateInfoSQL, mid)
if err = row.Scan(&nickname, &categoryID); err != nil {
if err == sql.ErrNoRows {
err = nil
} else {
log.Error("row.Scan error(%v)", err)
}
}
return
}
// Stat return fans and avs count
func (d *Dao) Stat(c context.Context, mid int64) (fans int, avs int, err error) {
row := d.rddb.QueryRow(c, _upsStatInfoSQL, mid)
if err = row.Scan(&fans, &avs); err != nil {
if err == sql.ErrNoRows {
err = nil
} else {
log.Error("row.Scan error(%v)", err)
}
}
return
}
// UpsCount get count by query
func (d *Dao) UpsCount(c context.Context, table, query string) (count int, err error) {
row := d.rddb.QueryRow(c, fmt.Sprintf(_upsCountSQL, table, query))
err = row.Scan(&count)
return
}
// UpsVideoInfo get up infos by query
func (d *Dao) UpsVideoInfo(c context.Context, query string) (ups []*model.UpInfo, err error) {
rows, err := d.rddb.Query(c, fmt.Sprintf(_upsInfoSQL, query))
if err != nil {
return
}
defer rows.Close()
for rows.Next() {
up := &model.UpInfo{}
err = rows.Scan(&up.MID, &up.Nickname, &up.AccountType, &up.OriginalArchiveCount, &up.MainCategory, &up.Fans, &up.AccountState, &up.SignType, &up.Reason, &up.ApplyAt, &up.SignedAt, &up.RejectAt, &up.ForbidAt, &up.QuitAt, &up.DismissAt, &up.ExpiredIn, &up.CTime, &up.MTime, &up.IsDeleted, &up.CreditScore, &up.TotalPlayCount, &up.Avs)
if err != nil {
return
}
ups = append(ups, up)
}
return
}
// UpsColumnInfo get up column infos by query
func (d *Dao) UpsColumnInfo(c context.Context, query string) (ups []*model.UpInfo, err error) {
rows, err := d.rddb.Query(c, fmt.Sprintf(_upsColumnInfoSQL, query))
if err != nil {
return
}
defer rows.Close()
for rows.Next() {
up := &model.UpInfo{}
err = rows.Scan(&up.MID, &up.Nickname, &up.AccountType, &up.ArticleCount, &up.MainCategory, &up.Fans, &up.AccountState, &up.SignType, &up.TotalViewCount, &up.ApplyAt, &up.SignedAt, &up.RejectAt, &up.ForbidAt, &up.QuitAt, &up.DismissAt, &up.ExpiredIn)
if err != nil {
return
}
ups = append(ups, up)
}
return
}
// UpsBgmInfo get ups bgm infos by query
func (d *Dao) UpsBgmInfo(c context.Context, query string) (ups []*model.UpInfo, err error) {
rows, err := d.rddb.Query(c, fmt.Sprintf(_upsBgmInfoSQL, query))
if err != nil {
return
}
defer rows.Close()
for rows.Next() {
up := &model.UpInfo{}
err = rows.Scan(&up.MID, &up.Nickname, &up.BGMs, &up.BgmPlayCount, &up.BgmApplyCount, &up.Fans, &up.AccountState, &up.SignedAt, &up.ForbidAt, &up.QuitAt, &up.DismissAt, &up.ExpiredIn)
if err != nil {
return
}
ups = append(ups, up)
}
return
}
// Reject batch update reject
func (d *Dao) Reject(c context.Context, table string, state int, reason string, rejectAt, expiredIn time.Time, mids []int64) (rows int64, err error) {
res, err := d.rddb.Exec(c, fmt.Sprintf(_rejectUpsSQL, table, xstr.JoinInts(mids)), state, reason, rejectAt, expiredIn)
if err != nil {
return
}
return res.RowsAffected()
}
// Pass pass the apply
func (d *Dao) Pass(c context.Context, table string, state int, signedAt time.Time, mids []int64) (rows int64, err error) {
res, err := d.rddb.Exec(c, fmt.Sprintf(_passUpsSQL, table, xstr.JoinInts(mids)), state, signedAt)
if err != nil {
return
}
return res.RowsAffected()
}
// Dismiss dismiss up
func (d *Dao) Dismiss(c context.Context, table string, newState, oldState int, reason string, dismissAt, quitAt time.Time, mid int64) (rows int64, err error) {
res, err := d.rddb.Exec(c, fmt.Sprintf(_dismissUpSQL, table), newState, reason, dismissAt, quitAt, mid, oldState)
if err != nil {
return
}
return res.RowsAffected()
}
// TxDismiss tx dismiss up
func (d *Dao) TxDismiss(tx *sql.Tx, table string, newState, oldState int, reason string, dismissAt, quitAt time.Time, mid int64) (rows int64, err error) {
res, err := tx.Exec(fmt.Sprintf(_dismissUpSQL, table), newState, reason, dismissAt, quitAt, mid, oldState)
if err != nil {
return
}
return res.RowsAffected()
}
// Forbid forbid up
func (d *Dao) Forbid(c context.Context, table string, newState, oldState int, reason string, forbidAt, expiredIn time.Time, mid int64) (rows int64, err error) {
res, err := d.rddb.Exec(c, fmt.Sprintf(_forbidUpSQL, table), newState, reason, forbidAt, expiredIn, mid, oldState)
if err != nil {
return
}
return res.RowsAffected()
}
// TxForbid tx forbid up
func (d *Dao) TxForbid(tx *sql.Tx, table string, newState, oldState int, reason string, forbidAt, expiredIn time.Time, mid int64) (rows int64, err error) {
res, err := tx.Exec(fmt.Sprintf(_forbidUpSQL, table), newState, reason, forbidAt, expiredIn, mid, oldState)
if err != nil {
return
}
return res.RowsAffected()
}
// UpdateAccountState update up account state
func (d *Dao) UpdateAccountState(c context.Context, table string, state int, mid int64) (rows int64, err error) {
res, err := d.rddb.Exec(c, fmt.Sprintf(_updateAccStateSQL, table), state, mid)
if err != nil {
return
}
return res.RowsAffected()
}
// DelUpInfo soft delete up info
func (d *Dao) DelUpInfo(c context.Context, table string, mid int64) (rows int64, err error) {
return d.updateUpInfoDel(c, table, mid, 1)
}
// RecUpInfo recover up info from soft delete
func (d *Dao) RecUpInfo(c context.Context, table string, mid int64) (rows int64, err error) {
return d.updateUpInfoDel(c, table, mid, 0)
}
func (d *Dao) updateUpInfoDel(c context.Context, table string, mid int64, isDeleted int) (rows int64, err error) {
res, err := d.rddb.Exec(c, fmt.Sprintf(_updateUpInfoDelSQL, table), isDeleted, mid)
if err != nil {
return
}
return res.RowsAffected()
}
// DelUpAccount update mid is_deleted = 1 in up_account
func (d *Dao) DelUpAccount(c context.Context, mid int64) (rows int64, err error) {
res, err := d.rddb.Exec(c, _delUpAccountSQL, mid)
if err != nil {
return
}
return res.RowsAffected()
}
// UpdateUpAccount update up_account
func (d *Dao) UpdateUpAccount(c context.Context, mid int64, isDeleted int, withdrawDate string) (rows int64, err error) {
res, err := d.rddb.Exec(c, fmt.Sprintf(_updateUpAccountSQL, withdrawDate), isDeleted, mid)
if err != nil {
return
}
return res.RowsAffected()
}
// DelCreditRecord soft del credit record by id
func (d *Dao) DelCreditRecord(c context.Context, id int64) (rows int64, err error) {
res, err := d.rddb.Exec(c, _delCreditRecordSQL, id)
if err != nil {
log.Error("db.delCreditRecordSQL.Exec(%s) error(%v)", _delCreditRecordSQL, err)
return
}
return res.RowsAffected()
}
// TxDelCreditRecord tx soft del credit record by id
func (d *Dao) TxDelCreditRecord(tx *sql.Tx, id int64) (rows int64, err error) {
res, err := tx.Exec(_delCreditRecordSQL, id)
if err != nil {
log.Error("tx.delCreditRecordSQL.Exec(%s) error(%v)", _delCreditRecordSQL, err)
return
}
return res.RowsAffected()
}
// UpInfo get up info by account_state and mid
func (d *Dao) UpInfo(c context.Context, mid, state int64) (info *model.UpInfo, err error) {
row := d.rddb.QueryRow(c, _upInfoSQL, mid, state)
info = &model.UpInfo{}
if err = row.Scan(&info.MID, &info.Nickname, &info.Fans, &info.SignedAt); err != nil {
if err == sql.ErrNoRows {
err = nil
} else {
log.Error("row.Scan error(%v)", err)
}
}
return
}
// GetUpInfoByState get up_info by state
func (d *Dao) GetUpInfoByState(c context.Context, table string, mids []int64, state int) (info map[int64]struct{}, err error) {
info = make(map[int64]struct{})
rows, err := d.rddb.Query(c, fmt.Sprintf(_upInfoStateSQL, table, xstr.JoinInts(mids)), state)
if err != nil {
return
}
defer rows.Close()
for rows.Next() {
var mid int64
err = rows.Scan(&mid)
if err != nil {
log.Error("GetUpInfoByState rows.Scan error(%v)", err)
return
}
info[mid] = struct{}{}
}
return
}
// GetUpState get up state
func (d *Dao) GetUpState(c context.Context, table string, mid int64) (state int, err error) {
err = d.rddb.QueryRow(c, fmt.Sprintf(_upStateSQL, table), mid).Scan(&state)
if err == sql.ErrNoRows {
state = 0
err = nil
}
return
}
// BGMCount bgm count by mid
func (d *Dao) BGMCount(c context.Context, mid int64) (count int, err error) {
row := d.rddb.QueryRow(c, _bgmCountSQL, mid)
if err = row.Scan(&count); err != nil {
if err == sql.ErrNoRows {
err = nil
count = 0
} else {
log.Error("db.QueryRow(%s) error(%v)", _bgmCountSQL, err)
}
}
return
}

View File

@@ -0,0 +1,36 @@
package dao
import (
"context"
"fmt"
"go-common/app/admin/main/growup/model"
"go-common/library/log"
)
const (
// select
_upTagIncomeSQL = "SELECT id, mid, av_id, income, base_income, total_income, date, is_deleted FROM up_tag_income WHERE date = ? AND tag_id = ? %s"
)
// GetUpTagIncome get up_tag_income by query
func (d *Dao) GetUpTagIncome(c context.Context, date string, tagID int64, query string) (infos []*model.UpTagIncome, err error) {
if query != "" {
query = fmt.Sprintf("AND %s", query)
}
rows, err := d.rddb.Query(c, fmt.Sprintf(_upTagIncomeSQL, query), date, tagID)
if err != nil {
log.Error("d.rddb.Query error(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
a := &model.UpTagIncome{}
if err = rows.Scan(&a.ID, &a.MID, &a.AvID, &a.Income, &a.BaseIncome, &a.TotalIncome, &a.Date, &a.IsDeleted); err != nil {
log.Error("rows.Scan error(%v)", err)
return
}
infos = append(infos, a)
}
return
}

View File

@@ -0,0 +1,43 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoGetUpTagIncome(t *testing.T) {
convey.Convey("GetUpTagIncome", t, func(ctx convey.C) {
var (
c = context.Background()
date = "2018-01-01"
tagID = int64(11111)
query = ""
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
Exec(c, "INSERT INTO up_tag_income(tag_id, mid, av_id, date) VALUES(11111, 10, 10, '2018-01-01')")
infos, err := d.GetUpTagIncome(c, date, tagID, query)
ctx.Convey("Then err should be nil.infos should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(infos, convey.ShouldNotBeNil)
})
})
})
convey.Convey("GetUpTagIncome query error", t, func(ctx convey.C) {
var (
c = context.Background()
date = "2018-01-01"
tagID = int64(11111)
query = "AND name = 'test'"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
Exec(c, "INSERT INTO up_tag_income(tag_id, mid, av_id, date) VALUES(11111, 10, 10, '2018-01-01')")
_, err := d.GetUpTagIncome(c, date, tagID, query)
ctx.Convey("Then err should be nil.infos should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,578 @@
package dao
import (
"context"
"testing"
"time"
"go-common/app/admin/main/growup/model"
xtime "go-common/library/time"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoInsertWhitelist(t *testing.T) {
convey.Convey("InsertWhitelist", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(1001)
typ = int(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
Exec(c, "DELETE FROM up_white_list where mid = 1001")
rows, err := d.InsertWhitelist(c, mid, typ)
ctx.Convey("Then err should be nil.rows should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rows, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoPendings(t *testing.T) {
convey.Convey("Pendings", t, func(ctx convey.C) {
var (
c = context.Background()
mids = []int64{1001}
table = "up_info_video"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
Exec(c, "INSERT INTO up_info_video(mid, account_state) VALUES(1001, 2) ON DUPLICATE KEY UPDATE account_state = 2")
ms, err := d.Pendings(c, mids, table)
ctx.Convey("Then err should be nil.ms should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(ms, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoUnusualUps(t *testing.T) {
convey.Convey("UnusualUps", t, func(ctx convey.C) {
var (
c = context.Background()
mids = []int64{1002}
table = "up_info_video"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
Exec(c, "INSERT INTO up_info_video(mid, account_state) VALUES(1002, 5) ON DUPLICATE KEY UPDATE account_state = 5")
ms, err := d.UnusualUps(c, mids, table)
ctx.Convey("Then err should be nil.ms should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(ms, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoInsertUpVideo(t *testing.T) {
convey.Convey("InsertUpVideo", t, func(ctx convey.C) {
var (
c = context.Background()
now = xtime.Time(time.Now().Unix())
v = &model.UpInfo{
MID: 1003,
Nickname: "aa",
AccountType: 1,
AccountState: 1,
OriginalArchiveCount: 1,
MainCategory: 1,
Fans: 1,
SignType: 1,
Reason: "",
ApplyAt: now,
SignedAt: now,
RejectAt: now,
ForbidAt: now,
QuitAt: now,
DismissAt: now,
ExpiredIn: now,
}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
Exec(c, "DELETE FROM up_info_video WHERE mid = 1003")
rows, err := d.InsertUpVideo(c, v)
ctx.Convey("Then err should be nil.rows should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rows, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoInsertUpColumn(t *testing.T) {
convey.Convey("InsertUpColumn", t, func(ctx convey.C) {
var (
c = context.Background()
up = &model.UpInfo{
MID: 1004,
Nickname: "aa",
}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
Exec(c, "DELETE FROM up_info_column WHERE mid = 1004")
rows, err := d.InsertUpColumn(c, up)
ctx.Convey("Then err should be nil.rows should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rows, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoInsertBgmUpInfo(t *testing.T) {
convey.Convey("InsertBgmUpInfo", t, func(ctx convey.C) {
var (
c = context.Background()
m = &model.UpInfo{
MID: 1005,
AccountState: 3,
}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
Exec(c, "DELETE FROM up_info_bgm WHERE mid = 1005")
rows, err := d.InsertBgmUpInfo(c, m)
ctx.Convey("Then err should be nil.rows should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rows, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoCategoryInfo(t *testing.T) {
convey.Convey("CategoryInfo", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(1001)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
nickname, categoryID, err := d.CategoryInfo(c, mid)
Exec(c, "INSERT INTO up_category_info(mid,nick_name) VALUES(1001, 'tt')")
ctx.Convey("Then err should be nil.nickname,categoryID should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(categoryID, convey.ShouldNotBeNil)
ctx.So(nickname, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoStat(t *testing.T) {
convey.Convey("Stat", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(1001)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
Exec(c, "INSERT INTO up_base_statistics(mid, fans, avs) VALUES(1001, 10, 10)")
fans, avs, err := d.Stat(c, mid)
ctx.Convey("Then err should be nil.fans,avs should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(avs, convey.ShouldNotBeNil)
ctx.So(fans, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoUpsCount(t *testing.T) {
convey.Convey("UpsCount", t, func(ctx convey.C) {
var (
c = context.Background()
table = "up_info_video"
query = "id > 0"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
Exec(c, "INSERT INTO up_info_video(mid, account_state) VALUES(1006, 3)")
count, err := d.UpsCount(c, table, query)
ctx.Convey("Then err should be nil.count should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(count, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoUpsVideoInfo(t *testing.T) {
convey.Convey("UpsVideoInfo", t, func(ctx convey.C) {
var (
c = context.Background()
query = "id > 0"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
ups, err := d.UpsVideoInfo(c, query)
ctx.Convey("Then err should be nil.ups should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(ups, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoUpsColumnInfo(t *testing.T) {
convey.Convey("UpsColumnInfo", t, func(ctx convey.C) {
var (
c = context.Background()
query = "id > 0"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
ups, err := d.UpsColumnInfo(c, query)
ctx.Convey("Then err should be nil.ups should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(ups, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoUpsBgmInfo(t *testing.T) {
convey.Convey("UpsBgmInfo", t, func(ctx convey.C) {
var (
c = context.Background()
query = "id > 0"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
ups, err := d.UpsBgmInfo(c, query)
ctx.Convey("Then err should be nil.ups should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(ups, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoReject(t *testing.T) {
convey.Convey("Reject", t, func(ctx convey.C) {
var (
c = context.Background()
table = "up_info_video"
state = int(6)
reason = "test"
rejectAt = xtime.Time(time.Now().Unix())
expiredIn = xtime.Time(time.Now().Unix())
mids = []int64{1007}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
Exec(c, "INSERT INTO up_info_video(mid, account_state) VALUES(1007, 3) ON DUPLICATE KEY UPDATE account_state = 3")
rows, err := d.Reject(c, table, state, reason, rejectAt, expiredIn, mids)
ctx.Convey("Then err should be nil.rows should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rows, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoPass(t *testing.T) {
convey.Convey("Pass", t, func(ctx convey.C) {
var (
c = context.Background()
table = "up_info_video"
state = int(3)
signedAt = xtime.Time(time.Now().Unix())
mids = []int64{1008}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
Exec(c, "INSERT INTO up_info_video(mid, account_state) VALUES(1008, 2) ON DUPLICATE KEY UPDATE account_state = 2")
rows, err := d.Pass(c, table, state, signedAt, mids)
ctx.Convey("Then err should be nil.rows should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rows, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoDismiss(t *testing.T) {
convey.Convey("Dismiss", t, func(ctx convey.C) {
var (
c = context.Background()
table = "up_info_video"
newState = int(6)
oldState = int(3)
reason = "test"
dismissAt = xtime.Time(time.Now().Unix())
quitAt = xtime.Time(time.Now().Unix())
mid = int64(1008)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
Exec(c, "INSERT INTO up_info_video(mid, account_state) VALUES(1008, 3) ON DUPLICATE KEY UPDATE account_state = 3")
rows, err := d.Dismiss(c, table, newState, oldState, reason, dismissAt, quitAt, mid)
ctx.Convey("Then err should be nil.rows should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rows, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoTxDismiss(t *testing.T) {
convey.Convey("TxDismiss", t, func(ctx convey.C) {
var (
c = context.Background()
tx, _ = d.BeginTran(c)
table = "up_info_video"
newState = int(6)
oldState = int(3)
reason = ""
dismissAt = xtime.Time(time.Now().Unix())
quitAt = xtime.Time(time.Now().Unix())
mid = int64(1008)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
defer tx.Commit()
Exec(c, "INSERT INTO up_info_video(mid, account_state) VALUES(1008, 3) ON DUPLICATE KEY UPDATE account_state = 3")
rows, err := d.TxDismiss(tx, table, newState, oldState, reason, dismissAt, quitAt, mid)
ctx.Convey("Then err should be nil.rows should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rows, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoForbid(t *testing.T) {
convey.Convey("Forbid", t, func(ctx convey.C) {
var (
c = context.Background()
table = "up_info_video"
newState = int(7)
oldState = int(3)
reason = ""
forbidAt = xtime.Time(time.Now().Unix())
expiredIn = xtime.Time(time.Now().Unix())
mid = int64(1008)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
Exec(c, "INSERT INTO up_info_video(mid, account_state) VALUES(1008, 3) ON DUPLICATE KEY UPDATE account_state = 3")
rows, err := d.Forbid(c, table, newState, oldState, reason, forbidAt, expiredIn, mid)
ctx.Convey("Then err should be nil.rows should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rows, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoTxForbid(t *testing.T) {
convey.Convey("TxForbid", t, func(ctx convey.C) {
var (
c = context.Background()
tx, _ = d.BeginTran(c)
table = "up_info_video"
newState = int(6)
oldState = int(3)
reason = "test"
forbidAt = xtime.Time(time.Now().Unix())
expiredIn = xtime.Time(time.Now().Unix())
mid = int64(1008)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
defer tx.Commit()
Exec(c, "INSERT INTO up_info_video(mid, account_state) VALUES(1008, 3) ON DUPLICATE KEY UPDATE account_state = 3")
rows, err := d.TxForbid(tx, table, newState, oldState, reason, forbidAt, expiredIn, mid)
ctx.Convey("Then err should be nil.rows should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rows, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoUpdateAccountState(t *testing.T) {
convey.Convey("UpdateAccountState", t, func(ctx convey.C) {
var (
c = context.Background()
table = "up_info_video"
state = int(4)
mid = int64(1008)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
Exec(c, "INSERT INTO up_info_video(mid, account_state) VALUES(1008, 3) ON DUPLICATE KEY UPDATE account_state = 3")
rows, err := d.UpdateAccountState(c, table, state, mid)
ctx.Convey("Then err should be nil.rows should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rows, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoDelUpInfo(t *testing.T) {
convey.Convey("DelUpInfo", t, func(ctx convey.C) {
var (
c = context.Background()
table = "up_info_video"
mid = int64(1008)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
Exec(c, "INSERT INTO up_info_video(mid, is_deleted) VALUES(1008, 0) ON DUPLICATE KEY UPDATE is_deleted = 0")
rows, err := d.DelUpInfo(c, table, mid)
ctx.Convey("Then err should be nil.rows should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rows, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoRecUpInfo(t *testing.T) {
convey.Convey("RecUpInfo", t, func(ctx convey.C) {
var (
c = context.Background()
table = "up_info_video"
mid = int64(1008)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
Exec(c, "INSERT INTO up_info_video(mid, is_deleted) VALUES(1008, 1) ON DUPLICATE KEY UPDATE is_deleted = 1")
rows, err := d.RecUpInfo(c, table, mid)
ctx.Convey("Then err should be nil.rows should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rows, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoupdateUpInfoDel(t *testing.T) {
convey.Convey("updateUpInfoDel", t, func(ctx convey.C) {
var (
c = context.Background()
table = "up_info_video"
mid = int64(1008)
isDeleted = int(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
Exec(c, "INSERT INTO up_info_video(mid, is_deleted) VALUES(1008, 1) ON DUPLICATE KEY UPDATE is_deleted = 1")
rows, err := d.updateUpInfoDel(c, table, mid, isDeleted)
ctx.Convey("Then err should be nil.rows should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rows, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoDelUpAccount(t *testing.T) {
convey.Convey("DelUpAccount", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(1008)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
Exec(c, "INSERT INTO up_account(mid, is_deleted) VALUES(1008, 0) ON DUPLICATE KEY UPDATE is_deleted = 0")
rows, err := d.DelUpAccount(c, mid)
ctx.Convey("Then err should be nil.rows should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rows, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoDelCreditRecord(t *testing.T) {
convey.Convey("DelCreditRecord", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(1000)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
Exec(c, "INSERT INTO credit_score_record(id, is_deleted) VALEUS(1000, 0) ON DUPLICATE KEY UPDATE is_deleted = 0")
rows, err := d.DelCreditRecord(c, id)
ctx.Convey("Then err should be nil.rows should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rows, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoTxDelCreditRecord(t *testing.T) {
convey.Convey("TxDelCreditRecord", t, func(ctx convey.C) {
var (
c = context.Background()
tx, _ = d.BeginTran(c)
id = int64(1000)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
defer tx.Commit()
Exec(c, "INSERT INTO credit_score_record(id, is_deleted) VALEUS(1000, 0) ON DUPLICATE KEY UPDATE is_deleted = 0")
rows, err := d.TxDelCreditRecord(tx, id)
ctx.Convey("Then err should be nil.rows should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rows, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoUpInfo(t *testing.T) {
convey.Convey("UpInfo", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(1008)
state = int64(3)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
Exec(c, "INSERT INTO up_info_video(mid, account_state, is_deleted) VALUES(1008, 3, 0) ON DUPLICATE KEY UPDATE account_state = 3, is_deleted = 0")
info, err := d.UpInfo(c, mid, state)
ctx.Convey("Then err should be nil.info should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(info, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoGetUpInfoByState(t *testing.T) {
convey.Convey("GetUpInfoByState", t, func(ctx convey.C) {
var (
c = context.Background()
table = "up_info_video"
mids = []int64{1008}
state = int(3)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
info, err := d.GetUpInfoByState(c, table, mids, state)
ctx.Convey("Then err should be nil.info should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(info, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoGetUpState(t *testing.T) {
convey.Convey("GetUpState", t, func(ctx convey.C) {
var (
c = context.Background()
table = "up_info_video"
mid = int64(1008)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
state, err := d.GetUpState(c, table, mid)
ctx.Convey("Then err should be nil.state should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(state, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoBGMCount(t *testing.T) {
convey.Convey("BGMCount", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(1008)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
Exec(c, "INSERT INTO background_music(sid, mid) VALUES(100, 1008)")
count, err := d.BGMCount(c, mid)
ctx.Convey("Then err should be nil.count should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(count, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,90 @@
package dao
import (
"context"
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"errors"
"fmt"
"hash"
"io"
"net/http"
"strconv"
"go-common/library/log"
"go-common/library/net/trace"
)
const (
_uploadURL = "/%s/%s"
_moduleName = "http_client"
_template = "%s\n%s\n%s\n%d\n"
_method = "PUT"
)
var (
errUpload = errors.New("Upload failed")
)
// Upload upload picture or log file to bfs
func (d *Dao) Upload(c context.Context, fileName, fileType string, expire int64, body io.Reader) (location string, err error) {
var (
url string
req *http.Request
resp *http.Response
header http.Header
code string
)
bfsConf := d.c.Bfs
url = fmt.Sprintf(bfsConf.Addr+_uploadURL, bfsConf.Bucket, fileName)
if req, err = http.NewRequest(_method, url, body); err != nil {
log.Error("http.NewRequest() Upload(%v) error(%v)", url, err)
return
}
authorization := authorize(bfsConf.Key, bfsConf.Secret, _method, bfsConf.Bucket, fileName, expire)
req.Header.Set("Host", bfsConf.Addr)
req.Header.Add("Date", fmt.Sprint(expire))
req.Header.Add("Authorization", authorization)
req.Header.Add("Content-Type", fileType)
t, ok := trace.FromContext(c)
if ok {
t = t.Fork("http_client", "bfs_upload")
t.SetTag(trace.String(trace.TagAddress, _moduleName), trace.String(trace.TagComment, req.URL.Path))
}
resp, err = http.DefaultClient.Do(req)
if err != nil {
t.Finish(&err)
log.Error("httpClient.Do(%s) error(%v)", url, err)
return
}
if resp.StatusCode != http.StatusOK {
log.Error("Upload url(%s) http.statuscode:%d", url, resp.StatusCode)
err = errUpload
return
}
header = resp.Header
code = header.Get("Code")
if code != strconv.Itoa(http.StatusOK) {
log.Error("Upload url(%s) code:%s", url, code)
err = errUpload
return
}
location = header.Get("Location")
return
}
// authorize returns authorization for upload file to bfs
func authorize(key, secret, method, bucket, file string, expire int64) (authorization string) {
var (
content string
mac hash.Hash
signature string
)
content = fmt.Sprintf(_template, method, bucket, file, expire)
mac = hmac.New(sha1.New, []byte(secret))
mac.Write([]byte(content))
signature = base64.StdEncoding.EncodeToString(mac.Sum(nil))
authorization = fmt.Sprintf("%s:%s:%d", key, signature, expire)
return
}

View File

@@ -0,0 +1,26 @@
package dao
import (
"bytes"
"context"
"testing"
. "github.com/smartystreets/goconvey/convey"
)
func Test_UploadSql(t *testing.T) {
Convey("upload picture or log file to bfs", t, WithMysql(func(d *Dao) {
var (
fileName = "bilibili.png"
fileType = "png"
expire int64 = 1
bt = []byte("/9j/4QAo.Reader(bt)YRXhpZgAASUkqAAgAAAAAAAAAAAAAA")
body = bytes.NewReader(bt)
)
_, err := d.Upload(context.Background(), fileName, fileType, expire, body)
if err == errUpload {
err = nil
}
So(err, ShouldBeNil)
}))
}