Initial commit

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

View File

@@ -0,0 +1,21 @@
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [
":package-srcs",
"//app/interface/main/credit/cmd:all-srcs",
"//app/interface/main/credit/conf:all-srcs",
"//app/interface/main/credit/dao:all-srcs",
"//app/interface/main/credit/http:all-srcs",
"//app/interface/main/credit/model:all-srcs",
"//app/interface/main/credit/service:all-srcs",
],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

View File

@@ -0,0 +1,362 @@
# credit 用户账号会员系统的服务层。
# v1.25.0
> 1.接入 account-service gRPC服务
# v1.24.3
> 1.增加勋章发放重试
# v1.24.2
> 1.增加封禁类型(恶意冒充他人)
# v1.24.1
> 1.fix block list panic
# v1.24.0
> 1.使用member-service的block的接口
# v1.23.1
> 1.fix jury cache redelete
# v1.23.0
> 1.使用filter-service的grpc协议
# v1.22.1
> 1.fix 挂件的post协议
# v1.22.0
> 1.替换老发放勋章接口
> 2.优化代码
# v1.21.0
> 1.改为 metadata RemoteIP
# v1.20.2
> 1.fix async var change
# v1.20.1
> 1.去掉cache压缩
# v1.20.0
> 1.风纪委缓存优化
> 2.实名认证使用memrpc
# v1.19.1
> 1.劳改是否答题增加缓存
# v1.19.0
> 1.use new auth
# v1.18.3
> 1.fix block time bug
# v1.18.2
> 1.强制永久封禁的 blocked day的为0
# v1.18.1
> 1.新增动态、相簿、小视频类封禁
# v1.18.0
> 1.答题吐稿件id + title
# v1.17.2
> 1.fix api /blocked/info/batch/add
# v1.17.1
> 1.原来的content的check没有作用
# v1.17.0
> 1.old bind to new
# v1.16.12
> 1.产品变动小黑屋封禁理由
# v1.16.11
> 1.add reason code (28、29)
# v1.16.10
> 1.add reason code (27)
# v1.16.9
> 1. 匿名去昵称
# v1.16.8
> 1. debug 观点显示
# v1.16.7
> 1. 观点换key
# v1.16.6
> 1.观点列表直接取新表数据
# v1.16.5
> 1.小黑屋未同步到封禁数据兼容前端强制封禁次数为1
# v1.16.4
> 1.rollback answer code
# v1.16.3
> 1.punish_time to now
# v1.16.2
> 1.clear old code
> 2.新增批量封禁接口
> 3.众议院匿名安全漏洞
# v1.16.1
> 1.风纪委封禁信息判断
# v1.16.0
> 1.众裁举报理由变更
# v1.15.6
> 1.使用account-service v7
# v1.15.5
> 1.fix async context to timeout bug
# v1.15.4
> 1.删除 “发布色情低俗信息”
> 2.新增 “破坏网络安全”、“发布虚假误导信息”
# v1.15.3
> 1. 更新“发布怂恿教唆信息”为“发布不适宜内容”
> 2. 新增“发布青少年不良内容”
# v1.15.2
> 1.delete statsd
# v1.15.1
> 1.config fix case_give_hours
# v1.15.0
> 1.风纪委投票计数分级
# v1.14.1
> 1.修复appeal status
# v1.14.0
> 1.add case list punishTitle
> 2.clear old code
# v1.13.9
> 1.update cache logic for blocked info
# v1.13.8
> 1.update cache key for blocked info and log
# v1.13.7
> 1.fix block info status check
# v1.13.6
> 1.fix tagID map nil
# v1.13.5
> 1.workflow tagid 从配置文件获取
# v1.13.4
> 1.修复 blocked sql
# v1.13.3
> 1.修改workfolw tagID
# v1.13.2
> 1.增加封禁申诉
# v1.13.1
> 1. 新增批量获取case的info接口
# v1.13.0
> 1. http使用BM框架
# v1.12.4
> 1. 案件移交加入举报时间字段
# v1.12.3
> 1. add goconvey test
# v1.12.2
> 1. fix_bug
# v1.12.1
> 1. 案件移交过滤已经移交过的案件
# v1.12.0
> 1. 弱鸡的观点防刷机制
> 2. code fix
# v1.11.15
> 1. expland get manager user ps.
# v1.11.14
> 1. load manager admin users
> 2. notice order by id desc
# v1.11.13
> 1. 操作者封禁做后台操作者转操作ID转换
# v1.11.12
> 1. 优化 KPI list
# v1.11.11
> 1. fix 排序字段bug
# v1.11.10
> 1. 修改blocked/list排序字段
> 2. 格式优化部分代码
# v1.11.9
> 1. 封禁接口新增业务字段和逻辑判断
# v1.11.8
> 1. 新增专栏理由
# v1.11.7
> 1.fix blockedlist expire bug
# v1.11.6
> 1.代码优化
# v1.11.5
> 1.增加专栏与头图描述
# v1.11.4
> 1.老萧产品需求,封禁历史记录一年三次以上可永久封禁
# v1.11.3
> 1.劳改题目is_del字段
# v1.11.2
> 1.del opinion join
# v1.11.1
> 1.reason_type fix bug
# v1.11.0
> 1.blocked_opinion 冗余mid和vote字段
# v1.10.10
> 1.KPI优化新增被赞数
# v1.10.9
> 1.支持publish的status字段
> 2.支持info的status字段
> 2.支持publish的show_time字段
# v1.10.8
> 1.修改publish/infos接口返回data为map
# v1.10.7
> 1.整理业务代码
> 2.新增查询用户封禁次数接口
> 3.新增业务封禁
> 4.批量查询封禁信息
> 5.批量查询封禁历史
> 6.批量查询公告信息
> 7.批量查询封禁委员信息
# v1.10.6
> 1.修改reason_type
# v1.10.5
> 1.新增大众总裁逻辑
# v1.10.4
> 1.修改reason_type
# v1.10.3
> 1.修改系统消息和徽章发放为co域名接口
> 2.整理域名
# v1.10.2
> 1.小黑屋中获得风纪委员的资格的bug
# v1.10.0
> 1.风纪委获取case逻辑变更
# v1.9.2
> 1.fix blockedinfo log
# v1.9.1
> 1.credit 3.0
# v1.9.0
> 1.credit dao add prom
# v1.8.9
> 1.fix caseobtain bug
# v1.8.8
> 1.fix caseobtain bug
# v1.8.7
> 1.fix panic nil
# v1.8.6
> 1.fix panic nil
# v1.8.5
> 1.风纪委 发放勋章
# v1.8.4
> 1.删除无用类型的参数绑定的默认default
> 2.加入答题防刷
# v1.8.3
> 1.fix bug
# v1.8.2
> 1.fix filter add log
# v1.8.1
> 1.fix filter bug
# v1.8.0
> 1.迁出member-interface的风纪委的对外接口
> 2.接入新版httpclient
> 3.项目修改为credit
# v1.7.3
> 1.添加originType音频
# v1.7.2
> 1.批量移交风纪委案件接口
# v1.7.0
> 1.jury2.2 观点关键词屏蔽 观点赞-踩<=-5不显示观点 投票后展示赞踩数
# v1.6.0
> 1.小黑板
# v1.5.0
> 1.风纪委公开裁决
> 1.风纪委公开裁决
# v1.4.2
> 1.劳改 增加内网软删除接口
> 2.劳改 增加获取题目错误码
# v1.4.1
> 1.添加rpc method
# v1.4.0
> 1.合并=进大仓库
# v1.3.0
> 1.风纪委众议
# v1.2.1
> 1.fix 重复提交返回空数据
> 2.增加永久封禁不能答题
# v1.2.0
> 1.劳改项目
# v1.1.1
> 1.修复sql id字段缺失
# v1.1.0
> 1.风纪委重构
# v1.0.0
> 1.基础api

View File

@@ -0,0 +1,12 @@
# Owner
zhaogangtao
wanghuan01
zhoujiahui
# Author
lintanghui
wangyuzhe
# Reviewer
zhaogangtao
lintanghui

View File

@@ -0,0 +1,18 @@
# See the OWNERS docs at https://go.k8s.io/owners
approvers:
- lintanghui
- wanghuan01
- wangyuzhe
- zhaogangtao
- zhoujiahui
labels:
- interface
- interface/main/credit
- main
options:
no_parent_owners: true
reviewers:
- lintanghui
- wangyuzhe
- zhaogangtao

View File

@@ -0,0 +1,13 @@
#### credit
##### 项目简介
> 1.信用体系服务
##### 编译环境
> 请只用golang v1.7.x以上版本编译执行。
##### 依赖包
> 1.公共包go-common
##### 特别说明
> 1.model目录可能会被其他项目引用请谨慎更改并通知各方。

View File

@@ -0,0 +1,46 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_binary",
"go_library",
)
go_binary(
name = "cmd",
embed = [":go_default_library"],
tags = ["automanaged"],
)
go_library(
name = "go_default_library",
srcs = ["main.go"],
data = [
"convey-test.toml",
"credit-test.toml",
],
importpath = "go-common/app/interface/main/credit/cmd",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/interface/main/credit/conf:go_default_library",
"//app/interface/main/credit/http:go_default_library",
"//library/ecode/tip:go_default_library",
"//library/log:go_default_library",
"//library/net/trace: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,188 @@
# This is a TOML document. Boom.
version = "1.0.0"
[host]
MessageURI = "http://message.bilibili.co"
BigDataURI = "http://172.18.33.147:3000"
APICoURI = "http://api.bilibili.co"
ManagersURI = "http://manager.bilibili.co"
[app]
key = "903f486ae7dc87fa"
secret = "6b03fa3e00334166ba3659e2c04201fc"
[xlog]
dir = "/data/log/credit/"
[bm]
[bm.inner]
addr = "0.0.0.0:6827"
maxListen = 10
timeout="1s"
[bm.local]
addr = "0.0.0.0:6828"
maxListen = 10
timeout="1s"
[httpClient]
key = "903f486ae7dc87fa"
secret = "6b03fa3e00334166ba3659e2c04201fc"
dial = "1s"
timeout = "2s"
keepAlive = "60s"
[httpClient.breaker]
window = "3s"
sleep = "100ms"
bucket = 10
ratio = 0.5
request = 100
[rpcClient2]
[rpcClient2.account]
timeout = "1s"
[rpcClient2.filter]
timeout = "1s"
[rpcClient2.Archive]
timeout = "1s"
[rpcClient2.member]
timeout = "1s"
[grpcClient]
[grpcClient.filter]
dial = "1s"
timeout = "1s"
[identify]
whiteAccessKey = "a2a1eb0ac97d6ba08b85aa0151528f34"
whiteMid = 23675773
csrf = false
[identify.app]
key = "e7482d29be4a95b8"
secret = "9e803791cdef756e75faee68e12b7442"
[identify.memcache]
name = "go-business/identify"
proto = "tcp"
addr = "172.16.33.54:11211"
active = 5
idle = 5
dialTimeout = "1s"
readTimeout = "1s"
writeTimeout = "1s"
idleTimeout = "80s"
[identify.host]
auth = "http://uat-passport.bilibili.co"
secret = "http://uat-open.bilibili.co"
[identify.httpClient]
key = "e7482d29be4a95b8"
secret = "9e803791cdef756e75faee68e12b7442"
dial = "1s"
timeout = "1s"
keepAlive = "60s"
[identify.httpClient.breaker]
window = "10s"
sleep = "100ms"
bucket = 10
ratio = 0.5
request = 100
[identify.httpClient.url]
"http://uat-passport.bilibili.co/intranet/auth/tokenInfo" = {timeout = "100ms"}
"http://uat-passport.bilibili.co/intranet/auth/cookieInfo" = {timeout = "100ms"}
"http://uat-open.bilibili.co/api/getsecret" = {timeout = "500ms"}
[mysql]
addr = "172.16.33.205:3306"
dsn = "blocked:mUdFycLKSbvPgdE28lCveqN77SqsGOmy@tcp(172.16.33.205:3306)/blocked?timeout=5s&readTimeout=5s&writeTimeout=5s&parseTime=true&loc=Local&charset=utf8,utf8mb4"
active = 5
idle = 2
IdleTimeout ="4h"
queryTimeout = "1s"
execTimeout = "1s"
tranTimeout = "5s"
[mysql.breaker]
window = "3s"
sleep = "100ms"
bucket = 10
ratio = 0.5
request = 100
[memcache]
name = "credit"
proto = "tcp"
addr = "172.16.33.54:11211"
idle = 5
active = 5
dialTimeout = "1s"
readTimeout = "1s"
writeTimeout = "1s"
idleTimeout = "10s"
userexpire = "5m"
mincommonexpire = "10m"
commonexpire = "24h"
[redis]
name = "credit"
proto = "tcp"
addr = "172.16.33.54:6379"
idle = 5
active = 5
dialTimeout = "500ms"
readTimeout = "1s"
writeTimeout = "1s"
idleTimeout = "80s"
expire = "10m"
[judge]
confTimer="120s"
ReservedTime = "600s"
LoadManagerTime = "1h"
[DataBus]
key = "0QEO9F8JuuIxZzNDvklH"
secret = "0QEO9F8JuuIxZzNDvklI"
group = "AccLabour-Labour-P"
topic = "AccLabour-T"
action = "pub"
name = "credit/databus"
proto = "tcp"
addr = "172.16.33.158:6205"
idle = 5
active = 5
dialTimeout = "1s"
readTimeout = "60s"
writeTimeout = "1s"
idleTimeout = "10s"
[antispam]
on=true
second=2
n=1
hour=12
m=5
[antispam.redis]
name = "credit"
proto = "tcp"
addr = "172.16.33.54:6379"
idle = 5
active = 5
dialTimeout = "500ms"
readTimeout = "1s"
writeTimeout = "1s"
idleTimeout = "80s"
expire = "10m"
[tagID]
reply = 42
dm = 43
msg = 44
tag = 45
member = 46
archive = 47
music = 48
article = 49
spacetop = 50
[property]
qsnum = 40
perscore = 5

View File

@@ -0,0 +1,190 @@
# This is a TOML document. Boom.
version = "1.0.0"
[host]
MessageURI = "http://message.bilibili.co"
BigDataURI = "http://172.18.33.147:3000"
APICoURI = "http://api.bilibili.co"
ManagersURI = "http://manager.bilibili.co"
[app]
key = "903f486ae7dc87fa"
secret = "6b03fa3e00334166ba3659e2c04201fc"
[xlog]
dir = "/data/log/credit/"
[bm]
[bm.inner]
addr = "0.0.0.0:6827"
maxListen = 10
timeout="1s"
[bm.local]
addr = "0.0.0.0:6828"
maxListen = 10
timeout="1s"
[httpClient]
key = "903f486ae7dc87fa"
secret = "6b03fa3e00334166ba3659e2c04201fc"
dial = "1s"
timeout = "2s"
keepAlive = "60s"
[httpClient.breaker]
window = "3s"
sleep = "100ms"
bucket = 10
ratio = 0.5
request = 100
[rpcClient2]
[rpcClient2.account]
timeout = "1s"
[rpcClient2.filter]
timeout = "1s"
[rpcClient2.Archive]
timeout = "1s"
[rpcClient2.member]
timeout = "1s"
[grpcClient]
[grpcClient.filter]
dial = "1s"
timeout = "1s"
[identify]
whiteAccessKey = "a2a1eb0ac97d6ba08b85aa0151528f34"
whiteMid = 23675773
csrf = false
[identify.app]
key = "e7482d29be4a95b8"
secret = "9e803791cdef756e75faee68e12b7442"
[identify.memcache]
name = "go-business/identify"
proto = "tcp"
addr = "172.16.33.54:11211"
active = 5
idle = 5
dialTimeout = "1s"
readTimeout = "1s"
writeTimeout = "1s"
idleTimeout = "80s"
[identify.host]
auth = "http://uat-passport.bilibili.co"
secret = "http://uat-open.bilibili.co"
[identify.httpClient]
key = "e7482d29be4a95b8"
secret = "9e803791cdef756e75faee68e12b7442"
dial = "1s"
timeout = "1s"
keepAlive = "60s"
[identify.httpClient.breaker]
window = "10s"
sleep = "100ms"
bucket = 10
ratio = 0.5
request = 100
[identify.httpClient.url]
"http://uat-passport.bilibili.co/intranet/auth/tokenInfo" = {timeout = "100ms"}
"http://uat-passport.bilibili.co/intranet/auth/cookieInfo" = {timeout = "100ms"}
"http://uat-open.bilibili.co/api/getsecret" = {timeout = "500ms"}
[mysql]
addr = "172.16.33.205:3306"
dsn = "blocked:mUdFycLKSbvPgdE28lCveqN77SqsGOmy@tcp(172.16.33.205:3306)/blocked?timeout=5s&readTimeout=5s&writeTimeout=5s&parseTime=true&loc=Local&charset=utf8,utf8mb4"
active = 5
idle = 2
IdleTimeout ="4h"
queryTimeout = "1s"
execTimeout = "1s"
tranTimeout = "5s"
[mysql.breaker]
window = "3s"
sleep = "100ms"
bucket = 10
ratio = 0.5
request = 100
[memcache]
name = "credit"
proto = "tcp"
addr = "172.16.33.54:11211"
idle = 5
active = 5
dialTimeout = "1s"
readTimeout = "1s"
writeTimeout = "1s"
idleTimeout = "10s"
userexpire = "5m"
mincommonexpire = "10m"
commonexpire = "24h"
[redis]
name = "credit"
proto = "tcp"
addr = "172.16.33.54:6379"
idle = 5
active = 5
dialTimeout = "500ms"
readTimeout = "1s"
writeTimeout = "1s"
idleTimeout = "80s"
expire = "10m"
[judge]
confTimer="120s"
ReservedTime = "600s"
LoadManagerTime = "1h"
[DataBus]
key = "0QEO9F8JuuIxZzNDvklH"
secret = "0QEO9F8JuuIxZzNDvklI"
group = "AccLabour-Labour-P"
topic = "AccLabour-T"
action = "pub"
name = "credit/databus"
proto = "tcp"
addr = "172.16.33.158:6205"
idle = 5
active = 5
dialTimeout = "1s"
readTimeout = "60s"
writeTimeout = "1s"
idleTimeout = "10s"
[antispam]
on=true
second=2
n=1
hour=12
m=5
[antispam.redis]
name = "credit"
proto = "tcp"
addr = "172.16.33.54:6379"
idle = 5
active = 5
dialTimeout = "500ms"
readTimeout = "1s"
writeTimeout = "1s"
idleTimeout = "80s"
expire = "10m"
[tagID]
reply = 42
dm = 43
msg = 44
tag = 45
member = 46
archive = 47
music = 48
article = 49
spacetop = 50
[property]
qsnum = 40
perscore = 5

View File

@@ -0,0 +1,48 @@
package main
import (
"flag"
"os"
"os/signal"
"syscall"
"time"
"go-common/app/interface/main/credit/conf"
"go-common/app/interface/main/credit/http"
ecode "go-common/library/ecode/tip"
"go-common/library/log"
"go-common/library/net/trace"
)
func main() {
flag.Parse()
// init conf,log,trace,stat,perf.
if err := conf.Init(); err != nil {
panic(err)
}
log.Init(conf.Conf.Xlog)
defer log.Close()
trace.Init(conf.Conf.Tracer)
defer trace.Close()
// service init
ecode.Init(conf.Conf.Ecode)
http.Init(conf.Conf)
// signal handler
log.Info("credit start")
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT)
for {
s := <-c
log.Info("credit get a signal %s", s.String())
switch s {
case syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT:
time.Sleep(time.Second * 2)
log.Info("credit exit")
return
case syscall.SIGHUP:
// TODO reload
default:
return
}
}
}

