Create & Init Project...

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

View File

@@ -0,0 +1,26 @@
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [
":package-srcs",
"//app/service/main/vip/api:all-srcs",
"//app/service/main/vip/cmd:all-srcs",
"//app/service/main/vip/conf:all-srcs",
"//app/service/main/vip/dao:all-srcs",
"//app/service/main/vip/http:all-srcs",
"//app/service/main/vip/model:all-srcs",
"//app/service/main/vip/rpc/client:all-srcs",
"//app/service/main/vip/rpc/server:all-srcs",
"//app/service/main/vip/server/grpc:all-srcs",
"//app/service/main/vip/service:all-srcs",
"//app/service/main/vip/verify:all-srcs",
],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

View File

@@ -0,0 +1,250 @@
v2.34.0
1. 大会员福利社
v2.33.1
1. json omitempty
v2.33.0
1. 代金券【最优选择+兑换功能】
v2.32.3
1. fixed platform map lock
v2.32.2
1. add platform map lock
v2.32.1
1. UseBatch orderNO upgrade to string
v2.32.0
1. IAP自动续费首月价格
v2.31.1
1. fix coupon/usable,coupon/list接口 参数bug
v2.31.0
1. 大会员代金券限制商品
v2.30.3
1. 获取bilibili账号缓存
2. 权益发放补偿grpc
v2.30.2
1. add ele coupon limit
v2.30.1
1. userip def []byte{}
v2.30.0
1. 大会员-饿了么&bilibili联合会员
v2.26.1
1. fix platform匹配
v2.26.0
1. 权益国际化
v2.25.1
1. 兼容platform=ipad
v2.25.0
1. 价格面板后台+build号逻辑
2. 国际版的面板接口x/vip/price/panel 里 兼容代金券,激活码,好友赠送的入口关闭
v.2.24.0
1. 新增购买平台配置
v2.23.2
1. 去掉微信过期用户自动续费套餐露出
v2.23.1
1. refined opends sql
v2.23.0
1. 自动续费v2
v2.22.2
1. 降级发起支付displayAccount入参
v2.22.1
1.默认选中第一个
v2.22.0
1. 价格面板v8
2. 包年包季
3. 审核态面板
v2.21.1
1. unfrozen double check
v2.21.0
1. 安卓国际版&iPhone蓝版接入
v2.20.0
1. vip dialog
v2.19.3
1. cancel order suc remove
v2.19.2
1. fix code addcoin
v2.19.1
1. frozen vip java
v2.19.0
1. frozen vip
v2.18.3
1. cancel order status
v2.18.2
1. pay/close -> pay/cancel
v2.18.1
1. refined batch code check sql
v2.18.0
1. vip 权益增加ID字段
v2.17.1
1. fix price config map
v2.17.0
1. create order v2
v2.16.4
1. fix code open panic
v2.16.3
1. default chose
v2.16.2
1. fix sync filed
v2.16.1
1. vip type fix
v2.16.0
1. add batch code limit
v2.15.1
1. open vip change
v2.15.0
1. update batch open vip
v2.14.0
1. refund order notify
v2.13.0
1. update remote ip
v2.12.3
1. update sync AnnualVipOverdueTime
v2.12.1
1. refined sync user info
1. 修改dao ut
v2.12.0
1. vip 公众号
v2.11.0
1. sync user info
v2.10.1
1. clear code
v2.10.0
1. vip pc插件
v2.9.0
1. AppStore购买页
v2.8.0
1. 大会员权益
v2.7.0
1. 大会员联名业务
v2.6.1
1. vip 提供联通查询
v2.6.0
1. vip-java 逻辑补充
v2.5.1
1. fix vip panel_type code reduction
v2.5.0
1. 代金券
v2.4.2
1. 新增好友赠送平台
v2.4.1
1. 折扣价为0的时候默认附上原价
v2.4.0
1. 价格面板v2版本
v2.3.1
1. 去掉面板每秒load内存
v2.3.0
1. 追番列表增加开通提醒
v2.2.2
1. change mc vip key
v2.2.1
1. 变更vip config load 内存的时间
v2.2.0
1. vip暑期活动
v2.1.2
1. vip fix datetime defualt
v2.1.1
1. vip fix datetime defualt
v2.1.0
1. vip panel
v2.0.5
1. fix verify
v2.0.4
1. vip过期时vip info paytype置为正常购买
v2.0.3
1. 小黄条配置
v2.0.2
1. vip过期时vip info paytype置为正常购买
v2.0.1
1. user bo interface add ios_overdue_time
v2.0.0
1. vip-service v2
v1.2.1
1. 更改验证码的url
v1.2.0
1. 激活码开通
2. update build
v1.1.1
1. move path
v1.1.0
1. vipInfo添加最近开通时间
v1.0.0
1. 资源池基础api

View File

@@ -0,0 +1,10 @@
# Owner
zhaogangtao
# Author
zhaozhihao
yubaihai
# Reviewer
zhaozhihao
yubaihai

View File

@@ -0,0 +1,15 @@
# See the OWNERS docs at https://go.k8s.io/owners
approvers:
- yubaihai
- zhaogangtao
- zhaozhihao
labels:
- main
- service
- service/main/vip
options:
no_parent_owners: true
reviewers:
- yubaihai
- zhaozhihao

View File

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

View File

@@ -0,0 +1,57 @@
load(
"@io_bazel_rules_go//proto:def.bzl",
"go_proto_library",
)
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
proto_library(
name = "v1_proto",
srcs = ["api.proto"],
tags = ["automanaged"],
deps = ["@gogo_special_proto//github.com/gogo/protobuf/gogoproto"],
)
go_proto_library(
name = "v1_go_proto",
compilers = ["@io_bazel_rules_go//proto:gogofast_grpc"],
importpath = "go-common/app/service/main/vip/api",
proto = ":v1_proto",
tags = ["automanaged"],
deps = ["@com_github_gogo_protobuf//gogoproto:go_default_library"],
)
go_library(
name = "go_default_library",
srcs = ["client.go"],
embed = [":v1_go_proto"],
importpath = "go-common/app/service/main/vip/api",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//library/net/rpc/warden:go_default_library",
"@com_github_gogo_protobuf//gogoproto:go_default_library",
"@com_github_gogo_protobuf//proto:go_default_library",
"@org_golang_google_grpc//:go_default_library",
"@org_golang_x_net//context: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"],
)

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,391 @@
syntax = "proto3";
// use {app_id}.{version} as package name
package account.vip;
import "github.com/gogo/protobuf/gogoproto/gogo.proto";
option go_package = "v1";
message RegisterOpenIDReq {
int64 mid = 1;
int64 app_id = 2;
}
message RegisterOpenIDReply {
string open_id = 1;
}
message OpenBindByOutOpenIDReq {
string open_id = 1;
string out_open_id = 2;
int64 app_id = 3;
}
message OpenBindByOutOpenIDReply{
}
message UserInfoByOpenIDReq{
string ip = 1;
string open_id = 2;
int64 app_id = 3;
}
message UserInfoByOpenIDReply {
string name = 1;
int32 bind_state =2 [(gogoproto.jsontag) = "bind_state"];
string out_open_id =3;
}
message BindInfoByMidReq{
int64 mid = 1;
int64 app_id = 2;
}
message BindInfoByMidReply{
Account account =1;
BindOuter outer =2;
}
message Account {
int64 mid = 1;
string name = 2;
string face =3;
}
message BindOuter {
string tel = 1;
int32 bind_state = 2 [(gogoproto.jsontag) = "bind_state"];
}
message BilibiliPrizeGrantReq{
string prize_key = 1;
string unique_no =2;
string open_id =3;
int64 app_id =4;
}
message BilibiliPrizeGrantReply{
double amount = 1;
double full_amount =2;
string description =3;
}
message BilibiliVipGrantReq{
string open_id = 1;
string out_open_id = 2;
string out_order_no = 3;
int32 duration = 4;
int64 app_id = 5;
}
message BilibiliVipGrantReply{
}
message CreateAssociateOrderReq {
int64 mid =1;
int32 month =2;
string platform=3;
string mobi_app =4;
string device = 5;
int64 appId = 6;
string appSubId = 7;
int32 orderType = 8;
int32 dtype =9;
string returnUrl = 10;
string coupon_token = 11;
int64 bmid = 12;
string panel_type = 13;
int64 build = 14;
string IP = 15;
}
message CreateAssociateOrderReply{
string pay_param = 1;
double dprice =2;
double oprice =3;
double coupon_money =4;
}
message AssociatePanelReq{
int64 mid = 1;
int32 SortTp =2;
string IP =3;
string MobiApp =4;
string Device =5;
string Platform =6;
int32 Plat =7;
string PanelType =8;
int32 SubType =9;
int32 Month =10;
int64 Build =11;
}
message AssociatePanelReply{
repeated AssociatePanelInfo list = 1;
}
message AssociatePanelInfo {
int64 id =1;
int32 month=2;
string product_name=3;
string product_id=4;
int32 sub_type=5;
int32 suit_type=6;
double original_price =7;
double discount_price =8;
string discount_rate =9;
string remark =10;
int32 selected =11;
int32 pay_state =12 [(gogoproto.jsontag) = "pay_state"];
string pay_message =13;
}
message OpenAuthCallBackReq {
int64 mid =1;
string third_code =2;
int64 app_id =3;
}
message OpenAuthCallBackReply {
}
message EleRedPackagesReq {
}
message EleRedPackagesReply{
repeated ModelEleRedPackage list = 1;
}
message ModelEleRedPackage{
string name =1;
double amount =2;
double sum_condition =3;
}
message EleSpecailFoodsReq{
}
message EleSpecailFoodsReply {
repeated ModelEleSpecailFoods list = 1;
}
message ModelEleSpecailFoods {
string restaurant_name = 1;
string food_name =2;
string food_url =3;
double discount =4;
double amount = 5;
double original_amount = 6;
double rating_point =7;
}
message EleVipGrantReq{
string order_no =1;
}
message EleVipGrantReply{
}
message VipUserPanelReq{
int64 mid = 1;
int32 sortTp = 2;
string ip = 3;
string mobiApp = 4;
string device = 5;
string platform = 6;
int32 plat = 7;
string panelType = 8;
int32 subType = 9;
int32 month = 10;
int64 build = 11;
string lang = 12;
}
message VipUserPanelReply{
repeated ModelVipPanelInfo price_list =1;
CouponBySuitIDReply coupon =2;
int32 coupon_switch =3;
int32 code_switch = 4;
int32 give_switch = 5;
map<int32,ModelPrivilegeResp> privileges = 6;
}
message CouponBySuitIDReply{
string coupon_tip = 1;
ModelCouponAllowancePanelInfo coupon_info = 2;
}
message ModelCouponAllowancePanelInfo{
string coupon_token = 1;
double coupon_amount = 2 [(gogoproto.jsontag) = "coupon_amount"];
int32 state = 3 [(gogoproto.jsontag) = "state"];
string full_limit_explain = 4;
string scope_explain = 5;
double full_amount = 6 [(gogoproto.jsontag) = "full_amount"];
double coupon_discount_price = 7 [(gogoproto.jsontag) = "coupon_discount_price"];
int64 start_time = 8 [(gogoproto.jsontag) = "start_time"];
int64 expire_time = 9 [(gogoproto.jsontag) = "expire_time"];
int32 selected = 10 [(gogoproto.jsontag) = "selected"];
string disables_explains = 11;
string order_no = 12;
string name = 13;
int32 usable = 14 [(gogoproto.jsontag) = "usable"];
}
message ModelVipPanelInfo {
int32 month = 1 [(gogoproto.jsontag) = "month"];
string product_name = 2;
string product_id = 3;
int32 sub_type = 4 [(gogoproto.jsontag) = "sub_type"];
int32 suit_type = 5 [(gogoproto.jsontag) = "suit_type"];
double original_price = 6 [(gogoproto.jsontag) = "original_price"];
double discount_price = 7 [(gogoproto.jsontag) = "discount_price"];
string discount_rate = 8;
string remark = 9;
int32 selected = 10 [(gogoproto.jsontag) = "selected"];
int64 id = 11 [(gogoproto.jsontag) = "id"];
int32 type = 12 [(gogoproto.jsontag) = "type"];
}
message ModelPrivilegeResp{
string title = 1;
repeated ModelPrivilege list = 2;
}
message ModelPrivilege {
string name = 1;
string icon_url = 2;
int32 type =3 [(gogoproto.jsontag) = "type"];
}
message CouponBySuitIDReq {
int64 mid = 1;
int64 sid = 2;
string mobiApp = 3;
string device = 4;
string platform = 5;
string panelType = 6;
int64 build = 7;
}
message WelfareReq{
int64 tid = 1;
int64 recommend = 2;
int64 ps = 3;
int64 pn = 4;
}
message WelfareReply{
int64 count = 1;
repeated WelfareListDetail list = 2;
}
message WelfareListDetail{
int32 id = 1 [(gogoproto.jsontag) = "id"];
string name = 2 [(gogoproto.jsontag) = "name"];
string homepage_uri = 3 [(gogoproto.jsontag) = "homepage_uri"];
string backdrop_uri = 4 [(gogoproto.jsontag) = "backdrop_uri"];
int32 tid = 5 [(gogoproto.jsontag) = "tid"];
int32 rank = 6 [(gogoproto.jsontag) = "rank"];
}
message WelfareTypeReq{
}
message WelfareTypeReply{
repeated WelfareTypeListDetail list = 1;
}
message WelfareTypeListDetail{
int32 id = 1 [(gogoproto.jsontag) = "id"];
string name = 2 [(gogoproto.jsontag) = "name"];
}
message WelfareInfoReq{
int64 id = 1;
int64 mid = 2;
}
message WelfareInfoReply{
int32 id = 1 [(gogoproto.jsontag) = "id"];
string name = 2 [(gogoproto.jsontag) = "name"];
string desc = 3 [(gogoproto.jsontag) = "desc"];
string homepage_uri = 4 [(gogoproto.jsontag) = "homepage_uri"];
string backdrop_uri = 5 [(gogoproto.jsontag) = "backdrop_uri"];
bool finished = 6 [(gogoproto.jsontag) = "finished"];
bool received = 7 [(gogoproto.jsontag) = "received"];
int64 vip_type = 8 [(gogoproto.jsontag) = "vip_type"];
int64 stime = 9 [(gogoproto.jsontag) = "stime"];
int64 etime = 10 [(gogoproto.jsontag) = "etime"];
}
message WelfareReceiveReq{
int64 wid = 1;
int64 mid = 2;
}
message WelfareReceiveReply{
}
message MyWelfareReq{
int64 mid = 1;
}
message MyWelfareReply{
repeated MyWelfareDetail list = 1;
}
message MyWelfareDetail{
int32 wid = 1 [(gogoproto.jsontag) = "wid"];
string name = 2 [(gogoproto.jsontag) = "name"];
string desc = 3 [(gogoproto.jsontag) = "desc"];
int32 usage_form = 4 [(gogoproto.jsontag) = "usage_form"];
string receive_uri = 5 [(gogoproto.jsontag) = "receive_uri"];
string code = 6 [(gogoproto.jsontag) = "code"];
int64 stime = 7 [(gogoproto.jsontag) = "stime"];
int64 etime = 8 [(gogoproto.jsontag) = "etime"];
bool expired = 9 [(gogoproto.jsontag) = "expired"];
}
service Vip {
// RegisterOpenIDReq register by mid.
rpc RegisterOpenID(RegisterOpenIDReq) returns(RegisterOpenIDReply);
// OpenBindByOutOpenID associate user bind by out_open_id [third -> bilibili].
rpc OpenBindByOutOpenID(OpenBindByOutOpenIDReq) returns(OpenBindByOutOpenIDReply);
// UserInfoByOpenID get userinfo by open_id.
rpc UserInfoByOpenID(UserInfoByOpenIDReq) returns(UserInfoByOpenIDReply);
// BindInfoByMid bind info by mid[bilibili->third].
rpc BindInfoByMid(BindInfoByMidReq) returns(BindInfoByMidReply);
// BilibiliPrizeGrant bilibili associate vip grant.
rpc BilibiliPrizeGrant(BilibiliPrizeGrantReq) returns(BilibiliPrizeGrantReply);
// BilibiliVipGrant bilibili associate vip grant.
rpc BilibiliVipGrant(BilibiliVipGrantReq) returns(BilibiliVipGrantReply);
// CreateAssociateOrder create associate order.
rpc CreateAssociateOrder(CreateAssociateOrderReq) returns(CreateAssociateOrderReply);
// AssociatePanel associate panel.
rpc AssociatePanel(AssociatePanelReq) returns(AssociatePanelReply);
// OpenAuthCallBack third open call back.
rpc OpenAuthCallBack(OpenAuthCallBackReq) returns(OpenAuthCallBackReply);
// EleRedPackages ele red packages.
rpc EleRedPackages(EleRedPackagesReq) returns(EleRedPackagesReply);
// EleRedPackages ele specail foods.
rpc EleSpecailFoods(EleSpecailFoodsReq) returns(EleSpecailFoodsReply);
// EleVipGrant ele vip grant [bilibili -> third].
rpc EleVipGrant(EleVipGrantReq) returns(EleVipGrantReply);
// VipUserPanel vip user panel
rpc VipUserPanel(VipUserPanelReq) returns(VipUserPanelReply);
// CouponBySuitID get coupon by mid and suit info.
rpc CouponBySuitID(CouponBySuitIDReq) returns(CouponBySuitIDReply);
// WelfareList get Welfare list
rpc WelfareList(WelfareReq) returns(WelfareReply);
// WelfareTypeList get Welfare type list
rpc WelfareTypeList(WelfareTypeReq) returns(WelfareTypeReply);
// WelfareInfo get Welfare detail
rpc WelfareInfo(WelfareInfoReq) returns(WelfareInfoReply);
// WelfareReceive receive welfare
rpc WelfareReceive(WelfareReceiveReq) returns(WelfareReceiveReply);
// MyWelfare get my welfares
rpc MyWelfare(MyWelfareReq) returns(MyWelfareReply);
}

View File

@@ -0,0 +1,23 @@
package v1
import (
"fmt"
"go-common/library/net/rpc/warden"
context "golang.org/x/net/context"
grpc "google.golang.org/grpc"
)
// AppID .
const AppID = "account.service.vip"
// NewClient new grpc client
func NewClient(cfg *warden.ClientConfig, opts ...grpc.DialOption) (VipClient, error) {
client := warden.NewClient(cfg, opts...)
cc, err := client.Dial(context.Background(), fmt.Sprintf("discovery://default/%s", AppID))
if err != nil {
return nil, err
}
return NewVipClient(cc), nil
}

View File

@@ -0,0 +1,45 @@
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 = ["vip-service-test.toml"],
importpath = "go-common/app/service/main/vip/cmd",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/service/main/vip/conf:go_default_library",
"//app/service/main/vip/http:go_default_library",
"//app/service/main/vip/rpc/server:go_default_library",
"//app/service/main/vip/server/grpc:go_default_library",
"//app/service/main/vip/service:go_default_library",
"//library/ecode/tip:go_default_library",
"//library/log: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,57 @@
package main
import (
"context"
"flag"
"os"
"os/signal"
"syscall"
"time"
"go-common/app/service/main/vip/conf"
"go-common/app/service/main/vip/http"
rpc "go-common/app/service/main/vip/rpc/server"
grpc "go-common/app/service/main/vip/server/grpc"
"go-common/app/service/main/vip/service"
ecode "go-common/library/ecode/tip"
"go-common/library/log"
)
func main() {
flag.Parse()
// init conf,log,trace,stat,perf.
if err := conf.Init(); err != nil {
panic(err)
}
log.Init(conf.Conf.Log)
defer log.Close()
// service init
svr := service.New(conf.Conf)
//ecode init FIXME
ecode.Init(conf.Conf.Ecode)
// rpc server init
rpcSvr := rpc.New(conf.Conf, svr)
http.Init(conf.Conf, svr)
ws := grpc.New(conf.Conf.WardenServer, svr)
// signal handler
log.Info("vip-service start")
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT)
for {
s := <-c
log.Info("vip-service get a signal %s", s.String())
switch s {
case syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT:
rpcSvr.Close()
ws.Shutdown(context.Background())
time.Sleep(time.Second * 2)
log.Info("vip-service exit")
return
case syscall.SIGHUP:
// TODO reload
default:
return
}
}
}

View File

@@ -0,0 +1,210 @@
# This is a TOML document. Boom.
version = "1.0.0"
MsgURI = "http://uat-message.bilibili.com"
PayURI = "http://pay.bilibili.co"
vipURI = "http://uat-vip.bilibili.co"
[payConf]
CustomerID = 10004
Token ="0ff3d296ee0d7a28b4db1d761d2db907"
OrderNotifyURL ="http://uat-vip.bilibili.co/pay/payOrderNotify"
SignNotifyURL ="http://uat-vip.bilibili.co/pay/paySignNotify"
returnUrl = "https://uat-account.bilibili.com/account/big?type=payCallBack"
PlanID = 108217
ProductID ="vip_buy"
Version ="1.0"
OrderExpire = 600
SignType = "MD5"
IAPProductID = {1 = "tv.danmaku.bilianimex1VIPbf1",3="tv.danmaku.bilianimex3VIPbf1",12="tv.danmaku.bilianimex12VIPbf1"}
AutoProductID = "tv.danmaku.bilianimexAuto1VIP"
ProductIDTpl = "VIP_DEFAULT_PRODUCT_%d"
[property]
annualVipBcoinDay = 10
annualVipBcoinCouponMoney = 5
annualVipBcoinCouponActivityId = 142
MsgURL = "http://uat-message.bilibili.com"
PayURL = "http://uat-pay.bilibili.com"
PayCoURL = "http://pay.bilibili.co"
AccountURL = "http://account.bilibili.com/api"
PassportURL = "http://passport.bilibili.co"
pointGetRule = {2 = 20,3 = 50}
VipURL = "http://uat-vip.bilibili.co"
pointActiveDate = {startDate = "2018-02-01",endDate = "2018-04-01"}
payType = {android ="alipay,wechat,bp",ios="iospay"}
payChannelMapping = {3="wechat",100="IAP",10015="wechat"}
expireDay = 60
activeDate = "2018-01-01"
pointBalance = 1250
BubbleTicker = "60s"
TokenBID="account"
apiURL="http://uat-api.bilibili.com"
apiCoUrl = "http://uat-api.bilibili.co"
confMap = {1="限时五折",2="五折"}
pointExchangeTitle = {title = "您的积分足以兑换%s大会员,快去兑换吧!",expired = "300"}
WillExpiredTitle = {title = "您的大会员资格即将失效,快点续期吧!",expired = "250"}
expiredTitle = {title = "您的大会员资格已经失效,快点续期吧!",expired = "200"}
tipButtonName = "开通"
tipButtonLink = "bilibili://user_center/vip/buy/22"
allowanceSwitch = 1
codeSwitch = 1
giveSwitch = 1
codeOpenedSearchSize = 5
panelBgURL = "http://i0.hdslb.com/bfs/vip/BG@3x.png"
welfareBgHost = "http://uat-i%v.hdslb.com"
[bm]
addr = "0.0.0.0:6821"
maxListen = 1000
timeout = "2s"
[rpcServer2]
[[rpcServer2.servers]]
proto = "tcp"
addr = "0.0.0.0:6009"
weight = 10
[rpcServer2.zookeeper]
root = "/microservice/vip/"
addrs = ["172.18.33.50:2199","172.18.33.51:2199","172.18.33.52:2199"]
timeout = "1s"
[memcache]
name = "vip"
proto = "tcp"
addr = "172.18.33.60:11234"
idle = 8
active = 10
dialTimeout = "1s"
readTimeout = "1s"
writeTimeout = "1s"
idleTimeout = "10s"
expire = "24h"
[identify]
whiteAccessKey = ""
whiteMid = 0
[identify.app]
key = "6a29f8ed87407c11"
secret = "d3c5a85f5b895a03735b5d20a273bc57"
[identify.memcache]
name = "go-business/identify"
proto = "unix"
addr = "/tmp/uat-platform-identify-mc.sock"
active = 5
idle = 3
dialTimeout = "1s"
readTimeout = "1s"
writeTimeout = "1s"
idleTimeout = "80s"
[identify.host]
auth = "http://uat-passport.bilibili.com"
secret = "http://uat-open.bilibili.com"
[identify.httpClient]
key = "f022126a8a365e20"
secret = "b7b86838145d634b487e67b811b8fab2"
dial = "30ms"
timeout = "100ms"
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"
dsn = "zhaozhihao:MN9havOfnzY3kd6L78IVucRxgywe0p2P@tcp(172.16.33.205:3308)/bilibili_vip?timeout=5s&readTimeout=5s&writeTimeout=5s&parseTime=true&loc=Local&charset=utf8,utf8mb4"
active = 5
idle = 2
IdleTimeout ="4h"
queryTimeout = "2s"
execTimeout = "2s"
tranTimeout = "2s"
[mysql.breaker]
window = "3s"
sleep = "100ms"
bucket = 10
ratio = 0.5
request = 100
[oldMysql]
addr = "172.22.34.101"
dsn = "vip:qwDb5kQ0syUIo8EKNGrAvcdZLCnROm4j@tcp(172.22.34.101:3309)/vip?timeout=5s&readTimeout=5s&writeTimeout=5s&parseTime=true&loc=Local&charset=utf8,utf8mb4"
active = 8
idle = 5
IdleTimeout ="4h"
queryTimeout = "200ms"
execTimeout = "200ms"
tranTimeout = "300ms"
[oldMysql.breaker]
window = "3s"
sleep = "100ms"
bucket = 10
ratio = 0.5
request = 100
[redis]
name = "vip"
proto = "tcp"
addr = "172.18.33.61:6879"
idle = 10
active = 10
dialTimeout = "1s"
readTimeout = "1s"
writeTimeout = "1s"
idleTimeout = "10s"
expire = "1m"
[httpClient]
key = "f022126a8a365e20"
secret = "b7b86838145d634b487e67b811b8fab2"
dial = "1s"
timeout = "2s"
keepAlive = "60s"
[httpClient.breaker]
window = "10s"
sleep = "100ms"
bucket = 10
ratio = 0.5
request = 100
[rpcClient2]
[rpcClient2.account]
timeout = "1s"
[rpcClient2.point]
timeout = "1s"
[rpcClient2.coupon]
timeout = "1s"
[rpcClient2.member]
timeout = "300ms"
[associateConf]
grantDurationMap = {1=8,12=3}
bilibiliBuyDurationMap = {1=9,12=5}
actStartTime = 1544488082
actEndTime = 1554488082
bilibiliPrizeGrantKeyMap = {"coupon_ele_1"="193710024520181211112507","coupon_ele_2"="421488078220181211112656"}
mailCouponID1="9c09cb6a8950753a"
mailCouponID2="3d005e8ba01c5cb0"
[eLEConf]
key = "4400479257"
secret = "23x01bb2592378e55a874c5f0073884ec2f2d869"
[Host]
ele = "https://httpizza.ele.me/base.openapi.proxy.ppe"
mail = "http://uat-mall.bilibili.co"
[wardenServer]
addr = "0.0.0.0:9000"
timeout = "3s"

View File

@@ -0,0 +1,42 @@
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/service/main/vip/conf",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/service/main/vip/dao/ele-api-client:go_default_library",
"//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/rpc:go_default_library",
"//library/net/rpc/warden: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,201 @@
package conf
import (
"errors"
"flag"
eleclient "go-common/app/service/main/vip/dao/ele-api-client"
"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/rpc"
"go-common/library/net/rpc/warden"
xtime "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 {
MsgURI string
PayURI string
VipURI string
// log
Log *log.Config
// gorpc server
RPCServer *rpc.ServerConfig
// db
Mysql *sql.Config
// ecodes FIXME
Ecode *ecode.Config
//old db
OldMysql *sql.Config
// http client
HTTPClient *bm.ClientConfig
// mc
Memcache *Memcache
// pay conf
PayConf *PayConf
// rpc clients
RPCClient2 *RPC
// property
Property *Property
// http
BM *bm.ServerConfig
// redis
Redis *Redis
// associate conf
AssociateConf *AssociateConf
// ele conf
ELEConf *eleclient.Config
Host *Host
// grpc server
WardenServer *warden.ServerConfig
// grpc client
CouponClient *warden.ClientConfig
}
// Host host.
type Host struct {
Ele string
Mail string
}
// Redis redis
type Redis struct {
*redis.Config
Expire xtime.Duration
}
// Memcache memcache
type Memcache struct {
*memcache.Config
Expire xtime.Duration
}
//PayConf pay config
type PayConf struct {
CustomerID int64
Token string
OrderNotifyURL string
SignNotifyURL string
PlanID int32
ProductID string
Version string
ReturnURL string
OrderExpire int
SignType string
}
// RPC clients config.
type RPC struct {
Member *rpc.ClientConfig
Point *rpc.ClientConfig
Coupon *rpc.ClientConfig
}
// Property config for biz logic.
type Property struct {
NotifyURL string
MsgURL string
PayURL string
PayCoURL string
AccountURL string
PassportURL string
APIURL string
APICoURL string
VipURL string
TokenBID string
PGCURL string
ActiveDate string
ActiveTip string
Expire string
AnnualVipBcoinDay int16
AnnualVipBcoinCouponMoney int
AnnualVipBcoinCouponActivityID int
GiveBpDay int8
PointGetRule map[string]int
PointActiveDate map[string]string
BubbleTicker xtime.Duration
PayType map[string]string
PayChannelMapping map[string]string
PointBalance int64
ActiveStart string
ActiveEnd string
ConfigMap map[string]string
PointExchangeTitle map[string]string
WillExpiredTitle map[string]string
ExpiredTitle map[string]string
TipButtonName string
TipButtonLink string
AllowanceSwitch int8
CodeSwitch int8
GiveSwitch int8
PanelBgURL string
CodeOpenedSearchSize int
WelfareBgHost string
}
// AssociateConf associate vip conf.
type AssociateConf struct {
// user grant count limit
GrantDurationMap map[string]int64 //限制饿了么发放联合会员的次数
BilibiliPrizeGrantKeyMap map[string]string
MailCouponID1 string //票务优惠券满99减5
MailCouponID2 string //电商优惠券满299减20
BilibiliBuyDurationMap map[string]int64 //限制bilibili购买联合会员的次数
}
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
}
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,129 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_test",
"go_library",
)
go_test(
name = "go_default_test",
srcs = [
"associate_banner_test.go",
"associate_ele_api_test.go",
"associate_mc_test.go",
"associate_old_test.go",
"associate_open_test.go",
"associate_order_test.go",
"bcoin_test.go",
"business_test.go",
"cache_test.go",
"dao.cache_test.go",
"dao_test.go",
"dialog_test.go",
"http_test.go",
"jointly_test.go",
"mail_api_test.go",
"memcache_test.go",
"mysql_test.go",
"old_order_test.go",
"oldvip_test.go",
"order_test.go",
"panel_test.go",
"pay_test.go",
"platform_test.go",
"point_test.go",
"privilege_test.go",
"redis_test.go",
"resource_test.go",
"tips_test.go",
"user_test.go",
"welfare_test.go",
],
embed = [":go_default_library"],
rundir = ".",
tags = ["automanaged"],
deps = [
"//app/service/main/vip/conf:go_default_library",
"//app/service/main/vip/model:go_default_library",
"//library/ecode:go_default_library",
"//library/time:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
"//vendor/gopkg.in/h2non/gock.v1:go_default_library",
],
)
go_library(
name = "go_default_library",
srcs = [
"associate_banner.go",
"associate_ele_api.go",
"associate_mc.go",
"associate_old.go",
"associate_open.go",
"associate_order.go",
"bcoin.go",
"business.go",
"cache.go",
"dao.cache.go",
"dao.go",
"dialog.go",
"http.go",
"jointly.go",
"mail_api.go",
"memcache.go",
"mysql.go",
"old_order.go",
"oldvip.go",
"order.go",
"panel.go",
"pay.go",
"platform.go",
"point.go",
"privilege.go",
"redis.go",
"resource.go",
"tips.go",
"user.go",
"welfare.go",
],
importpath = "go-common/app/service/main/vip/dao",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/service/main/vip/conf:go_default_library",
"//app/service/main/vip/dao/ele-api-client:go_default_library",
"//app/service/main/vip/dao/mail-api-client:go_default_library",
"//app/service/main/vip/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/stat/prom:go_default_library",
"//library/sync/pipeline/fanout: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",
"//app/service/main/vip/dao/ele-api-client:all-srcs",
"//app/service/main/vip/dao/mail-api-client:all-srcs",
],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

View File

@@ -0,0 +1,35 @@
package dao
import (
"context"
"go-common/app/service/main/vip/model"
"go-common/library/database/sql"
"github.com/pkg/errors"
)
const (
_effectiveAssociateVipsSQL = "SELECT title,remark,link,associate_platform FROM vip_associate_vip WHERE state = 0 AND deleted = 0 ORDER BY order_num DESC;"
)
// EffectiveAssociateVips effective associate vips.
func (d *Dao) EffectiveAssociateVips(c context.Context) (res []*model.AssociateVipResp, err error) {
var rows *sql.Rows
if rows, err = d.db.Query(c, _effectiveAssociateVipsSQL); err != nil {
err = errors.WithStack(err)
return
}
defer rows.Close()
for rows.Next() {
r := new(model.AssociateVipResp)
if err = rows.Scan(&r.Title, &r.Remark, &r.Link, &r.AssociatePlatform); err != nil {
err = errors.WithStack(err)
res = nil
return
}
res = append(res, r)
}
err = rows.Err()
return
}

View File