View File

@@ -0,0 +1,46 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = ["conf.go"],
importpath = "go-common/app/interface/main/credit/conf",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//library/cache/memcache:go_default_library",
"//library/cache/redis:go_default_library",
"//library/conf:go_default_library",
"//library/database/sql:go_default_library",
"//library/ecode/tip:go_default_library",
"//library/log:go_default_library",
"//library/net/http/blademaster:go_default_library",
"//library/net/http/blademaster/middleware/antispam:go_default_library",
"//library/net/http/blademaster/middleware/auth:go_default_library",
"//library/net/http/blademaster/middleware/verify:go_default_library",
"//library/net/rpc:go_default_library",
"//library/net/rpc/warden:go_default_library",
"//library/net/trace:go_default_library",
"//library/queue/databus:go_default_library",
"//library/time:go_default_library",
"//vendor/github.com/BurntSushi/toml: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,211 @@
package conf
import (
"errors"
"flag"
"go-common/library/cache/memcache"
"go-common/library/cache/redis"
"go-common/library/conf"
"go-common/library/database/sql"
ecode "go-common/library/ecode/tip"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
"go-common/library/net/http/blademaster/middleware/antispam"
"go-common/library/net/http/blademaster/middleware/auth"
"go-common/library/net/http/blademaster/middleware/verify"
"go-common/library/net/rpc"
"go-common/library/net/rpc/warden"
"go-common/library/net/trace"
"go-common/library/queue/databus"
"go-common/library/time"
"github.com/BurntSushi/toml"
)
// Conf global variable.
var (
Conf = &Config{}
client *conf.Client
confPath string
)
// Config struct of conf.
type Config struct {
// base
// host
Host *Host
// log
Xlog *log.Config
// AuthN
AuthN *auth.Config
// Verify
Verify *verify.Config
// http
BM *HTTPServers
// db
Mysql *sql.Config
// mc
Memcache *Memcache
//redis
Redis *Redis
// databus
DataBus *databus.Config
// tracer
Tracer *trace.Config
// bm client
HTTPClient *bm.ClientConfig
// Judge conf
Judge *Judge
// ecodes
Ecode *ecode.Config
// Antispam
Antispam *antispam.Config
// TagID
TagID *TagID
// Property
Property *Property
// rpc client
RPCClient2 *RPC
// GRPCClient
GRPCClient *GRPC
}
// Redis define redis conf.
type Redis struct {
*redis.Config
Expire time.Duration
}
// Memcache define memcache conf.
type Memcache struct {
*memcache.Config
UserExpire time.Duration
MinCommonExpire time.Duration
CommonExpire time.Duration
}
// Host define host conf.
type Host struct {
MessageURI string
BigDataURI string
APICoURI string
ManagersURI string
}
// Judge define judge conf.
type Judge struct {
ConfTimer time.Duration // 定时load数据时间间隔
ReservedTime time.Duration // 结案前N分钟停止获取case
LoadManagerTime time.Duration // load manager user的时间间隔
CaseGiveHours int64 // 案件发放时长
CaseCheckTime int64 // 单案审核时长
JuryRatio int64 // 投准率下限
JudgeRadio int64 // 判决阙值
CaseVoteMin int64 // 案件投票数下限
CaseObtainMax int64 // 每日获取案件数
CaseVoteMax int64 // 结案投票数
JuryApplyMax int64 // 每日发放风纪委上限
CaseLoadMax int // 案件发放最大队列数
CaseLoadSwitch int8 // 案件发放进入队列开关
VoteNum
}
// VoteNum .
type VoteNum struct {
RateS int8 `json:"rate_s"`
RateA int8 `json:"rate_a"`
RateB int8 `json:"rate_b"`
RateC int8 `json:"rate_c"`
RateD int8 `json:"rate_d"`
}
// RPC rpc client config.
type RPC struct {
Archive *rpc.ClientConfig
Member *rpc.ClientConfig
}
// GRPC .
type GRPC struct {
Filter *warden.ClientConfig
Account *warden.ClientConfig
}
// HTTPServers Http Servers
type HTTPServers struct {
Inner *bm.ServerConfig
Local *bm.ServerConfig
}
// TagID is workflow id .
type TagID struct {
Reply int64
DM int64
Msg int64
Tag int64
Member int64
Archive int64
Music int64
Article int64
SpaceTop int64
}
// Property .
type Property struct {
QsNum int
PerScore int64
}
func init() {
flag.StringVar(&confPath, "conf", "", "default config path")
}
// Init create config instance.
func Init() (err error) {
if confPath != "" {
return local()
}
return remote()
}
func local() (err error) {
_, err = toml.DecodeFile(confPath, &Conf)
return
}
func remote() (err error) {
if client, err = conf.New(); err != nil {
return
}
if err = load(); err != nil {
return
}
go func() {
for range client.Event() {
log.Info("config reload")
if load() != nil {
log.Error("config reload error (%v)", err)
}
}
}()
return
}
func load() (err error) {
var (
s string
ok bool
tmpConf *Config
)
if s, ok = client.Toml2(); !ok {
return errors.New("load config center error")
}
if _, err = toml.Decode(s, &tmpConf); err != nil {
return errors.New("could not decode config")
}
*Conf = *tmpConf
return
}

View File