@@ -0,0 +1,19 @@
package dao
import (
"context"
"fmt"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoEffectiveAssociateVips(t *testing.T) {
convey.Convey("EffectiveAssociateVips", t, func(ctx convey.C) {
res, err := d.EffectiveAssociateVips(context.Background())
fmt.Println("res", res)
ctx.Convey(" EffectiveAssociateVips ", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}

View File

@@ -0,0 +1,244 @@
package dao
import (
"context"
eleclient "go-common/app/service/main/vip/dao/ele-api-client"
"go-common/app/service/main/vip/model"
"go-common/library/ecode"
"go-common/library/log"
)
// api name
const (
_oauthGenerateAccessTokenURI = "/base.openservice/oauth_generate_access_token"
_unionReceivePrizesURI = "/member/bilibili/union/receive_prizes"
_unionUpdateOpenIDURI = "/member/bilibili/union/update_open_id"
_bindUnionURI = "/member/bilibili/bind_union"
_canPurchaseURI = "/member/bilibili/union/can_purchase"
_getUnionMobileURI = "/member/bilibili/union/get_union_mobile"
_hongbaosURI = "/member/bilibili/union/hongbaos"
_specailFoodsURI = "/member/bilibili/union/special_foods"
)
// EleOauthGenerateAccessToken get access_token by auth_code.
func (d *Dao) EleOauthGenerateAccessToken(c context.Context, a *model.ArgEleAccessToken) (data *model.EleAccessTokenResp, err error) {
args := new(struct {
Request *model.ArgEleAccessToken `json:"request"`
})
args.Request = a
resp := new(struct {
Message string `json:"message"`
Name string `json:"name"`
Data *model.EleAccessTokenResp `json:"data"`
})
err = d.eleclient.Post(c, d.c.Host.Ele, _oauthGenerateAccessTokenURI, args, resp)
if err != nil {
log.Error("ele faild api(%s) a(%+v) resp(%+v) error(%+v)", _oauthGenerateAccessTokenURI, a, resp, err)
err = ecode.VipEleUnionReqErr
return
}
if !eleclient.IsSuccess(resp.Message) {
log.Error("ele message faild api(%s) a(%+v) resp(%+v) error(%+v)", _oauthGenerateAccessTokenURI, a, resp, err)
err = ecode.VipEleUnionRespCodeErr
return
}
data = resp.Data
log.Info("ele success api(%s) a(%+v) resp(%+v) data(%+v)", _oauthGenerateAccessTokenURI, a, resp, data)
return
}
// EleUnionReceivePrizes union receive prizes.
func (d *Dao) EleUnionReceivePrizes(c context.Context, a *model.ArgEleReceivePrizes) (data []*model.EleReceivePrizesResp, err error) {
args := new(struct {
Request *model.ArgEleReceivePrizes `json:"request"`
})
args.Request = a
resp := new(struct {
Message string `json:"message"`
Name string `json:"name"`
Data []*model.EleReceivePrizesResp `json:"data"`
})
err = d.eleclient.Post(c, d.c.Host.Ele, _unionReceivePrizesURI, args, resp)
if err != nil {
log.Error("ele faild api(%s) a(%+v) resp(%+v) error(%+v)", _unionReceivePrizesURI, a, resp, err)
err = ecode.VipEleUnionReqErr
return
}
if !eleclient.IsSuccess(resp.Message) {
log.Error("ele message faild api(%s) a(%+v) resp(%+v) error(%+v)", _unionReceivePrizesURI, a, resp, err)
err = ecode.VipEleUnionRespCodeErr
return
}
data = resp.Data
log.Info("ele success api(%s) a(%+v) resp(%+v) data(%+v)", _unionReceivePrizesURI, a, resp, data)
return
}
// EleUnionUpdateOpenID update_open_id req.
func (d *Dao) EleUnionUpdateOpenID(c context.Context, a *model.ArgEleUnionUpdateOpenID) (data *model.EleUnionUpdateOpenIDResp, err error) {
args := new(struct {
Request *model.ArgEleUnionUpdateOpenID `json:"request"`
})
args.Request = a
resp := new(struct {
Message string `json:"message"`
Name string `json:"name"`
Data *model.EleUnionUpdateOpenIDResp `json:"data"`
})
err = d.eleclient.Post(c, d.c.Host.Ele, _unionUpdateOpenIDURI, args, resp)
if err != nil {
log.Error("ele faild api(%s) a(%+v) resp(%+v) error(%+v)", _unionUpdateOpenIDURI, a, resp, err)
err = ecode.VipEleUnionReqErr
return
}
if !eleclient.IsSuccess(resp.Message) {
log.Error("ele message faild api(%s) a(%+v) resp(%+v) error(%+v)", _unionUpdateOpenIDURI, a, resp, err)
err = ecode.VipEleUnionRespCodeErr
return
}
data = resp.Data
log.Info("ele success api(%s) a(%+v) resp(%+v) data(%+v)", _unionUpdateOpenIDURI, a, resp, data)
return
}
// EleBindUnion ele bind union salary vip.
func (d *Dao) EleBindUnion(c context.Context, a *model.ArgEleBindUnion) (data *model.EleBindUnionResp, err error) {
args := new(struct {
Request *model.ArgEleBindUnion `json:"request"`
})
args.Request = a
resp := new(struct {
Message string `json:"message"`
Name string `json:"name"`
Data *model.EleBindUnionResp `json:"data"`
})
err = d.eleclient.Post(c, d.c.Host.Ele, _bindUnionURI, args, resp)
if err != nil {
log.Error("ele faild api(%s) a(%+v) resp(%+v) error(%+v)", _bindUnionURI, a, resp, err)
err = ecode.VipEleUnionReqErr
return
}
if !eleclient.IsSuccess(resp.Message) {
log.Error("ele message faild api(%s) a(%+v) resp(%+v) error(%+v)", _bindUnionURI, a, resp, err)
err = ecode.VipEleUnionRespCodeErr
return
}
data = resp.Data
// 1.发放成功
if data.Status != 1 && data.Status != 6 {
log.Error("ele status faild api(%s) a(%+v) resp(%+v) data(%+v) error(%+v)", _bindUnionURI, a, resp, data, err)
err = ecode.VipOrderEleVipGrantFaildErr
}
log.Info("ele success api(%s) a(%+v) resp(%+v) data(%+v)", _bindUnionURI, a, resp, data)
return
}
// EleCanPurchase ele can purchase.
func (d *Dao) EleCanPurchase(c context.Context, a *model.ArgEleCanPurchase) (data *model.EleCanPurchaseResp, err error) {
args := new(struct {
Request *model.ArgEleCanPurchase `json:"request"`
})
args.Request = a
resp := new(struct {
Message string `json:"message"`
Name string `json:"name"`
Data *model.EleCanPurchaseResp `json:"data"`
})
err = d.eleclient.Post(c, d.c.Host.Ele, _canPurchaseURI, args, resp)
if err != nil {
log.Error("ele faild api(%s) a(%+v) resp(%+v) error(%+v)", _canPurchaseURI, a, resp, err)
err = ecode.VipEleUnionReqErr
return
}
// 系统请求是否有误
if !eleclient.IsSuccess(resp.Message) {
log.Error("ele message faild api(%s) a(%+v) resp(%+v) error(%+v)", _canPurchaseURI, a, resp, err)
err = ecode.VipEleUnionRespCodeErr
return
}
// 业务逻辑是否有误
data = resp.Data
if data.Status != 1 {
log.Error("ele status faild api(%s) a(%+v) resp(%+v) data(%+v) error(%+v)", _canPurchaseURI, a, resp, data, err)
err = ecode.VipEleUnionBuyCanPurchaseErr
return
}
log.Info("ele success api(%s) a(%+v) resp(%+v) data(%+v)", _canPurchaseURI, a, resp, data)
return
}
// EleUnionMobile get ele union mobile.
func (d *Dao) EleUnionMobile(c context.Context, a *model.ArgEleUnionMobile) (data *model.EleUnionMobileResp, err error) {
args := new(struct {
Request *model.ArgEleUnionMobile `json:"request"`
})
args.Request = a
resp := new(struct {
Message string `json:"message"`
Name string `json:"name"`
Data *model.EleUnionMobileResp `json:"data"`
})
err = d.eleclient.Post(c, d.c.Host.Ele, _getUnionMobileURI, args, resp)
if err != nil {
log.Error("ele faild api(%s) a(%+v) resp(%+v) error(%+v)", _getUnionMobileURI, a, resp, err)
err = ecode.VipEleUnionReqErr
return
}
if !eleclient.IsSuccess(resp.Message) {
log.Error("ele message faild api(%s) a(%+v) resp(%+v) error(%+v)", _getUnionMobileURI, a, resp, err)
err = ecode.VipEleUnionRespCodeErr
return
}
data = resp.Data
log.Info("ele success api(%s) a(%+v) resp(%+v) data(%+v)", _getUnionMobileURI, a, resp, data)
return
}
// EleRedPackages get ele red packages.
func (d *Dao) EleRedPackages(c context.Context) (data []*model.EleRedPackagesResp, err error) {
args := new(struct{})
resp := new(struct {
Message string `json:"message"`
Name string `json:"name"`
Data []*model.EleRedPackagesResp `json:"data"`
})
err = d.eleclient.Post(c, d.c.Host.Ele, _hongbaosURI, args, resp)
if err != nil {
log.Error("ele faild api(%s)resp(%+v) error(%+v)", _hongbaosURI, resp, err)
err = ecode.VipEleUnionReqErr
return
}
if !eleclient.IsSuccess(resp.Message) {
log.Error("ele message faild api(%s) resp(%+v) error(%+v)", _hongbaosURI, resp, err)
err = ecode.VipEleUnionRespCodeErr
return
}
data = resp.Data
log.Info("ele success api(%s) resp(%+v) data(%+v)", _hongbaosURI, resp, data)
return
}
// EleSpecailFoods get ele specail foods.
func (d *Dao) EleSpecailFoods(c context.Context) (data []*model.EleSpecailFoodsResp, err error) {
args := new(struct{})
resp := new(struct {
Message string `json:"message"`
Name string `json:"name"`
Data []*model.EleSpecailFoodsResp `json:"data"`
})
err = d.eleclient.Post(c, d.c.Host.Ele, _specailFoodsURI, args, resp)
if err != nil {
log.Error("ele faild api(%s)resp(%+v) error(%+v)", _specailFoodsURI, resp, err)
err = ecode.VipEleUnionReqErr
return
}
if !eleclient.IsSuccess(resp.Message) {
log.Error("ele message faild api(%s) resp(%+v) error(%+v)", _specailFoodsURI, resp, err)
err = ecode.VipEleUnionRespCodeErr
return
}
data = resp.Data
log.Info("ele success api(%s) resp(%+v) data(%+v)", _specailFoodsURI, resp, data)
return
}

View File

@@ -0,0 +1,98 @@
package dao
import (
"context"
"testing"
"go-common/app/service/main/vip/model"
"go-common/library/ecode"
"github.com/smartystreets/goconvey/convey"
)
// func TestDaoEleOauthGenerateAccessToken(t *testing.T) {
// convey.Convey("TestDaoEleOauthGenerateAccessToken", t, func(ctx convey.C) {
// defer gock.OffAll()
// httpMock("POST", _oauthGenerateAccessTokenURI).Reply(200).JSON(`{"code":0}`)
// _, err := d.EleOauthGenerateAccessToken(context.Background(), &model.ArgEleAccessToken{
// AuthCode: "abc"})
// ctx.So(err, convey.ShouldBeNil)
// })
// }
func TestDaoEleUnionReceivePrizes(t *testing.T) {
convey.Convey("TestDaoEleUnionReceivePrizes", t, func(ctx convey.C) {
_, err := d.EleUnionReceivePrizes(context.Background(), &model.ArgEleReceivePrizes{
ElemeOpenID: "o8f999ad5d724b4a2ljbp7cm",
BliOpenID: "e11303e8c26268a6cbdc2dc7fce55199",
SourceID: "1",
})
ctx.So(err, convey.ShouldEqual, ecode.VipEleUnionReqErr)
})
}
func TestDaoEleUnionUpdateOpenID(t *testing.T) {
convey.Convey("TestDaoEleUnionUpdateOpenID", t, func(ctx convey.C) {
_, err := d.EleUnionUpdateOpenID(context.Background(), &model.ArgEleUnionUpdateOpenID{
ElemeOpenID: "oe1822de904ceed07bpvCUOU",
BliOpenID: "bdca8b71e7a6726885d40a395bf9ccd1",
})
ctx.So(err, convey.ShouldEqual, ecode.VipEleUnionReqErr)
})
}
// func TestDaoEleCanPurchase(t *testing.T) {
// convey.Convey("TestDaoEleCanPurchase", t, func(ctx convey.C) {
// _, err := d.EleCanPurchase(context.Background(), &model.ArgEleCanPurchase{
// ElemeOpenID: "oe1822de904ceed07bpvCUOU",
// BliOpenID: "8551e7e9827f759d7fe13bc41b8a7613",
// UserIP: "10.23.167.25",
// VipType: 2,
// })
// ctx.So(err, convey.ShouldBeNil)
// })
// }
func TestDaoEleUnionMobile(t *testing.T) {
convey.Convey("TestDaoEleUnionMobile", t, func(ctx convey.C) {
_, err := d.EleUnionMobile(context.Background(), &model.ArgEleUnionMobile{
ElemeOpenID: "o8f999ad5d724b4a2ljbp7cm",
BliOpenID: "e11303e8c26268a6cbdc2dc7fce55199",
})
ctx.So(err, convey.ShouldEqual, ecode.VipEleUnionReqErr)
})
}
// func TestDaoEleBindUnion(t *testing.T) {
// convey.Convey("TestDaoEleBindUnion", t, func(ctx convey.C) {
// res, err := d.EleBindUnion(context.Background(), &model.ArgEleBindUnion{
// ElemeOpenID: "o8f999ad5d724b4a2ljbp7cm",
// BliOpenID: "e11303e8c26268a6cbdc2dc7fce55199",
// VipType: 2,
// SourceID: "123456789",
// UserIP: "121.46.231.66",
// })
// ctx.Convey("TestDaoEleBindUnion ", func(ctx convey.C) {
// ctx.So(err, convey.ShouldBeNil)
// ctx.So(res, convey.ShouldNotBeNil)
// })
// })
// }
func TestDaoEleRedPackages(t *testing.T) {
convey.Convey("TestDaoEleRedPackages", t, func(ctx convey.C) {
_, err := d.EleRedPackages(context.Background())
ctx.Convey("TestDaoEleRedPackages ", func(ctx convey.C) {
ctx.So(err, convey.ShouldEqual, ecode.VipEleUnionReqErr)
})
})
}
func TestDaoEleSpecailFoods(t *testing.T) {
convey.Convey("TestDaoEleSpecailFoods", t, func(ctx convey.C) {
_, err := d.EleSpecailFoods(context.Background())
ctx.Convey("TestDaoEleSpecailFoods ", func(ctx convey.C) {
ctx.So(err, convey.ShouldEqual, ecode.VipEleUnionReqErr)
})
})
}

View File

@@ -0,0 +1,123 @@
package dao
import (
"context"
"strconv"
"go-common/app/service/main/vip/model"
mc "go-common/library/cache/memcache"
"github.com/pkg/errors"
)
const (
_prefixBindByMid = "b:m:"
_prefixOpenInfoByOpenID = "o:i:"
)
func keyBindByMid(mid int64, appID int64) string {
return _prefixBindByMid + strconv.FormatInt(mid, 10) + ":" + strconv.FormatInt(appID, 10)
}
func keyOpenInfoByOpenID(openID string, appID int64) string {
return _prefixOpenInfoByOpenID + openID + ":" + strconv.FormatInt(appID, 10)
}
// CacheBindInfoByMid get vip bind by mid cache.
func (d *Dao) CacheBindInfoByMid(c context.Context, mid int64, appID int64) (v *model.OpenBindInfo, err error) {
key := keyBindByMid(mid, appID)
conn := d.mc.Get(c)
defer conn.Close()
r, err := conn.Get(key)
if err != nil {
if err == mc.ErrNotFound {
err = nil
return
}
err = errors.Wrapf(err, "dao cache bind by mid")
return
}
v = new(model.OpenBindInfo)
if err = conn.Scan(r, v); err != nil {
err = errors.Wrapf(err, "dao cache scan bind by mid")
}
return
}
// CacheOpenInfoByOpenID get vip open info by open id cache.
func (d *Dao) CacheOpenInfoByOpenID(c context.Context, openID string, appID int64) (v *model.OpenInfo, err error) {
key := keyOpenInfoByOpenID(openID, appID)
conn := d.mc.Get(c)
defer conn.Close()
r, err := conn.Get(key)
if err != nil {
if err == mc.ErrNotFound {
err = nil
return
}
err = errors.Wrapf(err, "dao cache open by openid")
return
}
v = new(model.OpenInfo)
if err = conn.Scan(r, v); err != nil {
err = errors.Wrapf(err, "dao cache scan open by openid")
}
return
}
// AddCacheBindInfoByMid add bind info cache.
func (d *Dao) AddCacheBindInfoByMid(c context.Context, mid int64, v *model.OpenBindInfo, appID int64) (err error) {
item := &mc.Item{
Key: keyBindByMid(mid, appID),
Object: v,
Expiration: d.mcExpire,
Flags: mc.FlagProtobuf,
}
conn := d.mc.Get(c)
err = conn.Set(item)
conn.Close()
if err != nil {
err = errors.Wrapf(err, "dao add cache bind by mid")
}
return
}
// AddCacheOpenInfoByOpenID add open info cache.
func (d *Dao) AddCacheOpenInfoByOpenID(c context.Context, openID string, v *model.OpenInfo, appID int64) (err error) {
item := &mc.Item{
Key: keyOpenInfoByOpenID(openID, appID),
Object: v,
Expiration: d.mcExpire,
Flags: mc.FlagProtobuf,
}
conn := d.mc.Get(c)
err = conn.Set(item)
conn.Close()
if err != nil {
err = errors.Wrapf(err, "dao add cache open by openid")
}
return
}
// DelBindInfoCache del bind info cache.
func (d *Dao) DelBindInfoCache(c context.Context, mid int64, appID int64) (err error) {
return d.delCache(c, keyBindByMid(mid, appID))
}
// DelOpenInfoCache del open info cache.
func (d *Dao) DelOpenInfoCache(c context.Context, openID string, appID int64) (err error) {
return d.delCache(c, keyOpenInfoByOpenID(openID, appID))
}
func (d *Dao) delCache(c context.Context, key string) (err error) {
conn := d.mc.Get(c)
defer conn.Close()
if err = conn.Delete(key); err != nil {
if err == mc.ErrNotFound {
err = nil
} else {
err = errors.Wrapf(err, "del cache")
}
}
return
}

View File

@@ -0,0 +1,142 @@
package dao
import (
"context"
"fmt"
"testing"
"go-common/app/service/main/vip/model"
"github.com/smartystreets/goconvey/convey"
)
func TestDaokeyBindByMid(t *testing.T) {
convey.Convey("keyBindByMid", t, func(convCtx convey.C) {
var (
mid = int64(0)
appID = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
p1 := keyBindByMid(mid, appID)
convCtx.Convey("Then p1 should not be nil.", func(convCtx convey.C) {
convCtx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
// func TestDaoCacheBindInfoByMid(t *testing.T) {
// convey.Convey("CacheBindInfoByMid", t, func(convCtx convey.C) {
// var (
// c = context.Background()
// mid = int64(0)
// appID = int64(0)
// )
// convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
// v, err := d.CacheBindInfoByMid(c, mid, appID)
// convCtx.Convey("Then err should be nil.v should not be nil.", func(convCtx convey.C) {
// convCtx.So(err, convey.ShouldBeNil)
// convCtx.So(v, convey.ShouldNotBeNil)
// })
// })
// })
// }
func TestDaoAddCacheBindInfoByMid(t *testing.T) {
convey.Convey("AddCacheBindInfoByMid", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(0)
v = &model.OpenBindInfo{}
appID = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.AddCacheBindInfoByMid(c, mid, v, appID)
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoDelBindInfoCache(t *testing.T) {
convey.Convey("DelBindInfoCache", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(0)
appID = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.DelBindInfoCache(c, mid, appID)
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaodelCacheUnion(t *testing.T) {
convey.Convey("delCacheUnion", t, func(convCtx convey.C) {
var (
c = context.Background()
key = "t_key"
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.delCache(c, key)
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoAddCacheOpenInfoByOpenID(t *testing.T) {
convey.Convey("AddCacheOpenInfoByOpenID", t, func(convCtx convey.C) {
var (
c = context.Background()
openID = "xx101"
appID = int64(32)
)
v := &model.OpenInfo{OpenID: openID, Mid: 101, AppID: appID}
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.AddCacheOpenInfoByOpenID(c, openID, v, appID)
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoCacheOpenInfoByOpenID(t *testing.T) {
convey.Convey("CacheOpenInfoByOpenID", t, func(convCtx convey.C) {
var (
c = context.Background()
openID = "xx101"
appID = int64(32)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
v, err := d.CacheOpenInfoByOpenID(c, openID, appID)
fmt.Println("v--", v)
convCtx.Convey("Then err should be nil.v should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(v, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoDelOpenInfoCache(t *testing.T) {
convey.Convey("DelOpenInfoCache", t, func(convCtx convey.C) {
var (
c = context.Background()
openID = "xx101"
appID = int64(32)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.DelOpenInfoCache(c, openID, appID)
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
})
}

View File

@@ -0,0 +1,55 @@
package dao
import (
"context"
xsql "database/sql"
"go-common/app/service/main/vip/model"
"go-common/library/database/sql"
"github.com/pkg/errors"
)
const (
_activityOrderSQL = "SELECT id,mid,order_no,product_id,months,panel_type,associate_state,ctime,mtime FROM vip_order_activity_record WHERE order_no = ?;"
_updateActivityStateSQL = "UPDATE vip_order_activity_record SET associate_state =? WHERE order_no = ?;"
_productBuyCountSQL = "SELECT current_count as count FROM vip_product_pay_record WHERE mid = ? AND months=? AND panel_type = ?;"
)
//ActivityOrder get activity order by order_no.
func (d *Dao) ActivityOrder(c context.Context, orderNO string) (res *model.VipOrderActivityRecord, err error) {
res = new(model.VipOrderActivityRecord)
if err = d.olddb.QueryRow(c, _activityOrderSQL, orderNO).
Scan(&res.ID, &res.Mid, &res.OrderNO, &res.ProductID, &res.Months, &res.PanelType, &res.AssociateState, &res.Ctime, &res.Mtime); err != nil {
if err == sql.ErrNoRows {
res = nil
err = nil
return
}
err = errors.Wrapf(err, "dao activity order(%s)", orderNO)
}
return
}
// UpdateActivityState update act vip grant state.
func (d *Dao) UpdateActivityState(c context.Context, state int8, orderNO string) (aff int64, err error) {
var res xsql.Result
if res, err = d.olddb.Exec(c, _updateActivityStateSQL, state, orderNO); err != nil {
err = errors.Wrapf(err, "dao update associate state(%d,%s)", state, orderNO)
return
}
return res.RowsAffected()
}
// CountProductBuy get user by product count.
func (d *Dao) CountProductBuy(c context.Context, mid int64, months int32, panelType string) (count int64, err error) {
row := d.olddb.QueryRow(c, _productBuyCountSQL, mid, months, panelType)
if err = row.Scan(&count); err != nil {
if err == sql.ErrNoRows {
err = nil
return
}
err = errors.Wrapf(err, "dao update associate state(%d,%d,%s)", mid, months, panelType)
}
return
}

View File

@@ -0,0 +1,59 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoActivityOrder(t *testing.T) {
convey.Convey("ActivityOrder", t, func(convCtx convey.C) {
var (
c = context.Background()
orderNo = "test_activity_no"
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
_, err := d.ActivityOrder(c, orderNo)
convCtx.So(err, convey.ShouldBeNil)
})
convCtx.Convey("clean data", func(convCtx convey.C) {
d.olddb.Exec(c, "delete from vip_order_activity_record where order_no=? ", orderNo)
})
})
}
func TestDaoUpdateActivityState(t *testing.T) {
convey.Convey("UpdateActivityState", t, func(convCtx convey.C) {
var (
c = context.Background()
state = int8(0)
orderNO = ""
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
aff, err := d.UpdateActivityState(c, state, orderNO)
convCtx.Convey("Then err should be nil.aff should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(aff, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoCountProductBuy(t *testing.T) {
convey.Convey("CountProductBuy", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(0)
months = int32(0)
panelType = ""
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
count, err := d.CountProductBuy(c, mid, months, panelType)
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,138 @@
package dao
import (
"context"
"go-common/app/service/main/vip/model"
"go-common/library/database/sql"
"github.com/pkg/errors"
)
const (
_openInfoOpenIDSQL = "SELECT mid,open_id,app_id FROM oauth_open_id WHERE open_id = ? AND app_id = ?;"
_openInfoByMidSQL = "SELECT mid,open_id,app_id FROM oauth_open_id WHERE mid = ? AND app_id = ?;"
_bindByOutOpenIDSQL = "SELECT id,mid,app_id,out_open_id,state,ver FROM oauth_user_bind WHERE out_open_id = ? AND app_id =?;"
_bindByMidSQL = "SELECT id,mid,app_id,out_open_id,state,ver FROM oauth_user_bind WHERE mid = ? AND app_id =?;"
_addBindSQL = "INSERT IGNORE INTO oauth_user_bind (mid,app_id,out_open_id)VALUES(?,?,?);"
_updateBindByOutOpenID = "UPDATE oauth_user_bind SET mid = ?,app_id = ?,out_open_id = ?,ver = ver + 1 WHERE out_open_id = ? AND app_id = ? AND ver = ?;"
_updateBindStateSQL = "UPDATE oauth_user_bind SET state = ?,ver = ver + 1 WHERE mid = ? AND app_id = ? AND ver = ?;"
_addOpenInfoSQL = "INSERT IGNORE INTO oauth_open_id (mid,open_id,app_id)VALUES(?,?,?);"
_bindInfoByOutOpenIDAndMidSQL = "SELECT mid,app_id,out_open_id,state,ver FROM oauth_user_bind WHERE mid = ? AND out_open_id = ? AND app_id =?;"
_deleteBindInfoSQL = "DELETE FROM oauth_user_bind WHERE id = ?;"
)
//RawOpenInfoByOpenID get info by open id.
func (d *Dao) RawOpenInfoByOpenID(c context.Context, openID string, appID int64) (res *model.OpenInfo, err error) {
res = new(model.OpenInfo)
if err = d.db.QueryRow(c, _openInfoOpenIDSQL, openID, appID).
Scan(&res.Mid, &res.OpenID, &res.AppID); err != nil {
if err == sql.ErrNoRows {
res = nil
err = nil
return
}
err = errors.Wrapf(err, "dao associate openinfo openid(%s,%d)", openID, appID)
}
return
}
// OpenInfoByMid get open info by mid.
func (d *Dao) OpenInfoByMid(c context.Context, mid int64, appID int64) (res *model.OpenInfo, err error) {
res = new(model.OpenInfo)
if err = d.db.QueryRow(c, _openInfoByMidSQL, mid, appID).
Scan(&res.Mid, &res.OpenID, &res.AppID); err != nil {
if err == sql.ErrNoRows {
res = nil
err = nil
return
}
err = errors.Wrapf(err, "dao associate openinfo bymid(%d,%d)", mid, appID)
}
return
}
//ByOutOpenID get open bind info by out_open_id.
func (d *Dao) ByOutOpenID(c context.Context, outOpenID string, appID int64) (res *model.OpenBindInfo, err error) {
res = new(model.OpenBindInfo)
if err = d.db.QueryRow(c, _bindByOutOpenIDSQL, outOpenID, appID).
Scan(&res.ID, &res.Mid, &res.AppID, &res.OutOpenID, &res.State, &res.Ver); err != nil {
if err == sql.ErrNoRows {
res = nil
err = nil
return
}
err = errors.Wrapf(err, "dao associate by out_open_id (%s,%d)", outOpenID, appID)
}
return
}
//RawBindInfoByMid get open bind info by mid.
func (d *Dao) RawBindInfoByMid(c context.Context, mid int64, appID int64) (res *model.OpenBindInfo, err error) {
res = new(model.OpenBindInfo)
if err = d.db.QueryRow(c, _bindByMidSQL, mid, appID).
Scan(&res.ID, &res.Mid, &res.AppID, &res.OutOpenID, &res.State, &res.Ver); err != nil {
if err == sql.ErrNoRows {
res = nil
err = nil
return
}
err = errors.Wrapf(err, "dao associate by mid (%d,%d)", mid, appID)
}
return
}
// TxAddBind add bind.
func (d *Dao) TxAddBind(tx *sql.Tx, arg *model.OpenBindInfo) (err error) {
if _, err = tx.Exec(_addBindSQL, arg.Mid, arg.AppID, arg.OutOpenID); err != nil {
err = errors.Wrapf(err, "dao add bind(%+v)", arg)
}
return
}
// TxUpdateBindByOutOpenID update bind by out_open_id.
func (d *Dao) TxUpdateBindByOutOpenID(tx *sql.Tx, arg *model.OpenBindInfo) (err error) {
if _, err = tx.Exec(_updateBindByOutOpenID, arg.Mid, arg.AppID, arg.OutOpenID, arg.OutOpenID, arg.AppID, arg.Ver); err != nil {
err = errors.Wrapf(err, "dao update bind by out_open_id(%+v)", arg)
}
return
}
// UpdateBindState update bind state.
func (d *Dao) UpdateBindState(c context.Context, arg *model.OpenBindInfo) (err error) {
if _, err = d.db.Exec(c, _updateBindStateSQL, arg.State, arg.Mid, arg.AppID, arg.Ver); err != nil {
err = errors.Wrapf(err, "dao update bind state(%+v)", arg)
}
return
}
// AddOpenInfo add open info.
func (d *Dao) AddOpenInfo(c context.Context, a *model.OpenInfo) (err error) {
if _, err = d.db.Exec(c, _addOpenInfoSQL, a.Mid, a.OpenID, a.AppID); err != nil {
err = errors.Wrapf(err, "dao insert open infp state(%+v)", a)
}
return
}
//BindInfoByOutOpenIDAndMid get bind info by out_open_id AND mid.
func (d *Dao) BindInfoByOutOpenIDAndMid(c context.Context, mid int64, outOpenID string, appID int64) (res *model.OpenBindInfo, err error) {
res = new(model.OpenBindInfo)
if err = d.db.QueryRow(c, _bindInfoByOutOpenIDAndMidSQL, mid, outOpenID, appID).
Scan(&res.Mid, &res.AppID, &res.OutOpenID, &res.State, &res.Ver); err != nil {
if err == sql.ErrNoRows {
res = nil
err = nil
return
}
err = errors.Wrapf(err, "dao associate by out_open_id (%s,%d)", outOpenID, appID)
}
return
}
// TxDeleteBindInfo bind info.
func (d *Dao) TxDeleteBindInfo(tx *sql.Tx, id int64) (err error) {
if _, err = tx.Exec(_deleteBindInfoSQL, id); err != nil {
err = errors.Wrapf(err, "dao delete bind(%d)", id)
}
return
}

View File

@@ -0,0 +1,165 @@
package dao
import (
"context"
"testing"
"go-common/app/service/main/vip/model"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoOpenInfoOpenID(t *testing.T) {
convey.Convey("OpenInfoOpenID", t, func(convCtx convey.C) {
var (
c = context.Background()
openID = ""
appID = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
res, err := d.RawOpenInfoByOpenID(c, openID, appID)
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 TestDaoOpenInfoByMid(t *testing.T) {
convey.Convey("OpenInfoByMid", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(0)
appID = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
res, err := d.OpenInfoByMid(c, mid, appID)
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 TestDaoByOutOpenID(t *testing.T) {
convey.Convey("ByOutOpenID", t, func(convCtx convey.C) {
var (
c = context.Background()
outOpenID = ""
appID = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
res, err := d.ByOutOpenID(c, outOpenID, appID)
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 TestDaoRawBindInfoByMid(t *testing.T) {
convey.Convey("RawBindInfoByMid", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(0)
appID = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
res, err := d.RawBindInfoByMid(c, mid, appID)
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 TestDaoTxAddBind(t *testing.T) {
convey.Convey("TxAddBind", t, func(convCtx convey.C) {
var (
tx, _ = d.BeginTran(context.Background())
arg = &model.OpenBindInfo{}
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.TxAddBind(tx, arg)
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
tx.Commit()
})
})
}
func TestDaoTxUpdateBindByOutOpenID(t *testing.T) {
convey.Convey("TxUpdateBindByOutOpenID", t, func(convCtx convey.C) {
var (
tx, _ = d.BeginTran(context.Background())
arg = &model.OpenBindInfo{
AppID: 32,
OutOpenID: "test-2333",
}
)
convCtx.Convey("When TxAddBind", func(convCtx convey.C) {
err := d.TxAddBind(tx, arg)
convCtx.So(err, convey.ShouldBeNil)
tx.Commit()
})
convCtx.Convey("When TxUpdateBindByOutOpenID", func(convCtx convey.C) {
err := d.TxUpdateBindByOutOpenID(tx, arg)
convCtx.So(err, convey.ShouldBeNil)
tx.Commit()
})
convCtx.Convey("When TxDeleteBindInfo", func(convCtx convey.C) {
err := d.TxDeleteBindInfo(tx, arg.ID)
convCtx.So(err, convey.ShouldBeNil)
tx.Commit()
})
})
}
func TestDaoUpdateBindState(t *testing.T) {
convey.Convey("UpdateBindState", t, func(convCtx convey.C) {
var (
c = context.Background()
arg = &model.OpenBindInfo{}
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.UpdateBindState(c, arg)
convCtx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoAddOpenInfo(t *testing.T) {
convey.Convey("AddOpenInfo", t, func(convCtx convey.C) {
var (
c = context.Background()
a = &model.OpenInfo{}
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.AddOpenInfo(c, a)
convCtx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoBindInfoByOutOpenIDAndMid(t *testing.T) {
convey.Convey("BindInfoByOutOpenIDAndMid", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(0)
outOpenID = ""
appID = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
res, err := d.BindInfoByOutOpenIDAndMid(c, mid, outOpenID, appID)
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,106 @@
package dao
import (
"context"
xsql "database/sql"
"go-common/app/service/main/vip/model"
"go-common/library/database/sql"
"github.com/pkg/errors"
)
const (
_countOrderByAppidSQL = "SELECT COUNT(1) FROM vip_pay_order WHERE mid = ? AND app_id = ? AND status=2;"
_countAssociateGrantSQL = "SELECT COUNT(1) FROM vip_order_associate_grant WHERE mid = ? AND app_id = ?;"
_countAssociateByOrderNoSQL = "SELECT COUNT(1) FROM vip_order_associate_grant WHERE out_trade_no = ? AND app_id = ?;"
_countAssociateByMidAndMonthsSQL = "SELECT COUNT(1) FROM vip_order_associate_grant WHERE mid = ? AND app_id = ? AND months = ?;"
_insertAssociateGrantOrderSQL = "INSERT INTO vip_order_associate_grant(app_id,mid,months,out_open_id,out_trade_no,state,ctime)VALUES(?,?,?,?,?,?,?);"
_updateAssociateGrantStateSQL = "UPDATE vip_order_associate_grant SET state = ? WHERE out_trade_no = ? AND app_id = ?"
_associateGrantCountInfoSQL = "SELECT id,app_id,mid,months,current_count,ctime,mtime FROM vip_order_associate_grant_count WHERE mid = ? AND app_id = ? AND months = ?;"
_addAssociateGrantCountSQL = "INSERT IGNORE INTO vip_order_associate_grant_count(app_id,mid,months,current_count)VALUES(?,?,?,?);"
_updateAssociateGrantCountSQL = "UPDATE vip_order_associate_grant_count SET current_count = current_count + 1 WHERE mid = ? AND months = ? AND app_id = ? AND current_count = ?;"
)
// CountAssociateOrder associate order count.
func (d *Dao) CountAssociateOrder(c context.Context, mid int64, appID int64) (count int64, err error) {
if err = d.olddb.QueryRow(c, _countOrderByAppidSQL, mid, appID).Scan(&count); err != nil {
err = errors.Wrapf(err, "dao associate count orders(%d,%d)", mid, appID)
}
return
}
// CountAssociateGrants associate grant count.
func (d *Dao) CountAssociateGrants(c context.Context, mid int64, appID int64) (count int64, err error) {
if err = d.olddb.QueryRow(c, _countAssociateGrantSQL, mid, appID).Scan(&count); err != nil {
err = errors.Wrapf(err, "dao associate count grant(%d,%d)", mid, appID)
}
return
}
// CountGrantOrderByOutTradeNo grant order by out_trade_no count.
func (d *Dao) CountGrantOrderByOutTradeNo(c context.Context, outTradeNo string, appID int64) (count int64, err error) {
if err = d.olddb.QueryRow(c, _countAssociateByOrderNoSQL, outTradeNo, appID).Scan(&count); err != nil {
err = errors.Wrapf(err, "dao associate count grant by outno (%s,%d)", outTradeNo, appID)
}
return
}
// CountAssociateByMidAndMonths count grant order by mid and months .
func (d *Dao) CountAssociateByMidAndMonths(c context.Context, mid int64, appID int64, months int32) (count int64, err error) {
if err = d.olddb.QueryRow(c, _countAssociateByMidAndMonthsSQL, mid, appID, months).Scan(&count); err != nil {
err = errors.Wrapf(err, "dao associate count grant by mid and months (%d,%d,%d)", mid, appID, months)
}
return
}
// TxInsertAssociateGrantOrder insert associate grant order.
func (d *Dao) TxInsertAssociateGrantOrder(tx *sql.Tx, oa *model.VipOrderAssociateGrant) (aff int64, err error) {
var res xsql.Result
if res, err = tx.Exec(_insertAssociateGrantOrderSQL, oa.AppID, oa.Mid, oa.Months, oa.OutOpenID, oa.OutTradeNO, oa.State, oa.Ctime); err != nil {
err = errors.Wrapf(err, "dao insert grant(%+v)", oa)
return
}
return res.RowsAffected()
}
// TxUpdateAssociateGrantState update associate grant state.
func (d *Dao) TxUpdateAssociateGrantState(tx *sql.Tx, oa *model.VipOrderAssociateGrant) (aff int64, err error) {
var res xsql.Result
if res, err = tx.Exec(_updateAssociateGrantStateSQL, oa.State, oa.OutTradeNO, oa.AppID); err != nil {
err = errors.Wrapf(err, "dao update grant(%+v)", oa)
return
}
return res.RowsAffected()
}
// AssociateGrantCountInfo associate grant count info.
func (d *Dao) AssociateGrantCountInfo(c context.Context, mid int64, appID int64, months int32) (res *model.VipAssociateGrantCount, err error) {
res = new(model.VipAssociateGrantCount)
if err = d.olddb.QueryRow(c, _associateGrantCountInfoSQL, mid, appID, months).
Scan(&res.ID, &res.AppID, &res.Mid, &res.Months, &res.CurrentCount, &res.Ctime, &res.Mtime); err != nil {
if err == sql.ErrNoRows {
res = nil
err = nil
return
}
err = errors.Wrapf(err, "dao associate openinfo openid(%d,%d,%d)", mid, appID, months)
}
return
}
// AddAssociateGrantCount add associate grant count.
func (d *Dao) AddAssociateGrantCount(c context.Context, arg *model.VipAssociateGrantCount) (err error) {
if _, err = d.olddb.Exec(c, _addAssociateGrantCountSQL, arg.AppID, arg.Mid, arg.Months, arg.CurrentCount); err != nil {
err = errors.Wrapf(err, "dao update bind state(%+v)", arg)
}
return
}
// UpdateAssociateGrantCount update associate grant count.
func (d *Dao) UpdateAssociateGrantCount(c context.Context, arg *model.VipAssociateGrantCount) (err error) {
if _, err = d.olddb.Exec(c, _updateAssociateGrantCountSQL, arg.Mid, arg.Months, arg.AppID, arg.CurrentCount); err != nil {
err = errors.Wrapf(err, "dao update associate grant count(%+v)", arg)
}
return
}

View File

@@ -0,0 +1,163 @@
package dao
import (
"context"
"testing"
"go-common/app/service/main/vip/model"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoCountAssociateOrder(t *testing.T) {
convey.Convey("CountAssociateOrder", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(0)
appID = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
count, err := d.CountAssociateOrder(c, mid, appID)
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 TestDaoCountAssociateGrants(t *testing.T) {
convey.Convey("CountAssociateGrants", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(0)
appID = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
count, err := d.CountAssociateGrants(c, mid, appID)
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 TestDaoCountGrantOrderByOutTradeNo(t *testing.T) {
convey.Convey("CountGrantOrderByOutTradeNo", t, func(convCtx convey.C) {
var (
c = context.Background()
outTradeNo = ""
appID = int64(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
count, err := d.CountGrantOrderByOutTradeNo(c, outTradeNo, appID)
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 TestDaoCountAssociateByMidAndMonths(t *testing.T) {
convey.Convey("CountAssociateByMidAndMonths", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(0)
appID = int64(0)
months = int32(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
count, err := d.CountAssociateByMidAndMonths(c, mid, appID, months)
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 TestDaoTxInsertAssociateGrantOrder(t *testing.T) {
convey.Convey("TxInsertAssociateGrantOrder", t, func(convCtx convey.C) {
var (
oa = &model.VipOrderAssociateGrant{}
c = context.Background()
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
oldtx, err := d.OldStartTx(c)
convCtx.So(err, convey.ShouldBeNil)
aff, err := d.TxInsertAssociateGrantOrder(oldtx, oa)
convCtx.Convey("Then err should be nil.aff should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(aff, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoTxUpdateAssociateGrantState(t *testing.T) {
convey.Convey("TxUpdateAssociateGrantState", t, func(convCtx convey.C) {
var (
oa = &model.VipOrderAssociateGrant{}
c = context.Background()
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
oldtx, err := d.OldStartTx(c)
convCtx.So(err, convey.ShouldBeNil)
aff, err := d.TxUpdateAssociateGrantState(oldtx, oa)
convCtx.Convey("Then err should be nil.aff should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(aff, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoAssociateGrantCountInfo(t *testing.T) {
convey.Convey("AssociateGrantCountInfo", t, func(convCtx convey.C) {
var (
c = context.Background()
mid = int64(0)
appID = int64(0)
months = int32(0)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
res, err := d.AssociateGrantCountInfo(c, mid, appID, months)
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 TestDaoAddAssociateGrantCount(t *testing.T) {
convey.Convey("AddAssociateGrantCount", t, func(convCtx convey.C) {
var (
c = context.Background()
arg = &model.VipAssociateGrantCount{}
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.AddAssociateGrantCount(c, arg)
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoUpdateAssociateGrantCount(t *testing.T) {
convey.Convey("UpdateAssociateGrantCount", t, func(convCtx convey.C) {
var (
c = context.Background()
arg = &model.VipAssociateGrantCount{}
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.UpdateAssociateGrantCount(c, arg)
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
})
}

View File

@@ -0,0 +1,72 @@
package dao
import (
"context"
"time"
"go-common/app/service/main/vip/model"
"go-common/library/database/sql"
"github.com/pkg/errors"
)
const (
_vipUserBcoinSalaryList = "SELECT `id`,`mid`,`status`,`give_now_status`,`payday`,`amount`,`memo`,`ctime`,`mtime` FROM `vip_user_bcoin_salary` WHERE `mid` = ? AND `payday` > ? AND `payday` < ?;"
_SelLastBCoinByMid = "SELECT id,mid,`status`,give_now_status,payday,amount,memo,ctime,mtime from vip_user_bcoin_salary WHERE mid = ? ORDER BY payday DESC"
_InsertVipBcoinSalary = "INSERT INTO vip_user_bcoin_salary(mid,status,give_now_status,payday,amount,memo) VALUES(?,?,?,?,?,?)"
_delBcoinSalary = "DELETE FROM vip_bcoin_salary WHERE mid=? AND month>=?"
)
//BcoinSalaryList vip user bcoin salary list.
func (d *Dao) BcoinSalaryList(c context.Context, mid int64, start, end time.Time) (res []*model.VipBcoinSalary, err error) {
var rows *sql.Rows
if rows, err = d.db.Query(c, _vipUserBcoinSalaryList, mid, start, end); err != nil {
err = errors.WithStack(err)
d.errProm.Incr("query_db")
return
}
defer rows.Close()
for rows.Next() {
r := new(model.VipBcoinSalary)
if err = rows.Scan(&r.ID, &r.Mid, &r.Status, &r.GiveNowStatus, &r.Month, &r.Amount, &r.Memo, &r.Ctime, &r.Mtime); err != nil {
err = errors.WithStack(err)
d.errProm.Incr("row_scan_db")
res = nil
return
}
res = append(res, r)
}
err = rows.Err()
return
}
//SelLastBcoin sel last bcoin by mid.
func (d *Dao) SelLastBcoin(c context.Context, mid int64) (r *model.VipBcoinSalary, err error) {
row := d.db.QueryRow(c, _SelLastBCoinByMid, mid)
r = new(model.VipBcoinSalary)
if err = row.Scan(&r.ID, &r.Mid, &r.Status, &r.GiveNowStatus, &r.Amount, &r.Memo, &r.Ctime, &r.Mtime); err != nil {
if err == sql.ErrNoRows {
err = nil
r = nil
} else {
err = errors.WithStack(err)
}
}
return
}
//InsertVipBcoinSalary insert vip bcoin salary
func (d *Dao) InsertVipBcoinSalary(c context.Context, r *model.VipBcoinSalary) (err error) {
if _, err = d.db.Exec(c, _InsertVipBcoinSalary, &r.Mid, &r.Status, &r.GiveNowStatus, &r.PayDay, &r.Amount, &r.Memo); err != nil {
err = errors.WithStack(err)
}
return
}
//OldTxDelBcoinSalary del bcoin salary
func (d *Dao) OldTxDelBcoinSalary(tx *sql.Tx, mid int64, month time.Time) (err error) {
if _, err = tx.Exec(_delBcoinSalary, mid, month); err != nil {
err = errors.WithStack(err)
}
return
}

View File

@@ -0,0 +1,56 @@
package dao
import (
"context"
"go-common/app/service/main/vip/model"
"testing"
"time"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoBcoinSalaryList(t *testing.T) {
var (
c = context.TODO()
mid = int64(0)
start = time.Now()
end = time.Now()
expRes []*model.VipBcoinSalary
)
convey.Convey("BcoinSalaryList", t, func(ctx convey.C) {
res, err := d.BcoinSalaryList(c, mid, start, end)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
ctx.Convey("res should not be nil", func(ctx convey.C) {
ctx.So(res, convey.ShouldEqual, expRes)
})
})
}
func TestDaoSelLastBcoin(t *testing.T) {
var (
c = context.TODO()
mid = int64(20606508)
)
convey.Convey("SelLastBcoin", t, func(ctx convey.C) {
_, err := d.SelLastBcoin(c, mid)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoInsertVipBcoinSalary(t *testing.T) {
var (
c = context.TODO()
r = &model.VipBcoinSalary{}
)
convey.Convey("InsertVipBcoinSalary", t, func(ctx convey.C) {
err := d.InsertVipBcoinSalary(c, r)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}

View File

@@ -0,0 +1,90 @@
package dao
import (
"context"
"fmt"
"net/url"
"strconv"
"time"
"go-common/library/ecode"
"go-common/library/log"
"github.com/pkg/errors"
)
const (
_SendUserNotify = "/api/notify/send.user.notify.do"
_PayAPIAdd = "/api/coupon/regular/add"
_CleanCache = "/notify/cleanCacheAndNotify"
_loginout = "/intranet/acc/security/mid"
)
//Loginout login out
func (d *Dao) Loginout(c context.Context, mid int64) (err error) {
val := url.Values{}
val.Add("mids", strconv.FormatInt(mid, 10))
val.Add("operator", strconv.FormatInt(mid, 10))
val.Add("desc", "大会员解冻")
resp := new(struct {
Code int `json:"code"`
Msg string `json:"msg"`
})
defer func() {
log.Info("vip Loginout url:%+v params:%+v return:%+v", d.loginOutURL, val, resp)
}()
if err = d.client.Post(c, d.loginOutURL, "", val, resp); err != nil {
err = errors.Errorf("vip Loginout url:%+v params:%+v return:%+v,err:%+v", d.loginOutURL, val, resp, err)
return
}
if resp.Code != ecode.OK.Code() {
err = ecode.Int(resp.Code)
}
return
}
//SendCleanCache clean cache
func (d *Dao) SendCleanCache(c context.Context, mid int64, months int16, days int64, t int, ip string) (err error) {
params := url.Values{}
params.Set("mid", strconv.FormatInt(int64(mid), 10))
params.Set("months", strconv.FormatInt(int64(months), 10))
params.Set("days", strconv.FormatInt(int64(days), 10))
params.Set("type", strconv.FormatInt(int64(t), 10))
if err = d.client.Get(c, d.vipURI, ip, params, nil); err != nil {
log.Error("SendCleanCache error(%v) url(%v)", err, d.vipURI)
return
}
return
}
//SendMultipMsg send multip msg
func (d *Dao) SendMultipMsg(c context.Context, mids, content, title, mc, ip string, dataType int) (err error) {
params := url.Values{}
params.Set("mc", mc)
params.Set("title", title)
params.Set("context", content)
params.Set("data_type", strconv.FormatInt(int64(dataType), 10))
params.Set("mid_list", mids)
if err = d.client.Post(c, d.msgURI, ip, params, nil); err != nil {
log.Error("SendMultipMsg error(%v)", err)
return
}
return
}
//SendBcoinCoupon send bcoin coupon
func (d *Dao) SendBcoinCoupon(c context.Context, mids, activityID string, money int64, dueTime time.Time) (err error) {
params := url.Values{}
params.Set("activity_id", activityID)
params.Set("mids", mids)
params.Set("money", strconv.FormatInt(int64(money), 10))
params.Set("due_time", dueTime.Format("2006-01-02"))
if err = d.client.Post(c, d.payURI, "127.0.0.1", params, nil); err != nil {
log.Error("SendBcoinCoupon error(%v)", err)
fmt.Printf("SendBcoinCoupon error(%v)", err)
return
}
return
}

View File

@@ -0,0 +1,81 @@
package dao
import (
"context"
"testing"
"time"
gock "gopkg.in/h2non/gock.v1"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoLoginout(t *testing.T) {
var (
c = context.Background()
mid = int64(1)
)
convey.Convey("TestDaoLoginout", t, func(ctx convey.C) {
defer gock.OffAll()
httpMock("POST", d.loginOutURL).Reply(200).JSON(`{"code":0}`)
err := d.Loginout(c, mid)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoSendCleanCache(t *testing.T) {
var (
c = context.TODO()
mid = int64(0)
months = int16(0)
days = int64(0)
no = int(0)
ip = ""
)
convey.Convey("SendCleanCache", t, func(ctx convey.C) {
err := d.SendCleanCache(c, mid, months, days, no, ip)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoSendMultipMsg(t *testing.T) {
var (
c = context.TODO()
mids = ""
content = ""
title = ""
mc = ""
ip = ""
dataType = int(0)
)
convey.Convey("SendMultipMsg", t, func(ctx convey.C) {
defer gock.OffAll()
httpMock("POST", d.msgURI).Reply(200).JSON(`{"code":0}`)
err := d.SendMultipMsg(c, mids, content, title, mc, ip, dataType)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoSendBcoinCoupon(t *testing.T) {
var (
c = context.TODO()
mids = "20606508"
activityID = "1"
money = int64(0)
dueTime = time.Now()
)
convey.Convey("SendBcoinCoupon", t, func(ctx convey.C) {
defer gock.OffAll()
httpMock("POST", d.payURI).Reply(200).JSON(`{"code":0}`)
err := d.SendBcoinCoupon(c, mids, activityID, money, dueTime)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}

View File

@@ -0,0 +1,15 @@
package dao
import (
"context"
"go-common/app/service/main/vip/model"
)
//go:generate $GOPATH/src/go-common/app/tool/cache/gen
type _cache interface {
// cache: -nullcache=&model.OpenBindInfo{Mid:-1} -check_null_code=$!=nil&&$.Mid==-1
BindInfoByMid(c context.Context, mid int64, appID int64) (*model.OpenBindInfo, error)
// cache: -nullcache=&model.OpenInfo{Mid:-1} -check_null_code=$!=nil&&$.Mid==-1
OpenInfoByOpenID(c context.Context, openID string, appID int64) (*model.OpenInfo, error)
}

View File

@@ -0,0 +1 @@
package dao

View File

@@ -0,0 +1,93 @@
// Code generated by $GOPATH/src/go-common/app/tool/cache/gen. DO NOT EDIT.
/*
Package dao is a generated cache proxy package.
It is generated from:
type _cache interface {
// cache: -nullcache=&model.OpenBindInfo{Mid:-1} -check_null_code=$!=nil&&$.Mid==-1
BindInfoByMid(c context.Context, mid int64, appID int64) (*model.OpenBindInfo, error)
// cache: -nullcache=&model.OpenInfo{Mid:-1} -check_null_code=$!=nil&&$.Mid==-1
OpenInfoByOpenID(c context.Context, openID string, appID int64) (*model.OpenInfo, error)
}
*/
package dao
import (
"context"
"go-common/app/service/main/vip/model"
"go-common/library/stat/prom"
)
var _ _cache
// BindInfoByMid get data from cache if miss will call source method, then add to cache.
func (d *Dao) BindInfoByMid(c context.Context, id int64, appID int64) (res *model.OpenBindInfo, err error) {
addCache := true
res, err = d.CacheBindInfoByMid(c, id, appID)
if err != nil {
addCache = false
err = nil
}
defer func() {
if res != nil && res.Mid == -1 {
res = nil
}
}()
if res != nil {
prom.CacheHit.Incr("BindInfoByMid")
return
}
prom.CacheMiss.Incr("BindInfoByMid")
res, err = d.RawBindInfoByMid(c, id, appID)
if err != nil {
return
}
miss := res
if miss == nil {
miss = &model.OpenBindInfo{Mid: -1}
}
if !addCache {
return
}
d.cache.Do(c, func(c context.Context) {
d.AddCacheBindInfoByMid(c, id, miss, appID)
})
return
}
// OpenInfoByOpenID get data from cache if miss will call source method, then add to cache.
func (d *Dao) OpenInfoByOpenID(c context.Context, id string, appID int64) (res *model.OpenInfo, err error) {
addCache := true
res, err = d.CacheOpenInfoByOpenID(c, id, appID)
if err != nil {
addCache = false
err = nil
}
defer func() {
if res != nil && res.Mid == -1 {
res = nil
}
}()
if res != nil {
prom.CacheHit.Incr("OpenInfoByOpenID")
return
}
prom.CacheMiss.Incr("OpenInfoByOpenID")
res, err = d.RawOpenInfoByOpenID(c, id, appID)
if err != nil {
return
}
miss := res
if miss == nil {
miss = &model.OpenInfo{Mid: -1}
}
if !addCache {
return
}
d.cache.Do(c, func(c context.Context) {
d.AddCacheOpenInfoByOpenID(c, id, miss, appID)
})
return
}

View File

@@ -0,0 +1,42 @@
package dao
import (
"context"
"fmt"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoBindInfoByMid(t *testing.T) {
convey.Convey("BindInfoByMid", t, func(convCtx convey.C) {
var (
c = context.Background()
id = int64(1)
appID = int64(32)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
_, err := d.BindInfoByMid(c, id, appID)
convCtx.Convey("Then err should be nil.res should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoOpenInfoByOpenID(t *testing.T) {
convey.Convey("OpenInfoByOpenID", t, func(convCtx convey.C) {
var (
c = context.Background()
id = "bdca8b71e7a6726885d40a395bf9ccd1"
appID = int64(32)
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
res, err := d.OpenInfoByOpenID(c, id, appID)
fmt.Println("res", res)
convCtx.Convey("Then err should be nil.res should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
})
}

View File

@@ -0,0 +1,113 @@
package dao
import (
"context"
"time"
"go-common/app/service/main/vip/conf"
eleclient "go-common/app/service/main/vip/dao/ele-api-client"
mailclient "go-common/app/service/main/vip/dao/mail-api-client"
"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/stat/prom"
"go-common/library/sync/pipeline/fanout"
)
// Dao struct info of Dao.
type Dao struct {
// mysql
db *sql.DB
olddb *sql.DB
// http
client *bm.Client
// ele api http client
eleclient *eleclient.EleClient
// mail api http client
mailclient *mailclient.Client
// conf
c *conf.Config
msgURI string
payURI string
payCloseURL string
vipURI string
passportDetail string
mc *memcache.Pool
mcExpire int32
errProm *prom.Prom
loginOutURL string
//redis pool
redis *redis.Pool
// cache async save
cache *fanout.Fanout
}
// New new a Dao and return.
func New(c *conf.Config) (d *Dao) {
d = &Dao{
// conf
c: c,
// db
db: sql.NewMySQL(c.Mysql),
olddb: sql.NewMySQL(c.OldMysql),
// http client.
client: bm.NewClient(c.HTTPClient),
msgURI: c.MsgURI + _SendUserNotify,
payURI: c.PayURI + _PayAPIAdd,
payCloseURL: c.Property.PayCoURL + _payClose,
passportDetail: c.Property.PassportURL + _passportDetail,
vipURI: c.VipURI + _CleanCache,
mc: memcache.NewPool(c.Memcache.Config),
mcExpire: int32(time.Duration(c.Memcache.Expire) / time.Second),
errProm: prom.BusinessErrCount,
loginOutURL: c.Property.PassportURL + _loginout,
redis: redis.NewPool(c.Redis.Config),
// cache chan
cache: fanout.New("cache", fanout.Worker(10), fanout.Buffer(10240)),
}
// ele
d.eleclient = eleclient.NewEleClient(c.ELEConf, d.client)
d.mailclient = mailclient.NewClient(d.client)
return
}
// Ping ping health of db.
func (d *Dao) Ping(c context.Context) (err error) {
if err = d.pingMC(c); err != nil {
return
}
if err = d.olddb.Ping(c); err != nil {
return
}
return d.db.Ping(c)
}
// Close close connections of mc, redis, db.
func (d *Dao) Close() {
if d.db != nil {
d.db.Close()
}
if d.olddb != nil {
d.olddb.Close()
}
if d.mc != nil {
d.mc.Close()
}
}
//StartTx start tx
func (d *Dao) StartTx(c context.Context) (tx *sql.Tx, err error) {
if d.db != nil {
tx, err = d.db.Begin(c)
}
return
}
//OldStartTx old start tx
func (d *Dao) OldStartTx(c context.Context) (tx *sql.Tx, err error) {
if d.db != nil {
tx, err = d.olddb.Begin(c)
}
return
}

View File

@@ -0,0 +1,45 @@
package dao
import (
"flag"
"os"
"strings"
"testing"
"go-common/app/service/main/vip/conf"
"gopkg.in/h2non/gock.v1"
)
var (
d *Dao
)
func TestMain(m *testing.M) {
if os.Getenv("DEPLOY_ENV") != "" {
flag.Set("app_id", "main.account.vip-service")
flag.Set("conf_token", "48c1c43b703d238f0cba6d8d63ec9463")
flag.Set("tree_id", "10964")
flag.Set("conf_version", "docker-1")
flag.Set("deploy_env", "uat")
flag.Set("conf_host", "config.bilibili.co")
flag.Set("conf_path", "/tmp")
flag.Set("region", "sh")
flag.Set("zone", "sh001")
} else {
flag.Set("conf", "../cmd/vip-service-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
}

View File

@@ -0,0 +1,39 @@
package dao
import (
"context"
"time"
"go-common/app/service/main/vip/model"
xsql "go-common/library/database/sql"
"github.com/pkg/errors"
)
const (
_dialogAll = "SELECT id,app_id,platform,start_time,end_time,title,content,follow,left_button,left_link,right_button,right_link FROM vip_conf_dialog WHERE stage=true AND start_time<=? AND (end_time='1970-01-01 08:00:00' OR end_time >?)"
)
// DialogAll .
func (d *Dao) DialogAll(c context.Context) (res []*model.ConfDialog, err error) {
var (
rows *xsql.Rows
curr = time.Now().Format("2006-01-02 15:04:05")
)
if rows, err = d.db.Query(c, _dialogAll, curr, curr); err != nil {
err = errors.WithStack(err)
return
}
defer rows.Close()
for rows.Next() {
r := new(model.ConfDialog)
if err = rows.Scan(&r.ID, &r.AppID, &r.Platform, &r.StartTime, &r.EndTime, &r.Title, &r.Content, &r.Follow, &r.LeftButton, &r.LeftLink, &r.RightButton, &r.RightLink); err != nil {
err = errors.WithStack(err)
res = nil
return
}
res = append(res, r)
}
err = rows.Err()
return
}

View File

@@ -0,0 +1,15 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoDialogAll(t *testing.T) {
convey.Convey("DialogAll", t, func() {
_, err := d.DialogAll(context.TODO())
convey.So(err, convey.ShouldBeNil)
})
}

View File

@@ -0,0 +1,48 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_test",
"go_library",
)
go_test(
name = "go_default_test",
srcs = ["ele_client_test.go"],
embed = [":go_default_library"],
tags = ["automanaged"],
deps = [
"//library/net/http/blademaster:go_default_library",
"//library/net/netutil/breaker:go_default_library",
"//library/time:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
],
)
go_library(
name = "go_default_library",
srcs = ["ele_client.go"],
importpath = "go-common/app/service/main/vip/dao/ele-api-client",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//library/log:go_default_library",
"//library/net/http/blademaster:go_default_library",
"//vendor/github.com/pkg/errors:go_default_library",
"//vendor/github.com/satori/go.uuid: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,130 @@
package client
import (
"bytes"
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
xhttp "net/http"
"strconv"
"strings"
"time"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
pkgerr "github.com/pkg/errors"
"github.com/satori/go.uuid"
)
const (
_contentTypeJSON = "application/json"
)
//EleClient client is http client, for third ele server.
type EleClient struct {
client *bm.Client
conf *Config
}
// Config is http client conf.
type Config struct {
*App
}
// App bilibili intranet authorization.
type App struct {
Key string
Secret string
}
// NewEleClient new a http client.
func NewEleClient(c *Config, client *bm.Client) *EleClient {
cl := new(EleClient)
cl.conf = c
// check appkey
if c.Key == "" || c.Secret == "" {
panic("http client must config appkey and appsecret")
}
cl.client = client
return cl
}
// Get a json req http get.
func (cl *EleClient) Get(c context.Context, host, path string, args interface{}, res interface{}) (err error) {
req, err := cl.newRequest(xhttp.MethodGet, host, path, args)
if err != nil {
return
}
return cl.client.Do(c, req, res)
}
// Post a json req http post.
func (cl *EleClient) Post(c context.Context, host, path string, args interface{}, res interface{}) (err error) {
req, err := cl.newRequest(xhttp.MethodPost, host, path, args)
if err != nil {
return
}
return cl.client.Do(c, req, res)
}
// IsSuccess check ele api is success.
func IsSuccess(message string) bool {
return message == "ok"
}
// newRequest new http request with host, path, method, ip, values and headers, without sign.
func (cl *EleClient) newRequest(method, host, path string, args interface{}) (req *xhttp.Request, err error) {
consumerKey := cl.conf.Key
nonce := UUID4() //TODO uuid 有问题?
timestamp := strconv.FormatInt(time.Now().Unix(), 10)
sign := eleSign(consumerKey, nonce, timestamp, path, cl.conf.Secret)
params := map[string]interface{}{}
params["consumer_key"] = consumerKey
params["nonce"] = nonce
params["timestamp"] = timestamp
params["sign"] = sign
params["args"] = args
url := host + path
marshal, err := json.Marshal(params)
if err != nil {
err = pkgerr.Wrapf(err, "marshal:%v", params)
return
}
rj := string(marshal)
log.Info("ele_client req method(%s) url(%s) rj(%s)", method, url, rj)
req, err = xhttp.NewRequest(method, url, strings.NewReader(rj))
if err != nil {
err = pkgerr.Wrapf(err, "uri:%s", url+" "+rj)
return
}
req.Header.Set("Content-Type", _contentTypeJSON)
return
}
func eleSign(consumerKey, nonce, timestamp, path, secret string) string {
var b bytes.Buffer
b.WriteString(path)
b.WriteString("&")
b.WriteString("consumer_key=")
b.WriteString(consumerKey)
b.WriteString("&nonce=")
b.WriteString(nonce)
b.WriteString("&timestamp=")
b.WriteString(timestamp)
return computeHmac256(b, secret)
}
func computeHmac256(b bytes.Buffer, secret string) string {
key := []byte(secret)
h := hmac.New(sha256.New, key)
h.Write(b.Bytes())
return hex.EncodeToString(h.Sum(nil))
}
// UUID4 is generate uuid
func UUID4() string {
return uuid.NewV4().String()
}

View File

@@ -0,0 +1,92 @@
package client
import (
"bytes"
"context"
"testing"
"time"
bm "go-common/library/net/http/blademaster"
"go-common/library/net/netutil/breaker"
xtime "go-common/library/time"
"github.com/smartystreets/goconvey/convey"
)
var cl *EleClient
func TestNewEleClient(t *testing.T) {
var c = &Config{
App: &App{
Key: "sdfsdf",
Secret: "sdfsdf",
},
}
var client = bm.NewClient(&bm.ClientConfig{
App: &bm.App{
Key: "53e2fa226f5ad348",
Secret: "3cf6bd1b0ff671021da5f424fea4b04a",
},
Dial: xtime.Duration(time.Second),
Timeout: xtime.Duration(time.Second),
KeepAlive: xtime.Duration(time.Second),
Breaker: &breaker.Config{
Window: 10 * xtime.Duration(time.Second),
Sleep: 50 * xtime.Duration(time.Millisecond),
Bucket: 10,
Ratio: 0.5,
Request: 100,
},
},
)
convey.Convey("NewEleClient", t, func() {
cl = NewEleClient(c, client)
convey.So(cl, convey.ShouldNotBeNil)
})
convey.Convey("Get", t, func() {
err := cl.Get(context.TODO(), "http://api.bilibili.co", "/x/internal/vip/user/info", nil, nil)
convey.So(err, convey.ShouldBeNil)
})
convey.Convey("Post", t, func() {
err := cl.Post(context.TODO(), "http://api.bilibili.co", "/x/internal/vip/order/create", nil, nil)
convey.So(err, convey.ShouldBeNil)
})
convey.Convey("newRequest", t, func() {
req, err := cl.newRequest("POST", "http://api.bilibili.co", "/x/internal/vip/user/info", nil)
convey.So(err, convey.ShouldBeNil)
convey.So(req, convey.ShouldNotBeNil)
})
}
func TestIsSuccess(t *testing.T) {
convey.Convey("IsSuccess", t, func() {
p1 := IsSuccess("ok")
convey.So(p1, convey.ShouldNotBeNil)
})
}
func TestEleSign(t *testing.T) {
convey.Convey("eleSign", t, func() {
p1 := eleSign("", "", "", "", "")
convey.So(p1, convey.ShouldNotBeNil)
})
}
func TestComputeHmac256(t *testing.T) {
convey.Convey("computeHmac256", t, func() {
var b bytes.Buffer
b.WriteString("http://bilibili.com/x/vip")
b.WriteString("&")
b.WriteString("consumer_key=")
p1 := computeHmac256(b, "xxx")
convey.So(p1, convey.ShouldNotBeNil)
})
}
func TestUUID4(t *testing.T) {
convey.Convey("UUID4", t, func() {
p1 := UUID4()
convey.So(p1, convey.ShouldNotBeNil)
})
}

View File

@@ -0,0 +1,122 @@
package dao
import (
"context"
"fmt"
"net/url"
"strconv"
"go-common/app/service/main/vip/model"
"go-common/library/ecode"
"go-common/library/log"
"go-common/library/net/metadata"
"github.com/pkg/errors"
)
const (
_token = "/x/internal/v1/captcha/token"
_verify = "/x/internal/v1/captcha/verify"
_openCode = "/pay/codeOpen"
_passportDetail = "/intranet/acc/detail"
token = "vip-service.token"
)
//GetPassportDetail get passport detail
func (d *Dao) GetPassportDetail(c context.Context, mid int64) (res *model.PassportDetail, err error) {
ip := metadata.String(c, metadata.RemoteIP)
val := url.Values{}
val.Add("mid", strconv.FormatInt(mid, 10))
resq := new(struct {
Code int `json:"code"`
Data *model.PassportDetail `json:"data"`
})
defer func() {
log.Info("get passport detail is error url:%+v params:%+v resq:%+v err:%+v", d.passportDetail, val, resq, err)
}()
if err = d.client.Get(c, d.passportDetail, ip, val, resq); err != nil {
err = errors.WithStack(err)
return
}
if resq.Code != ecode.OK.Code() {
err = ecode.Int(resq.Code)
return
}
res = resq.Data
return
}
//OpenCode open code.
func (d *Dao) OpenCode(c context.Context, mid, batchCodeID int64, unit int32, remark, code string) (data *model.CommonResq, err error) {
data = new(model.CommonResq)
val := url.Values{}
val.Add("token", token)
val.Add("remark", remark)
val.Add("code", code)
val.Add("mid", fmt.Sprintf("%v", mid))
if err = d.doRequest(c, d.c.Property.VipURL, _openCode, "", val, data, d.client.Post); err != nil {
err = errors.WithStack(err)
return
}
return
}
//GetOpenInfo get open info.
func (d *Dao) GetOpenInfo(c context.Context, code string) (data *model.OpenCodeResp, err error) {
data = new(model.OpenCodeResp)
val := url.Values{}
val.Add("token", token)
val.Add("code", code)
if err = d.doRequest(c, d.c.Property.VipURL, _openCode, "", val, data, d.client.Get); err != nil {
err = errors.WithStack(err)
return
}
return
}
//GetToken get open token.
func (d *Dao) GetToken(c context.Context, bid string, ip string) (data *model.TokenResq, err error) {
data = new(model.TokenResq)
val := url.Values{}
val.Add("bid", bid)
if err = d.doRequest(c, d.c.Property.APICoURL, _token, ip, val, data, d.client.Get); err != nil {
err = errors.WithStack(err)
return
}
return
}
//Verify verify code.
func (d *Dao) Verify(c context.Context, code, token, ip string) (data *model.TokenResq, err error) {
data = new(model.TokenResq)
val := url.Values{}
val.Add("token", token)
val.Add("code", code)
if err = d.doRequest(c, d.c.Property.APICoURL, _verify, ip, val, data, d.client.Post); err != nil {
err = errors.WithStack(err)
return
}
return
}
func (d *Dao) doRequest(c context.Context, basicURL, path, IP string, params url.Values, data interface{},
fn func(c context.Context, uri, ip string, params url.Values, res interface{}) error) (err error) {
var (
url = basicURL + path
)
if len(IP) == 0 {
IP = "127.0.0.1"
}
err = fn(c, url, IP, params, data)
log.Info("reques url %v params:%+v result:%+v", url, params, data)
if err != nil {
log.Error("request error %+v", err)
err = errors.WithStack(err)
return
}
return
}

View File

@@ -0,0 +1,95 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
gock "gopkg.in/h2non/gock.v1"
)
func TestDaoOpenCode(t *testing.T) {
var (
c = context.TODO()
mid = int64(0)
batchCodeID = int64(0)
unit = int32(0)
remark = ""
code = ""
)
convey.Convey("OpenCode", t, func(ctx convey.C) {
defer gock.OffAll()
httpMock("POST", _openCode).Reply(200).JSON(`{"code":0}`)
data, err := d.OpenCode(c, mid, batchCodeID, unit, remark, code)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
ctx.Convey("data should not be nil", func(ctx convey.C) {
ctx.So(data, convey.ShouldNotBeNil)
})
})
}
func TestDaoGetOpenInfo(t *testing.T) {
var (
c = context.TODO()
code = ""
)
convey.Convey("GetOpenInfo", t, func(ctx convey.C) {
defer gock.OffAll()
httpMock("GET", _openCode).Reply(200).JSON(`{"code":0}`)
data, err := d.GetOpenInfo(c, code)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
ctx.Convey("data should not be nil", func(ctx convey.C) {
ctx.So(data, convey.ShouldNotBeNil)
})
})
}
func TestDaoGetToken(t *testing.T) {
var (
c = context.TODO()
bid = "abc"
ip = ""
)
convey.Convey("GetToken", t, func(ctx convey.C) {
defer gock.OffAll()
httpMock("GET", d.c.Property.APICoURL+_token).Reply(200).JSON(`{"code":0}`)
_, err := d.GetToken(c, bid, ip)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoVerify(t *testing.T) {
var (
c = context.TODO()
code = "abc"
token = "abc"
ip = ""
)
convey.Convey("Verify", t, func(ctx convey.C) {
defer gock.OffAll()
httpMock("POST", _verify).Reply(200).JSON(`{"code":0}`)
data, err := d.Verify(c, code, token, ip)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
ctx.Convey("data should not be nil", func(ctx convey.C) {
ctx.So(data, convey.ShouldNotBeNil)
})
})
}
func TestDaoGetPassportDetail(t *testing.T) {
convey.Convey("passport", t, func() {
var mid int64 = 27515586
defer gock.OffAll()
httpMock("GET", _passportDetail).Reply(200).JSON(`{"code":0}`)
_, err := d.GetPassportDetail(context.TODO(), mid)
convey.So(err, convey.ShouldBeNil)
})
}

View File

@@ -0,0 +1,35 @@
package dao
import (
"context"
"go-common/app/service/main/vip/model"
"go-common/library/database/sql"
"github.com/pkg/errors"
)
const (
_jointlysSQL = "SELECT id,title,content,operator,start_time,end_time,link,is_hot,ctime,mtime FROM vip_jointly WHERE end_time > ? AND deleted = 0;"
)
// Jointlys jointly list.
func (d *Dao) Jointlys(c context.Context, now int64) (res []*model.Jointly, err error) {
var rows *sql.Rows
if rows, err = d.db.Query(c, _jointlysSQL, now); err != nil {
err = errors.WithStack(err)
return
}
defer rows.Close()
for rows.Next() {
r := new(model.Jointly)
if err = rows.Scan(&r.ID, &r.Title, &r.Content, &r.Operator, &r.StartTime, &r.EndTime, &r.Link, &r.IsHot, &r.CTime, &r.MTime); err != nil {
err = errors.WithStack(err)
res = nil
return
}
res = append(res, r)
}
err = rows.Err()
return
}

View File

@@ -0,0 +1,22 @@
package dao
import (
"context"
"testing"
"time"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoJointlys(t *testing.T) {
var (
c = context.TODO()
now = time.Now().Unix()
)
convey.Convey("DaoJointlys", t, func(ctx convey.C) {
_, err := d.Jointlys(c, now)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}

View File

@@ -0,0 +1,46 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
"go_test",
)
go_library(
name = "go_default_library",
srcs = ["mail_api_client.go"],
importpath = "go-common/app/service/main/vip/dao/mail-api-client",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//library/net/http/blademaster:go_default_library",
"//vendor/github.com/pkg/errors:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)
go_test(
name = "go_default_test",
srcs = ["mail_api_client_test.go"],
embed = [":go_default_library"],
tags = ["automanaged"],
deps = [
"//library/net/http/blademaster:go_default_library",
"//library/net/netutil/breaker:go_default_library",
"//library/time:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
],
)

View File

@@ -0,0 +1,62 @@
package client
import (
"context"
"encoding/json"
xhttp "net/http"
"strings"
bm "go-common/library/net/http/blademaster"
pkgerr "github.com/pkg/errors"
)
const (
_contentTypeJSON = "application/json"
)
//Client client is http client.
type Client struct {
client *bm.Client
}
// NewClient new a http client.
func NewClient(client *bm.Client) *Client {
cl := new(Client)
cl.client = client
return cl
}
// Get a json req http get.
func (client *Client) Get(c context.Context, uri string, params interface{}, res interface{}) (err error) {
req, err := client.NewRequest(xhttp.MethodGet, uri, params)
if err != nil {
return
}
return client.client.Do(c, req, res)
}
// Post a json req http post.
func (client *Client) Post(c context.Context, uri string, params interface{}, res interface{}) (err error) {
req, err := client.NewRequest(xhttp.MethodPost, uri, params)
if err != nil {
return
}
return client.client.Do(c, req, res)
}
// NewRequest new http request with method, uri, ip, values and headers.
func (client *Client) NewRequest(method, uri string, params interface{}) (req *xhttp.Request, err error) {
marshal, err := json.Marshal(params)
if err != nil {
err = pkgerr.Wrapf(err, "marshal:%v", params)
return
}
req, err = xhttp.NewRequest(method, uri, strings.NewReader(string(marshal)))
if err != nil {
err = pkgerr.Wrapf(err, "method:%s,uri:%s", method, string(marshal))
return
}
req.Header.Set("Content-Type", _contentTypeJSON)
return
}

View File

@@ -0,0 +1,80 @@
package client
import (
"context"
"testing"
"time"
bm "go-common/library/net/http/blademaster"
"go-common/library/net/netutil/breaker"
xtime "go-common/library/time"
"github.com/smartystreets/goconvey/convey"
)
var cl *Client
func TestNewClient(t *testing.T) {
var client = bm.NewClient(&bm.ClientConfig{
App: &bm.App{
Key: "53e2fa226f5ad348",
Secret: "3cf6bd1b0ff671021da5f424fea4b04a",
},
Dial: xtime.Duration(time.Second),
Timeout: xtime.Duration(time.Second),
KeepAlive: xtime.Duration(time.Second),
Breaker: &breaker.Config{
Window: 10 * xtime.Duration(time.Second),
Sleep: 50 * xtime.Duration(time.Millisecond),
Bucket: 10,
Ratio: 0.5,
Request: 100,
},
},
)
convey.Convey("NewEleClient", t, func() {
cl = NewClient(client)
convey.So(cl, convey.ShouldNotBeNil)
})
convey.Convey("Get", t, func() {
err := cl.Get(context.TODO(), "http://api.bilibili.co/x/internal/vip/user/info", nil, nil)
convey.So(err, convey.ShouldBeNil)
})
convey.Convey("Post", t, func() {
err := cl.Post(context.TODO(), "http://api.bilibili.co/x/internal/vip/order/create", nil, nil)
convey.So(err, convey.ShouldBeNil)
})
}
func TestClientNewClient(t *testing.T) {
convey.Convey("NewClient", t, func(convCtx convey.C) {
var (
client = &bm.Client{}
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
p1 := NewClient(client)
convCtx.Convey("Then p1 should not be nil.", func(convCtx convey.C) {
convCtx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestClientNewRequest(t *testing.T) {
convey.Convey("NewRequest", t, func(convCtx convey.C) {
var (
method = ""
uri = ""
params = interface{}(0)
client = &bm.Client{}
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
p1 := NewClient(client)
req, err := p1.NewRequest(method, uri, params)
convCtx.Convey("Then err should be nil.req should not be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
convCtx.So(req, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,35 @@
package dao
import (
"context"
"go-common/app/service/main/vip/model"
"go-common/library/ecode"
"go-common/library/log"
)
const (
_mailCreateCouponCodeURI = "/mall-marketing/coupon_code/create"
)
// MailCouponCodeCreate mail coupon code create.
func (d *Dao) MailCouponCodeCreate(c context.Context, a *model.ArgMailCouponCodeCreate) (err error) {
resp := new(struct {
Code int `json:"code"`
Message string `json:"message"`
Data *model.MailCouponCodeCreateResp `json:"data"`
})
err = d.mailclient.Post(c, d.c.Host.Mail+_mailCreateCouponCodeURI, a, resp)
if err != nil {
log.Error("mail faild api(%s) args(%+v) res(%+v) error(%+v)", _mailCreateCouponCodeURI, a, resp, err)
err = ecode.VipMailReqErr
return
}
if resp.Code != ecode.OK.Code() {
log.Error("mail code faild api(%s) args(%+v) res(%+v) error(%+v)", _mailCreateCouponCodeURI, a, resp, err)
err = ecode.VipMailRespCodeErr
return
}
log.Info("mail success api(%s) args(%+v) res(%+v) data(%+v)", _mailCreateCouponCodeURI, a, resp, resp.Data)
return
}

View File

@@ -0,0 +1,13 @@
package dao
// func TestDaoMailCouponCodeCreate(t *testing.T) {
// convey.Convey("TestDaoMailCouponCodeCreate", t, func(ctx convey.C) {
// err := d.MailCouponCodeCreate(context.Background(), &model.ArgMailCouponCodeCreate{
// Mid: 1,
// CouponID: "5fd64e3a08974791",
// })
// ctx.Convey("MailCouponCodeCreate ", func(ctx convey.C) {
// ctx.So(err, convey.ShouldBeNil)
// })
// })
// }

View File

@@ -0,0 +1,271 @@
package dao
import (
"context"
"fmt"
"go-common/app/service/main/vip/model"
gmc "go-common/library/cache/memcache"
"go-common/library/log"
"github.com/pkg/errors"
)
const (
_vipInfo = "vo:%d"
_open = "open:%d"
_pointTip = "pointTip:%d:%d"
_sign = "sign:%d"
_vipfrozen = "vipfrozen:%d"
)
func pointTip(mid, id int64) string {
return fmt.Sprintf(_pointTip, mid, id)
}
func openCode(mid int64) string {
return fmt.Sprintf(_open, mid)
}
func vipInfoKey(mid int64) string {
return fmt.Sprintf(_vipInfo, mid)
}
func signVip(mid int64) string {
return fmt.Sprintf(_sign, mid)
}
func vipfrozen(mid int64) string {
return fmt.Sprintf(_vipfrozen, mid)
}
//GetVipFrozen set vip frozen.
func (d *Dao) GetVipFrozen(c context.Context, mid int64) (val int, err error) {
var (
key = vipfrozen(mid)
)
conn := d.mc.Get(c)
defer conn.Close()
item, err := conn.Get(key)
if err != nil {
if err == gmc.ErrNotFound {
err = nil
return
}
err = errors.Wrapf(err, "conn.Get(%s)", key)
d.errProm.Incr("vipfrozen_mc")
return
}
if err = conn.Scan(item, &val); err != nil {
err = errors.WithStack(err)
return
}
return
}
//DelVipFrozen del vip frozen.
func (d *Dao) DelVipFrozen(c context.Context, mid int64) (err error) {
return d.DelCache(c, vipfrozen(mid))
}
// DelVipInfoCache delete vipinfo cache.
func (d *Dao) DelVipInfoCache(c context.Context, mid int64) (err error) {
return d.DelCache(c, vipInfoKey(mid))
}
// pingMC ping memcache.
func (d *Dao) pingMC(c context.Context) (err error) {
conn := d.mc.Get(c)
defer conn.Close()
if err = conn.Set(&gmc.Item{Key: "ping", Value: []byte{1}, Expiration: d.mcExpire}); err != nil {
log.Error("conn.Store(set, ping, 1) error(%v)", err)
}
return
}
// SetVipInfoCache set vip info cache.
func (d *Dao) SetVipInfoCache(c context.Context, mid int64, v *model.VipInfo) (err error) {
var (
key = vipInfoKey(mid)
)
conn := d.mc.Get(c)
defer conn.Close()
item := &gmc.Item{Key: key, Object: v, Expiration: d.mcExpire, Flags: gmc.FlagProtobuf}
if err = conn.Set(item); err != nil {
err = errors.Wrapf(err, " conn.Set(%s)", key)
d.errProm.Incr("vipinfo_mc")
}
return
}
// VipInfoCache get vip info.
func (d *Dao) VipInfoCache(c context.Context, mid int64) (v *model.VipInfo, err error) {
var (
key = vipInfoKey(mid)
)
conn := d.mc.Get(c)
defer conn.Close()
item, err := conn.Get(key)
if err != nil {
if err == gmc.ErrNotFound {
err = nil
return
}
err = errors.Wrapf(err, "conn.Get(%s)", key)
d.errProm.Incr("vipinfo_mc")
return
}
v = new(model.VipInfo)
if err = conn.Scan(item, v); err != nil {
err = errors.Wrapf(err, "conn.Scan(%s)", key)
}
return
}
//DelCache del cache.
func (d *Dao) DelCache(c context.Context, key string) (err error) {
conn := d.mc.Get(c)
defer conn.Close()
if err = conn.Delete(key); err != nil {
if err == gmc.ErrNotFound {
err = nil
} else {
log.Error("conn.Delete(%s) error(%v)", key, err)
d.errProm.Incr("del_mc")
}
}
return
}
// GetOpenCodeCount get open code count.
func (d *Dao) GetOpenCodeCount(c context.Context, mid int64) (val int, err error) {
var (
key = openCode(mid)
)
conn := d.mc.Get(c)
defer conn.Close()
item, err := conn.Get(key)
if err != nil {
if err == gmc.ErrNotFound {
err = nil
return
}
err = errors.Wrapf(err, "conn.Get(%s)", key)
d.errProm.Incr("opencode_mc")
return
}
if err = conn.Scan(item, &val); err != nil {
err = errors.WithStack(err)
return
}
return
}
//SetOpenCode set open code.
func (d *Dao) SetOpenCode(c context.Context, mid int64, count int) (err error) {
var (
key = openCode(mid)
)
conn := d.mc.Get(c)
defer conn.Close()
item := &gmc.Item{Key: key, Object: count, Expiration: d.mcExpire, Flags: gmc.FlagJSON}
if err = conn.Set(item); err != nil {
err = errors.WithStack(err)
return
}
return
}
//GetPointTip get pointTip.
func (d *Dao) GetPointTip(c context.Context, mid, id int64) (val int, err error) {
var (
key = pointTip(mid, id)
)
conn := d.mc.Get(c)
defer conn.Close()
item, err := conn.Get(key)
if err != nil {
if err == gmc.ErrNotFound {
err = nil
return
}
err = errors.Wrapf(err, "conn.Get(%s)", key)
d.errProm.Incr("opencode_mc")
return
}
if err = conn.Scan(item, &val); err != nil {
return
}
return
}
//SetPointTip set point tip.
func (d *Dao) SetPointTip(c context.Context, mid, id int64, val int, expired int32) (err error) {
var (
key = pointTip(mid, id)
)
conn := d.mc.Get(c)
defer conn.Close()
item := &gmc.Item{Key: key, Object: val, Expiration: expired, Flags: gmc.FlagJSON}
if err = conn.Set(item); err != nil {
err = errors.WithStack(err)
return
}
return
}
//SetSignVip .
func (d *Dao) SetSignVip(c context.Context, mid int64, t int) (err error) {
var (
key = signVip(mid)
)
conn := d.mc.Get(c)
defer conn.Close()
item := &gmc.Item{Key: key, Object: 1, Expiration: int32(t), Flags: gmc.FlagJSON}
if err = conn.Set(item); err != nil {
err = errors.WithStack(err)
return
}
return
}
//GetSignVip .
func (d *Dao) GetSignVip(c context.Context, mid int64) (val int, err error) {
var (
key = signVip(mid)
)
conn := d.mc.Get(c)
defer conn.Close()
item, err := conn.Get(key)
if err != nil {
if err == gmc.ErrNotFound {
err = nil
return
}
err = errors.Wrapf(err, "conn.Get(%s)", key)
d.errProm.Incr("signvip_mc")
return
}
if err = conn.Scan(item, &val); err != nil {
return
}
return
}
// AddTransferLock add lock.
func (d *Dao) AddTransferLock(c context.Context, key string) (succeed bool) {
var (
conn = d.mc.Get(c)
)
defer conn.Close()
item := &gmc.Item{
Key: key,
Value: []byte("0"),
Expiration: 3600,
}
if err := conn.Add(item); err != nil {
if err != gmc.ErrNotStored {
log.Error("conn.Add(%s) error(%v)", key, err)
}
} else {
succeed = true
}
return
}

View File

@@ -0,0 +1,217 @@
package dao
import (
"context"
"testing"
"go-common/app/service/main/vip/model"
"github.com/smartystreets/goconvey/convey"
)
func TestDaopointTip(t *testing.T) {
var (
mid = int64(0)
id = int64(0)
)
convey.Convey("pointTip", t, func(ctx convey.C) {
p1 := pointTip(mid, id)
ctx.Convey("p1 should not be nil", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
}
func TestDaoopenCode(t *testing.T) {
var (
mid = int64(0)
)
convey.Convey("openCode", t, func(ctx convey.C) {
p1 := openCode(mid)
ctx.Convey("p1 should not be nil", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
}
func TestDaovipInfoKey(t *testing.T) {
var (
mid = int64(0)
)
convey.Convey("vipInfoKey", t, func(ctx convey.C) {
p1 := vipInfoKey(mid)
ctx.Convey("p1 should not be nil", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
}
func TestDaosignVip(t *testing.T) {
var (
mid = int64(0)
)
convey.Convey("signVip", t, func(ctx convey.C) {
p1 := signVip(mid)
ctx.Convey("p1 should not be nil", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
}
func TestDaoDelVipInfoCache(t *testing.T) {
var (
c = context.TODO()
mid = int64(0)
)
convey.Convey("DelVipInfoCache", t, func(ctx convey.C) {
err := d.DelVipInfoCache(c, mid)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaopingMC(t *testing.T) {
var (
c = context.TODO()
)
convey.Convey("pingMC", t, func(ctx convey.C) {
err := d.pingMC(c)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoSetVipInfoCache(t *testing.T) {
var (
c = context.TODO()
mid = int64(0)
v = &model.VipInfo{}
)
convey.Convey("SetVipInfoCache", t, func(ctx convey.C) {
err := d.SetVipInfoCache(c, mid, v)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoVipInfoCache(t *testing.T) {
var (
c = context.TODO()
mid = int64(0)
)
convey.Convey("VipInfoCache", t, func(ctx convey.C) {
_, err := d.VipInfoCache(c, mid)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaodelCache(t *testing.T) {
var (
c = context.TODO()
key = "key"
)
convey.Convey("delCache", t, func(ctx convey.C) {
err := d.DelCache(c, key)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoGetOpenCodeCount(t *testing.T) {
var (
c = context.TODO()
mid = int64(0)
)
convey.Convey("GetOpenCodeCount", t, func(ctx convey.C) {
val, err := d.GetOpenCodeCount(c, mid)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
ctx.Convey("val should not be nil", func(ctx convey.C) {
ctx.So(val, convey.ShouldNotBeNil)
})
})
}
func TestDaoSetOpenCode(t *testing.T) {
var (
c = context.TODO()
mid = int64(0)
count = int(0)
)
convey.Convey("SetOpenCode", t, func(ctx convey.C) {
err := d.SetOpenCode(c, mid, count)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoGetPointTip(t *testing.T) {
var (
c = context.TODO()
mid = int64(0)
id = int64(0)
)
convey.Convey("GetPointTip", t, func(ctx convey.C) {
val, err := d.GetPointTip(c, mid, id)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
ctx.Convey("val should not be nil", func(ctx convey.C) {
ctx.So(val, convey.ShouldNotBeNil)
})
})
}
func TestDaoSetPointTip(t *testing.T) {
var (
c = context.TODO()
mid = int64(0)
id = int64(0)
val = int(0)
expired = int32(0)
)
convey.Convey("SetPointTip", t, func(ctx convey.C) {
err := d.SetPointTip(c, mid, id, val, expired)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoSetSignVip(t *testing.T) {
var (
c = context.TODO()
mid = int64(0)
no = int(0)
)
convey.Convey("SetSignVip", t, func(ctx convey.C) {
err := d.SetSignVip(c, mid, no)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoGetSignVip(t *testing.T) {
var (
c = context.TODO()
mid = int64(0)
)
convey.Convey("GetSignVip", t, func(ctx convey.C) {
val, err := d.GetSignVip(c, mid)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
ctx.Convey("val should not be nil", func(ctx convey.C) {
ctx.So(val, convey.ShouldNotBeNil)
})
})
}

View File

@@ -0,0 +1,248 @@
package dao
import (
"context"
xsql "database/sql"
"go-common/app/service/main/vip/model"
"go-common/library/database/sql"
"github.com/pkg/errors"
)
const (
_selVipUserInfoByMid = "select id,mid,vip_type,vip_status,vip_start_time,vip_overdue_time,annual_vip_overdue_time,wander,access_status,ctime,mtime,vip_recent_time from vip_user_info where mid = ?"
_updateVipUserInfoByID = "update vip_user_info set vip_type=?,vip_status=?,vip_overdue_time=?,annual_vip_overdue_time=?,vip_recent_time=? where id=?"
_insertVipUserInfo = "INSERT INTO vip_user_info(mid,vip_type,vip_status,vip_start_time,vip_overdue_time,annual_vip_overdue_time,wander,access_status,vip_recent_time) values(?,?,?,?,?,?,?,?,?)"
_insertVipChangeHistory = "INSERT INTO vip_change_history(mid,change_type,change_time,days,month,operator_id,relation_id,batch_id,remark) values(?,?,?,?,?,?,?,?,?)"
_selVipChangeHistory = "select id,mid,change_type,change_time,days,month,operator_id,relation_id,batch_id,remark,ctime from vip_change_history where relation_id=? AND batch_id=?"
_selVipResourceBatchByID = "select id,pool_id,unit,count,ver,start_time,end_time,surplus_count,code_use_count,direct_use_count,ctime,mtime from vip_resource_batch where id=?"
_updateBatchCountByID = "update vip_resource_batch set ver=ver+1,surplus_count=surplus_count-1,direct_use_count=direct_use_count+1,code_use_count=? where id=? and surplus_count>0"
_selResourcePoolByID = "select id,pool_name,business_id,business_name,reason,code_expire_time,start_time,end_time,contacts,contacts_number,ctime,mtime from vip_resource_pool where id=?"
_selBusinessByID = "select id,business_name,business_type,status,app_key,secret,contacts,contacts_number,ctime,mtime from vip_business_info where id=?"
_selVipAppInfo = "select id,type,name,app_key,purge_url,ctime,mtime from vip_app_info where type=?"
_selLastBCoinByMid = "select id,mid,status,give_now_status,month,amount,memo,ctime,mtime from vip_bcoin_salary where mid = ? order by month desc"
_selAllConfig = "select id,config_key,content from vip_config"
_insertVipBcoinSalary = "INSERT INTO vip_bcoin_salary(mid,status,give_now_status,month,amount,memo) values(?,?,?,?,?,?)"
//resouce sql
_selResourcePoolByIDSQL = "SELECT id,pool_name,business_id,reason,code_expire_time,start_time,end_time,contacts,contacts_number,ctime,mtime FROM vip_resource_pool WHERE id=?"
_selBusinessByIDSQL = "SELECT id,business_name,business_type,status,app_key,secret,contacts,contacts_number,ctime,mtime FROM vip_business_info WHERE id=?"
_selBusinessByAppkeySQL = "SELECT id,business_name,business_type,status,app_key,secret,contacts,contacts_number,ctime,mtime FROM vip_business_info WHERE app_key=?"
_selCodeSQL = "SELECT id,batch_code_id,status,code,mid,use_time,relation_id FROM vip_resource_code WHERE code = ?"
_selCodesSQL = "SELECT id,batch_code_id,status,code FROM vip_resource_code WHERE code IN ('%v')"
_selCodeOpenedSQL = "SELECT id,code,use_time FROM vip_resource_code WHERE status = 2 AND batch_code_id IN(%v) AND id>%d AND use_time>='%s' AND use_time<='%s' ORDER BY id ASC LIMIT %d"
_selBatchCodeSQL = "SELECT id,business_id,pool_id,status,batch_name,reason,unit,count,surplus_count,price,start_time,end_time,type,limit_day,max_count FROM vip_resource_batch_code WHERE id = ?"
_selBatchCodeByBisSQL = "SELECT id,business_id,pool_id,status,batch_name,reason,unit,count,surplus_count,price,start_time,end_time,type,limit_day,max_count FROM vip_resource_batch_code WHERE business_id = ?"
_selBatchCodesSQL = "SELECT id,business_id,pool_id,status,batch_name,reason,unit,count,surplus_count,price,start_time,end_time,type,limit_day,max_count FROM vip_resource_batch_code WHERE id IN(%v)"
_updateCodeSQL = "UPDATE vip_resource_code SET mid=?,use_time=? WHERE id = ?"
_updateCodeStatusSQL = "UPDATE vip_resource_code SET status=? WHERE id = ?"
_updateBatchCodeSQL = "UPDATE vip_resource_batch_code SET surplus_count=? WHERE id = ?"
_selActiveSQL = "SELECT id,type,product_name,product_pic,relation_id,bus_id,product_detail,use_type FROM vip_active_show WHERE relation_id IN ('%v')"
_selCodesByBmidSQL = "SELECT code FROM vip_resource_code WHERE bmid =?"
_selBatchCountSQL = "SELECT COUNT(1) FROM vip_resource_code WHERE mid=? AND batch_code_id=?"
_updateOrderCancelSQL = "UPDATE vip_pay_order SET status = ? WHERE order_no = ? AND status = ?;"
)
//OldUpdateOrderCancel order update order cancel.
func (d *Dao) OldUpdateOrderCancel(c context.Context, r *model.VipPayOrderOld) (a int64, err error) {
var res xsql.Result
if res, err = d.olddb.Exec(c, _updateOrderCancelSQL, r.Status, r.OrderNo, model.PAYING); err != nil {
err = errors.WithStack(err)
return
}
if a, err = res.RowsAffected(); err != nil {
err = errors.WithStack(err)
}
return
}
//OldInsertVipBcoinSalary insert vip bcoin salary
func (d *Dao) OldInsertVipBcoinSalary(c context.Context, r *model.VipBcoinSalary) (err error) {
if _, err = d.olddb.Exec(c, _insertVipBcoinSalary, &r.Mid, &r.Status, &r.GiveNowStatus, &r.Month, &r.Amount, &r.Memo); err != nil {
err = errors.WithStack(err)
}
return
}
//SelAllConfig sel all config
func (d *Dao) SelAllConfig(c context.Context) (res []*model.VipConfig, err error) {
var rows *sql.Rows
if rows, err = d.olddb.Query(c, _selAllConfig); err != nil {
err = errors.WithStack(err)
return
}
defer rows.Close()
for rows.Next() {
r := new(model.VipConfig)
if err = rows.Scan(&r.ID, &r.ConfigKey, &r.Content); err != nil {
err = errors.WithStack(err)
res = nil
return
}
res = append(res, r)
}
err = rows.Err()
return
}
//SelVipAppInfo selVipAppInfo
func (d *Dao) SelVipAppInfo(c context.Context, t int) (res []*model.VipAppInfo, err error) {
var rows *sql.Rows
if rows, err = d.olddb.Query(c, _selVipAppInfo, t); err != nil {
err = errors.WithStack(err)
return
}
defer rows.Close()
for rows.Next() {
r := new(model.VipAppInfo)
if err = rows.Scan(&r.ID, &r.Type, &r.Name, &r.AppKey, &r.PurgeURL, &r.Ctime, &r.Mtime); err != nil {
err = errors.WithStack(err)
res = nil
return
}
res = append(res, r)
}
err = rows.Err()
return
}
//OldSelLastBcoin sel last bcoin by mid
func (d *Dao) OldSelLastBcoin(c context.Context, mid int64) (r *model.VipBcoinSalary, err error) {
row := d.olddb.QueryRow(c, _selLastBCoinByMid, mid)
r = new(model.VipBcoinSalary)
if err = row.Scan(&r.ID, &r.Mid, &r.Status, &r.GiveNowStatus, &r.Month, &r.Amount, &r.Memo, &r.Ctime, &r.Mtime); err != nil {
if err == sql.ErrNoRows {
err = nil
r = nil
} else {
err = errors.WithStack(err)
}
}
return
}
//SelBusiness select businessInfo by id
func (d *Dao) SelBusiness(c context.Context, id int64) (r *model.VipBusinessInfo, err error) {
var row = d.olddb.QueryRow(c, _selBusinessByID, id)
r = new(model.VipBusinessInfo)
if err = row.Scan(&r.ID, &r.BusinessName, &r.BusinessType, &r.Status, &r.AppKey, &r.Secret, &r.Contacts, &r.ContactsNumber, &r.Ctime, &r.Mtime); err != nil {
if err == sql.ErrNoRows {
err = nil
r = nil
return
}
err = errors.WithStack(err)
}
return
}
//SelResourcePool select resource pool by id
func (d *Dao) SelResourcePool(c context.Context, id int64) (r *model.VipResourcePool, err error) {
var row = d.olddb.QueryRow(c, _selResourcePoolByID, id)
r = new(model.VipResourcePool)
if err = row.Scan(&r.ID, &r.PoolName, &r.BusinessID, &r.BusinessName, &r.Reason, &r.CodeExpireTime, &r.StartTime, &r.EndTime, &r.Contacts, &r.ContactsNumber, &r.Ctime, &r.Mtime); err != nil {
if err == sql.ErrNoRows {
r = nil
err = nil
return
}
err = errors.WithStack(err)
}
return
}
//OldSelVipUserInfo select user info by mid
func (d *Dao) OldSelVipUserInfo(c context.Context, mid int64) (r *model.VipUserInfo, err error) {
var row = d.olddb.QueryRow(c, _selVipUserInfoByMid, mid)
r = new(model.VipUserInfo)
if err = row.Scan(&r.ID, &r.Mid, &r.VipType, &r.VipStatus, &r.VipStartTime, &r.VipOverdueTime, &r.AnnualVipOverdueTime, &r.Wander, &r.AccessStatus, &r.Ctime, &r.Mtime, &r.VipRecentTime); err != nil {
if err == sql.ErrNoRows {
r = nil
err = nil
} else {
err = errors.WithStack(err)
}
}
return
}
//SelVipResourceBatch select vip resource Batch by id
func (d *Dao) SelVipResourceBatch(c context.Context, id int64) (r *model.VipResourceBatch, err error) {
var row = d.olddb.QueryRow(c, _selVipResourceBatchByID, id)
r = new(model.VipResourceBatch)
if err = row.Scan(&r.ID, &r.PoolID, &r.Unit, &r.Count, &r.Ver, &r.StartTime, &r.EndTime, &r.SurplusCount, &r.CodeUseCount, &r.DirectUseCount, &r.Ctime, &r.Mtime); err != nil {
if err == sql.ErrNoRows {
r = nil
err = nil
return
}
err = errors.WithStack(err)
}
return
}
//OldUpdateVipUserInfo update vip user info by id
func (d *Dao) OldUpdateVipUserInfo(c context.Context, tx *sql.Tx, r *model.VipUserInfo) (a int64, err error) {
var res xsql.Result
if res, err = tx.Exec(_updateVipUserInfoByID, r.VipType, r.VipStatus, r.VipOverdueTime, r.AnnualVipOverdueTime, r.VipRecentTime, r.ID); err != nil {
err = errors.WithStack(err)
} else {
if a, err = res.RowsAffected(); err != nil {
err = errors.WithStack(err)
}
}
return
}
//UpdateBatchCount updateBatch by Id
func (d *Dao) UpdateBatchCount(c context.Context, tx *sql.Tx, r *model.VipResourceBatch, ver int64) (a int64, err error) {
var res xsql.Result
if res, err = tx.Exec(_updateBatchCountByID, r.CodeUseCount, r.ID); err != nil {
err = errors.WithStack(err)
} else {
if a, err = res.RowsAffected(); err != nil {
err = errors.WithStack(err)
}
}
return
}
//OldInsertVipUserInfo insert vipUserInfo.
func (d *Dao) OldInsertVipUserInfo(c context.Context, tx *sql.Tx, r *model.VipUserInfo) (err error) {
if _, err = tx.Exec(_insertVipUserInfo, r.Mid, r.VipType, r.VipStatus, r.VipStartTime, r.VipOverdueTime, r.AnnualVipOverdueTime, r.Wander, r.AccessStatus, r.VipRecentTime); err != nil {
err = errors.WithStack(err)
}
return
}
//OldInsertVipChangeHistory insert vipChangeHistory
func (d *Dao) OldInsertVipChangeHistory(c context.Context, tx *sql.Tx, r *model.VipChangeHistory) (id int64, err error) {
var res xsql.Result
if res, err = tx.Exec(_insertVipChangeHistory, r.Mid, r.ChangeType, r.ChangeTime, r.Days, r.Month, r.OperatorID, r.RelationID, r.BatchID, r.Remark); err != nil {
err = errors.WithStack(err)
} else {
if id, err = res.LastInsertId(); err != nil {
err = errors.WithStack(err)
}
}
return
}
//OldVipchangeHistory old vip change history.
func (d *Dao) OldVipchangeHistory(c context.Context, relationID string, batchID int64) (r *model.VipChangeHistory, err error) {
var row = d.olddb.QueryRow(c, _selVipChangeHistory, relationID, batchID)
r = new(model.VipChangeHistory)
if err = row.Scan(&r.ID, &r.Mid, &r.ChangeType, &r.ChangeTime, &r.Days, &r.Month, &r.OperatorID, &r.RelationID, &r.BatchID, &r.Remark, &r.Ctime); err != nil {
if err == sql.ErrNoRows {
r = nil
err = nil
return
}
err = errors.WithStack(err)
d.errProm.Incr("scan_error")
}
return
}

View File

@@ -0,0 +1,221 @@
package dao
import (
"context"
"math/rand"
"testing"
"time"
"go-common/app/service/main/vip/model"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoOldInsertVipBcoinSalary(t *testing.T) {
var (
c = context.TODO()
r = &model.VipBcoinSalary{}
)
r.Amount = 10
r.Status = 0
r.Mid = 1
r.Memo = "年费会员发放B币"
r.GiveNowStatus = 0
convey.Convey("OldInsertVipBcoinSalary,should return true where err == nil", t, func(ctx convey.C) {
err := d.OldInsertVipBcoinSalary(c, r)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoSelAllConfig(t *testing.T) {
var (
c = context.TODO()
)
convey.Convey("SelAllConfig, should return true where err == nil and res not empty", t, func(ctx convey.C) {
res, err := d.SelAllConfig(c)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
ctx.Convey("res should not be nil", func(ctx convey.C) {
ctx.So(res, convey.ShouldNotBeNil)
})
})
}
func TestDaoSelVipAppInfo(t *testing.T) {
var (
c = context.TODO()
no = int(0)
)
convey.Convey("SelVipAppInfo", t, func(ctx convey.C) {
_, err := d.SelVipAppInfo(c, no)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoOldSelLastBcoin(t *testing.T) {
var (
c = context.TODO()
mid = int64(1)
)
convey.Convey("OldSelLastBcoin,should return true where err == nil and r != nil", t, func(ctx convey.C) {
r, err := d.OldSelLastBcoin(c, mid)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
ctx.Convey("r should not be nil", func(ctx convey.C) {
ctx.So(r, convey.ShouldNotBeNil)
})
})
}
func TestDaoSelBusiness(t *testing.T) {
var (
c = context.TODO()
id = int64(4)
)
convey.Convey("SelBusiness,should return true where err == nil and r != nil", t, func(ctx convey.C) {
_, err := d.SelBusiness(c, id)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoSelResourcePool(t *testing.T) {
var (
c = context.TODO()
id = int64(5)
)
convey.Convey("SelResourcePool", t, func(ctx convey.C) {
_, err := d.SelResourcePool(c, id)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoOldSelVipUserInfo(t *testing.T) {
var (
c = context.TODO()
mid = int64(1)
)
convey.Convey("OldSelVipUserInfo", t, func(ctx convey.C) {
_, err := d.OldSelVipUserInfo(c, mid)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoSelVipResourceBatch(t *testing.T) {
var (
c = context.TODO()
id = int64(5)
)
convey.Convey("SelVipResourceBatch,should return true where err == nil and r != nil", t, func(ctx convey.C) {
_, err := d.SelVipResourceBatch(c, id)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoOldSelVipChangeHistory(t *testing.T) {
var (
c = context.TODO()
relationID = "ad4bb9b8f5d9d4a7123459780"
batchID int64 = 1
)
convey.Convey("OldSelVipChangeHistory", t, func(ctx convey.C) {
_, err := d.OldVipchangeHistory(c, relationID, batchID)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoOldUpdateVipUserInfo(t *testing.T) {
var (
c = context.TODO()
r = &model.VipUserInfo{Mid: rand.Int63()}
)
convey.Convey("OldUpdateVipUserInfo", t, func(ctx convey.C) {
tx, err := d.StartTx(c)
ctx.Convey("Tx Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
defer tx.Commit()
a, err := d.OldUpdateVipUserInfo(c, tx, r)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
ctx.Convey("a should not be nil", func(ctx convey.C) {
ctx.So(a, convey.ShouldNotBeNil)
})
})
}
func TestDaoUpdateBatchCount3(t *testing.T) {
var (
c = context.TODO()
r = &model.VipResourceBatch{ID: 1}
ver = int64(0)
)
convey.Convey("UpdateBatchCount", t, func(ctx convey.C) {
tx, err := d.StartTx(c)
ctx.So(err, convey.ShouldBeNil)
defer tx.Commit()
a, err := d.UpdateBatchCount(c, tx, r, ver)
ctx.So(err, convey.ShouldBeNil)
ctx.So(a, convey.ShouldBeGreaterThan, 0)
})
}
func TestDaoOldInsertVipUserInfo(t *testing.T) {
var (
c = context.TODO()
r = &model.VipUserInfo{Mid: time.Now().Unix()}
)
convey.Convey("OldInsertVipUserInfo", t, func(ctx convey.C) {
tx, err := d.OldStartTx(c)
ctx.So(err, convey.ShouldBeNil)
err = d.OldInsertVipUserInfo(c, tx, r)
ctx.So(err, convey.ShouldBeNil)
})
}
func TestDaoOldInsertVipChangeHistory(t *testing.T) {
var (
c = context.TODO()
r = &model.VipChangeHistory{}
)
convey.Convey("OldInsertVipChangeHistory", t, func(ctx convey.C) {
tx, err := d.OldStartTx(c)
ctx.Convey("Tx Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
id, err := d.OldInsertVipChangeHistory(c, tx, r)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
ctx.Convey("id should not be nil", func(ctx convey.C) {
ctx.So(id, convey.ShouldNotBeNil)
})
})
}
func TestDao_OldTxDelBcoinSalary(t *testing.T) {
convey.Convey("old tx del bcoin salary", t, func() {
tx, _ := d.OldStartTx(context.TODO())
err := d.OldTxDelBcoinSalary(tx, 106138791, time.Now().AddDate(0, 1, 0))
tx.Commit()
convey.So(err, convey.ShouldBeNil)
})
}

View File

@@ -0,0 +1,33 @@
package dao
import (
"context"
"github.com/pkg/errors"
"go-common/app/service/main/vip/model"
)
const (
_insertOldPayOrder = "INSERT INTO vip_pay_order(order_no,app_id,mid,buy_months,money,status,ver,platform,app_sub_id,bmid,order_type,coupon_money,pid,user_ip)VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?);"
_insertOldRechargeOrder = "INSERT INTO vip_recharge_order(app_id,pay_mid,order_no,recharge_bp,pay_order_no,status,remark,ver,third_trade_no)VALUES(?,?,?,?,?,?,?,?,?);"
)
//AddOldPayOrder add old payorder.
func (d *Dao) AddOldPayOrder(c context.Context, r *model.VipOldPayOrder) (err error) {
if _, err = d.olddb.Exec(c, _insertOldPayOrder, &r.OrderNo, &r.AppID, &r.Mid, &r.BuyMonths, &r.Money, &r.Status, &r.Ver, &r.Platform, &r.AppSubID, &r.Bmid,
&r.OrderType, &r.CouponMoney, &r.PID, &r.UserIP); err != nil {
err = errors.Wrapf(err, "dao add old pay order(%+v)", r)
return
}
return
}
//AddOldRechargeOrder add recharge order.
func (d *Dao) AddOldRechargeOrder(c context.Context, r *model.VipOldRechargeOrder) (err error) {
if _, err = d.olddb.Exec(c, _insertOldRechargeOrder, &r.AppID, &r.PayMid, &r.OrderNo, &r.RechargeBp, &r.PayOrderNO, &r.Status, &r.Remark, &r.Ver, &r.ThirdTradeNO); err != nil {
err = errors.Wrapf(err, "dao add old recharge order(%+v)", r)
return
}
return
}

View File

@@ -0,0 +1,49 @@
package dao
import (
"context"
"testing"
"go-common/app/service/main/vip/model"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoAddOldPayOrder(t *testing.T) {
convey.Convey("AddOldPayOrder", t, func(convCtx convey.C) {
var (
c = context.Background()
orderNo = "20188888888"
r = &model.VipOldPayOrder{
OrderNo: orderNo,
UserIP: []byte("127.0.0.1"),
}
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.AddOldPayOrder(c, r)
convCtx.Convey("Then err should be nil.", func(convCtx convey.C) {
convCtx.So(err, convey.ShouldBeNil)
})
})
convCtx.Convey("clean data", func(convCtx convey.C) {
d.olddb.Exec(c, "delete from vip_pay_order where order_no=? ", orderNo)
})
})
}
func TestDaoAddOldRechargeOrder(t *testing.T) {
convey.Convey("AddOldRechargeOrder", t, func(convCtx convey.C) {
var (
c = context.Background()
orderNo = "201899999999"
r = &model.VipOldRechargeOrder{OrderNo: orderNo}
)
convCtx.Convey("When everything goes positive", func(convCtx convey.C) {
err := d.AddOldRechargeOrder(c, r)
convCtx.So(err, convey.ShouldBeNil)
})
convCtx.Convey("clean data", func(convCtx convey.C) {
d.olddb.Exec(c, "delete from vip_recharge_order where order_no=? ", orderNo)
})
})
}

View File

@@ -0,0 +1,34 @@
package dao
import (
"context"
"fmt"
"go-common/library/ecode"
"go-common/library/log"
"net/url"
)
const (
_frozenChange = "/internal/v1/user/frozenChange"
)
// OldFrozenChange .
func (d *Dao) OldFrozenChange(c context.Context, mid int64) (err error) {
params := url.Values{}
params.Set("mid", fmt.Sprintf("%v", mid))
params.Set("status", "0")
rel := new(struct {
Code int64 `json:"code"`
Data string `json:"data"`
})
if err = d.client.Get(c, d.c.Property.VipURL+_frozenChange, "127.0.0.1", params, rel); err != nil {
log.Error("send error(%v) url(%v)", err, d.c.Property.VipURL+_frozenChange+_frozenChange)
return
}
if rel != nil && rel.Code == int64(ecode.OK.Code()) {
return
}
err = ecode.VipJavaAPIErr
return
}

View File

@@ -0,0 +1,24 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
gock "gopkg.in/h2non/gock.v1"
)
func TestDaoOldFrozenChange(t *testing.T) {
convey.Convey("OldFrozenChange success", t, func() {
defer gock.OffAll()
httpMock("GET", _frozenChange).Reply(200).JSON(`{"code":0}`)
err := d.OldFrozenChange(context.TODO(), 7593623)
convey.So(err, convey.ShouldBeNil)
})
convey.Convey("OldFrozenChange fail", t, func() {
defer gock.OffAll()
httpMock("GET", _frozenChange).Reply(200).JSON(`{"code":-400}`)
err := d.OldFrozenChange(context.TODO(), 7593623)
convey.So(err, convey.ShouldNotBeNil)
})
}

View File

@@ -0,0 +1,276 @@
package dao
import (
"context"
xsql "database/sql"
"fmt"
"go-common/app/service/main/vip/model"
"go-common/library/database/sql"
"go-common/library/xstr"
"github.com/pkg/errors"
)
const (
_vipOrderListSQL = "SELECT id,order_no,app_id,platform,order_type,mid,to_mid,buy_months,money,refund_amount,status,pay_type,recharge_bp,third_trade_no,ver,payment_time,ctime,mtime,app_sub_id FROM vip_pay_order WHERE mid = ? AND status = ? ORDER BY id DESC LIMIT ?,?;"
_vipOrderCountSQL = "SELECT COUNT(1) FROM vip_pay_order WHERE mid = ? AND status = ? ORDER BY id desc;"
_getOrderInfoSQL = "SELECT id,order_no, app_id,platform,order_type,mid,to_mid,buy_months,money,refund_amount,status,pay_type,recharge_bp,third_trade_no,payment_time,ver,ctime,mtime,app_sub_id FROM `vip_pay_order` WHERE `order_no` = ?;"
_discountSQL = "SELECT mid,discount_id,status FROM vip_user_discount_history where mid=? AND discount_id = ? AND status = 1 "
_allPriceMapping = "SELECT id,month_id,month_type,money,selected,first_discount_money,discount_money,start_time,end_time,remark,operator,mtime FROM vip_month_price WHERE month_id = ? AND month_type = ? LIMIT 1;"
_insertPayOrder = "INSERT INTO vip_pay_order(order_no,app_id,platform,order_type,mid,to_mid,buy_months,money,status,pay_type,recharge_bp,third_trade_no,app_sub_id,coupon_money,pid,user_ip)VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);"
_allMonthOrderSQL = "SELECT id,month,month_type,operator,status,deleted,mtime FROM vip_month where deleted = 0 AND status = 1 ORDER BY month "
_updateOrderStatusSQL = "UPDATE vip_pay_order SET status = ?,pay_type = ?,third_trade_no = ? WHERE order_no = ?;"
_updatePayOrderSQL = "UPDATE vip_pay_order SET pay_type=?,third_trade_no=?,recharge_bp=?,ver=? WHERE id = ? AND ver=? "
_updateIosPayOrderSQL = "UPDATE vip_pay_order SET pay_type=?,third_trade_no=?,recharge_bp=?,ver=?,order_type=?,status=? WHERE id = ? AND ver=? "
_updatePayOrderStatusSQL = "UPDATE vip_pay_order SET status = ? WHERE id = ? AND ver=?;"
_addOrderLogSQL = "INSERT INTO vip_pay_order_log(order_no,refund_id,refund_amount,mid,status) VALUES(?,?,?,?,?);"
_payOrderLastSQL = "SELECT id,order_no,app_id,platform,order_type,mid,to_mid,buy_months,money,refund_amount,status,pay_type,recharge_bp,third_trade_no,payment_time,ver,ctime,mtime,app_sub_id FROM vip_pay_order WHERE mid = %v AND status = %v AND order_type IN (%v) ORDER BY id DESC LIMIT 1 "
_updatePayOrderRefundAmountSQL = "UPDATE vip_pay_order SET refund_amount=?,ver=? WHERE id=? AND ver=?"
_selOldPayOrder = "SELECT order_no,app_id,order_type,mid,IFNULL(buy_months,0),money,IFNULL(pay_type,4),IFNULL(status,1),ver,IFNULL(platform,3),mtime,app_sub_id,pid,user_ip from vip_pay_order WHERE order_no = ?;"
_selOrderLogSQL = "SELECT order_no,refund_id,mid,status FROM vip_pay_order_log WHERE order_no = ? AND refund_id = ? AND status = ?"
)
// BeginTran begin tran.
func (d *Dao) BeginTran(c context.Context) (tx *sql.Tx, err error) {
tx, err = d.db.Begin(c)
return
}
//OrderCount order count.
func (d *Dao) OrderCount(c context.Context, mid int64, status int8) (count int64, err error) {
var row *sql.Row
if row = d.db.QueryRow(c, _vipOrderCountSQL, mid, status); err != nil {
err = errors.WithStack(err)
d.errProm.Incr("query_db")
return
}
if err = row.Scan(&count); err != nil {
err = errors.WithStack(err)
d.errProm.Incr("row_scan_db")
return
}
return
}
// OrderList order list.
func (d *Dao) OrderList(c context.Context, mid int64, status int8, pn, ps int) (res []*model.PayOrder, err error) {
var rows *sql.Rows
if rows, err = d.db.Query(c, _vipOrderListSQL, mid, status, (pn-1)*ps, ps); err != nil {
err = errors.WithStack(err)
d.errProm.Incr("query_db")
return
}
defer rows.Close()
for rows.Next() {
r := new(model.PayOrder)
if err = rows.Scan(&r.ID, &r.OrderNo, &r.AppID, &r.Platform, &r.OrderType, &r.Mid, &r.ToMid, &r.BuyMonths, &r.Money, &r.RefundAmount, &r.Status, &r.PayType, &r.RechargeBp,
&r.ThirdTradeNo, &r.Ver, &r.PaymentTime, &r.Ctime, &r.Mtime, &r.AppSubID); err != nil {
err = errors.WithStack(err)
d.errProm.Incr("row_scan_db")
res = nil
return
}
res = append(res, r)
}
err = rows.Err()
return
}
//OrderInfo select order by order no.
func (d *Dao) OrderInfo(c context.Context, orderNo string) (r *model.OrderInfo, err error) {
var row = d.db.QueryRow(c, _getOrderInfoSQL, orderNo)
r = new(model.OrderInfo)
if err = row.Scan(&r.ID, &r.OrderNo, &r.AppID, &r.Platform, &r.OrderType, &r.Mid, &r.ToMid, &r.BuyMonths, &r.Money, &r.RefundAmount, &r.Status, &r.PayType,
&r.RechargeBP, &r.ThirdTradeNo, &r.PaymentTime, &r.Ver, &r.Ctime, &r.Mtime, &r.AppSubID); err != nil {
if err == sql.ErrNoRows {
r = nil
err = nil
} else {
err = errors.WithStack(err)
d.errProm.Incr("row_scan_db")
}
}
return
}
// DiscountSQL discount sql.
func (d *Dao) DiscountSQL(c context.Context, mid int64, discountID int64) (dh *model.VipUserDiscountHistory, err error) {
row := d.db.QueryRow(c, _discountSQL, mid, discountID)
dh = new(model.VipUserDiscountHistory)
if err = row.Scan(&dh.Mid, &dh.DiscountID, &dh.Status); err != nil {
if err == sql.ErrNoRows {
dh = nil
err = nil
} else {
err = errors.WithStack(err)
d.errProm.Incr("row_scan_db")
}
}
return
}
//PriceMapping all price mapping.
func (d *Dao) PriceMapping(c context.Context, monthID int64, platform int8) (r *model.PriceMapping, err error) {
row := d.db.QueryRow(c, _allPriceMapping, monthID, platform)
r = new(model.PriceMapping)
if err = row.Scan(&r.ID, &r.MonthID, &r.MonthType, &r.Money, &r.Selected, &r.FirstDiscountMoney, &r.DiscountMoney,
&r.StartTime, &r.EndTime, &r.Remark, &r.Operator, &r.Mtime); err != nil {
if err == sql.ErrNoRows {
err = nil
r = nil
} else {
err = errors.WithStack(err)
d.errProm.Incr("row_scan_db")
}
}
return
}
// TxAddOrder tx add order.
func (d *Dao) TxAddOrder(tx *sql.Tx, p *model.PayOrder) (id int64, err error) {
var result xsql.Result
if result, err = tx.Exec(_insertPayOrder, &p.OrderNo, &p.AppID, &p.Platform, &p.OrderType, &p.Mid, &p.ToMid,
&p.BuyMonths, &p.Money, &p.Status, &p.PayType, &p.RechargeBp, &p.ThirdTradeNo, &p.AppSubID, &p.CouponMoney, &p.PID, &p.UserIP); err != nil {
err = errors.WithStack(err)
d.errProm.Incr("exec_db")
return
}
if id, err = result.LastInsertId(); err != nil {
err = errors.WithStack(err)
}
return
}
//AllMonthByOrder order by month.
func (d *Dao) AllMonthByOrder(c context.Context, orderStr string) (res []*model.Month, err error) {
var rows *sql.Rows
if rows, err = d.db.Query(c, _allMonthOrderSQL+orderStr); err != nil {
err = errors.WithStack(err)
d.errProm.Incr("query_db")
return
}
defer rows.Close()
for rows.Next() {
r := new(model.Month)
if err = rows.Scan(&r.ID, &r.Month, &r.MonthType, &r.Operator, &r.Status, &r.Deleted, &r.Mtime); err != nil {
err = errors.WithStack(err)
d.errProm.Incr("row_scan_db")
res = nil
return
}
res = append(res, r)
}
err = rows.Err()
return
}
// TxUpdateOrderStatus update order status.
func (d *Dao) TxUpdateOrderStatus(c context.Context, tx *sql.Tx, status int8, payType string, thirdTradeNO string, orderNO string) (err error) {
if _, err = tx.Exec(_updateOrderStatusSQL, status, payType, thirdTradeNO, orderNO); err != nil {
err = errors.WithStack(err)
d.errProm.Incr("exec_db")
return
}
return
}
//TxUpdatePayOrder .
func (d *Dao) TxUpdatePayOrder(tx *sql.Tx, o *model.OrderInfo, ver int64) (err error) {
if _, err = tx.Exec(_updatePayOrderSQL, o.PayType, o.ThirdTradeNo, o.RechargeBP, o.Ver, o.ID, ver); err != nil {
err = errors.WithStack(err)
return
}
return
}
//TxUpdateIosPayOrder .
func (d *Dao) TxUpdateIosPayOrder(tx *sql.Tx, o *model.OrderInfo, ver int64) (err error) {
if _, err = tx.Exec(_updateIosPayOrderSQL, o.PayType, o.ThirdTradeNo, o.RechargeBP, o.Ver, o.OrderType, o.Status, o.ID, ver); err != nil {
err = errors.WithStack(err)
}
return
}
//TxUpdatePayOrderStatus .
func (d *Dao) TxUpdatePayOrderStatus(tx *sql.Tx, status int8, id int64, ver int64) (a int64, err error) {
var result xsql.Result
if result, err = tx.Exec(_updatePayOrderStatusSQL, status, id, ver); err != nil {
err = errors.WithStack(err)
return
}
if a, err = result.RowsAffected(); err != nil {
err = errors.WithStack(err)
return
}
return
}
//TxAddOrderLog .
func (d *Dao) TxAddOrderLog(tx *sql.Tx, arg *model.VipPayOrderLog) (err error) {
if _, err = tx.Exec(_addOrderLogSQL, arg.OrderNo, arg.RefundID, arg.RefundAmount, arg.Mid, arg.Status); err != nil {
err = errors.WithStack(err)
return
}
return
}
//PayOrderLast .
func (d *Dao) PayOrderLast(c context.Context, mid int64, status int8, orderTypes ...int64) (r *model.PayOrder, err error) {
row := d.db.QueryRow(c, fmt.Sprintf(_payOrderLastSQL, mid, status, xstr.JoinInts(orderTypes)))
r = new(model.PayOrder)
if err = row.Scan(&r.ID, &r.OrderNo, &r.AppID, &r.Platform, &r.OrderType, &r.Mid, &r.ToMid, &r.BuyMonths, &r.Money, &r.RefundAmount, &r.Status, &r.PayType,
&r.RechargeBp, &r.ThirdTradeNo, &r.PaymentTime, &r.Ver, &r.Ctime, &r.Mtime, &r.AppSubID); err != nil {
if err == sql.ErrNoRows {
r = nil
err = nil
} else {
err = errors.WithStack(err)
d.errProm.Incr("row_scan_db")
}
}
return
}
//SelOldPayOrder sel old payorder
func (d *Dao) SelOldPayOrder(c context.Context, orderNo string) (r *model.VipPayOrderOld, err error) {
var row = d.olddb.QueryRow(c, _selOldPayOrder, orderNo)
r = new(model.VipPayOrderOld)
if err = row.Scan(&r.OrderNo, &r.AppID, &r.OrderType, &r.Mid, &r.BuyMonths, &r.Money, &r.PayType, &r.Status, &r.Ver, &r.Platform, &r.PaymentTime, &r.AppSubID, &r.PID, &r.UserIP); err != nil {
if err == sql.ErrNoRows {
r = nil
err = nil
} else {
err = errors.WithStack(err)
d.errProm.Incr("row_scan_db")
}
}
return
}
// SelPayOrderLog sel pay order log.
func (d *Dao) SelPayOrderLog(c context.Context, orderNo, refundID string, status int8) (res *model.VipPayOrderLog, err error) {
row := d.db.QueryRow(c, _selOrderLogSQL, orderNo, refundID, status)
res = new(model.VipPayOrderLog)
if err = row.Scan(&res.OrderNo, &res.RefundID, &res.Mid, &res.Status); err != nil {
if err == sql.ErrNoRows {
res = nil
err = nil
return
}
err = errors.WithStack(err)
d.errProm.Incr("row_scan_db")
}
return
}
//TxUpdatePayOrderRefundAmount update payorder refund amount
func (d *Dao) TxUpdatePayOrderRefundAmount(tx *sql.Tx, id int64, refundAmount float64, ver, oldVer int64) (err error) {
if _, err = tx.Exec(_updatePayOrderRefundAmountSQL, refundAmount, ver, id, oldVer); err != nil {
err = errors.WithStack(err)
d.errProm.Incr("tx_db")
}
return
}

View File

@@ -0,0 +1,318 @@
package dao
import (
"context"
"fmt"
"math/rand"
"testing"
"time"
"go-common/app/service/main/vip/model"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoBeginTran(t *testing.T) {
var (
c = context.TODO()
)
convey.Convey("BeginTran", t, func(ctx convey.C) {
tx, err := d.BeginTran(c)
ctx.Convey("Tx Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
ctx.Convey("tx should not be nil", func(ctx convey.C) {
ctx.So(tx, convey.ShouldNotBeNil)
})
})
}
func TestDaoOrderCount(t *testing.T) {
var (
c = context.TODO()
mid = int64(20606508)
status = int8(1)
)
convey.Convey("OrderCount", t, func(ctx convey.C) {
count, err := d.OrderCount(c, mid, status)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
ctx.Convey("count should not be nil", func(ctx convey.C) {
ctx.So(count, convey.ShouldNotBeNil)
})
})
}
func TestDaoOrderList(t *testing.T) {
var (
c = context.TODO()
mid = int64(20606508)
status = int8(1)
pn = int(1)
ps = int(20)
)
convey.Convey("OrderList", t, func(ctx convey.C) {
_, err := d.OrderList(c, mid, status, pn, ps)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoOrderInfo(t *testing.T) {
var (
c = context.TODO()
orderNo = "12345"
)
convey.Convey("OrderInfo", t, func(ctx convey.C) {
_, err := d.OrderInfo(c, orderNo)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoDiscountSQL(t *testing.T) {
var (
c = context.TODO()
mid = int64(20606508)
discountID = int64(2)
)
convey.Convey("DiscountSQL", t, func(ctx convey.C) {
_, err := d.DiscountSQL(c, mid, discountID)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoPriceMapping(t *testing.T) {
var (
c = context.TODO()
monthID = int64(1)
platform = int8(1)
)
convey.Convey("PriceMapping", t, func(ctx convey.C) {
_, err := d.PriceMapping(c, monthID, platform)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoTxAddOrder(t *testing.T) {
var (
c = context.TODO()
p = &model.PayOrder{
OrderNo: fmt.Sprintf("%d_%d", time.Now().Unix(), rand.Int31()),
AppID: 1,
Platform: 1,
OrderType: 1,
AppSubID: "a",
Mid: 20606508,
ToMid: 1,
BuyMonths: 1,
Money: 1.0,
Status: 1,
PayType: 1,
RechargeBp: 1.0,
ThirdTradeNo: "209",
Ver: 1,
UserIP: []byte("127.0.0.1"),
}
)
convey.Convey("TxAddOrder", t, func(ctx convey.C) {
tx, err := d.StartTx(c)
ctx.Convey("Tx Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
ctx.Convey("TxAddOrder Error should be nil", func(ctx convey.C) {
id, err := d.TxAddOrder(tx, p)
ctx.So(err, convey.ShouldBeNil)
ctx.So(id, convey.ShouldNotBeNil)
err = tx.Commit()
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoAllMonthByOrder(t *testing.T) {
var (
c = context.TODO()
orderStr = ""
)
convey.Convey("AllMonthByOrder", t, func(ctx convey.C) {
res, err := d.AllMonthByOrder(c, orderStr)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
ctx.Convey("res should not be nil", func(ctx convey.C) {
ctx.So(res, convey.ShouldNotBeNil)
})
})
}
func TestDaoTxUpdateOrderStatus(t *testing.T) {
var (
c = context.TODO()
status = int8(0)
payType = ""
thirdTradeNO = ""
orderNO = ""
)
convey.Convey("TxUpdateOrderStatus", t, func(ctx convey.C) {
tx, err := d.StartTx(c)
ctx.Convey("Tx Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
defer tx.Commit()
err = d.TxUpdateOrderStatus(c, tx, status, payType, thirdTradeNO, orderNO)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoTxUpdatePayOrder(t *testing.T) {
var (
c = context.TODO()
o = &model.OrderInfo{
OrderNo: "12345",
AppID: 1,
OrderType: 2,
Platform: 1,
Mid: 20606508,
ToMid: 20606509,
BuyMonths: 1,
Money: 3.0,
Status: 1,
PayType: "1",
RechargeBP: 3.0,
ThirdTradeNo: "456",
Ver: 23,
AppSubID: "1234",
}
ver = int64(0)
)
convey.Convey("TxUpdatePayOrder", t, func(ctx convey.C) {
tx, err := d.StartTx(c)
ctx.Convey("Tx Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
defer tx.Commit()
err = d.TxUpdatePayOrder(tx, o, ver)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoTxUpdateIosPayOrder(t *testing.T) {
var (
c = context.TODO()
o = &model.OrderInfo{
OrderNo: "12345",
AppID: 1,
OrderType: 2,
Platform: 1,
Mid: 20606508,
ToMid: 20606509,
BuyMonths: 1,
Money: 3.0,
Status: 1,
PayType: "1",
RechargeBP: 3.0,
ThirdTradeNo: "456",
Ver: 23,
AppSubID: "1234",
}
ver = int64(0)
)
convey.Convey("TxUpdateIosPayOrder", t, func(ctx convey.C) {
tx, err := d.StartTx(c)
ctx.Convey("Tx Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
defer tx.Commit()
err = d.TxUpdateIosPayOrder(tx, o, ver)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoTxUpdatePayOrderStatus(t *testing.T) {
var (
c = context.TODO()
status = int8(0)
id = int64(0)
ver = int64(0)
)
convey.Convey("TxUpdatePayOrderStatus", t, func(ctx convey.C) {
tx, err := d.StartTx(c)
ctx.Convey("Tx Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
defer tx.Commit()
a, err := d.TxUpdatePayOrderStatus(tx, status, id, ver)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
ctx.Convey("a should not be nil", func(ctx convey.C) {
ctx.So(a, convey.ShouldNotBeNil)
})
})
}
func TestDaoTxAddOrderLog(t *testing.T) {
var (
c = context.TODO()
mid = int64(0)
orderNo = ""
status = int8(0)
)
convey.Convey("TxAddOrderLog", t, func(ctx convey.C) {
tx, err := d.StartTx(c)
ctx.Convey("Tx Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
defer tx.Commit()
olog := new(model.VipPayOrderLog)
olog.Mid = mid
olog.Status = status
olog.OrderNo = orderNo
err = d.TxAddOrderLog(tx, olog)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoPayOrderLast(t *testing.T) {
var (
c = context.TODO()
mid = int64(0)
status = int8(0)
orderTypes = int64(0)
)
convey.Convey("PayOrderLast", t, func(ctx convey.C) {
_, err := d.PayOrderLast(c, mid, status, orderTypes)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoSelOldPayOrder(t *testing.T) {
var (
c = context.TODO()
orderNo = ""
)
convey.Convey("SelOldPayOrder", t, func(ctx convey.C) {
_, err := d.SelOldPayOrder(c, orderNo)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}

View File

@@ -0,0 +1,157 @@
package dao
import (
"context"
"time"
"go-common/app/service/main/vip/model"
"go-common/library/database/sql"
"github.com/pkg/errors"
)
const (
_vipPayOrderSuccsSQL = "SELECT id,order_type,buy_months FROM vip_pay_order WHERE mid = ? and status= 2"
_vipPriceConfigsSQL = "SELECT id,platform,product_name,product_id,suit_type,month,sub_type,original_price,selected,remark,ctime,mtime,superscript,start_build,end_build FROM vip_price_config_v2 WHERE status = 0"
_vipPriceDiscountConfigsSQL = "SELECT vpc_id,product_id,discount_price,stime,etime,remark,ctime,mtime,first_price FROM vip_price_discount_config_v2 WHERE stime <= ? AND ((etime > ? AND etime <> '1970-01-01 08:00:00') OR (etime = '1970-01-01 08:00:00'))"
_vipPriceDiscountByProductIDSQL = "SELECT vpc_id,product_id,discount_price,stime,etime,remark,ctime,mtime FROM vip_price_discount_config_v2 WHERE product_id = ? ORDER BY mtime DESC"
_vipPriceByProductIDSQL = "SELECT id,platform,product_name,product_id,suit_type,month,sub_type,original_price,selected,remark,ctime,mtime,superscript FROM vip_price_config_v2 WHERE status = 0 AND product_id = ? ORDER BY mtime DESC LIMIT 1"
_vipPriceByIDSQL = "SELECT id,platform,product_name,product_id,suit_type,month,sub_type,original_price,selected,remark,ctime,mtime,superscript,start_build,end_build FROM vip_price_config_v2 WHERE id = ?"
)
// VipPayOrderSuccs get succ of vip pay orders.
func (d *Dao) VipPayOrderSuccs(c context.Context, mid int64) (mpo map[string]struct{}, err error) {
var rows *sql.Rows
if rows, err = d.db.Query(c, _vipPayOrderSuccsSQL, mid); err != nil {
err = errors.WithStack(err)
return
}
defer rows.Close()
mpo = make(map[string]struct{})
for rows.Next() {
po := new(model.PayOrder)
if err = rows.Scan(&po.ID, &po.OrderType, &po.BuyMonths); err != nil {
if err != sql.ErrNoRows {
err = errors.WithStack(err)
return
}
mpo = nil
err = nil
return
}
mpo[po.DoPayOrderTypeKey()] = struct{}{}
}
err = rows.Err()
return
}
// VipPriceConfigs get vip price configs.
func (d *Dao) VipPriceConfigs(c context.Context) (vpcs []*model.VipPriceConfig, err error) {
var rows *sql.Rows
if rows, err = d.db.Query(c, _vipPriceConfigsSQL); err != nil {
err = errors.WithStack(err)
return
}
defer rows.Close()
for rows.Next() {
vpc := new(model.VipPriceConfig)
if err = rows.Scan(&vpc.ID, &vpc.Plat, &vpc.PdName, &vpc.PdID, &vpc.SuitType, &vpc.Month, &vpc.SubType, &vpc.OPrice,
&vpc.Selected, &vpc.Remark, &vpc.CTime, &vpc.MTime, &vpc.Superscript, &vpc.StartBuild, &vpc.EndBuild); err != nil {
if err != sql.ErrNoRows {
err = errors.WithStack(err)
return
}
vpcs = nil
err = nil
return
}
vpcs = append(vpcs, vpc)
}
err = rows.Err()
return
}
// VipPriceDiscountConfigs get vip price discount configs.
func (d *Dao) VipPriceDiscountConfigs(c context.Context) (mvp map[int64]*model.VipDPriceConfig, err error) {
var (
rows *sql.Rows
now = time.Now()
)
mvp = make(map[int64]*model.VipDPriceConfig)
if rows, err = d.db.Query(c, _vipPriceDiscountConfigsSQL, now, now); err != nil {
err = errors.WithStack(err)
return
}
defer rows.Close()
for rows.Next() {
vpc := new(model.VipDPriceConfig)
if err = rows.Scan(&vpc.ID, &vpc.PdID, &vpc.DPrice, &vpc.STime, &vpc.ETime, &vpc.Remark, &vpc.CTime, &vpc.MTime, &vpc.FirstPrice); err != nil {
if err != sql.ErrNoRows {
err = errors.WithStack(err)
return
}
mvp = nil
err = nil
return
}
mvp[vpc.ID] = vpc
}
err = rows.Err()
return
}
//VipPriceDiscountByProductID select vip price discount by product id.
func (d *Dao) VipPriceDiscountByProductID(c context.Context, productID string) (vpc []*model.VipDPriceConfig, err error) {
var rows *sql.Rows
if rows, err = d.db.Query(c, _vipPriceDiscountByProductIDSQL, productID); err != nil {
err = errors.WithStack(err)
return
}
defer rows.Close()
for rows.Next() {
v := new(model.VipDPriceConfig)
if err = rows.Scan(&v.ID, &v.PdID, &v.DPrice, &v.STime, &v.ETime, &v.Remark, &v.CTime, &v.MTime); err != nil {
err = errors.WithStack(err)
vpc = nil
err = nil
return
}
vpc = append(vpc, v)
}
err = rows.Err()
return
}
//VipPriceByProductID select vip price by product id.
func (d *Dao) VipPriceByProductID(c context.Context, productID string) (vpc *model.VipPriceConfig, err error) {
var row = d.db.QueryRow(c, _vipPriceByProductIDSQL, productID)
vpc = new(model.VipPriceConfig)
if err = row.Scan(&vpc.ID, &vpc.Plat, &vpc.PdName, &vpc.PdID, &vpc.SuitType, &vpc.Month, &vpc.SubType, &vpc.OPrice,
&vpc.Selected, &vpc.Remark, &vpc.CTime, &vpc.MTime, &vpc.Superscript); err != nil {
if err == sql.ErrNoRows {
vpc = nil
err = nil
} else {
err = errors.WithStack(err)
d.errProm.Incr("row_scan_db")
}
}
return
}
//VipPriceByID vip price by id.
func (d *Dao) VipPriceByID(c context.Context, id int64) (vpc *model.VipPriceConfig, err error) {
var row = d.db.QueryRow(c, _vipPriceByIDSQL, id)
vpc = new(model.VipPriceConfig)
if err = row.Scan(&vpc.ID, &vpc.Plat, &vpc.PdName, &vpc.PdID, &vpc.SuitType, &vpc.Month, &vpc.SubType, &vpc.OPrice,
&vpc.Selected, &vpc.Remark, &vpc.CTime, &vpc.MTime, &vpc.Superscript, &vpc.StartBuild, &vpc.EndBuild); err != nil {
if err == sql.ErrNoRows {
vpc = nil
err = nil
} else {
err = errors.WithStack(err)
d.errProm.Incr("row_scan_db")
}
}
return
}

View File

@@ -0,0 +1,83 @@
package dao
import (
"context"
"fmt"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoVipPayOrderSuccs(t *testing.T) {
var (
c = context.TODO()
mid = int64(0)
)
convey.Convey("VipPayOrderSuccs", t, func(ctx convey.C) {
mpo, err := d.VipPayOrderSuccs(c, mid)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
ctx.Convey("mpo should not be nil", func(ctx convey.C) {
ctx.So(mpo, convey.ShouldNotBeNil)
})
})
}
func TestDaoVipPriceConfigs(t *testing.T) {
var (
c = context.TODO()
)
convey.Convey("VipPriceConfigs", t, func(ctx convey.C) {
vpcs, err := d.VipPriceConfigs(c)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
ctx.Convey("vpcs should not be nil", func(ctx convey.C) {
ctx.So(vpcs, convey.ShouldNotBeNil)
})
})
}
func TestDaoVipPriceDiscountConfigs(t *testing.T) {
var (
c = context.TODO()
)
convey.Convey("VipPriceDiscountConfigs", t, func(ctx convey.C) {
mvp, err := d.VipPriceDiscountConfigs(c)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
ctx.Convey("mvp should not be nil", func(ctx convey.C) {
ctx.So(mvp, convey.ShouldNotBeNil)
})
})
}
func TestDaoVipPriceDiscountByProductID(t *testing.T) {
var c = context.Background()
convey.Convey("TestDaoVipPriceDiscountByProductID", t, func(ctx convey.C) {
mvp, err := d.VipPriceDiscountByProductID(c, "tv.danmaku.bilibilihd.big12month")
fmt.Println("mvp:", mvp)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
ctx.Convey("mvp should not be nil", func(ctx convey.C) {
ctx.So(mvp, convey.ShouldNotBeNil)
})
})
}
func TestDaoVipPriceByProductID(t *testing.T) {
var c = context.Background()
convey.Convey("TestDaoVipPriceByProductID", t, func(ctx convey.C) {
mvp, err := d.VipPriceByProductID(c, "tv.danmaku.bilibilihd.big12month")
fmt.Println("mvp:", mvp)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
ctx.Convey("mvp should not be nil", func(ctx convey.C) {
ctx.So(mvp, convey.ShouldNotBeNil)
})
})
}

View File

@@ -0,0 +1,458 @@
package dao
import (
"bytes"
"context"
"crypto/md5"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"sort"
"strconv"
"strings"
"time"
"go-common/app/service/main/vip/model"
"go-common/library/ecode"
"go-common/library/log"
"github.com/pkg/errors"
)
const (
//pay url
_addPayOrder = "/api/add.pay.order"
_paySDK = "/api/pay.sdk"
_quickPayToken = "/api/quick.pay.token"
_quickPayDo = "/api/quick.pay.do"
_payQrcode = "/api/pay.qrcode"
_payCashier = "/api/pay.cashier"
_payIapAccess = "/api/add.iap.access"
_payBanks = "/api/pay.banks"
_payWallet = "/api/v2/user/account"
_payRescission = "/payplatform/pay/rescission"
_payClose = "/payplatform/pay/cancel"
_createPayQrCode = "/payplatform/qrcode/createPayQrCode"
_payRemark = "购买大会员服务%d个月"
_merchantID = 17
_productMonthID = 60
_productQuarterID = 61
_productYearID = 62
_quarterMonths = 3
_yearMonths = 12
_iapQuantity = "1"
_minRead = 1024 * 64
_retry = 3
_defversion = "1.0"
_defsigntype = "MD5"
)
//BasicResp pay response.
type BasicResp struct {
Code int `json:"code"`
Message string `json:"messge"`
Data *interface{} `json:"data"`
}
// merchantProduct get Product id by months
func (d *Dao) productID(months int16) (id int8) {
id = _productMonthID
if months >= _quarterMonths && months < _yearMonths {
id = _productQuarterID
} else if months >= _yearMonths {
id = _productYearID
}
return
}
//PayWallet .
func (d *Dao) PayWallet(c context.Context, mid int64, ip string, data *model.PayAccountResp) (err error) {
val := url.Values{}
val.Add("mid", fmt.Sprintf("%d", mid))
return d.dopay(c, _payWallet, ip, val, data, d.client.Post)
}
//PayBanks .
func (d *Dao) PayBanks(c context.Context, ip string, data []*model.PayBankResp) (err error) {
val := url.Values{}
return d.dopay(c, _payBanks, ip, val, data, d.client.Get)
}
//AddPayOrder add pay order.
func (d *Dao) AddPayOrder(c context.Context, ip string, o *model.PayOrder, data *model.AddPayOrderResp) (err error) {
val := url.Values{}
val.Add("mid", fmt.Sprintf("%d", o.Mid))
val.Add("to_mid", fmt.Sprintf("%d", o.ToMid))
val.Add("money", fmt.Sprintf("%f", o.Money))
val.Add("remark", fmt.Sprintf(_payRemark, o.BuyMonths))
val.Add("subject", fmt.Sprintf(_payRemark, o.BuyMonths))
val.Add("out_trade_no", o.OrderNo)
val.Add("notify_url", d.c.Property.NotifyURL)
val.Add("merchant_id", fmt.Sprintf("%d", _merchantID))
val.Add("merchant_product_id", fmt.Sprintf("%d", d.productID(o.BuyMonths)))
var platform string
switch o.Platform {
case model.DeviceIOS:
platform = "1"
case model.DeviceANDROID:
platform = "2"
default:
platform = "3"
}
val.Add("platform_type", platform)
return d.dopay(c, _addPayOrder, ip, val, data, d.client.Post)
}
// PaySDK moblie pay sdk.
func (d *Dao) PaySDK(c context.Context, ip string, o *model.PayOrder, data *model.APIPayOrderResp, payCode string) (err error) {
val := url.Values{}
val.Add("money", fmt.Sprintf("%f", o.Money))
val.Add("pay_order_no", o.OrderNo)
val.Add("pay_type", payCode)
return d.dopay(c, _paySDK, ip, val, data, d.client.Post)
}
// PayQrcode pay qrcode.
func (d *Dao) PayQrcode(c context.Context, ip string, o *model.PayOrder, data *model.APIPayOrderResp, payCode string) (err error) {
val := url.Values{}
val.Add("money", fmt.Sprintf("%f", o.Money))
val.Add("pay_order_no", o.OrderNo)
val.Add("pay_type", payCode)
return d.dopay(c, _payQrcode, ip, val, data, d.client.Post)
}
// QuickPayToken quick pay token.
func (d *Dao) QuickPayToken(c context.Context, ip string, accessKey string, cookie []*http.Cookie, data *model.QucikPayResp) (err error) {
params := make(map[string]string)
params["access_key"] = accessKey
//return d.dopay(c, _quickPayToken, ip, val, cookie, data, d.client.Post)
return d.doPaySend(c, d.c.Property.PayURL, _quickPayToken, ip, cookie, nil, http.MethodPost, params, data, d.PaySign)
}
// DoQuickPay do quick pay.
func (d *Dao) DoQuickPay(c context.Context, ip string, token string, thirdTradeNo string, data *model.PayRetResp) (err error) {
val := url.Values{}
val.Add("token", token)
val.Add("pay_order_no", thirdTradeNo)
return d.dopay(c, _quickPayDo, ip, val, data, d.client.Post)
}
// PayCashier pay cashier.
func (d *Dao) PayCashier(c context.Context, ip string, o *model.PayOrder, data *model.APIPayOrderResp, payCode string, bankCode string) (err error) {
val := url.Values{}
val.Add("pay_order_no", o.ThirdTradeNo)
val.Add("money", fmt.Sprintf("%f", o.Money))
val.Add("pay_type", payCode)
val.Add("bank_code", bankCode)
return d.dopay(c, _payCashier, ip, val, data, d.client.Post)
}
// PayIapAccess pay iap access.
func (d *Dao) PayIapAccess(c context.Context, ip string, o *model.PayOrder, data *model.APIPayOrderResp, productID string) (err error) {
val := url.Values{}
val.Add("mid", fmt.Sprintf("%d", o.Mid))
val.Add("product_id", productID)
val.Add("quantity", _iapQuantity)
val.Add("money", fmt.Sprintf("%f", o.Money))
val.Add("remark", fmt.Sprintf(_payRemark, o.BuyMonths))
val.Add("pay_order_no", o.ThirdTradeNo)
val.Add("merchant_id", fmt.Sprintf("%d", _merchantID))
val.Add("merchant_product_id", fmt.Sprintf("%d", d.productID(o.BuyMonths)))
return d.dopay(c, _payIapAccess, ip, val, data, d.client.Post)
}
//PayClose pay close.
func (d *Dao) PayClose(c context.Context, orderNO string, ip string) (data *model.APIPayCancelResp, err error) {
params := make(map[string]string)
params["customerId"] = strconv.FormatInt(d.c.PayConf.CustomerID, 10)
params["orderId"] = orderNO
params["timestamp"] = fmt.Sprintf("%d", time.Now().Unix()*1000)
params["traceId"] = model.UUID4()
params["version"] = _defversion
params["signType"] = _defsigntype
sign := d.PaySign(params, d.c.PayConf.Token)
params["sign"] = sign
resp := new(
struct {
Code int64 `json:"errno"`
Data *model.APIPayCancelResp `json:"data"`
})
header := make(map[string]string)
header["Content-Type"] = "application/json"
marshal, _ := json.Marshal(params)
if err = d.doSend(c, d.payCloseURL, "127.0.0.1", header, marshal, resp); err != nil {
err = errors.Wrapf(err, "Call pay service(%s)", d.payCloseURL+"?"+string(marshal))
return
}
if resp.Code != 0 {
err = fmt.Errorf("Call pay service(%s) error, response code is not 0, resp:%v", d.payCloseURL+"?"+string(marshal), resp)
return
}
data = resp.Data
log.Info("Call pay service(%s) successful, resp(%v)", d.payCloseURL+"?"+string(marshal), data)
return
}
//PayQrCode pay qr code.
func (d *Dao) PayQrCode(c context.Context, mid int64, orderID string, req map[string]interface{}) (data *model.PayQrCode, err error) {
payParam, _ := json.Marshal(req)
params := make(map[string]string)
params["customerId"] = strconv.FormatInt(d.c.PayConf.CustomerID, 10)
params["uid"] = fmt.Sprintf("%d", mid)
params["orderId"] = orderID
params["payParam"] = string(payParam)
params["timestamp"] = fmt.Sprintf("%d", time.Now().Unix()*1000)
params["traceId"] = model.UUID4()
params["version"] = d.c.PayConf.Version
params["signType"] = d.c.PayConf.SignType
sign := d.PaySign(params, d.c.PayConf.Token)
params["sign"] = sign
resp := new(
struct {
Code int64 `json:"errno"`
Data *model.PayQrCode `json:"data"`
})
url := d.c.Property.PayCoURL + _createPayQrCode
header := make(map[string]string)
header["Content-Type"] = "application/json"
marshal, _ := json.Marshal(params)
if err = d.doSend(c, url, "127.0.0.1", header, marshal, resp); err != nil {
err = errors.Wrapf(err, "Call pay service(%s)", url+"?"+string(marshal))
return
}
if resp.Code != 0 {
err = fmt.Errorf("Call pay service(%s) error, response code is not 0, resp:%v", url+"?"+string(marshal), resp)
return
}
data = resp.Data
log.Info("Call pay service(%s) successful, resp(%v)", url+"?"+string(marshal), data)
return
}
func (d *Dao) doSend(c context.Context, url, IP string, header map[string]string, marshal []byte, data interface{}) (err error) {
var (
req *http.Request
client = new(http.Client)
resp *http.Response
bs []byte
)
if req, err = http.NewRequest(http.MethodPost, url, strings.NewReader(string(marshal))); err != nil {
err = errors.WithStack(err)
return
}
for k, v := range header {
req.Header.Add(k, v)
}
if resp, err = client.Do(req); err != nil {
err = errors.Wrapf(err, "Call pay service(%s)", url+"?"+string(marshal))
return
}
defer resp.Body.Close()
defer func() {
log.Info("call url:%v params:(%v) result:(%+v) header:(%+v)", url, string(marshal), data, header)
}()
if resp.StatusCode >= http.StatusBadRequest {
err = errors.Errorf("incorrect http status:%d host:%s, url:%s", resp.StatusCode, req.URL.Host, req.URL.String())
return
}
if bs, err = readAll(resp.Body, _minRead); err != nil {
err = errors.Wrapf(err, "host:%s, url:%s", req.URL.Host, req.URL.String())
return
}
if err = json.Unmarshal(bs, data); err != nil {
err = errors.WithStack(err)
return
}
return
}
func (d *Dao) dopay(c context.Context,
urlPath string, ip string, params url.Values, data interface{},
fn func(c context.Context, uri string, ip string, params url.Values, r interface{}) error,
) (err error) {
var (
resp = &BasicResp{}
urlAddr string
)
urlAddr = d.c.Property.PayURL + urlPath
err = fn(c, urlAddr, ip, params, resp)
if err != nil {
err = errors.Wrapf(err, "Call pay service(%s)", urlAddr+"?"+params.Encode())
return
}
if resp.Code != 0 {
err = fmt.Errorf("Call pay service(%s) error, response code is not 0, resp:%v,%v", urlAddr+"?"+params.Encode(), resp, data)
err = errors.WithStack(err)
return
}
data = resp.Data
log.Info("Call pay service(%s) successful, resp: %v", urlAddr+"?"+params.Encode(), resp)
return
}
// PayRecission call pay refund api.
func (d *Dao) PayRecission(c context.Context, params map[string]interface{}, clietIP string) (err error) {
rel := new(struct {
Code int64 `json:"errno"`
Data int64 `json:"msg"`
})
paramsObj := make(map[string]string)
for k, v := range params {
paramsObj[k] = fmt.Sprintf("%v", v)
}
header := make(map[string]string)
header["Content-Type"] = "application/json"
defer func() {
log.Info("url:%v params:%+v return:%+v error(%+v)", d.c.Property.PayURL+_payRescission, paramsObj, rel, err)
}()
success := false
for i := 0; i < _retry; i++ {
if err = d.doPaySend(c, d.c.Property.PayURL, _payRescission, clietIP, nil, header, http.MethodPost, paramsObj, rel, d.PaySignNotDel); err != nil {
log.Error(" dopaysend(url:%v,params:%+v) return(%+v) ", d.c.Property.PayURL+_payRescission, paramsObj, rel)
continue
}
if rel.Code == int64(ecode.OK.Code()) {
success = true
break
}
}
if !success {
err = ecode.VipRescissionErr
}
return
}
// PaySign pay sign.
func (d *Dao) PaySign(params map[string]string, token string) (sign string) {
delete(params, "payChannelId")
delete(params, "payChannel")
delete(params, "accessKey")
delete(params, "sdkVersion")
delete(params, "openId")
delete(params, "sign")
delete(params, "device")
tmp := d.sortParamsKey(params)
var b bytes.Buffer
b.WriteString(tmp)
b.WriteString(fmt.Sprintf("&token=%s", token))
log.Info("pay sign params:(%s) \n", b.String())
mh := md5.Sum(b.Bytes())
// query
sign = hex.EncodeToString(mh[:])
log.Info("pay sign (%v)", sign)
return
}
//PaySignNotDel pay sign not del.
func (d *Dao) PaySignNotDel(params map[string]string, token string) (sign string) {
tmp := d.sortParamsKey(params)
var b bytes.Buffer
b.WriteString(tmp)
b.WriteString(fmt.Sprintf("&token=%s", token))
log.Info("pay sign params:(%s) \n", b.String())
mh := md5.Sum(b.Bytes())
// query
sign = hex.EncodeToString(mh[:])
log.Info("pay sign (%v)", sign)
return
}
func (d *Dao) sortParamsKey(v map[string]string) string {
if v == nil {
return ""
}
var buf bytes.Buffer
keys := make([]string, 0, len(v))
for k := range v {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
vs := v[k]
prefix := k + "="
if buf.Len() > 0 {
buf.WriteByte('&')
}
buf.WriteString(prefix)
buf.WriteString(vs)
}
return buf.String()
}
func (d *Dao) doPaySend(c context.Context, basePath, path, IP string, cookie []*http.Cookie, header map[string]string, method string, params map[string]string, data interface{}, signFn func(params map[string]string, token string) string) (err error) {
var (
req *http.Request
client = new(http.Client)
resp *http.Response
bs []byte
)
url := basePath + path
sign := signFn(params, d.c.PayConf.Token)
params["sign"] = sign
marshal, _ := json.Marshal(params)
if req, err = http.NewRequest(method, url, strings.NewReader(string(marshal))); err != nil {
err = errors.WithStack(err)
return
}
for _, v := range cookie {
req.AddCookie(v)
}
for k, v := range header {
req.Header.Add(k, v)
}
if resp, err = client.Do(req); err != nil {
log.Error("call url:%v params:(%+v)", basePath+path, params)
err = errors.WithStack(err)
return
}
defer resp.Body.Close()
if resp.StatusCode >= http.StatusBadRequest {
err = errors.Errorf("incorrect http status:%d host:%s, url:%s", resp.StatusCode, req.URL.Host, req.URL.String())
return
}
if bs, err = readAll(resp.Body, _minRead); err != nil {
err = errors.Wrapf(err, "host:%s, url:%s", req.URL.Host, req.URL.String())
return
}
if err = json.Unmarshal(bs, data); err != nil {
err = errors.WithStack(err)
return
}
log.Info("call url:%v params:%+v result:%+v", url, params, data)
return
}
func readAll(r io.Reader, capacity int64) (b []byte, err error) {
buf := bytes.NewBuffer(make([]byte, 0, capacity))
// If the buffer overflows, we will get bytes.ErrTooLarge.
// Return that as an error. Any other panic remains.
defer func() {
e := recover()
if e == nil {
return
}
if panicErr, ok := e.(error); ok && panicErr == bytes.ErrTooLarge {
err = panicErr
} else {
panic(e)
}
}()
_, err = buf.ReadFrom(r)
return buf.Bytes(), err
}

View File

@@ -0,0 +1,364 @@
package dao
import (
"bytes"
"context"
"fmt"
"net/http"
"net/url"
"testing"
"go-common/app/service/main/vip/model"
"go-common/library/ecode"
"github.com/smartystreets/goconvey/convey"
"gopkg.in/h2non/gock.v1"
)
func TestDaoproductID(t *testing.T) {
var (
months = int16(1)
)
convey.Convey("productID", t, func(ctx convey.C) {
id := d.productID(months)
ctx.Convey("id should not be nil", func(ctx convey.C) {
ctx.So(id, convey.ShouldEqual, _productMonthID)
})
})
convey.Convey("productID == _productQuarterID", t, func(ctx convey.C) {
months = 3
id := d.productID(months)
ctx.Convey("productID == 61", func(ctx convey.C) {
ctx.So(id, convey.ShouldEqual, 61)
})
})
convey.Convey("productID == _productYearID", t, func(ctx convey.C) {
months = _yearMonths
id := d.productID(months)
ctx.Convey("productID == 61", func(ctx convey.C) {
ctx.So(id, convey.ShouldEqual, _productYearID)
})
})
}
func TestDaoPayWallet(t *testing.T) {
var (
c = context.TODO()
mid = int64(20606508)
ip = ""
data = &model.PayAccountResp{}
)
convey.Convey("PayWallet", t, func(ctx convey.C) {
defer gock.OffAll()
httpMock("POST", _payWallet).Reply(200).JSON(`{"code":0}`)
err := d.PayWallet(c, mid, ip, data)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoPayBanks(t *testing.T) {
var (
c = context.TODO()
ip = ""
data []*model.PayBankResp
)
convey.Convey("PayBanks", t, func(ctx convey.C) {
defer gock.OffAll()
httpMock("GET", _payBanks).Reply(200).JSON(`{"code":0}`)
err := d.PayBanks(c, ip, data)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoAddPayOrder(t *testing.T) {
var (
c = context.TODO()
ip = ""
o = &model.PayOrder{
OrderNo: "201808141642435698853709",
Money: 148,
}
data = &model.AddPayOrderResp{}
)
convey.Convey("AddPayOrder", t, func(ctx convey.C) {
defer gock.OffAll()
httpMock("POST", _addPayOrder).Reply(200).JSON(`{"code":0}`)
err := d.AddPayOrder(c, ip, o, data)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoPaySDK(t *testing.T) {
var (
c = context.TODO()
ip = ""
o = &model.PayOrder{}
data = &model.APIPayOrderResp{}
payCode = ""
)
convey.Convey("PaySDK", t, func(ctx convey.C) {
defer gock.OffAll()
httpMock("POST", _paySDK).Reply(200).JSON(`{"code":0}`)
err := d.PaySDK(c, ip, o, data, payCode)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoPayQrcode(t *testing.T) {
var (
c = context.TODO()
ip = "120.11.188.230"
o = &model.PayOrder{
OrderNo: "2014100120411262876516",
Mid: 4908640,
Money: 148.00,
}
data = &model.APIPayOrderResp{}
payCode = "alipay"
)
convey.Convey("PayQrcode", t, func(ctx convey.C) {
defer gock.OffAll()
httpMock("POST", _payQrcode).Reply(200).JSON(`{"code":0}`)
err := d.PayQrcode(c, ip, o, data, payCode)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoQuickPayToken(t *testing.T) {
var (
c = context.TODO()
ip = ""
accessKey = ""
cookie []*http.Cookie
data = &model.QucikPayResp{}
)
convey.Convey("QuickPayToken", t, func(ctx convey.C) {
defer gock.OffAll()
httpMock("POST", d.c.Property.PayURL+_quickPayToken).Reply(200).JSON(`{"code":0}`)
err := d.QuickPayToken(c, ip, accessKey, cookie, data)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoDoQuickPay(t *testing.T) {
var (
c = context.TODO()
ip = ""
token = ""
thirdTradeNo = ""
data = &model.PayRetResp{}
)
convey.Convey("DoQuickPay", t, func(ctx convey.C) {
defer gock.OffAll()
httpMock("POST", _quickPayDo).Reply(200).JSON(`{"code":0}`)
err := d.DoQuickPay(c, ip, token, thirdTradeNo, data)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoPayCashier(t *testing.T) {
var (
c = context.TODO()
ip = ""
o = &model.PayOrder{}
data = &model.APIPayOrderResp{}
payCode = ""
bankCode = ""
)
convey.Convey("PayCashier", t, func(ctx convey.C) {
defer gock.OffAll()
httpMock("POST", _payCashier).Reply(200).JSON(`{"code":0}`)
err := d.PayCashier(c, ip, o, data, payCode, bankCode)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoPayIapAccess(t *testing.T) {
var (
c = context.TODO()
ip = ""
o = &model.PayOrder{
OrderNo: "123",
AppID: 1,
Platform: 1,
OrderType: 1,
AppSubID: "456",
Mid: 20606508,
ToMid: 20606509,
BuyMonths: 1,
Money: 3.0,
Status: 1,
PayType: 1,
RechargeBp: 1.0,
ThirdTradeNo: "123",
Ver: 1,
}
data = &model.APIPayOrderResp{}
productID = "123"
)
convey.Convey("PayIapAccess", t, func(ctx convey.C) {
defer gock.OffAll()
httpMock("POST", _payIapAccess).Reply(200).JSON(`{"code":0}`)
err := d.PayIapAccess(c, ip, o, data, productID)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoPayClose(t *testing.T) {
var (
c = context.TODO()
orderNO = "123456"
ip = "127.0.0.1"
)
convey.Convey("PayClose", t, func(ctx convey.C) {
defer gock.OffAll()
httpMock("POST", d.payCloseURL).Reply(200).JSON(`{"code":0}`)
_, err := d.PayClose(c, orderNO, ip)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaodopay(t *testing.T) {
var (
c = context.TODO()
urlPath = _payWallet
ip = "172.18.35.12"
params = url.Values{}
data = &model.PayAccountResp{}
mid = int64(20606508)
)
convey.Convey("dopay", t, func(ctx convey.C) {
params.Add("mid", fmt.Sprintf("%d", mid))
defer gock.OffAll()
httpMock("POST", _payWallet).Reply(200).JSON(`{"code":0}`)
err := d.dopay(c, urlPath, ip, params, data, d.client.Post)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoPayRecission(t *testing.T) {
var (
c = context.TODO()
params map[string]interface{}
clietIP = ""
)
convey.Convey("PayRecission", t, func(ctx convey.C) {
defer gock.OffAll()
httpMock("POST", _payWallet).Reply(200).JSON(`{"code":0}`)
err := d.PayRecission(c, params, clietIP)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldEqual, ecode.VipRescissionErr)
})
})
}
func TestDaoPaySign(t *testing.T) {
var (
params map[string]string
token = ""
)
convey.Convey("PaySign", t, func(ctx convey.C) {
sign := d.PaySign(params, token)
ctx.Convey("sign should not be nil", func(ctx convey.C) {
ctx.So(sign, convey.ShouldNotBeNil)
})
})
}
func TestDaoPaySignNotDel(t *testing.T) {
var (
params map[string]string
token = ""
)
convey.Convey("PaySignNotDel", t, func(ctx convey.C) {
sign := d.PaySignNotDel(params, token)
ctx.Convey("sign should not be nil", func(ctx convey.C) {
ctx.So(sign, convey.ShouldNotBeNil)
})
})
}
func TestDaosortParamsKey(t *testing.T) {
var (
v map[string]string
)
convey.Convey("sortParamsKey", t, func(ctx convey.C) {
p1 := d.sortParamsKey(v)
ctx.Convey("p1 should not be nil", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
}
func TestDaodoPaySend(t *testing.T) {
var (
c = context.TODO()
basePath = d.c.Property.PayURL
path = _quickPayToken
IP = ""
cookie []*http.Cookie
header map[string]string
method = http.MethodPost
params = map[string]string{"name": "vip"}
data = new(struct {
Code int64 `json:"errno"`
Data int64 `json:"msg"`
})
)
convey.Convey("doPaySend", t, func(ctx convey.C) {
defer gock.OffAll()
httpMock("POST", basePath+path).Reply(200).JSON(`{"code":0}`)
err := d.doPaySend(c, basePath, path, IP, cookie, header, method, params, data, d.PaySign)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoreadAll(t *testing.T) {
var (
r = bytes.NewReader([]byte{})
capacity = int64(0)
)
convey.Convey("readAll", t, func(ctx convey.C) {
b, err := readAll(r, capacity)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
ctx.Convey("b should not be nil", func(ctx convey.C) {
ctx.So(b, convey.ShouldNotBeNil)
})
})
}
// go test -test.v -test.run TestDaoPayClose
func TestDaoPayQrCode(t *testing.T) {
convey.Convey("TestDaoPayQrCode", t, func() {
res, err := d.PayQrCode(context.TODO(), 1, "1", make(map[string]interface{}))
convey.So(err, convey.ShouldBeNil)
convey.So(res, convey.ShouldNotBeNil)
})
}

View File

@@ -0,0 +1,52 @@
package dao
import (
"context"
"go-common/app/service/main/vip/model"
xsql "go-common/library/database/sql"
"github.com/pkg/errors"
)
const (
_platformAll = "SELECT id,platform_name,platform,device,mobi_app,panel_type FROM vip_platform_config WHERE is_del=0 ORDER BY id"
_platformByID = "SELECT id,platform_name,platform,device,mobi_app,panel_type FROM vip_platform_config WHERE id =?;"
)
// PlatformAll .
func (d *Dao) PlatformAll(c context.Context) (res []*model.ConfPlatform, err error) {
var rows *xsql.Rows
if rows, err = d.db.Query(c, _platformAll); err != nil {
err = errors.WithStack(err)
return
}
defer rows.Close()
res = make([]*model.ConfPlatform, 0)
for rows.Next() {
r := new(model.ConfPlatform)
if err = rows.Scan(&r.ID, &r.PlatformName, &r.Platform, &r.Device, &r.MobiApp, &r.PanelType); err != nil {
err = errors.WithStack(err)
res = nil
return
}
res = append(res, r)
}
err = rows.Err()
return
}
//PlatformByID get info by open id.
func (d *Dao) PlatformByID(c context.Context, id int64) (r *model.ConfPlatform, err error) {
r = new(model.ConfPlatform)
if err = d.db.QueryRow(c, _platformByID, id).
Scan(&r.ID, &r.PlatformName, &r.Platform, &r.Device, &r.MobiApp, &r.PanelType); err != nil {
if err == xsql.ErrNoRows {
r = nil
err = nil
return
}
err = errors.Wrapf(err, "dao platform by id(%d)", id)
}
return
}

View File

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

View File

@@ -0,0 +1,51 @@
package dao
import (
"context"
"go-common/app/service/main/vip/model"
"go-common/library/database/sql"
"github.com/pkg/errors"
)
const (
_allPointExchangePriceSQL = "SELECT origin_point,current_point,month,promotion_tip,promotion_color FROM vip_point_exchange_price"
_pointExchangePriceSQL = "SELECT origin_point,current_point,month,promotion_tip,promotion_color FROM vip_point_exchange_price WHERE month = ?"
)
//AllPointExchangePrice .
func (d *Dao) AllPointExchangePrice(c context.Context) (pe []*model.PointExchangePrice, err error) {
var rows *sql.Rows
if rows, err = d.db.Query(c, _allPointExchangePriceSQL); err != nil {
err = errors.WithStack(err)
return
}
defer rows.Close()
for rows.Next() {
r := new(model.PointExchangePrice)
if err = rows.Scan(&r.OriginPoint, &r.CurrentPoint, &r.Month, &r.PromotionTip, &r.PromotionColor); err != nil {
pe = nil
err = errors.WithStack(err)
d.errProm.Incr("row_scan_db")
}
pe = append(pe, r)
}
return
}
//PointExchangePrice def.
func (d *Dao) PointExchangePrice(c context.Context, month int16) (pe *model.PointExchangePrice, err error) {
row := d.db.QueryRow(c, _pointExchangePriceSQL, month)
pe = new(model.PointExchangePrice)
if err = row.Scan(&pe.OriginPoint, &pe.CurrentPoint, &pe.Month, &pe.PromotionTip, &pe.PromotionColor); err != nil {
if err == sql.ErrNoRows {
pe = nil
err = nil
} else {
err = errors.Wrapf(err, "scan error")
}
}
return
}

View File

@@ -0,0 +1,36 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoAllPointExchangePrice(t *testing.T) {
var (
c = context.TODO()
)
convey.Convey("AllPointExchangePrice", t, func(ctx convey.C) {
pe, err := d.AllPointExchangePrice(c)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
ctx.Convey("pe should not be nil", func(ctx convey.C) {
ctx.So(pe, convey.ShouldNotBeNil)
})
})
}
func TestDaoPointExchangePrice(t *testing.T) {
var (
c = context.TODO()
month = int16(0)
)
convey.Convey("PointExchangePrice", t, func(ctx convey.C) {
_, err := d.PointExchangePrice(c, month)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}

View File

@@ -0,0 +1,57 @@
package dao
import (
"context"
"go-common/app/service/main/vip/model"
"go-common/library/database/sql"
"github.com/pkg/errors"
)
const (
privilegeListSQL = "SELECT id, privileges_name, title, explains, privileges_type, operator, state, deleted, icon_url, icon_gray_url, order_num, lang_type, ctime, mtime FROM vip_privileges WHERE deleted = 0 AND state = 1 ORDER BY order_num;"
privilegeResourcesListSQL = "SELECT id,pid,link,image_url,resources_type,ctime,mtime FROM vip_privileges_resources;"
)
// PrivilegeList query .
func (d *Dao) PrivilegeList(c context.Context) (res []*model.Privilege, err error) {
var rows *sql.Rows
if rows, err = d.db.Query(c, privilegeListSQL); err != nil {
err = errors.WithStack(err)
return
}
defer rows.Close()
for rows.Next() {
r := new(model.Privilege)
if err = rows.Scan(&r.ID, &r.Name, &r.Title, &r.Explain, &r.Type, &r.Operator, &r.State, &r.Deleted, &r.IconURL, &r.IconGrayURL, &r.Order, &r.LangType, &r.Ctime, &r.Mtime); err != nil {
err = errors.WithStack(err)
res = nil
return
}
res = append(res, r)
}
err = rows.Err()
return
}
// PrivilegeResourcesList query privilege resources .
func (d *Dao) PrivilegeResourcesList(c context.Context) (res []*model.PrivilegeResources, err error) {
var rows *sql.Rows
if rows, err = d.db.Query(c, privilegeResourcesListSQL); err != nil {
err = errors.WithStack(err)
return
}
defer rows.Close()
for rows.Next() {
r := new(model.PrivilegeResources)
if err = rows.Scan(&r.ID, &r.PID, &r.Link, &r.ImageURL, &r.Type, &r.Ctime, &r.Mtime); err != nil {
err = errors.WithStack(err)
res = nil
return
}
res = append(res, r)
}
err = rows.Err()
return
}

View File

@@ -0,0 +1,36 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
// go test -test.v -test.run TestDaoPrivilegeList
func TestDaoPrivilegeList(t *testing.T) {
var (
c = context.TODO()
)
convey.Convey("PrivilegeList", t, func(ctx convey.C) {
res, err := d.PrivilegeList(c)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
ctx.Convey("res should not be nil", func(ctx convey.C) {
ctx.So(res, convey.ShouldNotBeNil)
})
})
}
func TestDaoPrivilegeResourcesList(t *testing.T) {
var (
c = context.TODO()
)
convey.Convey("PrivilegeResourcesList", t, func(ctx convey.C) {
_, err := d.PrivilegeResourcesList(c)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}

View File

@@ -0,0 +1,71 @@
package dao
import (
"context"
"fmt"
"go-common/library/cache/redis"
"github.com/pkg/errors"
)
const (
_frozenDelayQueue = "fdq"
_accLogin = "al:%d"
)
func accLoginKey(mid int64) string {
return fmt.Sprintf(_accLogin, mid)
}
// RemQueue del a frozen user from redis sortset queue
func (d *Dao) RemQueue(c context.Context, mid int64) (err error) {
var (
conn = d.redis.Get(c)
)
defer conn.Close()
if _, err = conn.Do("ZREM", _frozenDelayQueue, mid); err != nil {
err = errors.Wrap(err, "redis do zrem err")
return
}
return
}
//DelRedisCache del redis cache.
func (d *Dao) DelRedisCache(c context.Context, mid int64) (err error) {
var (
conn = d.redis.Get(c)
key = accLoginKey(mid)
)
defer conn.Close()
if _, err = conn.Do("DEL", key); err != nil {
err = errors.WithStack(err)
return
}
return
}
// LoginCount get user recent loggin count
func (d *Dao) LoginCount(c context.Context, mid int64) (count int64, err error) {
var conn = d.redis.Get(c)
defer conn.Close()
if count, err = redis.Int64(conn.Do("SCARD", accLoginKey(mid))); err != nil {
err = errors.Wrap(err, "redis send zcard err(%+v)")
}
return
}
//FrozenTime get user frozen time
func (d *Dao) FrozenTime(c context.Context, mid int64) (frozenTime int64, err error) {
var conn = d.redis.Get(c)
defer conn.Close()
if frozenTime, err = redis.Int64(conn.Do("ZSCORE", _frozenDelayQueue, mid)); err != nil {
if err == redis.ErrNil {
err = nil
return
}
err = errors.WithStack(err)
return
}
return
}

View File

@@ -0,0 +1,85 @@
package dao
import (
"context"
"fmt"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoaccLoginKey(t *testing.T) {
convey.Convey("accLoginKey", t, func(ctx convey.C) {
var (
mid = int64(1)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
p1 := accLoginKey(mid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldContainSubstring, fmt.Sprintf(_accLogin, mid))
})
})
})
}
func TestDaoRemQueue(t *testing.T) {
convey.Convey("RemQueue", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(1)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
err := d.RemQueue(c, mid)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoDelRedisCache(t *testing.T) {
convey.Convey("DelRedisCache", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(1)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
err := d.DelRedisCache(c, mid)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoLoginCount(t *testing.T) {
convey.Convey("LoginCount", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(1)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
count, err := d.LoginCount(c, mid)
ctx.Convey("Then err should be nil.count should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(count, convey.ShouldBeGreaterThanOrEqualTo, 0)
})
})
})
}
func TestDaoFrozenTime(t *testing.T) {
convey.Convey("FrozenTime", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(1)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
frozenTime, err := d.FrozenTime(c, mid)
ctx.Convey("Then err should be nil.frozenTime should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(frozenTime, convey.ShouldBeGreaterThanOrEqualTo, 0)
})
})
})
}

View File

@@ -0,0 +1,326 @@
package dao
import (
"context"
xsql "database/sql"
"fmt"
"strings"
"go-common/app/service/main/vip/model"
"go-common/library/database/sql"
"go-common/library/time"
"go-common/library/xstr"
"github.com/pkg/errors"
)
const (
_defaultsize = 10000
)
//SelNewResourcePool select new resource pool by id
func (d *Dao) SelNewResourcePool(c context.Context, id int64) (r *model.VipResourcePool, err error) {
var row = d.db.QueryRow(c, _selResourcePoolByIDSQL, id)
r = new(model.VipResourcePool)
if err = row.Scan(&r.ID, &r.PoolName, &r.BusinessID, &r.Reason, &r.CodeExpireTime, &r.StartTime, &r.EndTime, &r.Contacts, &r.ContactsNumber, &r.Ctime, &r.Mtime); err != nil {
if err == sql.ErrNoRows {
r = nil
err = nil
} else {
err = errors.WithStack(err)
d.errProm.Incr("row_scan_db")
return
}
}
return
}
//SelNewBusiness select newdb businessInfo by id.
func (d *Dao) SelNewBusiness(c context.Context, id int64) (r *model.VipBusinessInfo, err error) {
var row = d.db.QueryRow(c, _selBusinessByIDSQL, id)
r = new(model.VipBusinessInfo)
if err = row.Scan(&r.ID, &r.BusinessName, &r.BusinessType, &r.Status, &r.AppKey, &r.Secret, &r.Contacts, &r.ContactsNumber, &r.Ctime, &r.Mtime); err != nil {
if err == sql.ErrNoRows {
err = nil
r = nil
} else {
err = errors.WithStack(err)
d.errProm.Incr("row_scan_db")
}
}
return
}
//SelNewBusinessByAppkey select newdb businessInfo by id.
func (d *Dao) SelNewBusinessByAppkey(c context.Context, appkey string) (r *model.VipBusinessInfo, err error) {
var row = d.db.QueryRow(c, _selBusinessByAppkeySQL, appkey)
r = new(model.VipBusinessInfo)
if err = row.Scan(&r.ID, &r.BusinessName, &r.BusinessType, &r.Status, &r.AppKey, &r.Secret, &r.Contacts, &r.ContactsNumber, &r.Ctime, &r.Mtime); err != nil {
if err == sql.ErrNoRows {
err = nil
r = nil
} else {
err = errors.WithStack(err)
d.errProm.Incr("row_scan_db")
}
}
return
}
//SelCode sel code.
func (d *Dao) SelCode(c context.Context, codeStr string) (code *model.VipResourceCode, err error) {
row := d.db.QueryRow(c, _selCodeSQL, codeStr)
code = new(model.VipResourceCode)
if err = row.Scan(&code.ID, &code.BatchCodeID, &code.Status, &code.Code, &code.Mid, &code.UseTime, &code.RelationID); err != nil {
if sql.ErrNoRows == err {
c = nil
err = nil
return
}
err = errors.WithStack(err)
d.errProm.Incr("db_scan")
return
}
return
}
//SelCodes sel codes
func (d *Dao) SelCodes(c context.Context, codes []string) (cs []*model.VipResourceCode, err error) {
var (
rows *sql.Rows
)
if len(codes) <= 0 {
return
}
if rows, err = d.db.Query(c, fmt.Sprintf(_selCodesSQL, strings.Join(codes, "','"))); err != nil {
err = errors.WithStack(err)
return
}
defer rows.Close()
for rows.Next() {
code := new(model.VipResourceCode)
if err = rows.Scan(&code.ID, &code.BatchCodeID, &code.Status, &code.Code, &code.Mid, &code.UseTime, &code.RelationID); err != nil {
if sql.ErrNoRows == err {
c = nil
err = nil
return
}
err = errors.WithStack(err)
d.errProm.Incr("db_scan")
return
}
cs = append(cs, code)
}
err = rows.Err()
return
}
// SelBatchCode set batch code.
func (d *Dao) SelBatchCode(c context.Context, id int64) (bc *model.VipResourceBatchCode, err error) {
row := d.db.QueryRow(c, _selBatchCodeSQL, id)
bc = new(model.VipResourceBatchCode)
if err = row.Scan(&bc.ID, &bc.BusinessID, &bc.PoolID, &bc.Status, &bc.BatchName, &bc.Reason, &bc.Unit, &bc.Count, &bc.SurplusCount, &bc.Price, &bc.StartTime, &bc.EndTime, &bc.Type, &bc.LimitDay, &bc.MaxCount); err != nil {
if sql.ErrNoRows == err {
bc = nil
err = nil
return
}
err = errors.WithStack(err)
d.errProm.Incr("db_scan")
return
}
return
}
//SelBatchCodes sel batchcodes
func (d *Dao) SelBatchCodes(c context.Context, ids []int64) (bcs []*model.VipResourceBatchCode, err error) {
var (
rows *sql.Rows
)
if len(ids) <= 0 {
return
}
if rows, err = d.db.Query(c, fmt.Sprintf(_selBatchCodesSQL, xstr.JoinInts(ids))); err != nil {
err = errors.WithStack(err)
return
}
defer rows.Close()
for rows.Next() {
bc := new(model.VipResourceBatchCode)
if err = rows.Scan(&bc.ID, &bc.BusinessID, &bc.PoolID, &bc.Status, &bc.BatchName, &bc.Reason, &bc.Unit, &bc.Count, &bc.SurplusCount, &bc.Price, &bc.StartTime, &bc.EndTime, &bc.Type, &bc.LimitDay, &bc.MaxCount); err != nil {
if sql.ErrNoRows == err {
bc = nil
err = nil
return
}
err = errors.WithStack(err)
d.errProm.Incr("db_scan")
return
}
bcs = append(bcs, bc)
}
err = rows.Err()
return
}
// SelBatchCodesByBisID set batch codes by business id.
func (d *Dao) SelBatchCodesByBisID(c context.Context, bisID int64) (bcs []*model.VipResourceBatchCode, err error) {
var rows *sql.Rows
if rows, err = d.db.Query(c, _selBatchCodeByBisSQL, bisID); err != nil {
err = errors.WithStack(err)
return
}
defer rows.Close()
for rows.Next() {
bc := new(model.VipResourceBatchCode)
if err = rows.Scan(&bc.ID, &bc.BusinessID, &bc.PoolID, &bc.Status, &bc.BatchName, &bc.Reason, &bc.Unit, &bc.Count, &bc.SurplusCount, &bc.Price, &bc.StartTime, &bc.EndTime, &bc.Type, &bc.LimitDay, &bc.MaxCount); err != nil {
if sql.ErrNoRows == err {
bc = nil
err = nil
return
}
err = errors.WithStack(err)
d.errProm.Incr("db_scan")
return
}
bcs = append(bcs, bc)
}
err = rows.Err()
return
}
// SelCodeOpened set code open.
func (d *Dao) SelCodeOpened(c context.Context, bisIDs []int64, arg *model.ArgCodeOpened) (cs []*model.CodeInfoResp, err error) {
var rows *sql.Rows
size := d.c.Property.CodeOpenedSearchSize
if size == 0 {
size = _defaultsize
}
if rows, err = d.db.Query(c, fmt.Sprintf(_selCodeOpenedSQL, xstr.JoinInts(bisIDs), arg.Cursor, arg.StartTime.Time().Format("2006-01-02 15:04:05"), arg.EndTime.Time().Format("2006-01-02 15:04:05"), size)); err != nil {
err = errors.WithStack(err)
return
}
defer rows.Close()
for rows.Next() {
code := new(model.CodeInfoResp)
if err = rows.Scan(&code.ID, &code.Code, &code.UserTime); err != nil {
if sql.ErrNoRows == err {
c = nil
err = nil
return
}
err = errors.WithStack(err)
d.errProm.Incr("db_scan")
return
}
cs = append(cs, code)
}
err = rows.Err()
return
}
//TxUpdateCode tx update code.
func (d *Dao) TxUpdateCode(tx *sql.Tx, id int64, mid int64, useTime time.Time) (eff int64, err error) {
var result xsql.Result
if result, err = tx.Exec(_updateCodeSQL, mid, useTime, id); err != nil {
err = errors.WithStack(err)
d.errProm.Incr("db_update")
return
}
if eff, err = result.RowsAffected(); err != nil {
err = errors.WithStack(err)
d.errProm.Incr("db_row_affected")
return
}
return
}
//TxUpdateCodeStatus tx update code status.
func (d *Dao) TxUpdateCodeStatus(tx *sql.Tx, id int64, status int8) (eff int64, err error) {
var result xsql.Result
if result, err = tx.Exec(_updateCodeStatusSQL, status, id); err != nil {
err = errors.WithStack(err)
d.errProm.Incr("db_update")
return
}
if eff, err = result.RowsAffected(); err != nil {
err = errors.WithStack(err)
d.errProm.Incr("db_row_affected")
return
}
return
}
//TxUpdateBatchCode tx update batch code.
func (d *Dao) TxUpdateBatchCode(tx *sql.Tx, id int64, sc int32) (eff int64, err error) {
var result xsql.Result
if result, err = tx.Exec(_updateBatchCodeSQL, sc, id); err != nil {
err = errors.WithStack(err)
d.errProm.Incr("db_batch_code")
return
}
if eff, err = result.RowsAffected(); err != nil {
err = errors.WithStack(err)
d.errProm.Incr("db_row_affected")
return
}
return
}
//SelCodesByBMid sel codes by bmid
func (d *Dao) SelCodesByBMid(c context.Context, mid int64) (cs []string, err error) {
var rows *sql.Rows
if rows, err = d.db.Query(c, _selCodesByBmidSQL, mid); err != nil {
err = errors.WithStack(err)
d.errProm.Incr("db_query")
return
}
defer rows.Close()
for rows.Next() {
var r string
if err = rows.Scan(&r); err != nil {
if err == sql.ErrNoRows {
err = nil
return
}
err = errors.WithStack(err)
d.errProm.Incr("db_rows_scan")
return
}
cs = append(cs, r)
}
err = rows.Err()
return
}
//SelActives sel active data.
func (d *Dao) SelActives(c context.Context, relations []string) (rep []*model.VipActiveShow, err error) {
if len(relations) <= 0 {
return
}
var rows *sql.Rows
if rows, err = d.db.Query(c, fmt.Sprintf(_selActiveSQL, strings.Join(relations, "','"))); err != nil {
err = errors.WithStack(err)
return
}
defer rows.Close()
for rows.Next() {
r := new(model.VipActiveShow)
if err = rows.Scan(&r.ID, &r.Type, &r.ProductName, &r.ProductPic, &r.RelationID, &r.BusID, &r.ProductDetail, &r.UseType); err != nil {
err = errors.WithStack(err)
return
}
rep = append(rep, r)
}
err = rows.Err()
return
}
//SelBatchCount sel batch count
func (d *Dao) SelBatchCount(c context.Context, batchCodeID, mid int64) (count int64, err error) {
row := d.db.QueryRow(c, _selBatchCountSQL, mid, batchCodeID)
if err = row.Scan(&count); err != nil {
err = errors.WithStack(err)
}
return
}

View File

@@ -0,0 +1,244 @@
package dao
import (
"context"
"testing"
"time"
"go-common/app/service/main/vip/model"
xtime "go-common/library/time"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoSelNewResourcePool(t *testing.T) {
var (
c = context.TODO()
id = int64(0)
)
convey.Convey("SelNewResourcePool", t, func(ctx convey.C) {
_, err := d.SelNewResourcePool(c, id)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoSelNewBusiness(t *testing.T) {
var (
c = context.TODO()
id = int64(0)
)
convey.Convey("SelNewBusiness", t, func(ctx convey.C) {
_, err := d.SelNewBusiness(c, id)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoSelNewBusinessByAppkey(t *testing.T) {
var (
c = context.TODO()
appkey = ""
)
convey.Convey("SelNewBusinessByAppkey", t, func(ctx convey.C) {
_, err := d.SelNewBusinessByAppkey(c, appkey)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoSelCode(t *testing.T) {
var (
c = context.TODO()
codeStr = ""
)
convey.Convey("SelCode", t, func(ctx convey.C) {
code, err := d.SelCode(c, codeStr)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
ctx.Convey("code should not be nil", func(ctx convey.C) {
ctx.So(code, convey.ShouldNotBeNil)
})
})
}
func TestDaoSelCodes(t *testing.T) {
var (
c = context.TODO()
codes []string
)
convey.Convey("SelCodes", t, func(ctx convey.C) {
_, err := d.SelCodes(c, codes)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoSelBatchCode(t *testing.T) {
var (
c = context.TODO()
id = int64(0)
)
convey.Convey("SelBatchCode", t, func(ctx convey.C) {
_, err := d.SelBatchCode(c, id)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoSelBatchCodes(t *testing.T) {
var (
c = context.TODO()
ids []int64
)
convey.Convey("SelBatchCodes", t, func(ctx convey.C) {
_, err := d.SelBatchCodes(c, ids)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoSelBatchCodesByBisID(t *testing.T) {
var (
c = context.TODO()
bisID = int64(0)
)
convey.Convey("SelBatchCodesByBisID", t, func(ctx convey.C) {
_, err := d.SelBatchCodesByBisID(c, bisID)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoSelCodeOpened(t *testing.T) {
var (
c = context.TODO()
bisIDs = []int64{1}
arg = &model.ArgCodeOpened{}
)
convey.Convey("SelCodeOpened", t, func(ctx convey.C) {
_, err := d.SelCodeOpened(c, bisIDs, arg)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoTxUpdateCode(t *testing.T) {
var (
c = context.TODO()
id = int64(0)
mid = int64(0)
useTime = xtime.Time(time.Now().Unix())
)
convey.Convey("TxUpdateCode", t, func(ctx convey.C) {
tx, err := d.StartTx(c)
ctx.Convey("Tx Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
defer tx.Commit()
eff, err := d.TxUpdateCode(tx, id, mid, useTime)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
ctx.Convey("eff should not be nil", func(ctx convey.C) {
ctx.So(eff, convey.ShouldNotBeNil)
})
})
}
func TestDaoTxUpdateCodeStatus(t *testing.T) {
var (
c = context.TODO()
id = int64(0)
status = int8(0)
)
convey.Convey("TxUpdateCodeStatus", t, func(ctx convey.C) {
tx, err := d.StartTx(c)
ctx.Convey("Tx Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
defer tx.Commit()
eff, err := d.TxUpdateCodeStatus(tx, id, status)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
ctx.Convey("eff should not be nil", func(ctx convey.C) {
ctx.So(eff, convey.ShouldNotBeNil)
})
})
}
func TestDaoTxUpdateBatchCode(t *testing.T) {
var (
c = context.TODO()
id = int64(0)
sc = int32(0)
)
convey.Convey("TxUpdateBatchCode", t, func(ctx convey.C) {
tx, err := d.StartTx(c)
ctx.Convey("Tx Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
defer tx.Commit()
eff, err := d.TxUpdateBatchCode(tx, id, sc)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
ctx.Convey("eff should not be nil", func(ctx convey.C) {
ctx.So(eff, convey.ShouldNotBeNil)
})
})
}
func TestDaoSelCodesByBMid(t *testing.T) {
var (
c = context.TODO()
mid = int64(0)
)
convey.Convey("SelCodesByBMid", t, func(ctx convey.C) {
cs, err := d.SelCodesByBMid(c, mid)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
ctx.Convey("cs should not be nil", func(ctx convey.C) {
ctx.So(cs, convey.ShouldNotBeNil)
})
})
}
func TestDaoSelActives(t *testing.T) {
var (
c = context.TODO()
relations []string
)
convey.Convey("SelActives", t, func(ctx convey.C) {
_, err := d.SelActives(c, relations)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoSelBatchCount(t *testing.T) {
var (
c = context.TODO()
batchCodeID int64 = 1
mid int64 = 1001
)
convey.Convey("sel batch count", t, func(ctx convey.C) {
_, err := d.SelBatchCount(c, batchCodeID, mid)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}

View File

@@ -0,0 +1,33 @@
package dao
import (
"context"
"go-common/app/service/main/vip/model"
"go-common/library/database/sql"
"github.com/pkg/errors"
)
const (
_allTips = "SELECT `id`,`platform`,`version`,`tip`,`link`,`start_time`,`end_time`,`level`,`judge_type`,`operator`,`deleted`, `position`,`ctime`,`mtime`FROM `vip_tips` WHERE `deleted` = 0 AND `start_time` < ? AND `end_time`> ?;"
)
//AllTips all tips.
func (d *Dao) AllTips(c context.Context, now int64) (rs []*model.Tips, err error) {
var rows *sql.Rows
if rows, err = d.db.Query(c, _allTips, now, now); err != nil {
err = errors.WithStack(err)
return
}
defer rows.Close()
for rows.Next() {
r := new(model.Tips)
if err = rows.Scan(&r.ID, &r.Platform, &r.Version, &r.Tip, &r.Link, &r.StartTime, &r.EndTime, &r.Level, &r.JudgeType, &r.Operator, &r.Deleted, &r.Position, &r.Ctime, &r.Mtime); err != nil {
rs = nil
err = errors.WithStack(err)
}
rs = append(rs, r)
}
return
}

View File

@@ -0,0 +1,22 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoAllTips(t *testing.T) {
var (
c = context.TODO()
now = int64(20)
)
convey.Convey("AllTips", t, func(ctx convey.C) {
_, err := d.AllTips(c, now)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}

View File

@@ -0,0 +1,321 @@
package dao
import (
"context"
xsql "database/sql"
"fmt"
"go-common/app/service/main/vip/model"
"go-common/library/database/sql"
"go-common/library/time"
"github.com/pkg/errors"
)
const (
_vipUserInfoByMid = "SELECT id,mid,vip_type,vip_pay_type,vip_status,pay_channel_id,vip_start_time,vip_overdue_time,annual_vip_overdue_time,ctime,mtime,vip_recent_time,ios_overdue_time,ver FROM vip_user_info WHERE mid = ?;"
_updateVipStatusTypeSQL = "UPDATE `vip_user_info` SET `vip_status`=? AND `vip_type`=? WHERE `mid`=? ;"
_vipChangeHistorySQL = "SELECT id,mid,change_type,change_time,days,operator_id,relation_id,batch_id,remark FROM vip_user_change_history WHERE mid=? ORDER BY change_time DESC"
_changeHistoryCountSQL = "SELECT COUNT(1) FROM vip_user_change_history WHERE mid=?"
_updateChannelIDSQL = "UPDATE vip_user_info SET pay_channel_id=?,ver=? WHERE mid=? AND ver=?"
_dupUserDiscountSQL = "INSERT INTO vip_user_discount_history(mid,discount_id,order_no,status) VALUES(?,?,?,?) ON DUPLICATE KEY UPDATE order_no= VALUES(order_no) ,status = VALUES(status);"
_updatePayTypeSQL = "UPDATE vip_user_info SET vip_pay_type = ?,ver=? WHERE mid =? AND ver=?"
_selVipChangeHistoryByRelationIDSQL = "SELECT id,mid,change_type,change_time,days,operator_id,relation_id,batch_id,remark,ctime FROM vip_user_change_history WHERE relation_id=?"
_InsertVipChangeHistory = "INSERT INTO vip_user_change_history(mid,change_type,change_time,days,operator_id,relation_id,batch_id,remark,batch_code_id) VALUES(?,?,?,?,?,?,?,?,?)"
_SelVipUserInfoByMid = "SELECT id,mid,vip_type,vip_pay_type,vip_status,ver,vip_start_time,vip_overdue_time,annual_vip_overdue_time,ctime,mtime,vip_recent_time,ios_overdue_time FROM vip_user_info WHERE mid = ?"
_InsertVipUserInfo = "INSERT INTO vip_user_info(mid,vip_type,vip_pay_type,vip_status,vip_start_time,vip_overdue_time,annual_vip_overdue_time,vip_recent_time) VALUES(?,?,?,?,?,?,?,?)"
_addIosVipUserInfo = "INSERT INTO vip_user_info(mid,vip_type,vip_status,vip_start_time,ios_overdue_time) VALUES(?,?,?,?,?)"
_UpdateVipUserInfoByID = "UPDATE vip_user_info SET vip_type=?,vip_pay_type=?,vip_status=?,vip_overdue_time=?,annual_vip_overdue_time=?,vip_recent_time=?,ver=? WHERE mid=? AND ver=?"
_updateIosUserInfoSQL = "UPDATE vip_user_info SET ios_overdue_time=? WHERE mid = ?"
_updateIosRenewUserInfoSQL = "UPDATE vip_user_info SET vip_pay_type=?,ver=?,pay_channel_id=? WHERE mid = ? AND ver=?"
_addUserDiscount = "INSERT IGNORE INTO vip_user_discount_history(mid,discount_id,order_no,status) VALUES(?,?,?,?)"
//refund
_oldUpdateVipUserInfoByID = "UPDATE vip_user_info SET vip_type=?,vip_status=?,vip_overdue_time=?,annual_vip_overdue_time=?,ver=? WHERE id=? AND ver=?"
_oldSelVipUserInfoByMid = "SELECT id,mid,vip_type,vip_status,ver,vip_start_time,vip_overdue_time,annual_vip_overdue_time,vip_recent_time,ios_overdue_time FROM vip_user_info WHERE mid = ?"
_oldAddVipChangeHistory = "INSERT INTO vip_change_history(mid,change_type,change_time,days,operator_id,relation_id,batch_id,remark,batch_code_id) VALUES(?,?,?,?,?,?,?,?,?)"
//sync
_syncAddUser = "INSERT INTO vip_user_info(mid,vip_type,vip_pay_type,vip_status,vip_start_time,vip_overdue_time,annual_vip_overdue_time,vip_recent_time,ios_overdue_time,pay_channel_id,ver) VALUES(?,?,?,?,?,?,?,?,?,?,?)"
_syncUpdateUser = "UPDATE vip_user_info SET vip_type=?,vip_pay_type=?,vip_status=?,vip_overdue_time=?,annual_vip_overdue_time=?,vip_recent_time=?,ios_overdue_time=?,pay_channel_id=?,ver=? WHERE mid=? AND ver=?"
//clean job cache
_cleanjobSQL = "UPDATE vip_user_info SET ver = ver + 1 WHERE mid=?"
)
//VipInfo select user info by mid.
func (d *Dao) VipInfo(c context.Context, mid int64) (r *model.VipInfoDB, err error) {
var row = d.db.QueryRow(c, _vipUserInfoByMid, mid)
r = new(model.VipInfoDB)
if err = row.Scan(&r.ID, &r.Mid, &r.VipType, &r.VipPayType, &r.VipStatus, &r.PayChannelID, &r.VipStartTime, &r.VipOverdueTime, &r.AnnualVipOverdueTime,
&r.Ctime, &r.Mtime, &r.VipRecentTime, &r.IosOverdueTime, &r.Ver); err != nil {
if err == sql.ErrNoRows {
r = nil
err = nil
} else {
err = errors.WithStack(err)
d.errProm.Incr("row_scan_db")
}
}
return
}
// UpdateVipTypeAndStatus update vip type and status.
func (d *Dao) UpdateVipTypeAndStatus(c context.Context, mid int64, vipStatus int32, vipType int32) (ret int64, err error) {
var res xsql.Result
if res, err = d.db.Exec(c, _updateVipStatusTypeSQL, vipStatus, vipType, mid); err != nil {
err = errors.WithStack(err)
d.errProm.Incr("exec_db")
return
}
return res.RowsAffected()
}
//SelChangeHistoryCount .
func (d *Dao) SelChangeHistoryCount(c context.Context, arg *model.ArgChangeHistory) (count int64, err error) {
row := d.db.QueryRow(c, _changeHistoryCountSQL, arg.Mid)
if err = row.Scan(&count); err != nil {
if sql.ErrNoRows == err {
err = nil
count = 0
}
err = errors.WithStack(err)
}
return
}
//SelChangeHistory .
func (d *Dao) SelChangeHistory(c context.Context, arg *model.ArgChangeHistory) (vcs []*model.VipChangeHistory, err error) {
SQLStr := _vipChangeHistorySQL
if arg.Pn > 0 && arg.Ps > 0 {
SQLStr += fmt.Sprintf(" LIMIT %d,%d", (arg.Pn-1)*arg.Ps, arg.Ps)
}
var rows *sql.Rows
if rows, err = d.db.Query(c, SQLStr, arg.Mid); err != nil {
err = errors.WithStack(err)
d.errProm.Incr("query_db")
return
}
defer rows.Close()
for rows.Next() {
r := new(model.VipChangeHistory)
if rows.Scan(&r.ID, &r.Mid, &r.ChangeType, &r.ChangeTime, &r.Days, &r.OperatorID, &r.RelationID, &r.BatchID, &r.Remark); err != nil {
err = errors.WithStack(err)
d.errProm.Incr("row_scan_db")
vcs = nil
return
}
vcs = append(vcs, r)
}
err = rows.Err()
return
}
//TxUpdateChannelID .
func (d *Dao) TxUpdateChannelID(tx *sql.Tx, mid int64, payChannelID int32, ver int64, oldVer int64) (err error) {
if _, err = tx.Exec(_updateChannelIDSQL, payChannelID, ver, mid, oldVer); err != nil {
err = errors.WithStack(err)
return
}
return
}
//TxDupUserDiscount .
func (d *Dao) TxDupUserDiscount(tx *sql.Tx, mid, discountID int64, orderNo string, status int8) (err error) {
if _, err = tx.Exec(_dupUserDiscountSQL, mid, discountID, orderNo, status); err != nil {
err = errors.WithStack(err)
return
}
return
}
//UpdatePayType .
func (d *Dao) UpdatePayType(tx *sql.Tx, mid int64, payType int8, ver, oldVer int64) (a int64, err error) {
var result xsql.Result
if result, err = tx.Exec(_updatePayTypeSQL, payType, ver, mid, oldVer); err != nil {
err = errors.WithStack(err)
return
}
if a, err = result.RowsAffected(); err != nil {
err = errors.WithStack(err)
return
}
return
}
//SelVipChangeHistory select vip_change_history by relationId
func (d *Dao) SelVipChangeHistory(c context.Context, relationID string) (r *model.VipChangeHistory, err error) {
var row = d.db.QueryRow(c, _selVipChangeHistoryByRelationIDSQL, relationID)
r = new(model.VipChangeHistory)
if err = row.Scan(&r.ID, &r.Mid, &r.ChangeType, &r.ChangeTime, &r.Days, &r.OperatorID, &r.RelationID, &r.BatchID, &r.Remark, &r.Ctime); err != nil {
if err == sql.ErrNoRows {
r = nil
err = nil
} else {
err = errors.WithStack(err)
d.errProm.Incr("scan_error")
}
}
return
}
//InsertVipChangeHistory insert vipChangeHistory
func (d *Dao) InsertVipChangeHistory(tx *sql.Tx, r *model.VipChangeHistory) (id int64, err error) {
var res xsql.Result
if res, err = tx.Exec(_InsertVipChangeHistory, r.Mid, r.ChangeType, r.ChangeTime, r.Days, r.OperatorID, r.RelationID, r.BatchID, r.Remark, r.BatchCodeID); err != nil {
err = errors.WithStack(err)
} else {
if id, err = res.LastInsertId(); err != nil {
err = errors.WithStack(err)
}
}
return
}
//TxSelVipUserInfo .
func (d *Dao) TxSelVipUserInfo(tx *sql.Tx, mid int64) (r *model.VipInfoDB, err error) {
var row = tx.QueryRow(_SelVipUserInfoByMid, mid)
r = new(model.VipInfoDB)
if err = row.Scan(&r.ID, &r.Mid, &r.VipType, &r.VipPayType, &r.VipStatus, &r.Ver, &r.VipStartTime, &r.VipOverdueTime, &r.AnnualVipOverdueTime, &r.Ctime, &r.Mtime, &r.VipRecentTime, &r.IosOverdueTime); err != nil {
if err == sql.ErrNoRows {
r = nil
err = nil
} else {
err = errors.WithStack(err)
}
}
return
}
// TxAddIosVipUserInfo tx add ios vip user info.
func (d *Dao) TxAddIosVipUserInfo(tx *sql.Tx, r *model.VipInfoDB) (eff int64, err error) {
var result xsql.Result
if result, err = tx.Exec(_addIosVipUserInfo, r.Mid, r.VipType, r.VipStatus, r.VipStartTime, r.IosOverdueTime); err != nil {
err = errors.WithStack(err)
return
}
if eff, err = result.RowsAffected(); err != nil {
err = errors.WithStack(err)
}
return
}
//InsertVipUserInfo insert vipUserInfo
func (d *Dao) InsertVipUserInfo(tx *sql.Tx, r *model.VipInfoDB) (err error) {
if _, err = tx.Exec(_InsertVipUserInfo, r.Mid, r.VipType, r.VipPayType, r.VipStatus, r.VipStartTime, r.VipOverdueTime, r.AnnualVipOverdueTime, r.VipRecentTime); err != nil {
err = errors.WithStack(err)
}
return
}
//TxUpdateIosUserInfo update ios time
func (d *Dao) TxUpdateIosUserInfo(tx *sql.Tx, iosTime time.Time, mid int64) (eff int64, err error) {
var result xsql.Result
if result, err = tx.Exec(_updateIosUserInfoSQL, iosTime, mid); err != nil {
err = errors.WithStack(err)
return
}
if eff, err = result.RowsAffected(); err != nil {
err = errors.WithStack(err)
}
return
}
//TxUpdateIosRenewUserInfo .
func (d *Dao) TxUpdateIosRenewUserInfo(tx *sql.Tx, paychannelID, ver, oldVer, mid int64, payType int8) (err error) {
if _, err = tx.Exec(_updateIosRenewUserInfoSQL, payType, ver, paychannelID, mid, oldVer); err != nil {
err = errors.WithStack(err)
return
}
return
}
//UpdateVipUserInfo update vip user info by id
func (d *Dao) UpdateVipUserInfo(tx *sql.Tx, r *model.VipInfoDB, ver int64) (a int64, err error) {
var res xsql.Result
if res, err = tx.Exec(_UpdateVipUserInfoByID, r.VipType, r.VipPayType, r.VipStatus, r.VipOverdueTime, r.AnnualVipOverdueTime, r.VipRecentTime, r.Ver, r.Mid, ver); err != nil {
err = errors.WithStack(err)
} else {
if a, err = res.RowsAffected(); err != nil {
err = errors.WithStack(err)
}
}
return
}
// TxAddUserDiscount add user discount history.
func (d *Dao) TxAddUserDiscount(tx *sql.Tx, r *model.VipUserDiscountHistory) (eff int64, err error) {
var res xsql.Result
if res, err = tx.Exec(_addUserDiscount, r.Mid, r.DiscountID, r.OrderNo, r.Status); err != nil {
err = errors.WithStack(err)
return
}
eff, err = res.RowsAffected()
return
}
//SyncAddUser insert vipUserInfo
func (d *Dao) SyncAddUser(tx *sql.Tx, r *model.VipInfoDB) (err error) {
if _, err = tx.Exec(_syncAddUser, r.Mid, r.VipType, r.VipPayType, r.VipStatus, r.VipStartTime, r.VipOverdueTime, r.AnnualVipOverdueTime, r.VipRecentTime, r.IosOverdueTime, r.PayChannelID, r.Ver); err != nil {
err = errors.WithStack(err)
}
return
}
//SyncUpdateUser insert vipUserInfo
func (d *Dao) SyncUpdateUser(tx *sql.Tx, r *model.VipInfoDB, ver int64) (eff int64, err error) {
var res xsql.Result
if res, err = tx.Exec(_syncUpdateUser, r.VipType, r.VipPayType, r.VipStatus, r.VipOverdueTime, r.AnnualVipOverdueTime, r.VipRecentTime, r.IosOverdueTime, r.PayChannelID, r.Ver, r.Mid, ver); err != nil {
err = errors.WithStack(err)
return
}
if eff, err = res.RowsAffected(); err != nil {
err = errors.WithStack(err)
}
return
}
//OldTxSelVipUserInfo .
func (d *Dao) OldTxSelVipUserInfo(tx *sql.Tx, mid int64) (r *model.VipInfoDB, err error) {
var row = tx.QueryRow(_oldSelVipUserInfoByMid, mid)
r = new(model.VipInfoDB)
if err = row.Scan(&r.ID, &r.Mid, &r.VipType, &r.VipStatus, &r.Ver, &r.VipStartTime, &r.VipOverdueTime, &r.AnnualVipOverdueTime, &r.VipRecentTime, &r.IosOverdueTime); err != nil {
if err == sql.ErrNoRows {
r = nil
err = nil
} else {
err = errors.WithStack(err)
}
}
return
}
//OldTxUpdateVipUserInfo .
func (d *Dao) OldTxUpdateVipUserInfo(tx *sql.Tx, r *model.VipInfoDB, ver int64) (eff int64, err error) {
var res xsql.Result
if res, err = tx.Exec(_oldUpdateVipUserInfoByID, r.VipType, r.VipStatus, r.VipOverdueTime, r.AnnualVipOverdueTime, r.Ver, r.ID, ver); err != nil {
err = errors.WithStack(err)
return
}
eff, err = res.RowsAffected()
return
}
//OldTxAddChangeHistory .
func (d *Dao) OldTxAddChangeHistory(tx *sql.Tx, r *model.VipChangeHistory) (err error) {
if _, err = tx.Exec(_oldAddVipChangeHistory, r.Mid, r.ChangeType, r.ChangeTime, r.Days, r.OperatorID, r.RelationID, r.BatchID, r.Remark, r.BatchCodeID); err != nil {
err = errors.WithStack(err)
}
return
}
//CleanCache clean job cache.
func (d *Dao) CleanCache(c context.Context, mid int64) (err error) {
if _, err = d.db.Exec(c, _cleanjobSQL, mid); err != nil {
err = errors.WithStack(err)
}
return
}

View File

@@ -0,0 +1,310 @@
package dao
import (
"context"
"testing"
"time"
"go-common/app/service/main/vip/model"
xtime "go-common/library/time"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoVipInfo(t *testing.T) {
var (
c = context.TODO()
mid = int64(0)
)
convey.Convey("VipInfo", t, func(ctx convey.C) {
r, err := d.VipInfo(c, mid)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
ctx.Convey("r should not be nil", func(ctx convey.C) {
ctx.So(r, convey.ShouldNotBeNil)
})
})
}
func TestDaoUpdateVipTypeAndStatus(t *testing.T) {
var (
c = context.TODO()
mid = int64(0)
vipStatus = int32(0)
vipType = int32(0)
)
convey.Convey("UpdateVipTypeAndStatus", t, func(ctx convey.C) {
ret, err := d.UpdateVipTypeAndStatus(c, mid, vipStatus, vipType)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
ctx.Convey("ret should not be nil", func(ctx convey.C) {
ctx.So(ret, convey.ShouldNotBeNil)
})
})
}
func TestDaoSelChangeHistoryCount(t *testing.T) {
var (
c = context.TODO()
arg = &model.ArgChangeHistory{}
)
convey.Convey("SelChangeHistoryCount", t, func(ctx convey.C) {
count, err := d.SelChangeHistoryCount(c, arg)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
ctx.Convey("count should not be nil", func(ctx convey.C) {
ctx.So(count, convey.ShouldNotBeNil)
})
})
}
func TestDaoSelChangeHistory(t *testing.T) {
var (
c = context.TODO()
arg = &model.ArgChangeHistory{}
)
convey.Convey("SelChangeHistory", t, func(ctx convey.C) {
_, err := d.SelChangeHistory(c, arg)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoTxUpdateChannelID(t *testing.T) {
var (
c = context.TODO()
mid = int64(0)
payChannelID = int32(0)
ver = int64(0)
oldVer = int64(0)
)
convey.Convey("TxUpdateChannelID", t, func(ctx convey.C) {
tx, err := d.StartTx(c)
ctx.Convey("Tx Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
defer tx.Commit()
err = d.TxUpdateChannelID(tx, mid, payChannelID, ver, oldVer)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoTxDupUserDiscount(t *testing.T) {
var (
c = context.TODO()
mid = int64(0)
discountID = int64(0)
orderNo = ""
status = int8(0)
)
convey.Convey("TxDupUserDiscount", t, func(ctx convey.C) {
tx, err := d.StartTx(c)
ctx.Convey("Tx Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
defer tx.Commit()
err = d.TxDupUserDiscount(tx, mid, discountID, orderNo, status)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoUpdatePayType(t *testing.T) {
var (
c = context.TODO()
mid = int64(0)
payType = int8(0)
ver = int64(0)
oldVer = int64(0)
)
convey.Convey("UpdatePayType", t, func(ctx convey.C) {
tx, err := d.StartTx(c)
ctx.Convey("Tx Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
defer tx.Commit()
a, err := d.UpdatePayType(tx, mid, payType, ver, oldVer)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
ctx.Convey("a should not be nil", func(ctx convey.C) {
ctx.So(a, convey.ShouldNotBeNil)
})
})
}
func TestDaoSelVipChangeHistory(t *testing.T) {
var (
c = context.TODO()
relationID = ""
)
convey.Convey("SelVipChangeHistory", t, func(ctx convey.C) {
r, err := d.SelVipChangeHistory(c, relationID)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
ctx.Convey("r should not be nil", func(ctx convey.C) {
ctx.So(r, convey.ShouldNotBeNil)
})
})
}
func TestDaoInsertVipChangeHistory(t *testing.T) {
var (
c = context.TODO()
r = &model.VipChangeHistory{}
)
convey.Convey("InsertVipChangeHistory", t, func(ctx convey.C) {
tx, err := d.StartTx(c)
ctx.Convey("Tx Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
defer tx.Commit()
id, err := d.InsertVipChangeHistory(tx, r)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
ctx.Convey("id should not be nil", func(ctx convey.C) {
ctx.So(id, convey.ShouldNotBeNil)
})
})
}
func TestDaoTxSelVipUserInfo(t *testing.T) {
var (
c = context.TODO()
mid = int64(20606508)
)
convey.Convey("TxSelVipUserInfo", t, func(ctx convey.C) {
tx, err := d.StartTx(c)
ctx.Convey("Tx Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
defer tx.Commit()
r, err := d.TxSelVipUserInfo(tx, mid)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
ctx.Convey("r should not be nil", func(ctx convey.C) {
ctx.So(r, convey.ShouldNotBeNil)
})
})
}
func TestDaoTxAddIosVipUserInfo(t *testing.T) {
var (
c = context.TODO()
r = &model.VipInfoDB{
Mid: time.Now().Unix(),
VipType: 1,
VipPayType: 1,
VipStatus: 0,
VipStartTime: xtime.Time(time.Now().Unix()),
VipOverdueTime: xtime.Time(time.Now().Unix()),
AnnualVipOverdueTime: xtime.Time(time.Now().Unix()),
VipRecentTime: xtime.Time(time.Now().Unix()),
}
)
convey.Convey("TxAddIosVipUserInfo", t, func(ctx convey.C) {
tx, err := d.StartTx(c)
ctx.Convey("Tx Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
eff, err := d.TxAddIosVipUserInfo(tx, r)
err = tx.Commit()
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
ctx.Convey("eff should not be nil", func(ctx convey.C) {
ctx.So(eff, convey.ShouldNotBeNil)
})
err = d.InsertVipUserInfo(tx, r)
ctx.Convey("Error should not be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldNotBeNil)
})
})
}
func TestDaoTxUpdateIosUserInfo(t *testing.T) {
var (
c = context.TODO()
iosTime = xtime.Time(time.Now().Unix())
mid = int64(0)
)
convey.Convey("TxUpdateIosUserInfo", t, func(ctx convey.C) {
tx, err := d.StartTx(c)
ctx.Convey("Tx Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
defer tx.Commit()
eff, err := d.TxUpdateIosUserInfo(tx, iosTime, mid)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
ctx.Convey("eff should not be nil", func(ctx convey.C) {
ctx.So(eff, convey.ShouldNotBeNil)
})
})
}
func TestDaoTxUpdateIosRenewUserInfo(t *testing.T) {
var (
c = context.TODO()
paychannelID = int64(1)
ver = int64(1)
oldVer = int64(123)
mid = int64(20606508)
payType = int8(1)
)
convey.Convey("TxUpdateIosRenewUserInfo", t, func(ctx convey.C) {
tx, err := d.StartTx(c)
ctx.Convey("Tx Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
defer tx.Commit()
err = d.TxUpdateIosRenewUserInfo(tx, paychannelID, ver, oldVer, mid, payType)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoUpdateVipUserInfo(t *testing.T) {
var (
c = context.TODO()
r = &model.VipInfoDB{
Mid: 206065080,
VipType: 1,
VipPayType: 1,
VipStatus: 0,
VipStartTime: xtime.Time(time.Now().Unix()),
VipOverdueTime: xtime.Time(time.Now().Unix()),
AnnualVipOverdueTime: xtime.Time(time.Now().Unix()),
VipRecentTime: xtime.Time(time.Now().Unix()),
}
ver = int64(0)
)
convey.Convey("UpdateVipUserInfo", t, func(ctx convey.C) {
tx, err := d.StartTx(c)
ctx.Convey("Tx Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
defer tx.Commit()
a, err := d.UpdateVipUserInfo(tx, r, ver)
ctx.Convey("Error should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
ctx.Convey("a should not be nil", func(ctx convey.C) {
ctx.So(a, convey.ShouldNotBeNil)
})
})
}

View File

@@ -0,0 +1,283 @@
package dao
import (
"context"
xsql "database/sql"
"fmt"
"strings"
"go-common/app/service/main/vip/model"
"go-common/library/database/sql"
"github.com/pkg/errors"
)
const (
_getWelfareListSQL = "SELECT id, welfare_name, homepage_uri, backdrop_uri, tid, rank FROM vip_welfare WHERE state = 0 AND tid = ? AND recommend in (0,?) AND stime < ? AND etime > ? ORDER BY rank LIMIT ?,?"
_countWelfareSQL = "SELECT COUNT(1) FROM vip_welfare WHERE state = 0 AND tid = ? AND recommend in (0,?) AND stime < ? AND etime > ?"
_getRecommendWelfareSQL = "SELECT id, welfare_name, homepage_uri, backdrop_uri, tid, rank FROM vip_welfare WHERE state = 0 AND recommend = ? AND stime < ? AND etime > ? ORDER BY rank LIMIT ?,?"
_countRecommendWelfareSQL = "SELECT COUNT(1) FROM vip_welfare WHERE state = 0 AND recommend = ? AND stime < ? AND etime > ?"
_getWelfareTypeListSQL = "SELECT id, name FROM vip_welfare_type WHERE state = 0"
_getWelfareInfoSQL = "SELECT id, welfare_name, welfare_desc, receive_rate, homepage_uri, backdrop_uri, usage_form, vip_type, stime, etime FROM vip_welfare WHERE id = ?"
_getWelfareBatchSQL = "SELECT id, received_count, count, vtime FROM vip_welfare_code_batch WHERE state = 0 AND wid = ?"
_getReceivedCodeSQL = "SELECT id, mtime FROM vip_welfare_code WHERE state = 0 AND wid = ? AND mid = ?"
_getWelfareCodeListSQL = "SELECT id, bid, code FROM vip_welfare_code WHERE mid = 0 AND state = 0 AND wid = ? AND bid IN (%s) ORDER BY id limit 10"
_receiveWelfareSQL = "UPDATE vip_welfare_code SET mid = ? where id = ? and mid = 0"
_updateStockSQL = "UPDATE vip_welfare_code_batch SET received_count = received_count+1 WHERE received_count < count AND id = ? "
_getMyWelfareSQL = "SELECT a.id, a.welfare_name, a.welfare_desc, a.usage_form, a.receive_uri, a.stime, a.etime, b.code FROM vip_welfare a LEFT JOIN vip_welfare_code b ON a.id = b.wid WHERE b.mid = ? ORDER BY b.mtime desc"
_addReceiveRedirectWelfareSQL = "INSERT INTO vip_welfare_code (wid, mid) VALUES (?, ?)"
_countReceiveRedirectWelfareSQL = "SELECT COUNT(1) FROM vip_welfare_code WHERE wid = ? AND mid = ?"
_insertReceiveRecordSQL = "INSERT INTO vip_welfare_record (mid, wid, month, count) VALUES (?, ?, ?, 1)"
)
// GetWelfareList get welfare list
func (d *Dao) GetWelfareList(c context.Context, req *model.ArgWelfareList) (res []*model.WelfareListResp, err error) {
var rows *sql.Rows
if rows, err = d.db.Query(c, _getWelfareListSQL, req.Tid, req.Recommend, req.NowTime, req.NowTime, (req.Pn-1)*req.Ps, req.Ps); err != nil {
err = errors.WithStack(err)
return
}
defer rows.Close()
for rows.Next() {
r := &model.WelfareListResp{}
if err = rows.Scan(&r.ID, &r.Name, &r.HomepageUri, &r.BackdropUri, &r.Tid, &r.Rank); err != nil {
err = errors.WithStack(err)
res = nil
return
}
res = append(res, r)
}
return
}
// CountWelfare count welfare list
func (d *Dao) CountWelfare(c context.Context, req *model.ArgWelfareList) (count int64, err error) {
row := d.db.QueryRow(c, _countWelfareSQL, req.Tid, req.Recommend, req.NowTime, req.NowTime)
if err = row.Scan(&count); err != nil {
if sql.ErrNoRows == err {
err = nil
count = 0
return
}
err = errors.WithStack(err)
}
return
}
// GetRecommendWelfare get recommend welfare
func (d *Dao) GetRecommendWelfare(c context.Context, req *model.ArgWelfareList) (res []*model.WelfareListResp, err error) {
var rows *sql.Rows
if rows, err = d.db.Query(c, _getRecommendWelfareSQL, req.Recommend, req.NowTime, req.NowTime, (req.Pn-1)*req.Ps, req.Ps); err != nil {
err = errors.WithStack(err)
return
}
defer rows.Close()
for rows.Next() {
r := &model.WelfareListResp{}
if err = rows.Scan(&r.ID, &r.Name, &r.HomepageUri, &r.BackdropUri, &r.Tid, &r.Rank); err != nil {
err = errors.WithStack(err)
res = nil
return
}
res = append(res, r)
}
return
}
// CountRecommendWelfare count recommend welfare
func (d *Dao) CountRecommendWelfare(c context.Context, req *model.ArgWelfareList) (count int64, err error) {
row := d.db.QueryRow(c, _countRecommendWelfareSQL, req.Recommend, req.NowTime, req.NowTime)
if err = row.Scan(&count); err != nil {
if sql.ErrNoRows == err {
err = nil
count = 0
return
}
err = errors.WithStack(err)
}
return
}
// GetWelfareTypeList get welfare type list
func (d *Dao) GetWelfareTypeList(c context.Context) (res []*model.WelfareTypeListResp, err error) {
var rows *sql.Rows
if rows, err = d.db.Query(c, _getWelfareTypeListSQL); err != nil {
err = errors.WithStack(err)
return
}
defer rows.Close()
for rows.Next() {
r := &model.WelfareTypeListResp{}
if err = rows.Scan(&r.ID, &r.Name); err != nil {
err = errors.WithStack(err)
res = nil
return
}
res = append(res, r)
}
return
}
// GetWelfareInfo get welfare info
func (d *Dao) GetWelfareInfo(c context.Context, id int64) (res *model.WelfareInfoResp, err error) {
res = new(model.WelfareInfoResp)
if err = d.db.QueryRow(c, _getWelfareInfoSQL, id).
Scan(&res.ID, &res.Name, &res.Desc, &res.ReceiveRate, &res.HomepageUri, &res.BackdropUri, &res.UsageForm, &res.VipType, &res.Stime, &res.Etime); err != nil {
if err == sql.ErrNoRows {
res = nil
err = nil
return
}
err = errors.Wrapf(err, "dao GetWelfareInfo(%d)", id)
}
return
}
// GetWelfareBatch get welfare batch infos
func (d *Dao) GetWelfareBatch(c context.Context, wid int64) (res []*model.WelfareBatchResp, err error) {
var rows *sql.Rows
if rows, err = d.db.Query(c, _getWelfareBatchSQL, wid); err != nil {
err = errors.WithStack(err)
return
}
defer rows.Close()
for rows.Next() {
r := &model.WelfareBatchResp{}
if err = rows.Scan(&r.Id, &r.ReceivedCount, &r.Count, &r.Vtime); err != nil {
err = errors.WithStack(err)
res = nil
return
}
res = append(res, r)
}
return
}
// GetReceivedCode get received code
func (d *Dao) GetReceivedCode(c context.Context, wid, mid int64) (res []*model.ReceivedCodeResp, err error) {
var rows *sql.Rows
if rows, err = d.db.Query(c, _getReceivedCodeSQL, wid, mid); err != nil {
err = errors.WithStack(err)
return
}
defer rows.Close()
for rows.Next() {
r := &model.ReceivedCodeResp{}
if err = rows.Scan(&r.ID, &r.Mtime); err != nil {
err = errors.WithStack(err)
res = nil
return
}
res = append(res, r)
}
return
}
//UpdateWelfareCodeUser user receive welfare
func (d *Dao) UpdateWelfareCodeUser(c context.Context, tx *sql.Tx, id int, mid int64) (affectedRows int64, err error) {
var (
res xsql.Result
)
if res, err = tx.Exec(_receiveWelfareSQL, mid, id); err != nil {
err = errors.WithStack(err)
return
}
affectedRows, err = res.RowsAffected()
return
}
//UpdateWelfareBatch reduce count
func (d *Dao) UpdateWelfareBatch(c context.Context, tx *sql.Tx, bid int) (err error) {
if _, err = tx.Exec(_updateStockSQL, bid); err != nil {
err = errors.WithStack(err)
}
return
}
// GetWelfareCodeUnReceived get unReceived welfare code
func (d *Dao) GetWelfareCodeUnReceived(c context.Context, wid int64, bids []string) (res []*model.UnReceivedCodeResp, err error) {
var rows *sql.Rows
if rows, err = d.db.Query(c, fmt.Sprintf(_getWelfareCodeListSQL, strings.Join(bids, ",")), wid); err != nil {
err = errors.WithStack(err)
return
}
defer rows.Close()
for rows.Next() {
r := new(model.UnReceivedCodeResp)
if err = rows.Scan(&r.Id, &r.Bid, &r.Code); err != nil {
err = errors.WithStack(err)
res = nil
return
}
res = append(res, r)
}
return
}
// GetMyWelfare get my welfare infos
func (d *Dao) GetMyWelfare(c context.Context, mid int64) (res []*model.MyWelfareResp, err error) {
var rows *sql.Rows
if rows, err = d.db.Query(c, _getMyWelfareSQL, mid); err != nil {
err = errors.WithStack(err)
return
}
defer rows.Close()
for rows.Next() {
r := &model.MyWelfareResp{}
if err = rows.Scan(&r.Wid, &r.Name, &r.Desc, &r.UsageForm, &r.ReceiveUri, &r.Stime, &r.Etime, &r.Code); err != nil {
err = errors.WithStack(err)
res = nil
return
}
res = append(res, r)
}
return
}
// AddReceiveRedirectWelfare add redirect url
func (d *Dao) AddReceiveRedirectWelfare(c context.Context, wid, mid int64) (err error) {
if _, err = d.db.Exec(c, _addReceiveRedirectWelfareSQL, wid, mid); err != nil {
err = errors.WithStack(err)
return
}
return
}
// CountReceiveRedirectWelfare count it
func (d *Dao) CountReceiveRedirectWelfare(c context.Context, wid, mid int64) (count int64, err error) {
row := d.db.QueryRow(c, _countReceiveRedirectWelfareSQL, wid, mid)
if err = row.Scan(&count); err != nil {
if sql.ErrNoRows == err {
err = nil
count = 0
return
}
err = errors.WithStack(err)
}
return
}
// InsertReceiveRecord to prevent repeated receive
func (d *Dao) InsertReceiveRecord(c context.Context, tx *sql.Tx, mid, wid, monthYear int64) (err error) {
if _, err = tx.Exec(_insertReceiveRecordSQL, mid, wid, monthYear); err != nil {
err = errors.WithStack(err)
return
}
return
}

View File

@@ -0,0 +1,250 @@
package dao
import (
"context"
"go-common/app/service/main/vip/model"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoGetWelfareList(t *testing.T) {
convey.Convey("GetWelfareList", t, func(ctx convey.C) {
var (
c = context.Background()
req = &model.ArgWelfareList{}
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
_, err := d.GetWelfareList(c, req)
ctx.Convey("Then err should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoCountWelfare(t *testing.T) {
convey.Convey("CountWelfare", t, func(ctx convey.C) {
var (
c = context.Background()
req = &model.ArgWelfareList{}
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
count, err := d.CountWelfare(c, req)
ctx.Convey("Then err should be nil.count should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(count, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoGetRecommendWelfare(t *testing.T) {
convey.Convey("GetRecommendWelfare", t, func(ctx convey.C) {
var (
c = context.Background()
req = &model.ArgWelfareList{}
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
_, err := d.GetRecommendWelfare(c, req)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoCountRecommendWelfare(t *testing.T) {
convey.Convey("CountRecommendWelfare", t, func(ctx convey.C) {
var (
c = context.Background()
req = &model.ArgWelfareList{}
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
count, err := d.CountRecommendWelfare(c, req)
ctx.Convey("Then err should be nil.count should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(count, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoGetWelfareTypeList(t *testing.T) {
convey.Convey("GetWelfareTypeList", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
res, err := d.GetWelfareTypeList(c)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoGetWelfareInfo(t *testing.T) {
convey.Convey("GetWelfareInfo", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(0)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
_, err := d.GetWelfareInfo(c, id)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoGetWelfareBatch(t *testing.T) {
convey.Convey("GetWelfareBatch", t, func(ctx convey.C) {
var (
c = context.Background()
wid = int64(0)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
_, err := d.GetWelfareBatch(c, wid)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoGetReceivedCode(t *testing.T) {
convey.Convey("GetReceivedCode", t, func(ctx convey.C) {
var (
c = context.Background()
wid = int64(0)
mid = int64(0)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
_, err := d.GetReceivedCode(c, wid, mid)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoUpdateWelfareCodeUser(t *testing.T) {
convey.Convey("UpdateWelfareCodeUser", t, func(ctx convey.C) {
var (
c = context.Background()
id = int(0)
mid = int64(0)
)
tx, _ := d.StartTx(c)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
res, err := d.UpdateWelfareCodeUser(c, tx, id, mid)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoUpdateWelfareBatch(t *testing.T) {
convey.Convey("UpdateWelfareBatch", t, func(ctx convey.C) {
var (
c = context.Background()
bid = int(0)
)
tx, err := d.StartTx(c)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
err = d.UpdateWelfareBatch(c, tx, bid)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoGetWelfareCodeUnReceived(t *testing.T) {
convey.Convey("GetWelfareCodeUnReceived", t, func(ctx convey.C) {
var (
c = context.Background()
wid = int64(0)
bids = []string{}
)
bids = append(bids, "1")
bids = append(bids, "2")
ctx.Convey("When everything gose positive", func(ctx convey.C) {
_, err := d.GetWelfareCodeUnReceived(c, wid, bids)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoGetMyWelfare(t *testing.T) {
convey.Convey("GetMyWelfare", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(0)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
_, err := d.GetMyWelfare(c, mid)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoAddReceiveRedirectWelfare(t *testing.T) {
convey.Convey("AddReceiveRedirectWelfare", t, func(ctx convey.C) {
var (
c = context.Background()
wid = int64(0)
mid = int64(0)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
err := d.AddReceiveRedirectWelfare(c, wid, mid)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoCountReceiveRedirectWelfare(t *testing.T) {
convey.Convey("CountReceiveRedirectWelfare", t, func(ctx convey.C) {
var (
c = context.Background()
wid = int64(0)
mid = int64(0)
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
count, err := d.CountReceiveRedirectWelfare(c, wid, mid)
ctx.Convey("Then err should be nil.count should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(count, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoInsertReceiveRecord(t *testing.T) {
convey.Convey("InsertReceiveRecord", t, func(ctx convey.C) {
var (
c = context.Background()
wid = int64(0)
mid = int64(0)
monthYear = int64(0)
)
tx, err := d.StartTx(c)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
err = d.InsertReceiveRecord(c, tx, wid, mid, monthYear)
ctx.Convey("Then err should be nil.count should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}

View File

@@ -0,0 +1,53 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = [
"activity.go",
"bp.go",
"coupon.go",
"http.go",
"notify.go",
"order.go",
"order2.go",
"panel.go",
"point.go",
"resouce.go",
"sync.go",
"tips.go",
"user.go",
"vip.go",
],
importpath = "go-common/app/service/main/vip/http",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/service/main/vip/conf:go_default_library",
"//app/service/main/vip/model:go_default_library",
"//app/service/main/vip/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/verify:go_default_library",
"//library/net/metadata: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,15 @@
package http
import (
"go-common/app/service/main/vip/model"
bm "go-common/library/net/http/blademaster"
)
func thirdPrizeGrant(c *bm.Context) {
a := new(model.ArgThirdPrizeGrant)
if err := c.Bind(a); err != nil {
return
}
a.AppID = model.EleAppID
c.JSON(nil, vipSvc.ThirdPrizeGrant(c, a))
}

View File

@@ -0,0 +1,27 @@
package http
import (
"go-common/app/service/main/vip/model"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
)
func bpList(c *bm.Context) {
var (
err error
res *model.BcoinSalaryResp
)
arg := new(struct {
Mid int64 `form:"mid" validate:"required"`
})
if err = c.Bind(arg); err != nil {
log.Error("c.Bind err(%+v)", err)
return
}
if res, err = vipSvc.BcoinGive(c, arg.Mid); err != nil {
log.Error(" BcoinGive mid(%d), err(%+v)", arg.Mid, err)
c.JSON(nil, err)
return
}
c.JSON(res, nil)
}

View File

@@ -0,0 +1,29 @@
package http
import (
"go-common/app/service/main/vip/model"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
"go-common/library/net/metadata"
)
func cancelUseCoupon(c *bm.Context) {
var (
err error
arg = new(model.ArgCancelUseCoupon)
)
if err = c.Bind(arg); err != nil {
return
}
c.JSON(nil, vipSvc.CancelUseCoupon(c, arg.Mid, arg.CouponToken, metadata.String(c, metadata.RemoteIP)))
}
func allowanceInfo(c *bm.Context) {
var err error
arg := new(model.ArgCancelUseCoupon)
if err = c.Bind(arg); err != nil {
log.Error("use allowance coupon bind %+v", err)
return
}
c.JSON(vipSvc.AllowanceInfo(c, arg.Mid, arg.CouponToken))
}

View File

@@ -0,0 +1,128 @@
package http
import (
"net/http"
"go-common/app/service/main/vip/conf"
"go-common/app/service/main/vip/service"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
"go-common/library/net/http/blademaster/middleware/verify"
)
var (
vipSvc *service.Service
vrfSvr *verify.Verify
)
// Init init http sever instance.
func Init(c *conf.Config, s *service.Service) {
vrfSvr = verify.New(nil)
vipSvc = service.New(c)
// init router
engineOuter := bm.DefaultServer(c.BM)
innerRouter(engineOuter)
if err := engineOuter.Start(); err != nil {
log.Error("engineOuter.Start() error(%v)", err)
panic(err)
}
}
// innerRouter init inner router.
func innerRouter(e *bm.Engine) {
e.Ping(ping)
e.Register(register)
//internal api
big := e.Group("/x/internal/big", vrfSvr.Verify)
{
big.GET("/batchInfo", batchInfo)
big.POST("/useBatchInfo", useBatchInfo)
}
vip := e.Group("/x/internal/vip", vrfSvr.Verify)
{
// bcoin
vip.GET("/bcoin/list", bpList)
// point
vip.POST("/point/exchange_vip", buyVipWithPoint)
vip.POST("/point/rule", rule)
// user
vip.GET("/user/info", byMid)
vip.GET("/user/list", vipInfos)
vip.GET("/user/history", vipHistory)
vip.GET("/user/history/h5", vipH5History)
vip.GET("/user/infobo", vipInfo) // for old service.
// order
vip.GET("/order/status", status)
vip.GET("/order/list", orders)
vip.POST("/order/create", createOrder)
vip.POST("/order/oldcreate", createOldOrder) // for old service
vip.GET("/order/mng", orderMng)
vip.GET("/order/rescision", rescision)
//panel
vip.GET("/panel", pannelInfoNew)
// panel
vip.GET("/panel/single/info", vipUserMonthPanel)
vip.GET("/panel/pirce", vipPirce)
// price
vip.GET("/price/by_product_id", priceceByProductID)
vip.GET("/price/by_id", priceceByID)
// code
vip.GET("/code/verify", webToken)
vip.POST("/code/open", openCode)
vip.GET("/code/info", codeInfo)
vip.GET("/code/infos", codeInfos)
vip.POST("/code/belong", belong)
vip.POST("/active/infos", actives)
vip.GET("/code/opened", codeOpened)
// tips
vip.GET("/tips", tips)
//coupon
vip.POST("/coupon/cancel", cancelUseCoupon)
vip.GET("/coupon/info", allowanceInfo)
// FIXME: sync user
vip.POST("/sync/user", syncUser)
vip.POST("/order/create/qr", createQrCodeOrder)
//act
vip.POST("/activity/prize/grant", thirdPrizeGrant)
vip.POST("/ele/vip/grant", grantAssociateVip)
}
vip2 := e.Group("/x/internal/vip/v2", vrfSvr.Verify)
{
vip2.POST("/order/create", createOrder2)
}
vipNotSign := e.Group("/x/internal/vip")
{
// notify
vipNotSign.GET("/notify", notify)
vipNotSign.GET("/notify/v2", notify2)
vipNotSign.GET("/notify/sign", signNotify)
vipNotSign.GET("/notify/refund", refundOrderNotify)
}
}
// ping check server ok.
func ping(c *bm.Context) {
var err error
if err = vipSvc.Ping(c); err != nil {
log.Error("service ping error(%v)", err)
c.AbortWithStatus(http.StatusServiceUnavailable)
}
}
// register check server ok.
func register(c *bm.Context) {
c.JSON(map[string]interface{}{}, nil)
}

View File

@@ -0,0 +1,117 @@
package http
import (
"encoding/json"
"go-common/app/service/main/vip/model"
"go-common/library/ecode"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
)
const (
_payNotifySuccess = "SUCCESS"
_payNotifyFail = "FAIL"
)
func notify(c *bm.Context) {
d := new(model.PayCallBackResult)
if err := c.Bind(d); err != nil {
log.Error("pr.Bind err(%+v)", err)
return
}
if d.TradeNO == "" {
c.JSON(nil, ecode.RequestErr)
return
}
if d.OutTradeNO == "" {
c.JSON(nil, ecode.RequestErr)
return
}
if d.TradeStatus != model.TradeSuccess {
c.JSON(nil, ecode.RequestErr)
return
}
if err := vipSvc.PayNotify(c, d); err != nil {
log.Error("s.PayNotify err(%+v)", err)
c.JSON(nil, err)
return
}
c.JSON(nil, nil)
}
func notify2(c *bm.Context) {
var (
err error
)
arg := new(struct {
MsgContent string `form:"msgContent" validate:"required"`
})
if err = c.Bind(arg); err != nil {
log.Error("c.Bind err(%+v)", err)
c.Writer.Write([]byte(_payNotifyFail))
return
}
p := &model.PayNotifyContent{}
if err = json.Unmarshal([]byte(arg.MsgContent), p); err != nil {
c.Writer.Write([]byte(_payNotifyFail))
return
}
if err = vipSvc.PayNotify2(c, p); err != nil {
log.Error("s.PayNotify2 err(%+v)", err)
if err == ecode.VipOrderAlreadyHandlerErr {
c.Writer.Write([]byte(_payNotifySuccess))
return
}
c.Writer.Write([]byte(_payNotifyFail))
return
}
c.Writer.Write([]byte(_payNotifySuccess))
}
func signNotify(c *bm.Context) {
var (
err error
)
arg := new(struct {
MsgContent string `form:"msgContent" validate:"required"`
})
if err = c.Bind(arg); err != nil {
return
}
p := new(model.PaySignNotify)
if err = json.Unmarshal([]byte(arg.MsgContent), p); err != nil {
c.Writer.Write([]byte(_payNotifyFail))
return
}
if err = vipSvc.PaySignNotify(c, p); err != nil {
log.Error("vip.paySignNotify(%+v) error(%+v)", p, err)
c.Writer.Write([]byte(_payNotifyFail))
return
}
c.Writer.Write([]byte(_payNotifySuccess))
}
func refundOrderNotify(c *bm.Context) {
var (
err error
)
arg := new(struct {
MsgContent string `form:"msgContent" validate:"required"`
})
if err = c.Bind(arg); err != nil {
return
}
p := new(model.PayRefundNotify)
log.Info("refun order notify params:%+v", arg.MsgContent)
if err = json.Unmarshal([]byte(arg.MsgContent), p); err != nil {
log.Error("error(%+v)", err)
c.Writer.Write([]byte(_payNotifyFail))
return
}
if err = vipSvc.RefundNotify(c, p); err != nil {
log.Error("vip.refundNotify(%+v) error(%+v)", arg.MsgContent, err)
c.Writer.Write([]byte(_payNotifyFail))
return
}
c.Writer.Write([]byte(_payNotifySuccess))
}

View File

@@ -0,0 +1,179 @@
package http
import (
"fmt"
"go-common/app/service/main/vip/model"
"go-common/library/ecode"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
"go-common/library/net/metadata"
)
func status(c *bm.Context) {
var (
o *model.OrderInfo
vip *model.VipInfo
err error
)
arg := new(struct {
OrderNo string `form:"order_no" validate:"required"`
})
if err = c.Bind(arg); err != nil {
log.Error("c.Bind err(%+v)", err)
return
}
if o, err = vipSvc.OrderInfo(c, arg.OrderNo); err != nil {
log.Error("vipSvc.OrderInfo(%s) err(%+v)", arg.OrderNo, err)
c.JSON(nil, err)
return
}
if o == nil {
c.JSON(nil, ecode.VipOrderNotFoundErr)
return
}
res := new(struct {
OrderNo string `json:"order_no"`
Status int8 `json:"status"`
Message *model.OrderMessage `json:"message"`
})
res.OrderNo = o.OrderNo
res.Status = o.Status
if o.Status == model.SUCCESS {
if vip, err = vipSvc.VipInfo(c, o.Mid); err != nil {
c.JSON(nil, err)
return
}
message := new(model.OrderMessage)
message.RightButton = "知道了"
message.Title = "开通成功"
message.Content = fmt.Sprintf("你已成功开通%d个月大会员目前有效期%s", o.BuyMonths, vip.VipOverdueTime.Time().Format("2006-01-02"))
res.Message = message
} else if o.Status == model.FAILED {
message := new(model.OrderMessage)
message.RightButton = "知道了"
message.Title = "支付失败"
message.Content = fmt.Sprintf("订单号:%s \nUID:%d \n支付失败了试试重新购买吧。", o.OrderNo, vip.Mid)
res.Message = message
}
c.JSON(res, nil)
}
func orders(c *bm.Context) {
var (
orders []*model.PayOrderResp
total int64
err error
)
arg := new(struct {
Mid int64 `form:"mid" validate:"required,min=1,gte=1"`
Ps int `form:"ps" default:"20" validate:"min=0,max=50"`
Pn int `form:"pn" default:"1"`
})
if err = c.Bind(arg); err != nil {
log.Error("c.Bind err(%+v)", err)
return
}
if orders, total, err = vipSvc.OrderList(c, arg.Mid, arg.Pn, arg.Ps); err != nil {
log.Error("vipSvc.OrderList(%d) err(%+v)", arg.Mid, err)
c.JSON(nil, err)
return
}
res := new(struct {
Data []*model.PayOrderResp `json:"list"`
Total int64 `json:"total"`
})
res.Data = orders
res.Total = total
c.JSON(orders, nil)
}
func createOrder(c *bm.Context) {
var (
err error
pp map[string]interface{}
)
arg := new(model.ArgCreateOrder)
if err = c.Bind(arg); err != nil {
log.Error("c.Bind err(%+v)", err)
return
}
if pp, err = vipSvc.CreateOrder(c, arg, metadata.String(c, metadata.RemoteIP)); err != nil {
log.Error("vipSvc.CreateOrder(%d) err(%+v)", arg.Mid, err)
c.JSON(nil, err)
return
}
c.JSON(pp, nil)
}
func pannelInfoNew(c *bm.Context) {
var (
pi *model.PannelInfo
err error
)
arg := new(model.ArgPannel)
if err = c.Bind(arg); err != nil {
log.Error("pannelInfoNew(%+v)", err)
return
}
if pi, err = vipSvc.PannelInfoNew(c, arg.Mid, arg); err != nil {
log.Error("vipSvc.PannelInfoNew(%d) err(%+v)", arg.Mid, err)
c.JSON(nil, err)
return
}
c.JSON(pi, nil)
}
func createOldOrder(c *bm.Context) {
var (
err error
)
arg := new(model.ArgOldPayOrder)
if err = c.Bind(arg); err != nil {
log.Error("c.Bind err(%+v)", err)
return
}
c.JSON(nil, vipSvc.CreateOldOrder(c, arg))
}
func orderMng(c *bm.Context) {
var (
err error
order *model.OrderMng
)
arg := new(struct {
Mid int64 `form:"mid" validate:"required,min=1,gte=1"`
})
if err = c.Bind(arg); err != nil {
log.Error("c.Bind err(%+v)", err)
return
}
if order, err = vipSvc.OrderMng(c, arg.Mid); err != nil {
c.JSON(nil, err)
return
}
c.JSON(order, err)
}
func rescision(c *bm.Context) {
var (
err error
)
arg := new(struct {
Mid int64 `form:"mid" validate:"required,mid=1,gte=1"`
DeviceType int32 `form:"deviceType" validate:"required"`
})
if err = c.Bind(arg); err != nil {
return
}
err = vipSvc.Rescision(c, arg.Mid, arg.DeviceType)
c.JSON(nil, err)
}

View File

@@ -0,0 +1,42 @@
package http
import (
"net"
"go-common/app/service/main/vip/model"
bm "go-common/library/net/http/blademaster"
"go-common/library/net/metadata"
)
func createOrder2(c *bm.Context) {
var (
err error
r *model.CreateOrderRet
)
arg := new(model.ArgCreateOrder2)
if err = c.Bind(arg); err != nil {
return
}
arg.IP = net.ParseIP(metadata.String(c, metadata.RemoteIP))
r, _, err = vipSvc.CreateOrder2(c, arg)
c.JSON(r, err)
}
func createQrCodeOrder(c *bm.Context) {
var err error
arg := new(model.ArgCreateOrder2)
if err = c.Bind(arg); err != nil {
return
}
arg.IP = net.ParseIP(metadata.String(c, metadata.RemoteIP))
c.JSON(vipSvc.CreateQrCodeOrder(c, arg))
}
func grantAssociateVip(c *bm.Context) {
var err error
arg := new(model.ArgEleVipGrant)
if err = c.Bind(arg); err != nil {
return
}
c.JSON(nil, vipSvc.EleVipGrant(c, arg))
}

View File

@@ -0,0 +1,42 @@
package http
import (
"go-common/app/service/main/vip/model"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
)
func vipUserMonthPanel(c *bm.Context) {
arg := new(model.ArgVipConfigMonth)
if err := c.Bind(arg); err != nil {
return
}
plat := vipSvc.GetPlatID(c, arg.Platform, arg.PanelType, arg.MobiApp, arg.Device, 0)
c.JSON(vipSvc.VipUserPrice(c, arg.Mid, arg.Month, plat, arg.SubType, arg.IgnoreAutoRenewStatus, arg.Build))
}
func vipPirce(c *bm.Context) {
arg := new(model.ArgVipConfigMonth)
if err := c.Bind(arg); err != nil {
log.Error("c.Bind err(%+v)", err)
return
}
plat := vipSvc.GetPlatID(c, arg.Platform, arg.PanelType, arg.MobiApp, arg.Device, 0)
c.JSON(vipSvc.VipPrice(c, arg.Mid, arg.Month, plat, arg.SubType, arg.CouponToken, arg.Platform, arg.Build))
}
func priceceByProductID(c *bm.Context) {
arg := new(model.ArgPriceByProduct)
if err := c.Bind(arg); err != nil {
return
}
c.JSON(vipSvc.PriceByProductID(c, arg.ProductID))
}
func priceceByID(c *bm.Context) {
arg := new(model.ArgVipPriceByID)
if err := c.Bind(arg); err != nil {
return
}
c.JSON(vipSvc.VipPriceByID(c, arg))
}

View File

@@ -0,0 +1,28 @@
package http
import (
"go-common/app/service/main/vip/model"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
)
func buyVipWithPoint(c *bm.Context) {
var (
err error
)
arg := new(model.ArgBuyPoint)
if err = c.Bind(arg); err != nil {
log.Error("buyVipWithPoint Bind err(%+v)", err)
return
}
if err = vipSvc.BuyVipWithPoint(c, arg.Mid, arg.Month); err != nil {
log.Error("BuyVipWithPoint(%d) err(%+v)", arg.Mid, err)
c.JSON(nil, err)
return
}
c.JSON(nil, nil)
}
func rule(c *bm.Context) {
c.JSON(vipSvc.PointRule(c))
}

View File

@@ -0,0 +1,91 @@
package http
import (
"go-common/app/service/main/vip/model"
"go-common/library/ecode"
bm "go-common/library/net/http/blademaster"
)
func codeInfo(c *bm.Context) {
arg := new(struct {
Code string `form:"code" validate:"required"`
})
if err := c.Bind(arg); err != nil {
return
}
c.JSON(vipSvc.CodeInfo(c, arg.Code))
}
func codeInfos(c *bm.Context) {
arg := new(struct {
Codes []string `form:"codes,split" validate:"required"`
})
if err := c.Bind(arg); err != nil {
return
}
c.JSON(vipSvc.CodeInfos(c, arg.Codes))
}
func openCode(c *bm.Context) {
var (
token *model.TokenResq
code *model.VipResourceCode
err error
)
arg := new(struct {
Token string `form:"token" validate:"required"`
Code string `form:"code" validate:"required"`
Verify string `form:"verify" validate:"required"`
Mid int64 `form:"mid" validate:"required"`
})
if err = c.Bind(arg); err != nil {
return
}
if token, err = vipSvc.Verify(c, arg.Token, arg.Verify); err != nil {
c.JSON(nil, ecode.CreativeGeetestErr)
return
}
if token.Code != 0 {
c.JSON(nil, ecode.CreativeGeetestErr)
return
}
if code, err = vipSvc.OpenCode(c, arg.Code, arg.Mid); err != nil {
c.JSON(nil, err)
return
}
c.JSON(code, nil)
}
func belong(c *bm.Context) {
arg := new(struct {
Mid int64 `form:"mid" validate:"required"`
})
if err := c.Bind(arg); err != nil {
return
}
c.JSON(vipSvc.Belong(c, arg.Mid))
}
func actives(c *bm.Context) {
arg := new(struct {
RelationIDs []string `form:"relationIds,split" `
})
if err := c.Bind(arg); err != nil {
return
}
c.JSON(vipSvc.Actives(c, arg.RelationIDs))
}
func webToken(c *bm.Context) {
c.JSON(vipSvc.WebToken(c))
}
func codeOpened(c *bm.Context) {
arg := new(model.ArgCodeOpened)
if err := c.Bind(arg); err != nil {
return
}
c.JSON(vipSvc.CodeOpened(c, arg))
}

View File

@@ -0,0 +1,16 @@
package http
import (
"go-common/app/service/main/vip/model"
bm "go-common/library/net/http/blademaster"
)
func syncUser(c *bm.Context) {
var err error
user := new(model.VipUserInfo)
if err = c.Bind(user); err != nil {
return
}
vipSvc.SyncUser(c, user)
c.JSON(nil, nil)
}

View File

@@ -0,0 +1,26 @@
package http
import (
"go-common/app/service/main/vip/model"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
)
// tips info.
func tips(c *bm.Context) {
var (
res []*model.TipsResp
err error
arg = new(model.ArgTips)
)
if err = c.Bind(arg); err != nil {
log.Error("c.Bind err(%+v)", err)
return
}
if res, err = vipSvc.Tips(c, arg); err != nil {
log.Error("vipSvc.Tips(%+v) err(%+v)", arg, err)
c.JSON(nil, err)
return
}
c.JSON(res, nil)
}

View File

@@ -0,0 +1,101 @@
package http
import (
"go-common/app/service/main/vip/model"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
)
// byMid get vipinfo by mid.
func byMid(c *bm.Context) {
var (
res *model.VipInfoResp
err error
)
arg := new(struct {
Mid int64 `form:"mid" validate:"required"`
})
if err = c.Bind(arg); err != nil {
log.Error("c.Bind err(%+v)", err)
return
}
if res, err = vipSvc.ByMid(c, arg.Mid); err != nil {
log.Error("vipSvc.ByMid(%d) err(%+v)", arg.Mid, err)
c.JSON(nil, err)
return
}
c.JSON(res, nil)
}
func vipInfos(c *bm.Context) {
var (
vMap map[int64]*model.VipInfoResp
err error
)
arg := new(struct {
Mids []int64 `form:"mids,split" validate:"required"`
})
if err = c.Bind(arg); err != nil {
log.Error("c.Bind err %+v", err)
return
}
if vMap, err = vipSvc.VipInfos(c, arg.Mids); err != nil {
log.Error("vipSvc.VipInfos(%v) err(%+v)", arg.Mids, err)
c.JSON(nil, err)
return
}
c.JSON(vMap, nil)
}
func vipHistory(c *bm.Context) {
var (
err error
)
arg := new(model.ArgChangeHistory)
if c.Bind(arg); err != nil {
log.Error("vipHistory(%d) err(%+v)", arg.Mid, err)
return
}
vh, count, err := vipSvc.History(c, arg)
rel := make(map[string]interface{})
rel["data"] = vh
rel["total"] = count
c.JSON(rel, err)
}
func vipH5History(c *bm.Context) {
var (
err error
)
arg := new(model.ArgChangeHistory)
if c.Bind(arg); err != nil {
log.Error("vipH5History(%d) err(%+v)", arg.Mid, err)
return
}
c.JSON(vipSvc.H5History(c, arg))
}
// vipInfo (for old service).
func vipInfo(c *bm.Context) {
var (
res *model.VipInfoBoResp
err error
)
arg := new(struct {
Mid int64 `form:"mid" validate:"required"`
})
if err = c.Bind(arg); err != nil {
log.Error("c.Bind err(%+v)", err)
return
}
if res, err = vipSvc.VipInfoBo(c, arg.Mid); err != nil {
log.Error("vipSvc.VipInfo(%d) err(%+v)", arg.Mid, err)
c.JSON(nil, err)
return
}
c.JSON(res, nil)
}

View File

@@ -0,0 +1,52 @@
package http
import (
"go-common/app/service/main/vip/model"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
)
func batchInfo(c *bm.Context) {
var (
err error
vib *model.VipResourceBatch
)
arg := new(struct {
BatchID int64 `form:"batchId" validate:"required,min=1,gte=1"`
Appkey string `form:"appkey"`
})
if err = c.Bind(arg); err != nil {
log.Error("batchInfo Bind error(%v)", err)
return
}
if vib, _, err = vipSvc.BatchInfo(c, arg.BatchID, arg.Appkey); err != nil {
log.Error("vipSvc.BatchInfo(%d) error(%v)", arg.BatchID, err)
c.JSON(nil, err)
return
}
c.JSON(vib, nil)
}
func useBatchInfo(c *bm.Context) {
var (
err error
)
arg := new(struct {
BatchID int64 `form:"batchId" validate:"required,min=1,gte=1"`
Appkey string `form:"appkey"`
Mid int64 `form:"mid" validate:"required,min=1,gte=1"`
OrderNo string `form:"orderNo" validate:"required"`
Remark string `form:"remark" validate:"required"`
})
if err = c.Bind(arg); err != nil {
log.Error("useBatchInfo Bind error(%v)", err)
return
}
c.JSON(nil, vipSvc.ResourceBatchOpenVip(c, &model.ArgUseBatch{
Mid: arg.Mid,
OrderNo: arg.OrderNo,
Remark: arg.Remark,
Appkey: arg.Appkey,
BatchID: arg.BatchID,
}))
}

View File

@@ -0,0 +1,95 @@
load(
"@io_bazel_rules_go//proto:def.bzl",
"go_proto_library",
)
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = [
"associate_banner.go",
"associate_bind.go",
"associate_ele_api.go",
"associate_model.go",
"associate_old.go",
"associate_open.go",
"associate_order.go",
"associate_panel.go",
"associate_params.go",
"bp.go",
"coupon.go",
"dialog.go",
"http.go",
"jointly.go",
"mail_api.go",
"model.go",
"notify.go",
"oldvip.go",
"order.go",
"panel.go",
"params.go",
"pay.go",
"platform.go",
"point.go",
"privilege.go",
"resource.go",
"rpc.go",
"tips.go",
"user.go",
"vip.go",
"welfare.go",
],
embed = [":model_go_proto"],
importpath = "go-common/app/service/main/vip/model",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/admin/main/vip/model:go_default_library",
"//app/service/main/coupon/api:go_default_library",
"//app/service/main/coupon/model:go_default_library",
"//library/time:go_default_library",
"//vendor/github.com/satori/go.uuid:go_default_library",
"@com_github_gogo_protobuf//gogoproto:go_default_library",
"@com_github_gogo_protobuf//proto: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"],
)
proto_library(
name = "model_proto",
srcs = ["vip.proto"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = ["@gogo_special_proto//github.com/gogo/protobuf/gogoproto"],
)
go_proto_library(
name = "model_go_proto",
compilers = ["@io_bazel_rules_go//proto:gogofast_proto"],
importpath = "go-common/app/service/main/vip/model",
proto = ":model_proto",
tags = ["automanaged"],
deps = [
"//library/time:go_default_library",
"@com_github_gogo_protobuf//gogoproto:go_default_library",
],
)

View File

@@ -0,0 +1,31 @@
package model
// associate_platform
const (
AssociatePlatformNone int8 = iota
AssociatePlatformAndroidPink
AssociatePlatformIphonePink
AssociatePlatformIpadPink
)
// AssociatePlatform get platfrom.
func AssociatePlatform(platfrom, device, mobiApp string) int8 {
switch {
case platfrom == "ios" && device == "phone" && mobiApp == "iphone":
return AssociatePlatformIphonePink
case platfrom == "ios" && device == "pad" && mobiApp == "iphone":
return AssociatePlatformIpadPink
case platfrom == "android" && mobiApp == "android":
return AssociatePlatformAndroidPink
default:
return AssociatePlatformNone
}
}
// AssociateVipResp associate vip resp
type AssociateVipResp struct {
Title string `json:"title"`
Remark string `json:"remark"`
Link string `json:"link"`
AssociatePlatform int8 `json:"associate_platform"`
}

View File

@@ -0,0 +1,27 @@
package model
// BindInfo struct.
type BindInfo struct {
Account *BindAccount `json:"account"`
Outer *BindOuter `json:"outer"`
}
// BindAccount bind account.
type BindAccount struct {
Mid int64 `json:"mid"`
Name string `json:"name"`
Face string `json:"face"`
}
// BindOuter outer bind info.
type BindOuter struct {
Tel string `json:"tel"`
BindState int32 `json:"bind_state"`
}
// ArgOpenBindByMid args.
type ArgOpenBindByMid struct {
Mid int64
AppID int64
OutOpenID string
}

View File

@@ -0,0 +1,98 @@
package model
// ArgEleAccessToken ele access token args.
type ArgEleAccessToken struct {
AuthCode string `json:"auth_code"`
}
// EleAccessTokenResp ele access token resp.
type EleAccessTokenResp struct {
OpenID string `json:"open_id"`
}
// ArgEleReceivePrizes receive prizes args.
type ArgEleReceivePrizes struct {
ElemeOpenID string `json:"eleme_open_id"`
BliOpenID string `json:"bli_open_id"`
SourceID string `json:"source_id"`
}
// EleReceivePrizesResp receive prizes resp.
type EleReceivePrizesResp struct {
Amount float64 `json:"amount"`
SumCondition float64 `json:"sum_condition"`
Description string `json:"description"`
}
// ArgEleUnionUpdateOpenID union update open id args.
type ArgEleUnionUpdateOpenID struct {
ElemeOpenID string `json:"eleme_open_id"`
BliOpenID string `json:"bli_open_id"`
}
// EleUnionUpdateOpenIDResp union update resp.
type EleUnionUpdateOpenIDResp struct {
Status int32 `json:"status"`
Message string `json:"message"`
}
// ArgEleBindUnion ele salary bind vip args.
type ArgEleBindUnion struct {
ElemeOpenID string `json:"eleme_open_id"`
BliOpenID string `json:"bli_open_id"`
VipType int32 `json:"vip_type"`
SourceID string `json:"source_id"`
UserIP string `json:"user_ip"`
}
// EleBindUnionResp ele bind union resp.
type EleBindUnionResp struct {
Status int32 `json:"status"`
Message string `json:"message"`
}
// ArgEleCanPurchase ele can purchase args.
type ArgEleCanPurchase struct {
ElemeOpenID string `json:"eleme_open_id"`
BliOpenID string `json:"bli_open_id"`
UserIP string `json:"user_ip"`
VipType int32 `json:"vip_type"`
}
// EleCanPurchaseResp ele can purchase resp.
type EleCanPurchaseResp struct {
CanPurchase bool `json:"can_purchase"`
Status int32 `json:"status"`
Message string `json:"message"`
}
// ArgEleUnionMobile ele union mobile.
type ArgEleUnionMobile struct {
ElemeOpenID string `json:"eleme_open_id"`
BliOpenID string `json:"bli_open_id"`
}
// EleUnionMobileResp ele get union mobile resp.
type EleUnionMobileResp struct {
Status int32 `json:"status"`
Message string `json:"message"`
BlurMobile string `json:"blur_mobile"`
}
// EleRedPackagesResp ele red packages.
type EleRedPackagesResp struct {
Name string `json:"name"`
Amount float64 `json:"amount"`
SumCondition float64 `json:"sum_condition"`
}
// EleSpecailFoodsResp ele specail foods resp.
type EleSpecailFoodsResp struct {
RestaurantName string `json:"restaurant_name"`
FoodName string `json:"food_name"`
FoodURL string `json:"food_url"`
Discount float64 `json:"discount"`
Amount float64 `json:"amount"`
OriginalAmount float64 `json:"original_amount"`
RatingPoint float64 `json:"rating_point"`
}

Some files were not shown because too many files have changed in this diff Show More