@@ -0,0 +1,95 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_test",
"go_library",
)
go_test(
name = "go_default_test",
srcs = [
"appeal_test.go",
"blocked_mc_test.go",
"blocked_redis_test.go",
"blocked_test.go",
"case_mc_test.go",
"case_redis_test.go",
"case_test.go",
"dao_test.go",
"databus_test.go",
"http_test.go",
"jury_test.go",
"manager_test.go",
"mc_test.go",
"memcache_test.go",
"mysql_test.go",
"opinion_test.go",
"redis_test.go",
],
embed = [":go_default_library"],
rundir = ".",
tags = ["automanaged"],
deps = [
"//app/interface/main/credit/conf:go_default_library",
"//app/interface/main/credit/model:go_default_library",
"//vendor/github.com/go-sql-driver/mysql:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
"//vendor/gopkg.in/h2non/gock.v1:go_default_library",
],
)
go_library(
name = "go_default_library",
srcs = [
"appeal.go",
"blocked.go",
"blocked_mc.go",
"blocked_redis.go",
"case.go",
"case_mc.go",
"case_redis.go",
"dao.go",
"databus.go",
"http.go",
"jury.go",
"manager.go",
"memcache.go",
"mysql.go",
"opinion.go",
"redis.go",
],
importpath = "go-common/app/interface/main/credit/dao",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/interface/main/credit/conf:go_default_library",
"//app/interface/main/credit/model:go_default_library",
"//library/cache/memcache:go_default_library",
"//library/cache/redis:go_default_library",
"//library/database/sql:go_default_library",
"//library/ecode:go_default_library",
"//library/log:go_default_library",
"//library/net/http/blademaster:go_default_library",
"//library/net/metadata:go_default_library",
"//library/queue/databus:go_default_library",
"//library/sync/errgroup:go_default_library",
"//library/time:go_default_library",
"//library/xstr:go_default_library",
"//vendor/github.com/pkg/errors:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

View File

@@ -0,0 +1,64 @@
package dao
import (
"context"
"net/url"
"strconv"
"go-common/app/interface/main/credit/model"
"go-common/library/ecode"
"go-common/library/log"
"go-common/library/net/metadata"
"github.com/pkg/errors"
)
// AddAppeal add appeal.
func (d *Dao) AddAppeal(c context.Context, tid, btid, oid, mid, business int64, content, reason string) (err error) {
params := url.Values{}
params.Set("tid", strconv.FormatInt(tid, 10))
params.Set("oid", strconv.FormatInt(oid, 10))
params.Set("mid", strconv.FormatInt(mid, 10))
params.Set("business_mid", strconv.FormatInt(mid, 10))
params.Set("business_typeid", strconv.FormatInt(btid, 10))
params.Set("business", strconv.FormatInt(business, 10))
params.Set("business_content", content)
params.Set("description", reason)
var res struct {
Code int `json:"code"`
Data *struct {
ChallengeNo int64 `json:"challengeNo"`
} `json:"data"`
}
if err = d.client.Post(c, d.addAppealURL, metadata.String(c, metadata.RemoteIP), params, &res); err != nil {
err = errors.Wrapf(err, "AddAppeal url(%s) res(%v)", d.addAppealURL+"?"+params.Encode(), res)
return
}
if res.Code != 0 {
log.Warn("add appeal url(%s) mid(%d) res(%v)", d.addAppealURL+"?"+params.Encode(), mid, res)
err = ecode.Int(res.Code)
}
return
}
// AppealList appeal list .
func (d *Dao) AppealList(c context.Context, mid int64, business int) (as []*model.Appeal, err error) {
params := url.Values{}
params.Set("mid", strconv.FormatInt(mid, 10))
params.Set("business", strconv.Itoa(business))
var res struct {
Code int `json:"code"`
Data []*model.Appeal `json:"data"`
}
if err = d.client.Get(c, d.appealListURL, metadata.String(c, metadata.RemoteIP), params, &res); err != nil {
err = errors.Wrapf(err, "AppealList url(%s) res(%v)", d.appealListURL+"?"+params.Encode(), res)
return
}
if res.Code != 0 {
log.Warn("appeal list url(%s) mid(%d) res(%v)", d.appealListURL+"?"+params.Encode(), mid, res)
err = ecode.Int(res.Code)
return
}
as = res.Data
return
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,47 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = [
"appeal.go",
"blocked.go",
"credit.go",
"http.go",
"jury.go",
"labour.go",
],
importpath = "go-common/app/interface/main/credit/http",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/interface/main/credit/conf:go_default_library",
"//app/interface/main/credit/model:go_default_library",
"//app/interface/main/credit/service:go_default_library",
"//library/ecode:go_default_library",
"//library/log:go_default_library",
"//library/net/http/blademaster:go_default_library",
"//library/net/http/blademaster/middleware/antispam:go_default_library",
"//library/net/http/blademaster/middleware/auth:go_default_library",
"//library/net/http/blademaster/middleware/verify: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,64 @@
package http
import (
"go-common/library/ecode"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
"strconv"
)
func addAppeal(c *bm.Context) {
var (
err error
params = c.Request.Form
btid int64
bid int64
midI, _ = c.Get("mid")
btidStr = params.Get("business_typeid")
bidStr = params.Get("bid")
reason = params.Get("reason")
)
if btid, err = strconv.ParseInt(btidStr, 10, 64); err != nil {
log.Error("strconv.ParseInt err(err) %v", err)
c.JSON(nil, ecode.RequestErr)
return
}
if bid, err = strconv.ParseInt(bidStr, 10, 64); err != nil {
log.Error("strconv.ParseInt err(err) %v", err)
c.JSON(nil, ecode.RequestErr)
return
}
if err = creditSvc.AddAppeal(c, btid, bid, midI.(int64), reason); err != nil {
log.Error("creditSvc.AddAppeal error(%v)", err)
c.JSON(nil, err)
return
}
c.JSON(nil, nil)
}
func appealStatus(c *bm.Context) {
var (
err error
params = c.Request.Form
mid int64
bid int64
bidStr = params.Get("bid")
)
if bid, err = strconv.ParseInt(bidStr, 10, 64); err != nil {
log.Error("strconv.ParseInt err(err) %v", err)
c.JSON(nil, ecode.RequestErr)
return
}
midI, ok := c.Get("mid")
if ok {
mid, _ = midI.(int64)
}
state, err := creditSvc.AppealState(c, mid, bid)
if err != nil {
log.Error("creditSvc.AppealState error(%v)", err)
c.JSON(nil, err)
return
}
// 未申述过 true, 已申诉过flase
c.JSON(!state, nil)
}

View File

@@ -0,0 +1,233 @@
package http
import (
"strconv"
model "go-common/app/interface/main/credit/model"
"go-common/library/ecode"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
"go-common/library/xstr"
)
// requirement user status in apply jury.
func blockedUserCard(c *bm.Context) {
var mid, _ = c.Get("mid")
rq, err := creditSvc.BlockedUserCard(c, mid.(int64))
if err != nil {
log.Error("creditSvc.BlockedUserCard(%d) error(%v)", mid, err)
c.JSON(nil, err)
}
c.JSON(rq, nil)
}
func blockedUserList(c *bm.Context) {
var mid, _ = c.Get("mid")
rq, err := creditSvc.BlockedUserList(c, mid.(int64))
if err != nil {
log.Error("creditSvc.BlockedUserList(%d) error(%v)", mid, err)
c.JSON(nil, err)
return
}
c.JSON(rq, nil)
}
func blockedInfo(c *bm.Context) {
var idStr = c.Request.Form.Get("id")
id, err := strconv.ParseInt(idStr, 10, 64)
if err != nil {
log.Error("strconv.ParseInt err(%v)", err)
c.JSON(nil, ecode.RequestErr)
return
}
rq, err := creditSvc.BlockedInfo(c, id)
if err != nil {
log.Error("creditSvc.BlockedInfo(%d) error(%v)", id, err)
c.JSON(nil, err)
return
}
c.JSON(rq, nil)
}
func blockedAppeal(c *bm.Context) {
var (
mid int64
err error
idStr = c.Request.Form.Get("id")
)
midI, ok := c.Get("mid")
if ok {
mid = midI.(int64)
}
id, err := strconv.ParseInt(idStr, 10, 64)
if err != nil {
log.Error("strconv.ParseInt err(%v)", err)
c.JSON(nil, ecode.RequestErr)
return
}
rq, err := creditSvc.BlockedInfoAppeal(c, id, mid)
if err != nil {
log.Error("creditSvc.BlockedInfo(%d) error(%v)", id, err)
c.JSON(nil, err)
return
}
c.JSON(rq, nil)
}
func blockedList(c *bm.Context) {
var err error
v := new(model.ArgBlockedList)
if err = c.Bind(v); err != nil {
return
}
if v.PS <= 0 || v.PS > 10 {
v.PS = 10
}
rq, err := creditSvc.BlockedList(c, v.OType, v.BType, v.PN, v.PS)
if err != nil {
log.Error("creditSvc.Blockedlist(%d,%d) error(%v)", v.OType, v.BType, err)
c.JSON(nil, err)
return
}
c.JSON(rq, nil)
}
func announcementInfo(c *bm.Context) {
idStr := c.Request.Form.Get("id")
id, err := strconv.ParseInt(idStr, 10, 64)
if err != nil {
log.Error("strconv.ParseInt err(%v)", err)
c.JSON(nil, ecode.RequestErr)
return
}
rq, err := creditSvc.AnnouncementInfo(c, id)
if err != nil {
log.Error("creditSvc.AnnouncementInfo(%d) error(%v)", id, err)
c.JSON(nil, err)
return
}
c.JSON(rq, nil)
}
func announcementList(c *bm.Context) {
var (
params = c.Request.Form
tpStr = params.Get("tp")
pnStr = params.Get("pn")
psStr = params.Get("ps")
)
tp, err := strconv.ParseInt(tpStr, 10, 8)
if err != nil {
log.Error("strconv.ParseInt err(%v)", err)
c.JSON(nil, ecode.RequestErr)
return
}
pn, err := strconv.ParseInt(pnStr, 10, 64)
if err != nil || pn < 1 {
log.Error("strconv.ParseInt err(%v)", err)
c.JSON(nil, ecode.RequestErr)
return
}
ps, err := strconv.ParseInt(psStr, 10, 64)
if err != nil {
log.Error("strconv.ParseInt err(%v)", err)
c.JSON(nil, ecode.RequestErr)
return
}
if ps < 0 || ps > 10 {
ps = 10
}
rq, err := creditSvc.AnnouncementList(c, int8(tp), pn, ps)
if err != nil {
log.Error("creditSvc.AnnouncementList( tp %d) error(%v)", tp, err)
c.JSON(nil, err)
return
}
c.JSON(rq, nil)
}
func blockedNumUser(c *bm.Context) {
v := new(model.ArgBlockedNumUser)
if err := c.Bind(v); err != nil {
return
}
bn, err := creditSvc.BlockedNumUser(c, v.MID)
if err != nil {
log.Error("creditSvc.BlockedNumUser(%d) error(%v)", v.MID, err)
c.JSON(nil, err)
return
}
c.JSON(bn, nil)
}
func batchPublishs(c *bm.Context) {
v := new(model.ArgIDs)
if err := c.Bind(v); err != nil {
return
}
pubs, err := creditSvc.BatchPublishs(c, v.IDs)
if err != nil {
log.Error("creditSvc.BatchPublishs(%s) error(%v)", xstr.JoinInts(v.IDs), err)
c.JSON(nil, err)
return
}
c.JSON(pubs, nil)
}
func addBlockedInfo(c *bm.Context) {
var err error
v := new(model.ArgJudgeBlocked)
if err = c.Bind(v); err != nil {
return
}
err = creditSvc.AddBlockedInfo(c, v)
if err != nil {
log.Error("creditSvc.AddBlockedInfo(%+v) error(%v)", v, err)
c.JSON(nil, err)
return
}
c.JSON(nil, nil)
}
func addBatchBlockedInfo(c *bm.Context) {
var err error
v := new(model.ArgJudgeBatchBlocked)
if err = c.Bind(v); err != nil {
return
}
err = creditSvc.AddBatchBlockedInfo(c, v)
if err != nil {
log.Error("creditSvc.AddBatchBlockedInfo(%+v) error(%v)", v, err)
c.JSON(nil, err)
return
}
c.JSON(nil, nil)
}
func blkHistorys(c *bm.Context) {
v := new(model.ArgHistory)
if err := c.Bind(v); err != nil {
return
}
rhs, err := creditSvc.BLKHistorys(c, v)
if err != nil {
log.Error("creditSvc.BLKHistorys(%+v) error(%v)", v, err)
c.JSON(nil, err)
return
}
c.JSON(rhs, nil)
}
func batchBLKInfos(c *bm.Context) {
v := new(model.ArgIDs)
if err := c.Bind(v); err != nil {
return
}
mbi, err := creditSvc.BatchBLKInfos(c, v.IDs)
if err != nil {
log.Error("creditSvc.BatchBLKInfos(%+v) error(%v)", v, err)
c.JSON(nil, err)
return
}
c.JSON(mbi, nil)
}

View File

@@ -0,0 +1,279 @@
package http
import (
model "go-common/app/interface/main/credit/model"
"go-common/library/ecode"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
)
// requirement user status in apply jury.
func requirement(c *bm.Context) {
mid, _ := c.Get("mid")
rq, err := creditSvc.Requirement(c, mid.(int64))
if err != nil {
log.Error("creditSvc.Requirement(%d) error(%v)", mid, err)
c.JSON(nil, err)
return
}
c.JSON(rq, nil)
}
// apply user apply jury.
func apply(c *bm.Context) {
mid, _ := c.Get("mid")
err := creditSvc.Apply(c, mid.(int64))
if err != nil {
log.Error("creditSvc.Apply(%d) error(%v)", mid, err)
c.JSON(nil, err)
return
}
c.JSON(nil, nil)
}
// jury jury user info.
func jury(c *bm.Context) {
mid, _ := c.Get("mid")
ui, err := creditSvc.Jury(c, mid.(int64))
if err != nil {
log.Error("creditSvc.Jury(%d) error(%v)", mid, err)
c.JSON(nil, err)
return
}
c.JSON(ui, nil)
}
// caseObtain jury user obtain case list.
func caseObtain(c *bm.Context) {
mid, _ := c.Get("mid")
v := new(model.ArgCid)
if err := c.Bind(v); err != nil {
return
}
id, err := creditSvc.CaseObtain(c, mid.(int64), v.Cid)
if err != nil {
log.Error("creditSvc.CaseObtain(%d) error(%v)", mid, err)
c.JSON(nil, err)
return
}
type reid struct {
CID int64 `json:"id"`
}
var data reid
data.CID = id
c.JSON(data, nil)
}
// caseObtainByID jury user obtain case list.
func caseObtainByID(c *bm.Context) {
mid, _ := c.Get("mid")
v := new(model.ArgCid)
if err := c.Bind(v); err != nil {
return
}
if v.Cid == 0 {
c.JSON(nil, ecode.RequestErr)
return
}
err := creditSvc.CaseObtainByID(c, mid.(int64), v.Cid)
if err != nil {
log.Error("creditSvc.CaseObtain(%d) error(%v)", mid, err)
c.JSON(nil, err)
return
}
type reid struct {
CID int64 `json:"id"`
}
var data reid
data.CID = v.Cid
c.JSON(data, nil)
}
// vote jury user vote case.
func vote(c *bm.Context) {
mid, _ := c.Get("mid")
v := new(model.ArgVote)
if err := c.Bind(v); err != nil {
return
}
if err := creditSvc.Vote(c, mid.(int64), v.Cid, v.Attr, v.Vote, v.AType, v.AReason, v.Content, v.Likes, v.Hates); err != nil {
log.Error("creditSvc.Vote(%d,%+v) error(%v)", mid, v, err)
c.JSON(nil, err)
return
}
c.JSON(nil, nil)
}
// voteInfo jury user vote info.
func voteInfo(c *bm.Context) {
mid, _ := c.Get("mid")
v := new(model.ArgCid)
if err := c.Bind(v); err != nil {
return
}
vi, err := creditSvc.VoteInfo(c, mid.(int64), v.Cid)
if err != nil {
log.Error("creditSvc.VoteInfo(%d %d) error(%v)", mid, v.Cid, err)
c.JSON(nil, err)
return
}
var data interface{}
if vi == nil || vi.MID == 0 {
data = &struct{}{}
} else {
data = vi
}
c.JSON(data, nil)
}
// caseInfo jury get case info.
func caseInfo(c *bm.Context) {
v := new(model.ArgCid)
if err := c.Bind(v); err != nil {
return
}
ci, err := creditSvc.CaseInfo(c, v.Cid)
if err != nil {
log.Error("creditSvc.CaseInfo(%d) error(%v)", v.Cid, err)
c.JSON(nil, err)
return
}
c.JSON(ci, nil)
}
// juryCase jury user case info contain vote.
func juryCase(c *bm.Context) {
mid, _ := c.Get("mid")
v := new(model.ArgCid)
if err := c.Bind(v); err != nil {
return
}
jc, err := creditSvc.JuryCase(c, mid.(int64), v.Cid)
if err != nil {
log.Error("creditSvc.JuryCase(%d %d) error(%v)", mid, v.Cid, err)
c.JSON(nil, err)
return
}
c.JSON(jc, nil)
}
// spJuryCase get specific jury case info.
func spJuryCase(c *bm.Context) {
var mid int64
iMid, ok := c.Get("mid")
if ok {
mid = iMid.(int64)
}
v := new(model.ArgCid)
if err := c.Bind(v); err != nil {
return
}
jc, err := creditSvc.SpJuryCase(c, mid, v.Cid)
if err != nil {
log.Error("creditSvc.JuryCase(%d %d) error(%v)", mid, v.Cid, err)
c.JSON(nil, err)
return
}
c.JSON(jc, nil)
}
// caseList user case list.
func caseList(c *bm.Context) {
mid, _ := c.Get("mid")
v := new(model.ArgPage)
if err := c.Bind(v); err != nil {
return
}
cl, err := creditSvc.CaseList(c, mid.(int64), v.PN, v.PS)
if err != nil {
log.Error("creditSvc.CaseList(%d,%d,%d) error(%v)", mid, v.PN, v.PS, err)
c.JSON(nil, err)
return
}
c.JSON(cl, nil)
}
// notice get jury notice.
func notice(c *bm.Context) {
n, err := creditSvc.Notice(c)
if err != nil {
log.Error("creditSvc.notice error(%v)", err)
c.JSON(nil, err)
return
}
c.JSON(n, nil)
}
// reasonList get reason list.
func reasonList(c *bm.Context) {
n, err := creditSvc.ReasonList(c)
if err != nil {
log.Error("creditSvc.ReasonList error(%v)", err)
c.JSON(nil, err)
return
}
c.JSON(n, nil)
}
// kpiList get kpi list.
func kpiList(c *bm.Context) {
mid, _ := c.Get("mid")
n, err := creditSvc.KPIList(c, mid.(int64))
if err != nil {
log.Error("creditSvc.KpiList error(%v)", err)
c.JSON(nil, err)
return
}
c.JSON(n, nil)
}
// voteOpinion get vote opinion.
func voteOpinion(c *bm.Context) {
v := new(model.ArgOpinion)
if err := c.Bind(v); err != nil {
return
}
ops, count, err := creditSvc.VoteOpinion(c, v.Cid, v.PN, v.PS, v.Otype)
if err != nil {
log.Error("creditSvc.VoteOpinion error(%v)", err)
c.JSON(nil, err)
return
}
c.JSON(&model.OpinionRes{
Count: count,
Opinion: ops,
}, nil)
}
// caseOpinion get case opinion.
func caseOpinion(c *bm.Context) {
v := new(model.ArgOpinion)
if err := c.Bind(v); err != nil {
return
}
ops, count, err := creditSvc.CaseOpinion(c, v.Cid, v.PN, v.PS)
if err != nil {
log.Error("creditSvc.CaseOpinion error(%v)", err)
c.JSON(nil, err)
return
}
c.JSON(&model.OpinionRes{
Count: count,
Opinion: ops,
}, nil)
}
// batchBLKCases get case info.
func batchBLKCases(c *bm.Context) {
v := new(model.ArgIDs)
if err := c.Bind(v); err != nil {
return
}
cases, err := creditSvc.BatchBLKCases(c, v.IDs)
if err != nil {
log.Error("creditSvc.BatchBLKCases(%+v) error(%+v)", v.IDs, err)
c.JSON(nil, err)
return
}
c.JSON(cases, nil)
}

View File

@@ -0,0 +1,111 @@
package http
import (
"net/http"
"go-common/app/interface/main/credit/conf"
"go-common/app/interface/main/credit/service"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
"go-common/library/net/http/blademaster/middleware/antispam"
"go-common/library/net/http/blademaster/middleware/auth"
"go-common/library/net/http/blademaster/middleware/verify"
)
var (
creditSvc *service.Service
verifySvc *verify.Verify
authSvc *auth.Auth
antSvc *antispam.Antispam
)
// Init init http sever instance.
func Init(c *conf.Config) {
initService(c)
engineInner := bm.DefaultServer((c.BM.Inner))
// init inner router
innerRouter(engineInner)
if err := engineInner.Start(); err != nil {
log.Error("engineInner.Start() error(%v)", err)
panic(err)
}
}
// initService init service
func initService(c *conf.Config) {
verifySvc = verify.New(c.Verify)
authSvc = auth.New(c.AuthN)
creditSvc = service.New(c)
antSvc = antispam.New(c.Antispam)
}
// innerRouter init inner router.
func innerRouter(e *bm.Engine) {
// ping monitor
e.Ping(ping)
// internal api
ig := e.Group("/x/internal/credit", verifySvc.Verify)
{
ig.POST("/labour/addQs", addQs)
ig.POST("/labour/setQs", setQs)
ig.POST("/labour/delQs", delQs)
ig.GET("/labour/isanswered", isAnswered)
// blocked
ig.POST("/blocked/case/add", addBlockedCase)
ig.POST("/blocked/info/add", addBlockedInfo)
ig.POST("/blocked/info/batch/add", addBatchBlockedInfo)
ig.GET("/blocked/user/num", blockedNumUser)
ig.GET("/blocked/infos", batchBLKInfos)
ig.GET("/blocked/cases", batchBLKCases)
ig.GET("/blocked/historys", blkHistorys)
// jury
ig.GET("/jury/infos", batchJuryInfos)
// other
ig.POST("/opinion/del", delOpinion)
ig.GET("/publish/infos", batchPublishs)
}
og := e.Group("/x/credit", bm.CORS())
{
// jury
og.GET("/jury/requirement", authSvc.User, requirement)
og.POST("/jury/apply", authSvc.User, apply)
og.GET("/jury/jury", authSvc.User, jury)
og.POST("/jury/caseObtain", authSvc.User, caseObtain)
og.POST("/jury/vote", authSvc.User, vote)
og.GET("/jury/voteInfo", authSvc.User, voteInfo)
og.GET("/jury/caseInfo", authSvc.Guest, caseInfo)
og.GET("/jury/juryCase", authSvc.User, juryCase)
og.GET("/jury/caseList", authSvc.User, caseList)
og.GET("/jury/kpi", authSvc.User, kpiList)
og.GET("/jury/vote/opinion", authSvc.Guest, voteOpinion)
og.GET("/jury/case/opinion", authSvc.Guest, caseOpinion)
og.GET("/jury/notice", notice)
og.GET("/jury/reasonList", reasonList)
og.POST("/jury/caseObtain/open", authSvc.User, caseObtainByID)
og.GET("/jury/juryCase/open", authSvc.Guest, spJuryCase)
// appeal
og.POST("/jury/appeal/add", authSvc.User, addAppeal)
og.GET("/jury/appeal/status", authSvc.User, appealStatus)
// labour
og.GET("/labour/getQs", authSvc.User, getQs)
og.POST("/labour/commitQs", authSvc.User, antSvc.Handler(), commitQs)
// blocked
og.GET("/blocked/user", authSvc.User, blockedUserCard)
og.GET("/blocked/user/list", authSvc.User, blockedUserList)
og.GET("/blocked/info", blockedInfo)
og.GET("/blocked/info/appeal", authSvc.User, blockedAppeal)
og.GET("/blocked/list", blockedList)
// announcement
og.GET("/publish/info", announcementInfo)
og.GET("/publish/list", announcementList)
}
}
// ping check server ok.
func ping(c *bm.Context) {
err := creditSvc.Ping(c)
if err != nil {
log.Error("credit interface ping error")
c.AbortWithStatus(http.StatusServiceUnavailable)
}
}

View File

@@ -0,0 +1,72 @@
package http
import (
"encoding/json"
"strconv"
"go-common/app/interface/main/credit/model"
"go-common/library/ecode"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
)
func delOpinion(c *bm.Context) {
var (
err error
cid int64
opid int64
params = c.Request.Form
cidStr = params.Get("cid")
opidStr = params.Get("opid")
)
if cid, err = strconv.ParseInt(cidStr, 10, 64); err != nil {
log.Error("strconv.ParseInt err(err) %v", err)
c.JSON(nil, ecode.RequestErr)
return
}
if opid, err = strconv.ParseInt(opidStr, 10, 64); err != nil {
log.Error("strconv.ParseInt err(err) %v", err)
c.JSON(nil, ecode.RequestErr)
return
}
if err = creditSvc.DelOpinion(c, cid, opid); err != nil {
log.Error("creditSvc.DelOpinion(%d,%d) error(err) %v", cid, opid, err)
c.JSON(nil, err)
return
}
c.JSON(nil, nil)
}
func addBlockedCase(c *bm.Context) {
var (
err error
params = c.Request.Form
data = params.Get("data")
bc = make([]*model.ArgJudgeCase, 0)
)
if err = json.Unmarshal([]byte(data), &bc); err != nil {
log.Error("json.Unmarshal(%s),err:%v.", data, err)
c.JSON(nil, ecode.RequestErr)
return
}
if err = creditSvc.AddBlockedCases(c, bc); err != nil {
log.Error("creditSvc.AddBlockedCases error(err) %v", err)
c.JSON(nil, err)
return
}
c.JSON(nil, nil)
}
func batchJuryInfos(c *bm.Context) {
v := new(model.ArgMIDs)
if err := c.Bind(v); err != nil {
return
}
mbj, err := creditSvc.JuryInfos(c, v.MIDs)
if err != nil {
log.Error("creditSvc.JuryInfos(%+v) error(%v)", v, err)
c.JSON(nil, err)
return
}
c.JSON(mbj, nil)
}

View File

@@ -0,0 +1,140 @@
package http
import (
"strconv"
model "go-common/app/interface/main/credit/model"
"go-common/library/ecode"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
"go-common/library/xstr"
)
func getQs(c *bm.Context) {
mid, _ := c.Get("mid")
qs, err := creditSvc.GetQs(c, mid.(int64))
if err != nil {
log.Error("creditSvc.getQs(%d) error(%v)", mid, err)
c.JSON(nil, err)
return
}
c.JSON(qs, nil)
}
func commitQs(c *bm.Context) {
var (
mid, _ = c.Get("mid")
params = c.Request.Form
idStr = params.Get("id")
buvidStr = params.Get("buvid")
anStr = params.Get("ans")
labourAns = &model.LabourAns{}
refer = c.Request.Referer()
ua = c.Request.UserAgent()
)
ids, err := xstr.SplitInts(idStr)
if err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
answer, err := xstr.SplitInts(anStr)
if err != nil {
c.JSON(nil, ecode.RequestErr)
return
}
labourAns.ID = ids
labourAns.Answer = answer
commitRes, err := creditSvc.CommitQs(c, mid.(int64), refer, ua, buvidStr, labourAns)
if err != nil {
log.Error("creditSvc.commitQs(%d) error(%v)", mid, err)
c.JSON(nil, err)
return
}
c.JSON(commitRes, nil)
}
func addQs(c *bm.Context) {
var (
params = c.Request.Form
question = params.Get("question")
ansStr = params.Get("ans")
avIDStr = params.Get("av_id")
statusStr = params.Get("status")
sourceStr = params.Get("source")
)
ans, err := strconv.ParseInt(ansStr, 10, 64)
if err != nil || ans < 0 {
c.JSON(nil, ecode.RequestErr)
return
}
avID, err := strconv.ParseInt(avIDStr, 10, 64)
if err != nil || avID <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
status, err := strconv.ParseInt(statusStr, 10, 64)
if err != nil || status <= 0 {
c.JSON(nil, ecode.RequestErr)
return
}
source, err := strconv.ParseInt(sourceStr, 10, 64)
if err != nil || source < 0 {
c.JSON(nil, ecode.RequestErr)
return
}
var qs = &model.LabourQs{Question: question, Ans: ans, AvID: avID, Status: status, Source: source}
if err = creditSvc.AddQs(c, qs); err != nil {
log.Error("creditSvc.AddQs(%+v) error(%v)", qs, err)
c.JSON(nil, err)
return
}
c.JSON(nil, nil)
}
func setQs(c *bm.Context) {
var (
params = c.Request.Form
id, _ = strconv.ParseInt(params.Get("id"), 10, 64)
ans, _ = strconv.ParseInt(params.Get("ans"), 10, 64)
status, _ = strconv.ParseInt(params.Get("status"), 10, 64)
)
if err := creditSvc.SetQs(c, id, ans, status); err != nil {
log.Error("creditSvc.SetQs(id:%d ans:%d status:%d) error(%v)", id, ans, status, err)
c.JSON(nil, err)
return
}
c.JSON(nil, nil)
}
func delQs(c *bm.Context) {
var err error
v := new(model.ArgDElQS)
if err = c.Bind(v); err != nil {
return
}
if err = creditSvc.DelQs(c, v.ID, v.IsDel); err != nil {
log.Error("creditSvc.delQs(id:%d isDel:%d error(%v)", v.ID, v.IsDel, err)
c.JSON(nil, err)
return
}
c.JSON(nil, nil)
}
func isAnswered(c *bm.Context) {
v := new(model.ArgHistory)
if err := c.Bind(v); err != nil {
return
}
anState, err := creditSvc.IsAnswered(c, v.MID, v.STime)
if err != nil {
log.Error("creditSvc.isanswered(mid:%d mtime:%d error(%v)", v.MID, v.STime, err)
c.JSON(nil, err)
return
}
type data struct {
Status int8 `json:"status"`
}
var rs data
rs.Status = anState
c.JSON(rs, nil)
}

View File

@@ -0,0 +1,43 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = [
"appeal.go",
"archive.go",
"blocked.go",
"credit.go",
"credit_state.go",
"jury.go",
"labour.go",
"manager.go",
"param.go",
"rpc.go",
],
importpath = "go-common/app/interface/main/credit/model",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/service/main/archive/model/archive:go_default_library",
"//library/time: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,73 @@
package model
import (
"go-common/library/time"
)
// Appeal state
const (
// StateCreate 用户刚创建申诉
StateCreate = 1
// StateReply 管理员回复,并且用户已读
StateReply = 2
// StateAdminClose 管理员关闭申诉
StateAdminClose = 3
// StateUserFinished 用户已解决申诉(评分)
StateUserFinished = 4
// StateTimeoutClose 超时关闭申诉
StateTimeoutClose = 5
// StateNoRead 管理员回复,用户未读
StateNoRead = 6
// StateUserClosed 用户直接关闭申诉
StateUserClosed = 7
// StateAdminFinished 管理员已通过申诉
StateAdminFinished = 8
// EventStateAdminReply 管理员回复
EventStateAdminReply = 1
// EventStateAdminNote 管理员回复并记录
EventStateAdminNote = 2
// EventStateUserReply 用户回复
EventStateUserReply = 3
// EventStateSystem 系统回复
EventStateSystem = 4
// appeal business
Business = 5
)
// Appeal info.
type Appeal struct {
ID int64 `json:"id"`
Oid int64 `json:"oid"`
Cid int64 `json:"cid"`
Mid int64 `json:"mid"`
Aid int64 `json:"aid"`
Tid int8 `json:"tid"`
Title string `json:"title"`
State int8 `json:"state"`
Visit int8 `json:"visit"`
QQ string `json:"qq"`
Email string `json:"email"`
Phone string `json:"phone"`
Pics string `json:"pics"`
Content string `json:"content"`
Description string `json:"description"`
Star int8 `json:"star"`
CTime time.Time `json:"ctime"`
MTime time.Time `json:"mtime"`
}
// IsOpen appeal open state.
func IsOpen(state int8) bool {
return state == StateCreate || state == StateReply || state == StateNoRead
}
// OpenedStates open get appeal
func OpenedStates() (states []int64) {
return []int64{StateCreate, StateReply, StateNoRead}
}
// ClosedStates get appeal
func ClosedStates() (states []int64) {
return []int64{StateAdminClose, StateUserFinished, StateTimeoutClose, StateUserClosed, StateAdminFinished}
}

View File

@@ -0,0 +1,10 @@
package model
import (
arcMDL "go-common/app/service/main/archive/model/archive"
)
// ArcVisible .
func ArcVisible(state int32) bool {
return state == arcMDL.StateOpen || state == arcMDL.StateOrange || state == arcMDL.StateForbidFixed
}

View File

@@ -0,0 +1,38 @@
package model
import "go-common/library/time"
// BlockedUserCard usr blocked info.
type BlockedUserCard struct {
UID int64 `json:"uid"`
Uname string `json:"uname"`
Face string `json:"face"`
BlockedSum int `json:"blockedSum"`
MoralBlockedSum int `json:"moralBlockedSum"`
MoralNum int `json:"moralNum"`
BlockedStatus int `json:"blockedStatus"`
BlockedForever bool `json:"blockedForever"`
BlockedRestDay int64 `json:"blockedRestDays"`
AnsWerStatus bool `json:"answerStatus"`
BlockedEndTime int64 `json:"blockedEndTime"`
}
// BlockedAnnouncement blocked publish info.
type BlockedAnnouncement struct {
ID int64 `json:"id"`
Title string `json:"title"`
SubTitle string `json:"subTitle"`
PublishStatus uint8 `json:"-"`
StickStatus uint8 `json:"stickStatus"`
Content string `json:"content"`
URL string `json:"url"`
Ptype int8 `json:"ptype"`
CTime time.Time `json:"ctime"`
MTime time.Time `json:"mtime"`
}
// AnnounceList announce list.
type AnnounceList struct {
List []*BlockedAnnouncement `json:"list"`
Count int64 `json:"count"`
}

View File

@@ -0,0 +1,217 @@
package model
import (
"fmt"
xtime "go-common/library/time"
)
// CreditInfo credit info.
type CreditInfo struct {
Mid int64 `json:"mid"`
Status int64 `json:"status"`
PunishType int64 `json:"blockedType"`
PunishEnd xtime.Time `json:"punishEnd"`
CTime xtime.Time `json:"-"`
MTime xtime.Time `json:"mtime"`
}
// BlockedInfo blocked case info.
type BlockedInfo struct {
ID int64 `json:"id"`
Uname string `json:"uname"`
Face string `json:"face"`
UID int64 `json:"uid"`
OriginTitle string `json:"originTitle"`
BlockedRemark string `json:"blockedRemark"`
OriginURL string `json:"originUrl"`
OriginContent string `json:"originContent,omitempty"`
OriginContentModify string `json:"originContentModify"`
OriginType int64 `json:"originType"`
OriginTypeName string `json:"originTypeName"`
PunishTitle string `json:"punishTitle"`
PunishTime xtime.Time `json:"punishTime"`
PunishType int64 `json:"punishType"`
PunishTypeName string `json:"punishTypeName"`
MoralNum int64 `json:"moralNum"`
BlockedDays int64 `json:"blockedDays"`
PublishStatus int64 `json:"publishStatus"`
BlockedType int64 `json:"blockedType"`
BlockedForever int64 `json:"blockedForever"`
ReasonType int64 `json:"reasonType"`
ReasonTypeName string `json:"reasonTypeName"`
OperatorName string `json:"operatorName"`
CaseID int64 `json:"caseId"`
PublishTime xtime.Time `json:"-"`
CTime xtime.Time `json:"ctime"`
MTime xtime.Time `json:"-"`
CommentSum int64 `json:"commentSum"`
OID int64 `json:"-"`
}
// BlockedPublish blocked publish info.
type BlockedPublish struct {
ID int64 `json:"id"`
Title string `json:"title"`
SubTitle string `json:"subTitle"`
PublishStatus int8 `json:"publishStatus"`
StickStatus int8 `json:"stickStatus"`
Content string `json:"content"`
CTime xtime.Time `json:"ctime"`
MTime xtime.Time `json:"mtime"`
URL string `json:"url"`
}
// BlockedCase blocked case info.
type BlockedCase struct {
ID int64 `json:"id"`
MID int64 `json:"mid"`
Status int8 `json:"status"`
StatusTitle string `json:"statusTitle,omitempty"`
OriginType int8 `json:"originType"`
ReasonType int8 `json:"reasonType"`
OriginContent string `json:"originContent"`
PunishResult int64 `json:"punishResult"`
PunishTitle string `json:"punishTitle,omitempty"`
JudgeType int8 `json:"judgeType"`
OriginURL string `json:"originUrl"`
BlockedDays int32 `json:"blockedDays"`
PutTotal int64 `json:"putTotal"`
VoteRule int64 `json:"voteRule"`
VoteBreak int64 `json:"voteBreak"`
VoteDelete int64 `json:"voteDelete"`
StartTime xtime.Time `json:"startTime"`
EndTime xtime.Time `json:"endTime"`
Operator string `json:"-"`
CTime xtime.Time `json:"ctime"`
MTime xtime.Time `json:"mtime"`
OriginTitle string `json:"originTitle"`
RelationID string `json:"relationId"`
Face string `json:"face"`
Uname string `json:"uname"`
Vote int8 `json:"vote"`
VoteTime xtime.Time `json:"voteTime,omitempty"`
ExpiredMillis int64 `json:"expiredMillis,omitempty"`
CaseType int8 `json:"case_type"`
}
// BlockedCaseVote blocked_case_vote.
type BlockedCaseVote struct {
ID int64 `json:"id"`
CID int64 `json:"cid"`
MID int64 `json:"mid"`
Vote int8 `json:"vote"`
CTime xtime.Time `json:"ctime"`
MTime xtime.Time `json:"mtime"`
Expired xtime.Time `json:"expired"`
}
// BlockedJury blocked jury info.
type BlockedJury struct {
ID int64 `json:"id"`
MID int64 `json:"mid"`
Status int8 `json:"status"`
Expired xtime.Time `json:"expired"`
InvalidReason int8 `json:"invalidReason"`
VoteTotal int64 `json:"voteTotal"`
CaseTotal int64 `json:"caseTotal"`
VoteRadio int64 `json:"voteRadio"`
CTime xtime.Time `json:"ctime"`
MTime xtime.Time `json:"mtime"`
VoteRight int64 `json:"voteRight"`
Black int8 `json:"black"`
}
// JuryRequirement jury requirement info.
type JuryRequirement struct {
Blocked bool `json:"blocked"`
Cert bool `json:"cert"`
Level bool `json:"level"`
Rule bool `json:"rule"`
}
//UserInfo jury interface
type UserInfo struct {
CaseTotal int64 `json:"caseTotal"`
Face string `json:"face"`
RestDays int64 `json:"restDays"`
RightRadio int64 `json:"rightRadio"`
Status int8 `json:"status"`
Uname string `json:"uname"`
}
// BlockedConfig config struct.
type BlockedConfig struct {
CaseGiveHours string `json:"caseGiveHours"`
CaseCheckHours string `json:"caseCheckHours"`
JuryVoteRadio string `json:"juryVoteRadio"`
CaseJudgeRadio string `json:"caseJudgeRadio"`
CaseVoteMin string `json:"caseVoteMin"`
}
// VoteInfo vote info.
type VoteInfo struct {
ID int64 `json:"id"`
MID int64 `json:"mid"`
Vote int8 `json:"vote"`
CID int64 `json:"cid"`
Expired xtime.Time `json:"expired"`
Mtime xtime.Time `json:"mtime"`
}
// CaseInfo struct
type CaseInfo struct {
EndTime xtime.Time `json:"endTime"`
Face string `json:"face"`
ID int64 `json:"id"`
OriginContent string `json:"originContent"`
OriginTitle string `json:"originTitle"`
OriginURL string `json:"originUrl"`
Status int8 `json:"status"`
UID int64 `json:"uid"`
Uname string `json:"uname"`
VoteBreak int64 `json:"voteBreak"`
VoteRule int64 `json:"voteRule"`
}
// Build set blocked title info.
func (bi *BlockedInfo) Build() {
bi.OriginTypeName = _originType[int8(bi.OriginType)]
bi.ReasonTypeName = _reasonType[int8(bi.ReasonType)]
bi.PunishTypeName = _punishType[int8(bi.PunishType)]
bi.PunishTitle = fmt.Sprintf("在%s中%s", bi.OriginTypeName, bi.ReasonTypeName)
}
// Build set blocked title info.
func (bc *BlockedCase) Build() {
bc.PunishTitle = fmt.Sprintf("在%s中%s", _originType[int8(bc.OriginType)], _reasonType[int8(bc.ReasonType)])
}
// CheckVote check vote.
func CheckVote(vote int8) (ok bool) {
if vote == VoteBanned || vote == VoteRule || vote == VoteAbstain || vote == VoteDel {
ok = true
}
return
}
// IsCaseTypePublic is case type public.
func IsCaseTypePublic(caseType int8) (ok bool) {
if caseType == JudeCaseTypePublic {
ok = true
}
return
}
// GantMedalID .
func (bj *BlockedJury) GantMedalID() int64 {
switch bj.CaseTotal {
case GuardMedalPointC:
return GuardMedalC
case GuardMedalPointB:
return GuardMedalB
case GuardMedalPointA:
return GuardMedalA
}
return GuardMedalNone
}

View File

@@ -0,0 +1,337 @@
package model
// const credit state
const (
// blocked_opinion
BlockedOpinionAttrOn = int8(1)
BlockedOPinionAttrOff = int8(0)
// blocked_info.block_type
PunishBlock = int8(0) // 系统封禁
PunishJury = int8(1) // 风纪仲裁
CreditStatusBlocked = -2
// blocked_info.punish_type
PunishTypeMoral = int8(1)
PunishTypeBlock = int8(2)
PunishTypeForever = int8(3)
// Publish type
PublishTypedef = int8(0)
PublishTypePunish = int8(1)
PublishTypeBan = int8(2)
PublishTypeOptimize = int8(3)
// publish status
PublishStatusClose = int8(0) // 案件关闭状态
PublishStatusOpen = int8(1) // 案件公开状态
// origin_type.
OriginReply = int8(1) // 评论
OriginDM = int8(2) // 弹幕
OriginMsg = int8(3) // 私信
OriginTag = int8(4) // 标签
OriginMember = int8(5) // 个人资料
OriginArchive = int8(6) // 投稿
OriginMusic = int8(7) // 音频
OriginArticle = int8(8) // 专栏
OriginSpaceTop = int8(9) // 空间头图
OriginDsynamic = int8(10) // 动态
OriginPhoto = int8(11) // 相册
OriginMinVideo = int8(12) // 小视频
// blocked_publish init lenth
PublishInitLen = 4
// blocked_jury.status
JuryStatusEffect = int8(1)
JuryStatusNoEffect = int8(2)
// blocked_jury.case_type
JudeCaseTypePrivate = int8(0) // 小众众裁
JudeCaseTypePublic = int8(1) // 大众众裁
// case obtain day by mid
CaseObtainToday = true
CaseObtainNoToday = false
// message
ApplyJuryTitle = "获得风纪委员资格"
ApplyJuryContext = `恭喜您获得%d天风纪委员资格风纪委员应遵守以下原则
"1. 在了解举报案件背景后,公正客观投票。对不了解或难以判断的案件,可以选择弃权。
"2. 以身作则,不在举报案件相关视频、评论下讨论或发布不相关内容。相关违规举报被落实处罚后,将会失去风纪委员资格。`
AppealTitle = "申诉处理通知"
MaxAddCaseNum = 100 //批量增加案件最大数量
// list multi juryer info
JuryMultiJuryerInfoMax = 50
// jury expired
JuryExpiredDays = 30
// one day
OneDaySecond = 86400
// black or white
JuryBlack = int8(1)
JuryWhite = int8(2)
// blocked_info blocked_forever
NotInBlockedForever = int8(0)
InBlockedForever = int8(1)
// blocked_info blocked_forever bool
BlockedStateForever = true
BlockedStateNoForever = false
// guard
GuardMedalPointA = int64(5000)
GuardMedalPointB = int64(1000)
GuardMedalPointC = int64(200)
GuardMedalNone = int64(0)
GuardMedalA = int64(69)
GuardMedalB = int64(68)
GuardMedalC = int64(67)
// reasonType
ReasonOtherType = int8(0)
ReasonBrushScreen = int8(1)
ReasonGrabFloor = int8(2)
ReasonGamblingFraud = int8(4)
ReasonProhibited = int8(5)
ReasonGarbageAds = int8(6)
ReasonPersonalAttacks = int8(7)
ReasonViolatePrivacy = int8(8)
ReasonLeadBattle = int8(9)
ReasonSpoiler = int8(10)
ReasonAddUnrelatedTags = int8(11)
ReasonDelOtherTags = int8(12)
ReasonPornographic = int8(13)
ReasonVulgar = int8(14)
ReasonBloodyViolence = int8(15)
ReasonAnimusVideoUp = int8(16)
ReasonIllegalWebsite = int8(17)
ReasonSpreadErrinfo = int8(18)
ReasonAbettingEncouragement = int8(19)
ReasonAnimusBrushScreen = int8(20)
ReasonAccountViolation = int8(21)
ReasonMaliciousPlagiarism = int8(22)
ReasonPosingAsHomemade = int8(23)
ReasonPostTeenBadContent = int8(24)
ReasonDestroyCyberSecurity = int8(25)
ReasonPostingMisleadingInfo = int8(26)
ReasonCounterfeitOfficialAuth = int8(27)
ReasonPublishInappropriateContent = int8(28)
ReasonViolationOperatingRules = int8(29)
ReasonIllegalCreateTopic = int8(30)
ReasonIllegalDrawLottery = int8(31)
ReasonIllegalFakeMan = int8(32)
// reply reasonType
ReplyReasonOtherType = int8(0)
ReplyReasonGarbageAds = int8(1)
ReplyReasonPornographic = int8(2)
ReplyReasonAnimusBrushScreen = int8(3)
ReplyReasonLeadBattle = int8(4)
ReplyReasonSpoiler = int8(5)
ReplyReasonPolitical = int8(6)
ReplyReasonPersonalAttacks = int8(7)
ReplyReasonIrrelevantVideo = int8(8)
ReplyReasonProhibited = int8(9)
ReplyReasonVulgar = int8(10)
ReplyReasonIllegalWebsite = int8(11)
ReplyReasonGamblingFraud = int8(12)
ReplyReasonSpreadErrinfo = int8(13)
ReplyReasonAbettingEncouragement = int8(14)
ReplyReasonViolatePrivacy = int8(15)
ReplyReasonGrabFloor = int8(16)
ReplyReasonPostTeenBadContent = int8(17)
// tag reasonType
TagReasonAddUnrelatedTags = int8(1)
TagReasonProhibited = int8(2)
TagReasonPersonalAttacks = int8(3)
TagReasonSpoiler = int8(4)
TagReasonDelOtherTags = int8(5)
// case status.
CaseStatusGranting = 1 // 发放中
CaseStatusGrantStop = 2 // 停止发放
CaseStatusDealing = 3 // 结案中
CaseStatusDealed = 4 // 已裁决
CaseStatusRestart = 5 // 待重启
CaseStatusUndealed = 6 // 未裁决
CaseStatusFreeze = 7 // 冻结中
CaseStatusQueueing = 8 // 队列中
// blocked_case.punish_result
BlockNone = int8(0)
Block3Days = int8(1)
Block7Days = int8(2)
BlockForever = int8(3)
BlockCustom = int8(4)
Block15Days = int8(5)
BlockOnlyDel = int8(6)
// judge status.
JudgeTypeUndeal = 0 // 未裁决
JudgeTypeViolate = 1 // 违规
JudgeTypeLegal = 2 // 未违规
// vote type
VoteBanned = 1 // 违规封禁
VoteRule = 2
VoteAbstain = 3
VoteDel = 4 // 违规删除
// opinion type
OpinonBreak = 1 // 违规观点
OpinionRule = 2 // 不违规观点
// labour ans
LabourNoAnswer = int8(0)
LabourOkAnswer = int8(1)
// opinion state
OpinionStateOK = int8(0)
OpinionStateNoOK = int8(1)
// kpi rate
KPILevelS = int8(1)
KPILevelA = int8(2)
KPILevelB = int8(3)
KPILevelC = int8(4)
KPILevelD = int8(5)
// block status
BlockStatusNone = int8(0)
BlockStatusForever = int8(1)
BlockStatusOn = int8(2)
)
// var credit state
var (
_punishResult = map[int8]string{
BlockNone: "",
Block3Days: "封禁3天",
Block7Days: "封禁7天",
BlockForever: "永久封禁",
BlockCustom: "封禁%d天",
Block15Days: "封禁15天",
BlockOnlyDel: "扣节操",
}
_punishType = map[int8]string{
PunishTypeMoral: "节操",
PunishTypeBlock: "封禁",
PunishTypeForever: "永久封禁",
}
_reasonType = map[int8]string{
ReasonOtherType: "其他",
ReasonBrushScreen: "刷屏",
ReasonGrabFloor: "抢楼",
ReasonGamblingFraud: "发布赌博诈骗信息",
ReasonProhibited: "发布违禁相关信息",
ReasonGarbageAds: "发布垃圾广告信息",
ReasonPersonalAttacks: "发布人身攻击言论",
ReasonViolatePrivacy: "发布侵犯他人隐私信息",
ReasonLeadBattle: "发布引战言论",
ReasonSpoiler: "发布剧透信息",
ReasonAddUnrelatedTags: "恶意添加无关标签",
ReasonDelOtherTags: "恶意删除他人标签",
ReasonPornographic: "发布色情信息",
ReasonVulgar: "发布低俗信息",
ReasonBloodyViolence: "发布暴力血腥信息",
ReasonAnimusVideoUp: "涉及恶意投稿行为",
ReasonIllegalWebsite: "发布非法网站信息",
ReasonSpreadErrinfo: "发布传播不实信息",
ReasonAbettingEncouragement: "发布怂恿教唆信息",
ReasonAnimusBrushScreen: "恶意刷屏",
ReasonAccountViolation: "账号违规",
ReasonMaliciousPlagiarism: "恶意抄袭",
ReasonPosingAsHomemade: "冒充自制原创",
ReasonPostTeenBadContent: "发布青少年不良内容",
ReasonDestroyCyberSecurity: "破坏网络安全",
ReasonPostingMisleadingInfo: "发布虚假误导信息",
ReasonCounterfeitOfficialAuth: "仿冒官方认证账号",
ReasonPublishInappropriateContent: "发布不适宜内容",
ReasonViolationOperatingRules: "违反运营规则",
ReasonIllegalCreateTopic: "恶意创建话题",
ReasonIllegalDrawLottery: "发布违规抽奖",
ReasonIllegalFakeMan: "恶意冒充他人",
}
_originType = map[int8]string{
OriginReply: "评论",
OriginDM: "弹幕",
OriginMsg: "私信",
OriginTag: "标签",
OriginMember: "个人资料",
OriginArchive: "投稿",
OriginMusic: "音频",
OriginArticle: "专栏",
OriginSpaceTop: "空间头图",
OriginDsynamic: "动态",
OriginPhoto: "相册",
OriginMinVideo: "小视频",
}
_replyReasonType = map[int8]int8{
ReplyReasonOtherType: ReasonOtherType,
ReplyReasonGarbageAds: ReasonGarbageAds,
ReplyReasonPornographic: ReasonPornographic,
ReplyReasonAnimusBrushScreen: ReasonAnimusBrushScreen,
ReplyReasonLeadBattle: ReasonLeadBattle,
ReplyReasonSpoiler: ReasonSpoiler,
ReplyReasonPolitical: ReasonOtherType,
ReplyReasonPersonalAttacks: ReasonPersonalAttacks,
ReplyReasonIrrelevantVideo: ReasonOtherType,
ReplyReasonProhibited: ReasonProhibited,
ReplyReasonVulgar: ReasonVulgar,
ReplyReasonIllegalWebsite: ReasonIllegalWebsite,
ReplyReasonGamblingFraud: ReasonGamblingFraud,
ReplyReasonSpreadErrinfo: ReasonSpreadErrinfo,
ReplyReasonAbettingEncouragement: ReasonAbettingEncouragement,
ReplyReasonViolatePrivacy: ReasonViolatePrivacy,
ReplyReasonGrabFloor: ReasonGrabFloor,
ReplyReasonPostTeenBadContent: ReasonPostTeenBadContent,
}
_tagReasonType = map[int8]int8{
TagReasonAddUnrelatedTags: ReasonAddUnrelatedTags,
TagReasonProhibited: ReasonProhibited,
TagReasonPersonalAttacks: ReasonPersonalAttacks,
TagReasonSpoiler: ReasonSpoiler,
TagReasonDelOtherTags: ReasonDelOtherTags,
}
)
// PunishResultDesc get PunishResult desc
func PunishResultDesc(punishResult int8) (desc string) {
desc = _punishResult[punishResult]
return
}
// PunishTypeDesc get punishType desc
func PunishTypeDesc(punishType int8) (desc string) {
desc = _punishType[punishType]
return
}
// ReasonTypeDesc get reasonType desc
func ReasonTypeDesc(reasonType int8) (desc string) {
desc = _reasonType[reasonType]
return
}
// OriginTypeDesc get originType desc
func OriginTypeDesc(originType int8) (desc string) {
desc = _originType[originType]
return
}
// BlockedReasonTypeByReply get blocked reason type.
func BlockedReasonTypeByReply(replyReasonType int8) (reasonType int8) {
reasonType = _replyReasonType[replyReasonType]
return
}
// BlockedReasonTypeByTag get blocked reason type.
func BlockedReasonTypeByTag(tagReasonType int8) (reasonType int8) {
reasonType = _tagReasonType[tagReasonType]
return
}

View File

@@ -0,0 +1,75 @@
package model
import xtime "go-common/library/time"
// Notice struct
type Notice struct {
ID int64 `json:"id"`
Content string `json:"content"`
URL string `json:"url"`
}
// Reason struct
type Reason struct {
ID int64 `json:"id"`
Reason string `json:"reason"`
Content string `json:"content"`
}
// KPI is jury kpi info.
type KPI struct {
ID int64 `json:"id"`
Mid int64 `json:"mid"`
Number int64 `json:"number"`
Day xtime.Time `json:"day"`
Rate int64 `json:"rate"`
Rank int64 `json:"rank"`
RankPer int64 `json:"rankper"`
RankTotal int64 `json:"rankTotal"`
Point int64 `json:"point"`
ActiveDays int64 `json:"activeDays"`
VoteTotal int64 `json:"voteTotal"`
VoteRadio int64 `json:"voteRadio"`
BlockedTotal int64 `json:"blockedTotal"`
TermStart xtime.Time `json:"termStart"`
TermEnd xtime.Time `json:"termEnd"`
OpinionLikes int64 `json:"opinion_likes"`
}
//KPIData is jury kpi data info.
type KPIData struct {
KPI
VoteRealTotal int64 `json:"vote_real_total"`
}
// Opinion jury vote opinion.
type Opinion struct {
// user info.
Mid int64 `json:"mid,omitempty"`
Face string `json:"face,omitempty"`
Name string `json:"name,omitempty"`
OpID int64 `json:"opid"`
Vote int8 `json:"vote"`
Content string `json:"content"`
Attr int8 `json:"attr"`
Hate int64 `json:"hate"`
Like int64 `json:"like"`
}
// OpinionRes get opinion response.
type OpinionRes struct {
Count int `json:"count"`
Opinion []*Opinion `json:"opinion"`
}
// SimCase struct
type SimCase struct {
ID int64 `json:"id"`
Mid int64 `json:"mid"`
VoteRule int64 `json:"vote_rule"`
VoteBreak int64 `json:"vote_break"`
VoteDelete int64 `json:"vote_delete"`
CaseType int8 `json:"case_type"`
Stime xtime.Time `json:"start_time"`
Etime xtime.Time `json:"end_time"`
}

View File

@@ -0,0 +1,73 @@
package model
import xtime "go-common/library/time"
// LabourQs labour question.
type LabourQs struct {
ID int64 `json:"id"`
Question string `json:"question"`
Ans int64 `json:"-"`
TrueAns int64 `json:"-"` // 真实答案 答案0:未知 1:违规 2:不违规
AvID int64 `json:"av_id"`
AvTitle string `json:"av_title"`
Status int64 `json:"-"`
Source int64 `json:"-"`
Ctime xtime.Time `json:"-"`
Mtime xtime.Time `json:"-"`
}
// LabourAns labour answer.
type LabourAns struct {
ID []int64
Answer []int64
}
//AIQsID AI give question id.
type AIQsID struct {
Pend []int64 `json:"pend"` // 未审核
Done []int64 `json:"done"` // 已审核
}
// DataBusResult databus结果
type DataBusResult struct {
Mid int64 `json:"mid"` // 用户 ID
Buvid string `json:"buvid"` // 设备标识符 前端传入
IP string `json:"ip"` // 用户 IP 地址
Ua string `json:"ua"` // 客户端 User Agent
Refer string `json:"refer"` // 页面跳转来源地址 Refer
Score int64 `json:"score"` // 答题总分数
Rs []Rs
}
// Rs struct
type Rs struct {
ID int64 `json:"id"` // 题目自增 ID
Question string `json:"question"` // 问题内容
Ans int64 `json:"ans"` // 用户答案
TrueAns int64 `json:"trueAns"` // 真实答案 答案0:未知 1:违规 2:不违规
AvID int64 `json:"av_id"` // 相关视频id
Status int64 `json:"status"` // 问题状态 1:未申核 2:已审核
Source int64 `json:"source"` // 问题来源 0:未知1:评论 2:弹幕
Ctime xtime.Time `json:"ctime"` // 创建时间
Mtime xtime.Time `json:"mtime"` // 修改时间
}
// BlockAndMoralStatus blocked status and moral.
type BlockAndMoralStatus struct {
MID int64 `json:"mid"`
Status int8 `json:"status"`
STime xtime.Time `json:"start_time"`
ETime xtime.Time `json:"end_time"`
}
// CommitRs struct
type CommitRs struct {
Score int64 `json:"score"`
Day int64 `json:"day"`
}
// QsCache struct
type QsCache struct {
Stime xtime.Time
QsStr string
}

View File

@@ -0,0 +1,7 @@
package model
// MangerInfo mangerInfo struct
type MangerInfo struct {
OID int64 `json:"id"`
Uname string `json:"username"`
}

View File

@@ -0,0 +1,124 @@
package model
import xtime "go-common/library/time"
// ArgPage define page param.
type ArgPage struct {
PN int64 `form:"pn" default:"1"`
PS int64 `form:"ps" validate:"min=0,max=30" default:"30"`
}
// ArgBlockedNumUser user blocked number param.
type ArgBlockedNumUser struct {
MID int64 `form:"mid" validate:"required"`
}
// ResBlockedNumUser user blocked number result.
type ResBlockedNumUser struct {
BlockedSum int `json:"blockedSum"`
}
// ArgIDs ids param.
type ArgIDs struct {
IDs []int64 `form:"ids,split" validate:"min=0,max=100"`
}
// ArgMIDs mids param.
type ArgMIDs struct {
MIDs []int64 `form:"mids,split" validate:"min=0,max=100"`
}
// ResJuryerStatus blocked juryer status result.
type ResJuryerStatus struct {
Expired xtime.Time `json:"expired"`
Mid int64 `json:"mid"`
Status int8 `json:"status"`
}
// ArgJudgeBlocked judge blocked param.
type ArgJudgeBlocked struct {
MID int64 `form:"mid" validate:"required"`
OID int64 `form:"oper_id" default:"0"`
BDays int `form:"blocked_days" default:"0"`
BForever int8 `form:"blocked_forever" default:"0"`
BRemark string `form:"blocked_remark" default:""`
MoralNum int `form:"moral_num" default:"0"`
OContent string `form:"origin_content" default:""`
OTitle string `form:"origin_title" default:""`
OType int8 `form:"origin_type" validate:"min=1,max=20"`
OURL string `form:"origin_url" default:""`
PTime int64 `form:"punish_time" validate:"required"`
PType int8 `form:"punish_type" validate:"min=1,max=10"`
RType int8 `form:"reason_type" validate:"min=1,max=40"`
OPName string `form:"operator_name" default:""`
}
// ArgJudgeBatchBlocked judge batch blocked param.
type ArgJudgeBatchBlocked struct {
MID []int64 `form:"mids,split" validate:"min=1,max=200"`
OID int64 `form:"oper_id" default:"0"`
BDays int `form:"blocked_days" default:"0"`
BForever int8 `form:"blocked_forever" default:"0"`
BRemark string `form:"blocked_remark" default:""`
MoralNum int `form:"moral_num" default:"0"`
OContent string `form:"origin_content" default:""`
OTitle string `form:"origin_title" default:""`
OType int8 `form:"origin_type" validate:"min=1,max=20"`
OURL string `form:"origin_url" default:""`
PTime int64 `form:"punish_time" validate:"required"`
PType int8 `form:"punish_type" validate:"min=1,max=10"`
RType int8 `form:"reason_type" validate:"min=1,max=40"`
OPName string `form:"operator_name" default:""`
}
// ArgHistory blocked historys param.
type ArgHistory struct {
MID int64 `form:"mid" validate:"required"`
STime int64 `form:"start" validate:"required"`
PN int `form:"pn" default:"1"`
PS int `form:"ps" validate:"min=0,max=100" default:"100"`
}
// ResBLKHistorys blocked historys result.
type ResBLKHistorys struct {
TotalCount int64 `json:"total_count"`
PN int `json:"pn"`
PS int `json:"ps"`
Items []*BlockedInfo `json:"items"`
}
// ArgJudgeCase judge case param.
type ArgJudgeCase struct {
AID int64 `json:"aid"`
MID int64 `json:"mid"`
Operator string `json:"operator"`
OperID int64 `json:"oper_id"`
OContent string `json:"origin_content"`
OTitle string `json:"origin_title"`
OType int64 `json:"origin_type"`
OURL string `json:"origin_url"`
ReasonType int64 `json:"reason_type"`
OID int64 `json:"oid"`
RPID int64 `json:"rp_id"`
TagID int64 `json:"tag_id"`
Type int64 `json:"type"`
Page int64 `json:"page"`
BCTime xtime.Time `json:"business_time"`
RelationID string `json:"-"`
PunishResult int8 `json:"-"`
BlockedDays int32 `json:"-"`
}
// ArgDElQS labour question del param.
type ArgDElQS struct {
ID int64 `form:"id" validate:"required"`
IsDel int64 `form:"is_del" validate:"min=1,max=3"`
}
// ArgBlockedList blocked list param.
type ArgBlockedList struct {
OType int8 `form:"otype" default:"0"`
BType int8 `form:"btype" default:"-1"`
PN int `form:"pn" validate:"min=1" default:"1"`
PS int `form:"ps" default:"20"`
}

View File

@@ -0,0 +1,87 @@
package model
// ArgMid is rpc mid params.
type ArgMid struct {
Mid int64
RealIP string
}
// ArgVote is rpc vote params.
type ArgVote struct {
Mid int64
Cid int64 `form:"cid" validate:"required"`
RealIP string
Vote int8 `form:"vote" validate:"min=1,max=4"`
Attr int8 `form:"attr" validate:"min=0,max=1" default:"0"`
Content string `form:"content"`
Likes []int64 `form:"likes,split" validate:"min=0,max=20"`
Hates []int64 `form:"hates,split" validate:"min=0,max=20"`
AType int8 `form:"apply_type" default:"0"`
AReason int8 `form:"apply_reason" default:"0"`
}
// ArgMidCid is rpc mid and cid params.
type ArgMidCid struct {
Mid, Cid int64
RealIP string
}
// ArgCid is rpc cid params.
type ArgCid struct {
Cid int64 `form:"cid"`
RealIP string
}
// ArgCaseList is rpc case list params.
type ArgCaseList struct {
Mid int64
RealIP string
Pn int64
Ps int64
}
// ArgSetQs is rpc set question params.
type ArgSetQs struct {
ID int64
Ans int64
Status int64
}
// ArgAns is rpc answer params.
type ArgAns struct {
Mid int64
RealIP string
Refer string
UA string
Buvid string
Ans *LabourAns
}
// ArgOpinion is rpc opinion arg.
type ArgOpinion struct {
Cid int64 `form:"cid" validate:"required"`
PN int64 `form:"pn" default:"1"`
PS int64 `form:"ps" validate:"min=0,max=10" default:"10"`
IP string
Otype int8 `form:"otype" validate:"min=1,max=2" default:"1"`
}
// ArgID id.
type ArgID struct {
ID int64
}
// ArgBlocked struct
type ArgBlocked struct {
Otype int64
Btype int64
PS int64
PN int64
}
// ArgAnnounce struct
type ArgAnnounce struct {
Type int8
PS int64
PN int64
}

View File

@@ -0,0 +1,76 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_test",
"go_library",
)
go_test(
name = "go_default_test",
srcs = [
"appeal_test.go",
"blocked_test.go",
"jury_test.go",
"labour_test.go",
"service_test.go",
],
embed = [":go_default_library"],
rundir = ".",
tags = ["automanaged"],
deps = [
"//app/interface/main/credit/conf:go_default_library",
"//app/interface/main/credit/model:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
],
)
go_library(
name = "go_default_library",
srcs = [
"appeal.go",
"blocked.go",
"extra_func.go",
"jury.go",
"labour.go",
"service.go",
],
importpath = "go-common/app/interface/main/credit/service",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/interface/main/credit/conf:go_default_library",
"//app/interface/main/credit/dao:go_default_library",
"//app/interface/main/credit/model:go_default_library",
"//app/service/main/account/api:go_default_library",
"//app/service/main/archive/api:go_default_library",
"//app/service/main/archive/api/gorpc:go_default_library",
"//app/service/main/archive/model/archive:go_default_library",
"//app/service/main/filter/api/grpc/v1:go_default_library",
"//app/service/main/member/api/gorpc:go_default_library",
"//app/service/main/member/model:go_default_library",
"//app/service/main/member/model/block:go_default_library",
"//library/database/sql:go_default_library",
"//library/ecode:go_default_library",
"//library/log:go_default_library",
"//library/net/metadata:go_default_library",
"//library/sync/errgroup:go_default_library",
"//library/time:go_default_library",
"//library/xstr:go_default_library",
"//vendor/github.com/pkg/errors:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

View File

@@ -0,0 +1,76 @@
package service
import (
"context"
"time"
"go-common/app/interface/main/credit/model"
"go-common/library/ecode"
xtime "go-common/library/time"
"github.com/pkg/errors"
)
// AddAppeal add a new appeal .
func (s *Service) AddAppeal(c context.Context, btid, bid, mid int64, reason string) (err error) {
var (
isID bool
origin string
ctime xtime.Time
caseID int64
)
infos, err := s.BlockedUserList(c, mid)
if err != nil {
err = errors.Wrap(err, "s.dao.BlockedUserList error")
return
}
for _, v := range infos {
if bid == v.ID {
isID = true
origin = v.OriginContent
ctime = v.CTime
caseID = v.CaseID
}
}
if !isID {
err = ecode.CreditBlockNotExist
return
}
if xtime.Time(time.Now().AddDate(0, 0, -7).Unix()) > ctime {
err = ecode.CreditBlockExpired
return
}
if err = s.dao.AddAppeal(c, s.tagMap[int8(btid)], btid, caseID, mid, model.Business, origin, reason); err != nil {
err = errors.Wrap(err, "s.AddAppeal error")
}
return
}
// AppealState appeal status .
func (s *Service) AppealState(c context.Context, mid, bid int64) (state bool, err error) {
block, err := s.BlockedInfoAppeal(c, bid, mid)
if err != nil {
err = errors.Wrap(err, "BlockedInfo error")
return
}
if block == nil || block.UID != mid {
err = ecode.CreditBlockNotExist
return
}
if xtime.Time(time.Now().AddDate(0, 0, -7).Unix()) > block.CTime {
err = ecode.CreditBlockExpired
return
}
aps, err := s.dao.AppealList(c, mid, model.Business)
if err != nil {
err = errors.Wrap(err, "s.dao.AppealList error")
return
}
for _, v := range aps {
if block.CaseID == v.Oid {
return
}
}
state = true
return
}

View File

@@ -0,0 +1,25 @@
package service
import (
"context"
"testing"
. "github.com/smartystreets/goconvey/convey"
)
// TestAddAppeal add appeal testing.
func TestAddAppeal(t *testing.T) {
Convey("TestAddAppeal", t, func() {
err := s.AddAppeal(context.TODO(), 1, 111, 2222, "测试")
So(err, ShouldBeNil)
})
}
// TestAppealState appealstate testing.
func TestAppealState(t *testing.T) {
Convey("TestAddAppeal", t, func() {
state, err := s.AppealState(context.TODO(), 1, 111)
So(err, ShouldBeNil)
So(state, ShouldEqual, true)
})
}

View File

@@ -0,0 +1,503 @@
package service
import (
"context"
"strconv"
"time"
"go-common/app/interface/main/credit/model"
acmdl "go-common/app/service/main/account/api"
blkmdl "go-common/app/service/main/member/model/block"
xsql "go-common/library/database/sql"
"go-common/library/ecode"
"go-common/library/log"
xtime "go-common/library/time"
"github.com/pkg/errors"
)
var (
_emptyAnnounce = []*model.BlockedAnnouncement{}
_emptyBlockInfo = []*model.BlockedInfo{}
)
// BlockedUserCard get user blocked card info.
func (s *Service) BlockedUserCard(c context.Context, mid int64) (card *model.BlockedUserCard, err error) {
var (
count int
profile *acmdl.ProfileReply
)
accArg := &acmdl.MidReq{Mid: mid}
if profile, err = s.accountClient.Profile3(c, accArg); err != nil {
err = errors.Wrap(err, "accountClient.Profile3")
return
}
card = &model.BlockedUserCard{UID: mid, Uname: profile.Profile.Name, Face: profile.Profile.Face}
if count, err = s.dao.BlockedCount(c, mid); err != nil {
return
}
card.BlockedSum = count
bms, err := s.memRPC.BlockInfo(c, &blkmdl.RPCArgInfo{MID: mid})
if err != nil {
return
}
card.BlockedStatus = int(bms.BlockStatus)
status := int8(bms.BlockStatus)
if status == model.BlockStatusForever || status == model.BlockStatusOn {
card.BlockedStatus = 1
// TODO nothing record in credit.
if count <= 0 {
card.BlockedSum = 1
}
}
if status == model.BlockStatusForever {
card.BlockedForever = model.BlockedStateForever
}
card.BlockedEndTime = bms.EndTime
card.MoralNum = int(profile.Profile.Moral)
if status != 0 {
delta := time.Until(time.Unix(bms.EndTime, 0))
if int(delta) > 0 {
card.BlockedRestDay = int64(delta / (time.Hour * 24))
if delta%(time.Hour*24) > 0 {
card.BlockedRestDay++
}
}
if card.AnsWerStatus, err = s.dao.AnswerStatus(c, mid, time.Unix(bms.StartTime, 0)); err != nil {
return
}
}
return
}
// BlockedUserList get user blocked info list
func (s *Service) BlockedUserList(c context.Context, mid int64) (r []*model.BlockedInfo, err error) {
var mc = true
if r, err = s.dao.BlockedUserListCache(c, mid); err != nil {
err = nil
mc = false
}
if len(r) > 0 {
return
}
if r, err = s.dao.BlockedUserList(c, mid); err != nil {
return
}
if mc && len(r) > 0 {
s.addCache(func() {
s.dao.SetBlockedUserListCache(context.TODO(), mid, r)
})
}
return
}
// BlockedInfo blocked info
func (s *Service) BlockedInfo(c context.Context, id int64) (info *model.BlockedInfo, err error) {
var mc = true
if info, err = s.dao.BlockedInfoCache(c, id); err != nil {
err = nil
mc = false
}
if info != nil {
if int8(info.PublishStatus) == model.PublishStatusClose {
err = ecode.NothingFound
}
return
}
if info, err = s.dao.BlockedInfoByID(c, id); err != nil {
err = errors.Wrapf(err, "BlockedInfoByID(%d)", id)
return
}
if info == nil || (int8(info.PublishStatus) == model.PublishStatusClose) {
err = ecode.NothingFound
return
}
if mc {
s.addBlockedCache(c, info)
}
return
}
// BlockedInfoAppeal get blocked info for appeal .
func (s *Service) BlockedInfoAppeal(c context.Context, id, mid int64) (info *model.BlockedInfo, err error) {
defer func() {
if err == nil && info != nil && info.ID != 0 {
if mid != info.UID {
err = ecode.NothingFound
}
}
}()
var mc = true
if info, err = s.dao.BlockedInfoCache(c, id); err != nil {
err = nil
mc = false
}
if info != nil {
return
}
if info, err = s.dao.BlockedInfoByID(c, id); err != nil {
err = errors.Wrapf(err, "BlockedInfoByID(%d)", id)
return
}
if info == nil {
err = ecode.NothingFound
return
}
if mc {
s.addBlockedCache(c, info)
}
return
}
func (s *Service) addBlockedCache(c context.Context, info *model.BlockedInfo) {
var card *acmdl.CardReply
if card, _ = s.userInfo(c, info.UID); card != nil {
info.Uname = card.Card.Name
info.Face = card.Card.Face
}
info.Build()
s.addCache(func() {
s.dao.SetBlockedInfoCache(context.TODO(), info.ID, info)
})
}
// BlockedList blocked info list, public default.
func (s *Service) BlockedList(c context.Context, oType, bType int8, pn, ps int) (res []*model.BlockedInfo, err error) {
var (
start = (pn - 1) * ps
end = pn * ps
ok bool
ids []int64
missed []int64
cache = true
)
if ok, err = s.dao.ExpireBlockedIdx(c, oType, bType); ok && err == nil {
if ids, err = s.dao.BlockedIdxCache(c, oType, bType, start, end-1); err != nil {
return
}
} else {
var ls, tmpls []*model.BlockedInfo
if ls, err = s.dao.BlockedList(c, oType, bType); err != nil {
return
}
switch {
case len(ls) <= int(start):
tmpls = _emptyBlockInfo
case len(ls) <= int(end):
tmpls = ls[start:]
default:
tmpls = ls[start:end]
}
s.addCache(func() {
s.dao.LoadBlockedIdx(context.TODO(), oType, bType, ls)
})
for _, id := range tmpls {
ids = append(ids, id.ID)
}
}
if res, missed, err = s.dao.BlockedInfosCache(c, ids); err != nil {
err = nil
cache = false
missed = ids
}
var missInfos []*model.BlockedInfo
if len(missed) != 0 {
missInfos, err = s.dao.BlockedInfos(c, missed)
if err != nil {
return
}
res = append(res, missInfos...)
}
var (
mids []int64
oids []int64
)
for _, i := range res {
mids = append(mids, i.UID)
oids = append(oids, i.ID)
}
arg := &acmdl.MidsReq{
Mids: mids,
}
cards, err := s.accountClient.Infos3(c, arg)
if err != nil {
err = errors.Wrap(err, "Infos")
return
}
reply, _ := s.dao.ReplysCount(c, oids)
for _, i := range res {
if card, ok := cards.Infos[i.UID]; ok {
i.Uname = card.Name
i.Face = card.Face
}
i.CommentSum = reply[strconv.FormatInt(i.ID, 10)]
i.Build()
}
if cache {
s.addCache(func() {
s.dao.SetBlockedInfosCache(context.TODO(), missInfos)
})
}
return
}
// AnnouncementInfo get announcement detail.
func (s *Service) AnnouncementInfo(c context.Context, aid int64) (res *model.BlockedAnnouncement, err error) {
var ok bool
if res, ok = s.announcement.amap[aid]; !ok {
err = ecode.NothingFound
}
return
}
// AnnouncementList get announcement list.
func (s *Service) AnnouncementList(c context.Context, tp int8, pn, ps int64) (resp *model.AnnounceList, err error) {
var (
ok bool
start = (pn - 1) * ps
end = pn * ps
alist []*model.BlockedAnnouncement
count int64
)
resp = &model.AnnounceList{
List: _emptyAnnounce,
}
if tp == model.PublishTypedef {
resp.List = s.announcement.def
resp.Count = int64(len(s.announcement.def))
return
}
if alist, ok = s.announcement.alist[tp]; !ok {
return
}
count = int64(len(alist))
resp.Count = count
switch {
case count < start:
case end >= count:
resp.List = alist[start:]
default:
resp.List = alist[start:end]
}
return
}
// LoadAnnouncement load AnnouncementList.
func (s *Service) LoadAnnouncement(c context.Context) {
res, err := s.dao.AnnouncementList(c)
if err != nil {
return
}
var (
def []*model.BlockedAnnouncement
new = make([]*model.BlockedAnnouncement, 0, model.PublishInitLen)
top = make([]*model.BlockedAnnouncement, 0, model.PublishInitLen)
alist = make(map[int8][]*model.BlockedAnnouncement)
topList = make(map[int8][]*model.BlockedAnnouncement)
amap = make(map[int64]*model.BlockedAnnouncement)
)
for _, ann := range res {
if ann.StickStatus == 1 {
top = append(top, ann)
topList[ann.Ptype] = append(topList[ann.Ptype], ann)
} else if len(new) < model.PublishInitLen {
new = append(new, ann)
}
if ann.StickStatus != 1 {
alist[ann.Ptype] = append(alist[ann.Ptype], ann)
}
amap[ann.ID] = ann
}
for t, p := range alist {
alist[t] = append(topList[t], p...)
}
if len(top) < model.PublishInitLen {
lack := model.PublishInitLen - len(top)
if lack > len(new) {
def = append(top, new...)
} else {
def = append(top, new[:lack]...)
}
} else {
def = top[:model.PublishInitLen]
}
if len(def) == 0 {
def = _emptyAnnounce
}
s.announcement.def = def
s.announcement.alist = alist
s.announcement.amap = amap
}
// BlockedNumUser get blocked user number.
func (s *Service) BlockedNumUser(c context.Context, mid int64) (blockedSum *model.ResBlockedNumUser, err error) {
blockedSum = &model.ResBlockedNumUser{}
blockedSum.BlockedSum, err = s.dao.BlockedNumUser(c, mid)
return
}
// BatchPublishs get publish info list.
func (s *Service) BatchPublishs(c context.Context, ids []int64) (res map[int64]*model.BlockedAnnouncement, err error) {
res, err = s.dao.BatchPublishs(c, ids)
return
}
// AddBlockedInfo add blocked info.
func (s *Service) AddBlockedInfo(c context.Context, argJB *model.ArgJudgeBlocked) (err error) {
if argJB.OID == 0 && argJB.OPName == "" {
log.Error("origin_type(%d) oper_id(%d) && operator_name(%s) not both empty!", argJB.OType, argJB.OID, argJB.OPName)
err = ecode.RequestErr
return
}
if argJB.OID == 0 && argJB.OPName != "" {
argJB.OID = s.managers[argJB.OPName]
}
if (argJB.PType == model.PunishTypeForever && argJB.BForever != model.InBlockedForever) ||
(argJB.BForever == model.InBlockedForever && argJB.PType != model.PunishTypeForever) {
argJB.PType = model.PunishTypeForever
argJB.BForever = model.InBlockedForever
}
if argJB.PType == model.PunishTypeForever && argJB.BForever == model.InBlockedForever {
argJB.BDays = 0
}
bi := &model.BlockedInfo{
UID: argJB.MID,
OID: argJB.OID,
BlockedDays: int64(argJB.BDays),
BlockedForever: int64(argJB.BForever),
BlockedRemark: argJB.BRemark,
MoralNum: int64(argJB.MoralNum),
OriginContent: argJB.OContent,
OriginTitle: argJB.OTitle,
OriginType: int64(argJB.OType),
OriginURL: argJB.OURL,
PunishTime: xtime.Time(time.Now().Unix()),
PunishType: int64(argJB.PType),
ReasonType: int64(argJB.RType),
BlockedType: int64(model.PunishBlock),
OperatorName: argJB.OPName,
}
return s.dao.AddBlockedInfo(c, bi)
}
// AddBatchBlockedInfo add batch blocked info.
func (s *Service) AddBatchBlockedInfo(c context.Context, argJBs *model.ArgJudgeBatchBlocked) (err error) {
if argJBs.OID == 0 && argJBs.OPName == "" {
log.Error("origin_type(%d) oper_id(%d) && operator_name(%s) not both empty!", argJBs.OType, argJBs.OID, argJBs.OPName)
err = ecode.RequestErr
return
}
if argJBs.OID == 0 && argJBs.OPName != "" {
argJBs.OID = s.managers[argJBs.OPName]
}
if (argJBs.PType == model.PunishTypeForever && argJBs.BForever != model.InBlockedForever) ||
(argJBs.BForever == model.InBlockedForever && argJBs.PType != model.PunishTypeForever) {
argJBs.PType = model.PunishTypeForever
argJBs.BForever = model.InBlockedForever
}
if argJBs.PType == model.PunishTypeForever && argJBs.BForever == model.InBlockedForever {
argJBs.BDays = 0
}
var bis []*model.BlockedInfo
for _, mid := range argJBs.MID {
bi := &model.BlockedInfo{
UID: mid,
OID: argJBs.OID,
BlockedDays: int64(argJBs.BDays),
BlockedForever: int64(argJBs.BForever),
BlockedRemark: argJBs.BRemark,
MoralNum: int64(argJBs.MoralNum),
OriginContent: argJBs.OContent,
OriginTitle: argJBs.OTitle,
OriginType: int64(argJBs.OType),
OriginURL: argJBs.OURL,
PunishTime: xtime.Time(argJBs.PTime),
PunishType: int64(argJBs.PType),
ReasonType: int64(argJBs.RType),
BlockedType: int64(model.PunishBlock),
OperatorName: argJBs.OPName,
}
bis = append(bis, bi)
}
// begin tran
var tx *xsql.Tx
if tx, err = s.dao.BeginTran(c); err != nil {
err = errors.Wrap(err, "s.dao.BeginTran()")
return
}
defer func() {
if err != nil {
tx.Rollback()
} else {
tx.Commit()
}
}()
err = s.dao.TxAddBlockedInfo(tx, bis)
return
}
// BLKHistorys get blocked historys list.
func (s *Service) BLKHistorys(c context.Context, ah *model.ArgHistory) (rhs *model.ResBLKHistorys, err error) {
count, err := s.dao.BLKHistoryCount(c, ah)
if err != nil {
err = errors.Wrap(err, "s.dao.BLKHistoryCount")
return
}
rhs = &model.ResBLKHistorys{
TotalCount: count,
PN: ah.PN,
PS: ah.PS,
Items: _emptyBlockInfo,
}
if count == 0 {
return
}
rhs.Items, err = s.dao.BLKHistorys(c, ah)
if err != nil {
err = errors.Wrap(err, "s.dao.BLKHistorys")
return
}
var uids []int64
for _, item := range rhs.Items {
uids = append(uids, item.UID)
}
infoMap, err := s.infoMap(c, uids)
if err != nil {
err = errors.Wrap(err, "s.infoMap")
return
}
for _, item := range rhs.Items {
if info, ok := infoMap[item.UID]; ok {
item.Uname = info.Name
item.Face = info.Face
}
item.Build()
}
return
}
// BatchBLKInfos mutli get blocked info by ids.
func (s *Service) BatchBLKInfos(c context.Context, ids []int64) (items map[int64]*model.BlockedInfo, err error) {
items, err = s.dao.BlockedInfoIDs(c, ids)
if err != nil {
err = errors.Wrap(err, "s.dao.BLKHistorys")
return
}
var uids []int64
for _, item := range items {
uids = append(uids, item.UID)
}
infoMap, err := s.infoMap(c, uids)
if err != nil {
err = errors.Wrap(err, "s.infoMap")
return
}
for _, item := range items {
if info, ok := infoMap[item.UID]; ok {
item.Uname = info.Name
item.Face = info.Face
}
item.Build()
}
return
}

View File

@@ -0,0 +1,88 @@
package service
import (
"context"
"encoding/json"
"testing"
. "github.com/smartystreets/goconvey/convey"
)
// TestBatchBLKInfos .
func TestBatchBLKInfos(t *testing.T) {
Convey("TestBatchBLKInfos", t, func() {
res, err := s.BatchBLKInfos(context.TODO(), []int64{1111, 222})
So(err, ShouldBeNil)
out, err := json.Marshal(res)
So(err, ShouldBeNil)
So(out, ShouldNotBeNil)
})
}
// TestBlockedUserCard .
func TestBlockedUserCard(t *testing.T) {
Convey("TestBlockedUserCard", t, func() {
res, err := s.BlockedUserCard(context.TODO(), 21432418)
So(err, ShouldBeNil)
out, err := json.Marshal(res)
So(err, ShouldBeNil)
So(out, ShouldNotBeNil)
})
}
// TestBlockedUserList .
func TestBlockedUserList(t *testing.T) {
Convey("TestBlockedUserList", t, func() {
res, err := s.BlockedUserList(context.TODO(), 1)
So(err, ShouldBeNil)
out, err := json.Marshal(res)
So(err, ShouldBeNil)
So(out, ShouldNotBeNil)
})
}
// TestBlockedInfo .
func TestBlockedInfo(t *testing.T) {
Convey("TestBlockedInfo", t, func() {
res, err := s.BlockedInfo(context.TODO(), 1475)
So(err, ShouldBeNil)
out, err := json.Marshal(res)
So(err, ShouldBeNil)
So(out, ShouldNotBeNil)
})
}
// TestBlockedList .
func TestBlockedList(t *testing.T) {
Convey("TestBlockedList", t, func() {
res, err := s.BlockedList(context.TODO(), 0, -1, 1, 5)
So(err, ShouldBeNil)
out, err := json.Marshal(res)
So(err, ShouldBeNil)
So(out, ShouldNotBeNil)
})
}
// TestAnnouncementInfo .
func TestAnnouncementInfo(t *testing.T) {
Convey("TestAnnouncementInfo", t, func() {
s.LoadAnnouncement(context.TODO())
res, err := s.AnnouncementInfo(context.TODO(), 48)
So(err, ShouldBeNil)
out, err := json.Marshal(res)
So(err, ShouldBeNil)
So(out, ShouldNotBeNil)
})
}
// TestAnnouncementList .
func TestAnnouncementList(t *testing.T) {
Convey("TestAnnouncementList", t, func() {
s.LoadAnnouncement(context.TODO())
res, err := s.AnnouncementList(context.TODO(), 1, 1, 3)
So(err, ShouldBeNil)
out, err := json.Marshal(res)
So(err, ShouldBeNil)
So(out, ShouldNotBeNil)
})
}

View File

@@ -0,0 +1,228 @@
package service
import (
"context"
"math/rand"
"sync"
"time"
model "go-common/app/interface/main/credit/model"
acmdl "go-common/app/service/main/account/api"
"go-common/library/ecode"
"go-common/library/log"
"go-common/library/sync/errgroup"
)
func (s *Service) caseVoteID(c context.Context, mid int64, pubCid int64) (cid int64, err error) {
// 获取发放中cids的列表
mcases, err := s.dao.GrantCases(c)
if err != nil {
log.Error("s.dao.GrantCases error(%v)", err)
return
}
if len(mcases) == 0 {
log.Warn("no grant cases(%+v)!", mcases)
return
}
// 7天内已投cids
weekcases, err := s._caseObtainMID(c, mid, 7, model.CaseObtainNoToday)
if err != nil {
log.Error("s._caseObtainMID(%d, 7, %t) error(%v)", mid, model.CaseObtainNoToday, err)
return
}
// 今天内已投cids
todaycases, err := s._caseObtainMID(c, mid, 0, model.CaseObtainToday)
if err != nil {
log.Error("s._caseObtainMID(%d, 0, %t) error(%v)", mid, model.CaseObtainToday, err)
return
}
todayPubVote := 0
tpmcids := make(map[int64]struct{})
// 今天已投cid的map
for _, tcase := range todaycases {
if tcase.CaseType == model.JudeCaseTypePublic {
tpmcids[tcase.ID] = struct{}{}
todayPubVote++
}
}
vcids := []int64{}
for wcid := range weekcases {
vcids = append(vcids, wcid)
}
for cid, m := range mcases {
if _, ok := tpmcids[cid]; !ok && m.CaseType == model.JudeCaseTypePublic {
todayPubVote++
}
// 把被举报人是风纪委用户自己和结案时间后10分钟的稿件 加入用户已投稿列表
if m.Mid == mid || m.Etime.Time().Add(-time.Duration(s.c.Judge.ReservedTime)).Before(time.Now()) {
vcids = append(vcids, cid)
continue
}
}
tLen := len(todaycases)
// 获取案件最大数判断
if int64(tLen-todayPubVote) >= s.c.Judge.CaseObtainMax {
err = ecode.CreditCaseMax
return
}
// 制作非可投cids的map
vmcids := make(map[int64]struct{})
for _, uncid := range vcids {
vmcids[uncid] = struct{}{}
}
// 小众
pteCids := make([]int64, 0)
// 大众
pubCids := make([]int64, 0)
// 大众cid的map
mpCids := make(map[int64]struct{})
// 取出可投cids
for kcid, m := range mcases {
if _, ok := vmcids[kcid]; ok {
continue
}
if m.CaseType == model.JudeCaseTypePublic {
pubCids = append(pubCids, kcid)
mpCids[kcid] = struct{}{}
} else {
pteCids = append(pteCids, kcid)
}
}
pubLen := len(pubCids)
pteLen := len(pteCids)
// 没有可投的案件
if pubLen+pteLen == 0 {
log.Warn("mid(%d) no case can vote!", mid)
return
}
var caseType int8
_, ok := mpCids[pubCid]
if pubCid != 0 && !ok {
return
}
if pubCid != 0 && ok {
cid = pubCid
caseType = model.JudeCaseTypePublic
} else {
radio := rand.New(rand.NewSource(time.Now().UnixNano()))
if pubLen > 0 {
cid = s._randCid(pubCids, radio)
caseType = model.JudeCaseTypePublic
} else if pteLen > 0 {
cid = s._randCid(pteCids, radio)
caseType = model.JudeCaseTypePrivate
}
}
// db插入用户投票数据
if err = s.dao.InsVote(c, mid, cid, s.c.Judge.CaseCheckTime); err != nil {
log.Error("s.dao.InsVote( mid(%d), cid(%d), s.c.Judge.CaseCheckTime(%d)) error(%v)", mid, cid, s.c.Judge.CaseCheckTime, err)
return
}
mcid := &model.SimCase{ID: cid, CaseType: caseType}
// 从redis的set中设置用户已投cids
if err = s.dao.SetVoteCaseMID(c, mid, mcid); err != nil {
log.Error("s.dao.SetVoteCaseMID(%d,%+v) error(%v)", mid, mcid, err)
return
}
log.Info("CaseObtain mid:%d total:%d CaseObtainMax:%d cid:%d", mid, int64(tLen+todayPubVote), s.c.Judge.CaseObtainMax, cid)
// db插入case投放总数
if err = s.dao.AddCaseVoteTotal(c, "put_total", cid, 1); err != nil {
log.Error("s.dao.InsVote( mid(%d), cid(%d), s.c.Judge.CaseCheckTime(%d)) error(%v)", mid, cid, s.c.Judge.CaseCheckTime, err)
}
return
}
// 获取用户N天内已投列表
func (s *Service) _caseObtainMID(c context.Context, mid int64, day int, isToday bool) (cases map[int64]*model.SimCase, err error) {
isExpired, err := s.dao.IsExpiredObtainMID(c, mid, isToday)
if err != nil {
log.Error("s.dao.IsExpiredObtainMID(%d,%t) error(%v)", mid, isToday, err)
return
}
if isExpired {
cases, err = s.dao.CaseObtainMID(c, mid, isToday)
if err != nil {
log.Error("s.dao.CaseObtainByMID(%d,%t) error(%v)", mid, isToday, err)
return
}
} else {
if cases, err = s.dao.LoadVoteIDsMid(c, mid, day); err != nil {
log.Error("s.dao.LoadVoteIDsMid(%d,%d) error(%v)", mid, day, err)
return
}
if len(cases) == 0 {
return
}
s.addCache(func() {
if err = s.dao.LoadVoteCaseMID(context.TODO(), mid, cases, isToday); err != nil {
log.Error("s.dao.LoadVoteCaseMID(%d,%v,%t) error(%v)", mid, cases, isToday, err)
return
}
})
}
return
}
// cid 取值的随机算法
func (s *Service) _randCid(cids []int64, radio *rand.Rand) (cid int64) {
// 随机取出数组的游标
rand := int64(radio.Intn(len(cids)))
cid = cids[rand]
return
}
// 列表批量异步获取用户信息
func (s *Service) infoMap(c context.Context, uids []int64) (infoMap map[int64]*acmdl.Info, err error) {
total := len(uids)
pageNum := total / model.JuryMultiJuryerInfoMax
if total%model.JuryMultiJuryerInfoMax != 0 {
pageNum++
}
var (
g errgroup.Group
lk sync.RWMutex
)
infoMap = make(map[int64]*acmdl.Info, total)
for i := 0; i < pageNum; i++ {
start := i * model.JuryMultiJuryerInfoMax
end := (i + 1) * model.JuryMultiJuryerInfoMax
if end > total {
end = total
}
g.Go(func() (err error) {
var (
arg = &acmdl.MidsReq{Mids: uids[start:end]}
res *acmdl.InfosReply
)
if res, err = s.accountClient.Infos3(c, arg); err != nil {
log.Error("s.accountClient.Infos3(%v) error(%v)", arg, err)
err = nil
} else {
for uid, info := range res.Infos {
lk.Lock()
infoMap[uid] = info
lk.Unlock()
}
}
return
})
}
if err = g.Wait(); err != nil {
log.Error("g.Wait() error(%v)", err)
}
return
}
// userInfo one user card.
func (s *Service) userInfo(c context.Context, mid int64) (card *acmdl.CardReply, err error) {
if mid == 0 {
return
}
arg := &acmdl.MidReq{
Mid: mid,
}
if card, err = s.accountClient.Card3(c, arg); err != nil {
log.Error("s.accountClient.Card3(%+v) error(%+v)", arg, err)
}
return
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,239 @@
package service
import (
"context"
"testing"
credit "go-common/app/interface/main/credit/model"
. "github.com/smartystreets/goconvey/convey"
)
// TestSpJuryCase .
func TestSpJuryCase(t *testing.T) {
Convey("TestSpJuryCase", t, func() {
mid := int64(27515259)
cid := int64(797)
bc, err := s.SpJuryCase(context.TODO(), mid, cid)
So(err, ShouldBeNil)
So(bc, ShouldNotBeNil)
})
}
// TestVoteInfoMID .
func TestVoteInfoMID(t *testing.T) {
Convey("TestVoteInfoMID", t, func() {
mid := int64(27515259)
cid := int64(797)
bc, err := s.VoteInfoCache(context.TODO(), mid, cid)
So(err, ShouldBeNil)
So(bc, ShouldNotBeNil)
})
}
// TestObtainCase .
func TestObtainCase(t *testing.T) {
Convey("TestObtainCase", t, func() {
mid := int64(88889018)
cid, err := s.caseVoteID(context.TODO(), mid, 0)
So(err, ShouldBeNil)
So(cid, ShouldNotBeNil)
})
}
// TestServiceApply
func TestServiceApply(t *testing.T) {
Convey("TestServiceApply", t, func() {
var (
mid int64 = 2089809
c = context.TODO()
)
err := s.Apply(c, mid)
So(err, ShouldBeNil)
})
}
// TestServiceRequirement
func TestServiceRequirement(t *testing.T) {
Convey("TestServiceApply", t, func() {
var (
mid int64 = 88889019
c = context.TODO()
)
jr, err := s.Requirement(c, mid)
So(err, ShouldBeNil)
So(jr, ShouldNotBeNil)
})
}
// TestServiceJury
func TestServiceJury(t *testing.T) {
Convey("TestServiceJury", t, func() {
var (
mid int64 = 27515274
c = context.TODO()
)
res, err := s.Jury(c, mid)
So(err, ShouldBeNil)
So(res, ShouldNotBeNil)
})
}
// TestServiceCaseObtain
func TestServiceCaseObtain(t *testing.T) {
Convey("TestServiceJury", t, func() {
var (
mid int64 = 21432418
c = context.TODO()
)
cid, err := s.CaseObtain(c, mid, 308)
So(err, ShouldBeNil)
So(cid, ShouldNotBeNil)
})
}
// TestServiceVote .
func TestServiceVote(t *testing.T) {
Convey("TestServiceVote", t, func() {
var (
mid int64 = 9
cid int64 = 1
v int8 = 2
c = context.TODO()
)
err := s.Vote(c, mid, cid, v, 1, 1, 1, "", []int64{1, 2, 3}, []int64{4, 5, 6})
So(err, ShouldBeNil)
})
}
func TestServiceVoteInfo(t *testing.T) {
Convey("TestServiceVoteInfo", t, func() {
var (
mid int64 = 9
cid int64 = 1
c = context.TODO()
)
res, err := s.VoteInfo(c, mid, cid)
So(err, ShouldBeNil)
So(res, ShouldNotBeNil)
})
}
func TestServiceCaseInfo(t *testing.T) {
Convey("TestServiceCaseInfo", t, func() {
var (
c = context.TODO()
cid int64 = 304
)
res, err := s.CaseInfo(c, cid)
So(err, ShouldBeNil)
So(res, ShouldNotBeNil)
})
}
func TestServiceJuryCase(t *testing.T) {
Convey("TestServiceJuryCase", t, func() {
var (
mid int64 = 27515274
cid int64 = 708
c = context.TODO()
)
res, err := s.JuryCase(c, mid, cid)
So(err, ShouldBeNil)
So(res, ShouldNotBeNil)
})
}
func TestServiceCaseList(t *testing.T) {
Convey("TestServiceCaseList", t, func() {
var (
mid int64 = 21432418
pn int64 = 1
ps int64 = 10
c = context.TODO()
)
res, err := s.CaseList(c, mid, ps, pn)
So(err, ShouldBeNil)
So(res, ShouldNotBeNil)
})
}
func TestService_KPIList(t *testing.T) {
Convey("TestService_KPIList", t, func() {
var (
err error
c = context.TODO()
res []*credit.KPI
)
res, err = s.KPIList(c, 88889017)
So(err, ShouldBeNil)
So(res, ShouldNotBeNil)
})
}
func TestCaseOpinion(t *testing.T) {
Convey("TestCaseOpinion", t, func() {
res, _, err := s.CaseOpinion(context.TODO(), 679, 1, 3)
So(err, ShouldBeNil)
So(res, ShouldNotBeNil)
})
}
func TestVoteOpinion(t *testing.T) {
Convey("TestVoteOpinion", t, func() {
res, _, err := s.VoteOpinion(context.TODO(), 679, 1, 3, 1)
So(err, ShouldBeNil)
So(res, ShouldNotBeNil)
})
}
func TestAddBlockedCases(t *testing.T) {
Convey("TestVoteOpinion", t, func() {
var (
bc []*credit.ArgJudgeCase
b = &credit.ArgJudgeCase{}
b1 = &credit.ArgJudgeCase{}
)
b.MID = 1
b.Operator = "a"
b.OContent = "'aaaaa,"
b.PunishResult = 1
b.OTitle = "ot"
b.OType = 1
b.OURL = "ou"
b.BlockedDays = 1
b.ReasonType = 1
b.RelationID = "1-1"
b.RPID = 11
b.Type = 1
b.OID = 1111
b.MID = 1
b1.Operator = "b"
b1.OContent = ",'bbbbb'''"
b1.PunishResult = 2
b1.OTitle = "ot"
b1.OType = 1
b1.OURL = "ou"
b1.BlockedDays = 2
b1.ReasonType = 2
b1.RelationID = "1-1"
b1.RPID = 22
b1.Type = 2
b1.OID = 22222
bc = append(bc, b)
bc = append(bc, b1)
err := s.AddBlockedCases(context.TODO(), bc)
So(err, ShouldBeNil)
})
}
func TestCaseObtainByID(t *testing.T) {
Convey("TestVoteOpinion", t, func() {
var (
c = context.TODO()
)
err := s.CaseObtainByID(c, 88889018, 309)
So(err, ShouldBeNil)
})
}

View File

@@ -0,0 +1,231 @@
package service
import (
"context"
"encoding/json"
"time"
model "go-common/app/interface/main/credit/model"
"go-common/app/service/main/archive/api"
arcMDL "go-common/app/service/main/archive/model/archive"
blkmdl "go-common/app/service/main/member/model/block"
"go-common/library/ecode"
"go-common/library/log"
"go-common/library/net/metadata"
xtime "go-common/library/time"
"go-common/library/xstr"
)
// AddQs add labour question.
func (s *Service) AddQs(c context.Context, qs *model.LabourQs) (err error) {
return s.dao.AddQs(c, qs)
}
// SetQs set labour question field.
func (s *Service) SetQs(c context.Context, id int64, ans int64, status int64) (err error) {
return s.dao.SetQs(c, id, ans, status)
}
// DelQs del labour question.
func (s *Service) DelQs(c context.Context, id int64, isDel int64) (err error) {
return s.dao.DelQs(c, id, isDel)
}
// GetQs get question.
func (s *Service) GetQs(c context.Context, mid int64) (qs []*model.LabourQs, err error) {
var (
ok bool
arc *api.Arc
getids, qsids, avids []int64
marc map[int64]*api.Arc
block *blkmdl.RPCResInfo
)
defer func() {
if err == nil {
if len(avids) != 0 {
marc, _ = s.arcRPC.Archives3(c, &arcMDL.ArgAids2{Aids: avids, RealIP: metadata.String(c, metadata.RemoteIP)})
}
for _, q := range qs {
qsids = append(qsids, q.ID)
if arc, ok = marc[q.AvID]; !ok {
log.Warn("aid(%d) is not extists, [mid(%d)-qid(%d)]", q.AvID, mid, q.ID)
q.AvID = 0
continue
}
q.AvTitle = arc.Title
if !model.ArcVisible(arc.State) {
log.Warn("aid(%d) atitle(%s) state(%d) is not visible, [mid(%d)-qid(%d)]", q.AvID, q.AvTitle, arc.State, mid, q.ID)
q.AvID = 0
}
}
qsCache := &model.QsCache{
Stime: xtime.Time(time.Now().Unix()),
QsStr: xstr.JoinInts(qsids),
}
s.dao.SetQsCache(c, mid, qsCache)
}
}()
if block, err = s.memRPC.BlockInfo(c, &blkmdl.RPCArgInfo{MID: mid}); err != nil {
return
}
status := int8(block.BlockStatus)
if status == model.BlockStatusNone {
err = ecode.CreditNoblock
return
}
if status == model.BlockStatusForever {
err = ecode.CreditForeverBlock
return
}
var qsIDs *model.AIQsID
qsIDs, err = s.dao.GetQS(c, mid)
if err != nil {
log.Error("s.dao.GetQS(%d,%s) error(%+v)", mid, metadata.String(c, metadata.RemoteIP), err)
err = nil
qs = s.question
avids = s.avIDs
return
}
getids = append(getids, qsIDs.Pend...)
getids = append(getids, qsIDs.Done...)
idStr := xstr.JoinInts(getids)
if _, qs, avids, err = s.dao.QsAllList(c, idStr); err != nil {
return
}
if len(qs) != s.c.Property.QsNum {
log.Warn("creditQsNumError(mid:%d,idstr:%s,qs:%+v),len:%d", mid, idStr, qs, len(qs))
qs = s.question
avids = s.avIDs
}
return
}
// CommitQs commit questions.
func (s *Service) CommitQs(c context.Context, mid int64, refer string, ua string, buvid string, ans *model.LabourAns) (commitRs *model.CommitRs, err error) {
var (
num int64
qs map[int64]*model.LabourQs
block *blkmdl.RPCResInfo
)
if block, err = s.memRPC.BlockInfo(c, &blkmdl.RPCArgInfo{MID: mid}); err != nil {
return
}
status := int8(block.BlockStatus)
if status == model.BlockStatusNone {
err = ecode.CreditNoblock
return
}
if status == model.BlockStatusForever {
err = ecode.CreditForeverBlock
return
}
if len(ans.ID) != s.c.Property.QsNum || len(ans.Answer) != s.c.Property.QsNum {
err = ecode.CreditAnsNumError
log.Error("CreditAnsNumError(mid:%d,id:%+vans:%+v)", mid, ans.ID, ans.Answer)
return
}
idStr := xstr.JoinInts(ans.ID)
qsCache, _ := s.dao.GetQsCache(c, mid)
if qsCache == nil || qsCache.QsStr != idStr {
err = ecode.RequestErr
return
}
if qs, _, _, err = s.dao.QsAllList(c, idStr); err != nil {
return
}
if len(qs) != s.c.Property.QsNum {
log.Error("CreditRightAnsNumError(mid:%d,qs:%+v)", mid, qs)
}
for id, qsid := range ans.ID {
if ans.Answer[id] != 1 && ans.Answer[id] != 2 {
err = ecode.RequestErr
log.Error("CreditAnsError(mid:%d,id:%+vans:%+v)", mid, ans.ID, ans.Answer)
return
}
if v, ok := qs[qsid]; ok {
if v.Ans == ans.Answer[id] {
num++
}
}
}
commitRs = &model.CommitRs{}
commitRs.Score = num * s.c.Property.PerScore
if commitRs.Score >= 100 {
commitRs.Score = 100
if status == model.BlockStatusNone {
commitRs.Day = 0
} else {
rts := time.Until(time.Unix(block.EndTime, 0))
commitRs.Day = int64(rts / (time.Hour * 24))
if int64(rts%(time.Hour*24)) > 0 {
commitRs.Day++
}
}
}
anstr, err := json.Marshal(ans)
if err != nil {
log.Error("json.Marshal() error(%v)", err)
return
}
id, err := s.dao.AddAnsLog(c, mid, commitRs.Score, string(anstr), qsCache.Stime)
if err != nil {
return
}
var msg model.DataBusResult
msg.Mid = mid
msg.Buvid = buvid
msg.IP = metadata.String(c, metadata.RemoteIP)
msg.Ua = ua
msg.Refer = refer
msg.Score = commitRs.Score
for idx, qsid := range ans.ID {
var rs = model.Rs{}
rs.ID = qsid
rs.Ans = ans.Answer[idx]
if v, ok := qs[qsid]; ok {
rs.Question = v.Question
rs.TrueAns = v.Ans
rs.AvID = v.AvID
rs.Status = v.Status
rs.Source = v.Source
rs.Ctime = v.Ctime
rs.Mtime = v.Mtime
}
msg.Rs = append(msg.Rs, rs)
}
if err = s.dao.PubLabour(c, id, msg); err != nil {
log.Error("s.dao.PubLabour(%d,%+v) error(%+v)", id, msg, err)
return
}
log.Info("PubLabour id(%d) msg(%+v)", id, msg)
s.dao.DelQsCache(c, mid)
return
}
// IsAnswered labour check user is answwered question between the time.
func (s *Service) IsAnswered(c context.Context, mid int64, mtime int64) (state int8, err error) {
var (
mc = true
found bool
)
if state, found, err = s.dao.GetAnswerStateCache(c, mid); err != nil {
err = nil
mc = false
}
if found {
return
}
var status bool
if status, err = s.dao.AnswerStatus(c, mid, time.Unix(mtime, 0)); err != nil {
return
}
if status {
state = model.LabourOkAnswer
}
if mc {
s.addCache(func() {
s.dao.SetAnswerStateCache(context.TODO(), mid, state)
})
}
return
}

View File

@@ -0,0 +1,53 @@
package service
import (
"context"
"testing"
"go-common/app/interface/main/credit/model"
. "github.com/smartystreets/goconvey/convey"
)
// TestServiceAddQs .
func TestServiceAddQs(t *testing.T) {
Convey("TestServiceAddQs", t, func() {
qs := &model.LabourQs{}
qs.Question = "test"
qs.AvID = 666
qs.Source = 1
err := s.AddQs(context.TODO(), qs)
So(err, ShouldBeNil)
})
}
// TestServiceSetQs
func TestServiceSetQs(t *testing.T) {
Convey("TestServiceSetQs", t, func() {
var (
c = context.TODO()
id int64 = 3
ans int64 = 2
status int64 = 2
)
err := s.SetQs(c, id, ans, status)
So(err, ShouldBeNil)
})
}
// TestCommit .
func TestCommit(t *testing.T) {
Convey("TestCommit", t, func() {
ans := &model.LabourAns{
ID: []int64{},
Answer: []int64{},
}
for i := 0; i < 40; i++ {
ans.ID = append(ans.ID, int64(i))
ans.Answer = append(ans.Answer, 1)
}
res, err := s.CommitQs(context.TODO(), 88895349, "aa", "1", "11", ans)
So(err, ShouldBeNil)
So(res, ShouldNotBeNil)
})
}

View File

@@ -0,0 +1,226 @@
package service
import (
"context"
"encoding/json"
"strconv"
"time"
"go-common/app/interface/main/credit/conf"
dao "go-common/app/interface/main/credit/dao"
model "go-common/app/interface/main/credit/model"
accgrpc "go-common/app/service/main/account/api"
arcrpc "go-common/app/service/main/archive/api/gorpc"
fligrpc "go-common/app/service/main/filter/api/grpc/v1"
memrpc "go-common/app/service/main/member/api/gorpc"
"go-common/library/log"
"github.com/pkg/errors"
)
// Service struct of service.
type Service struct {
dao *dao.Dao
// rpc
arcRPC *arcrpc.Service2
memRPC *memrpc.Service
// grpc
accountClient accgrpc.AccountClient
fliClient fligrpc.FilterClient
// conf
c *conf.Config
question []*model.LabourQs
avIDs []int64
missch chan func()
// announcement
announcement *announcement
managers map[string]int64
tagMap map[int8]int64
}
type announcement struct {
def []*model.BlockedAnnouncement
alist map[int8][]*model.BlockedAnnouncement
amap map[int64]*model.BlockedAnnouncement
}
// New create service instance and return.
func New(c *conf.Config) (s *Service) {
s = &Service{
c: c,
dao: dao.New(c),
missch: make(chan func(), 1024000),
arcRPC: arcrpc.New2(c.RPCClient2.Archive),
memRPC: memrpc.New(c.RPCClient2.Member),
tagMap: make(map[int8]int64),
announcement: &announcement{
def: make([]*model.BlockedAnnouncement, 0, 4),
alist: make(map[int8][]*model.BlockedAnnouncement),
amap: make(map[int64]*model.BlockedAnnouncement),
},
}
var err error
if s.fliClient, err = fligrpc.NewClient(c.GRPCClient.Filter); err != nil {
panic(errors.WithMessage(err, "Failed to dial filter service"))
}
if s.accountClient, err = accgrpc.NewClient(c.GRPCClient.Account); err != nil {
panic(errors.WithMessage(err, "Failed to dial account service"))
}
s.initTag()
s.loadConf()
s.loadQuestion()
s.loadManager()
s.LoadAnnouncement(context.TODO())
go s.loadConfproc()
go s.loadQuestionproc()
go s.loadManagerproc()
go s.loadAnnouncementproc()
go s.cacheproc()
return
}
func (s *Service) loadConfproc() {
for {
time.Sleep(time.Duration(s.c.Judge.ConfTimer))
s.loadConf()
}
}
func (s *Service) loadQuestionproc() {
for {
time.Sleep(time.Duration(s.c.Judge.ConfTimer))
s.loadQuestion()
}
}
func (s *Service) loadManagerproc() {
for {
time.Sleep(time.Duration(s.c.Judge.LoadManagerTime))
s.loadManager()
}
}
func (s *Service) loadAnnouncementproc() {
for {
time.Sleep(time.Duration(s.c.Judge.ConfTimer))
s.LoadAnnouncement(context.TODO())
}
}
func (s *Service) loadConf() {
m, err := s.dao.LoadConf(context.TODO())
if err != nil {
log.Error("loadConf error(%v)", err)
return
}
if s.c.Judge.CaseGiveHours, err = strconv.ParseInt(m["case_give_hours"], 10, 64); err != nil {
log.Error("loadConf CaseGiveHours error(%v)", err)
}
if s.c.Judge.CaseCheckTime, err = strconv.ParseInt(m["case_check_hours"], 10, 64); err != nil {
log.Error("loadConf CaseCheckTime error(%v)", err)
}
if s.c.Judge.JuryRatio, err = strconv.ParseInt(m["jury_vote_radio"], 10, 64); err != nil {
log.Error("loadConf JuryRatio error(%v)", err)
}
if s.c.Judge.JudgeRadio, err = strconv.ParseInt(m["case_judge_radio"], 10, 64); err != nil {
log.Error("loadConf JudgeRadio error(%v)", err)
}
if s.c.Judge.CaseVoteMin, err = strconv.ParseInt(m["case_vote_min"], 10, 64); err != nil {
log.Error("loadConf CaseVoteMin error(%v)", err)
}
if s.c.Judge.CaseObtainMax, err = strconv.ParseInt(m["case_obtain_max"], 10, 64); err != nil {
log.Error("loadConf CaseObtainMax error(%v)", err)
}
if s.c.Judge.CaseVoteMax, err = strconv.ParseInt(m["case_vote_max"], 10, 64); err != nil {
log.Error("loadConf CaseVoteMax error(%v)", err)
}
if s.c.Judge.JuryApplyMax, err = strconv.ParseInt(m["jury_apply_max"], 10, 64); err != nil {
log.Error("loadConf JuryApplyMax error(%v)", err)
}
if s.c.Judge.CaseLoadMax, err = strconv.Atoi(m["case_load_max"]); err != nil {
log.Error("loadConf CaseLoadMax error(%v)", err)
}
var caseLoadSwitch int64
if caseLoadSwitch, err = strconv.ParseInt(m["case_load_switch"], 10, 64); err != nil {
log.Error("loadConf CaseLoadSwitch error(%v)", err)
}
s.c.Judge.CaseLoadSwitch = int8(caseLoadSwitch)
if _, ok := m["vote_num"]; !ok {
s.c.Judge.VoteNum.RateS = 1
s.c.Judge.VoteNum.RateA = 1
s.c.Judge.VoteNum.RateB = 1
s.c.Judge.VoteNum.RateC = 1
s.c.Judge.VoteNum.RateD = 1
return
}
if err = json.Unmarshal([]byte(m["vote_num"]), &s.c.Judge.VoteNum); err != nil {
log.Error("loadConf vote_num error(%v)", err)
}
}
func (s *Service) initTag() {
s.tagMap[model.OriginReply] = s.c.TagID.Reply
s.tagMap[model.OriginDM] = s.c.TagID.DM
s.tagMap[model.OriginMsg] = s.c.TagID.Msg
s.tagMap[model.OriginTag] = s.c.TagID.Tag
s.tagMap[model.OriginMember] = s.c.TagID.Member
s.tagMap[model.OriginArchive] = s.c.TagID.Archive
s.tagMap[model.OriginMusic] = s.c.TagID.Music
s.tagMap[model.OriginArticle] = s.c.TagID.Article
s.tagMap[model.OriginSpaceTop] = s.c.TagID.SpaceTop
}
func (s *Service) loadManager() {
managers, err := s.dao.Managers(context.TODO())
if err != nil {
log.Error("s.dao.Managers error(%v)", err)
return
}
s.managers = managers
}
func (s *Service) loadQuestion() {
audit, avIDs, err := s.dao.LastAuditQuestion(context.TODO())
if err != nil {
log.Error("s.dao.LastAuditQuestion error(%v)", err)
return
}
noAudit, noAvIDs, err := s.dao.LastNoAuditQuestion(context.TODO())
if err != nil {
log.Error("s.dao.LastNoAuditQuestion error(%v)", err)
return
}
audit = append(audit, noAudit...)
avIDs = append(avIDs, noAvIDs...)
s.question = audit
s.avIDs = avIDs
}
// Ping check server ok.
func (s *Service) Ping(c context.Context) (err error) {
if err = s.dao.Ping(c); err != nil {
return
}
return s.dao.Ping(c)
}
// Close dao.
func (s *Service) Close() {
s.dao.Close()
}
func (s *Service) addCache(f func()) {
select {
case s.missch <- f:
default:
log.Warn("cacheproc chan full")
}
}
// cacheproc is a routine for executing closure.
func (s *Service) cacheproc() {
for {
f := <-s.missch
f()
}
}

View File

@@ -0,0 +1,55 @@
package service
import (
"context"
"flag"
"fmt"
"path/filepath"
"testing"
"time"
"go-common/app/interface/main/credit/conf"
. "github.com/smartystreets/goconvey/convey"
)
var (
s *Service
)
// func CleanCache() {
// c := context.TODO()
// pool := redis.NewPool(conf.Conf.Redis.Config)
// pool.Get(c).Do("FLUSHDB")
// }
func init() {
dir, _ := filepath.Abs("../cmd/convey-test.toml")
flag.Set("conf", dir)
conf.Init()
s = New(conf.Conf)
time.Sleep(time.Second)
}
// func WithService(f func(s *Service)) func() {
// return func() {
// Reset(func() { CleanCache() })
// f(s)
// }
// }
func Test_LoadConf(t *testing.T) {
Convey("should return err be nil", t, func() {
s.loadConf()
fmt.Printf("%+v", s.c.Judge)
})
}
func Test_BatchBLKCases(t *testing.T) {
ids := []int64{111, 22, 333}
Convey("return someting", t, func() {
cas, err := s.BatchBLKCases(context.TODO(), ids)
So(err, ShouldBeNil)
So(cas, ShouldNotBeNil)
})
}