作者 yangfu

Merge remote-tracking branch 'origin/dev' into test

# Conflicts:
#	main.go
正在显示 84 个修改的文件 包含 3454 行增加480 行删除
@@ -59,11 +59,11 @@ spec: @@ -59,11 +59,11 @@ spec:
59 - name: POSTGRESQL_USER 59 - name: POSTGRESQL_USER
60 value: "postgres" 60 value: "postgres"
61 - name: POSTGRESQL_PASSWORD 61 - name: POSTGRESQL_PASSWORD
62 - value: "postgres_15432" 62 + value: "eagle1010"
63 - name: POSTGRESQL_HOST 63 - name: POSTGRESQL_HOST
64 - value: "101.37.68.23" 64 + value: "114.55.200.59"
65 - name: POSTGRESQL_PORT 65 - name: POSTGRESQL_PORT
66 - value: "15432" 66 + value: "31543"
67 - name: LOG_LEVEL 67 - name: LOG_LEVEL
68 value: "debug" 68 value: "debug"
69 - name: ERROR_BASE_CODE 69 - name: ERROR_BASE_CODE
@@ -74,6 +74,13 @@ spec: @@ -74,6 +74,13 @@ spec:
74 value: "https://suplus-worth-app-gateway-dev.fjmaimaimai.com" 74 value: "https://suplus-worth-app-gateway-dev.fjmaimaimai.com"
75 - name: MMM_OPEN_API_SERVICE_HOST 75 - name: MMM_OPEN_API_SERVICE_HOST
76 value: "http://mmm-open-api-dev.fjmaimaimai.com" 76 value: "http://mmm-open-api-dev.fjmaimaimai.com"
  77 + - name: UCENTER_SERVICE_HOST
  78 + value: "https://suplus-ucenter-dev.fjmaimaimai.com"
  79 + - name: BUSINESS_ADMIN_SERVICE_HOST
  80 + valueFrom:
  81 + configMapKeyRef:
  82 + name: suplus-config
  83 + key: service.businessadmin
77 volumes: 84 volumes:
78 - name: accesslogs 85 - name: accesslogs
79 emptyDir: {} 86 emptyDir: {}
@@ -74,6 +74,13 @@ spec: @@ -74,6 +74,13 @@ spec:
74 value: "https://ability.fjmaimaimai.com" 74 value: "https://ability.fjmaimaimai.com"
75 - name: MMM_OPEN_API_SERVICE_HOST 75 - name: MMM_OPEN_API_SERVICE_HOST
76 value: "https://public-interface.fjmaimaimai.com/openapi" 76 value: "https://public-interface.fjmaimaimai.com/openapi"
  77 + - name: UCENTER_SERVICE_HOST
  78 + value: "https://suplus-ucenter-prd.fjmaimaimai.com"
  79 + - name: BUSINESS_ADMIN_SERVICE_HOST
  80 + valueFrom:
  81 + configMapKeyRef:
  82 + name: suplus-config
  83 + key: service.businessadmin
77 volumes: 84 volumes:
78 - name: accesslogs 85 - name: accesslogs
79 emptyDir: {} 86 emptyDir: {}
@@ -74,6 +74,13 @@ spec: @@ -74,6 +74,13 @@ spec:
74 value: "https://suplus-worth-app-gateway-dev.fjmaimaimai.com" 74 value: "https://suplus-worth-app-gateway-dev.fjmaimaimai.com"
75 - name: MMM_OPEN_API_SERVICE_HOST 75 - name: MMM_OPEN_API_SERVICE_HOST
76 value: "http://mmm-open-api-dev.fjmaimaimai.com" 76 value: "http://mmm-open-api-dev.fjmaimaimai.com"
  77 + - name: UCENTER_SERVICE_HOST
  78 + value: "https://suplus-ucenter-test.fjmaimaimai.com"
  79 + - name: BUSINESS_ADMIN_SERVICE_HOST
  80 + valueFrom:
  81 + configMapKeyRef:
  82 + name: suplus-config
  83 + key: service.businessadmin
77 volumes: 84 volumes:
78 - name: accesslogs 85 - name: accesslogs
79 emptyDir: {} 86 emptyDir: {}
@@ -5,9 +5,11 @@ go 1.14 @@ -5,9 +5,11 @@ go 1.14
5 require ( 5 require (
6 github.com/astaxie/beego v1.12.1 6 github.com/astaxie/beego v1.12.1
7 github.com/dgrijalva/jwt-go v3.2.0+incompatible 7 github.com/dgrijalva/jwt-go v3.2.0+incompatible
  8 + github.com/gin-gonic/gin v1.5.0
  9 + github.com/go-pg/pg v8.0.6+incompatible
8 github.com/go-pg/pg/v10 v10.0.0-beta.2 10 github.com/go-pg/pg/v10 v10.0.0-beta.2
9 github.com/linmadan/egglib-go v0.0.0-20191217144343-ca4539f95bf9 11 github.com/linmadan/egglib-go v0.0.0-20191217144343-ca4539f95bf9
10 github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644 // indirect 12 github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644 // indirect
11 github.com/shopspring/decimal v1.2.0 13 github.com/shopspring/decimal v1.2.0
12 - github.com/tiptok/gocomm v1.0.0 14 + github.com/tiptok/gocomm v1.0.1
13 ) 15 )
@@ -4,9 +4,12 @@ import ( @@ -4,9 +4,12 @@ import (
4 "fmt" 4 "fmt"
5 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/application/factory" 5 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/application/factory"
6 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain" 6 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain"
  7 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/domain_service"
7 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/utils" 8 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/utils"
8 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/log" 9 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/log"
9 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/protocol" 10 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/protocol"
  11 + protocolx "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/protocol/auth"
  12 + "strconv"
10 "strings" 13 "strings"
11 "time" 14 "time"
12 ) 15 )
@@ -66,9 +69,15 @@ func Login(header *protocol.RequestHeader, request *protocol.LoginRequest) (rsp @@ -66,9 +69,15 @@ func Login(header *protocol.RequestHeader, request *protocol.LoginRequest) (rsp
66 err = protocol.NewCustomMessage(1, "登录方式不支持!") 69 err = protocol.NewCustomMessage(1, "登录方式不支持!")
67 break 70 break
68 } 71 }
69 - rsp.AuthCode, _ = utils.GenerateToken(partnerInfo.Id, protocol.AuthCodeExpire*time.Second) 72 + userClaim := utils.UserTokenClaims{
  73 + UserId: partnerInfo.Id,
  74 + Phone: partnerInfo.Account,
  75 + AdminType: int(protocolx.AdminTypePartner),
  76 + CompanyId: 1, //默认公司
  77 + }
  78 + rsp.AuthCode, _ = utils.GenerateTokenWithClaim(userClaim, protocol.AuthCodeExpire*time.Second)
70 79
71 - if err = InitOrUpdateUserIMInfo(partnerInfo, transactionContext); err != nil { 80 + if _, err = InitOrUpdateUserIMInfo(partnerInfo.Id, partnerInfo.PartnerName, transactionContext); err != nil {
72 log.Error(err) 81 log.Error(err)
73 return 82 return
74 } 83 }
@@ -105,8 +114,14 @@ func AccessToken(request *protocol.AccessTokenRequest) (rsp *protocol.AccessToke @@ -105,8 +114,14 @@ func AccessToken(request *protocol.AccessTokenRequest) (rsp *protocol.AccessToke
105 err = protocol.NewErrWithMessage(1, fmt.Errorf("jwt authCode (%v) valid", request.AuthCode)) 114 err = protocol.NewErrWithMessage(1, fmt.Errorf("jwt authCode (%v) valid", request.AuthCode))
106 return 115 return
107 } 116 }
108 - rsp.AccessToken, _ = utils.GenerateToken(claim.UserId, protocol.TokenExpire*time.Second)  
109 - rsp.RefreshToken, _ = utils.GenerateToken(claim.UserId, protocol.RefreshTokenExipre*time.Second) 117 + userClaims := utils.UserTokenClaims{
  118 + UserId: claim.UserId,
  119 + CompanyId: claim.CompanyId,
  120 + AdminType: claim.AdminType,
  121 + Phone: claim.Phone,
  122 + }
  123 + rsp.AccessToken, _ = utils.GenerateTokenWithClaim(userClaims, protocol.TokenExpire*time.Second)
  124 + rsp.RefreshToken, _ = utils.GenerateTokenWithClaim(userClaims, protocol.RefreshTokenExipre*time.Second)
110 rsp.ExpiresIn = protocol.TokenExpire 125 rsp.ExpiresIn = protocol.TokenExpire
111 126
112 //auth := userAuth.NewRedisUserAuth(userAuth.WithUserId(claim.UserId), 127 //auth := userAuth.NewRedisUserAuth(userAuth.WithUserId(claim.UserId),
@@ -121,8 +136,25 @@ func AccessToken(request *protocol.AccessTokenRequest) (rsp *protocol.AccessToke @@ -121,8 +136,25 @@ func AccessToken(request *protocol.AccessTokenRequest) (rsp *protocol.AccessToke
121 136
122 func RefreshToken(request *protocol.RefreshTokenRequest) (rsp *protocol.RefreshTokenResponse, err error) { 137 func RefreshToken(request *protocol.RefreshTokenRequest) (rsp *protocol.RefreshTokenResponse, err error) {
123 var ( 138 var (
124 - claim *utils.UserTokenClaims 139 + claim *utils.UserTokenClaims
  140 + transactionContext, _ = factory.CreateTransactionContext(nil)
  141 + PartnerInfoService, _ = factory.CreatePartnerInfoRepositoryIn(transactionContext)
  142 + UsersRepository, _ = factory.CreateUsersRepository(transactionContext)
  143 + CompanyRepository, _ = factory.CreateCompanyRepository(transactionContext)
  144 +
  145 + partnerInfo *domain.PartnerInfo
  146 + user *domain.Users
  147 + company *domain.Company
  148 + userId int64
125 ) 149 )
  150 +
  151 + if err = transactionContext.StartTransaction(); err != nil {
  152 + return nil, err
  153 + }
  154 + defer func() {
  155 + transactionContext.RollbackTransaction()
  156 + }()
  157 +
126 rsp = &protocol.RefreshTokenResponse{} 158 rsp = &protocol.RefreshTokenResponse{}
127 if claim, err = utils.ParseJWTToken(request.RefreshToken); err != nil { 159 if claim, err = utils.ParseJWTToken(request.RefreshToken); err != nil {
128 err = protocol.NewErrWithMessage(4140, err) 160 err = protocol.NewErrWithMessage(4140, err)
@@ -132,14 +164,48 @@ func RefreshToken(request *protocol.RefreshTokenRequest) (rsp *protocol.RefreshT @@ -132,14 +164,48 @@ func RefreshToken(request *protocol.RefreshTokenRequest) (rsp *protocol.RefreshT
132 err = protocol.NewErrWithMessage(1, fmt.Errorf("jwt refrshToken (%v) valid", request.RefreshToken)) 164 err = protocol.NewErrWithMessage(1, fmt.Errorf("jwt refrshToken (%v) valid", request.RefreshToken))
133 return 165 return
134 } 166 }
  167 + if company, err = CompanyRepository.FindOne(map[string]interface{}{"id": claim.CompanyId, "status": 1, "enable": 1}); err != nil || company == nil {
  168 + log.Error(err)
  169 + err = protocol.NewErrWithMessage(4140, err)
  170 + return
  171 + }
  172 +
  173 + switch claim.AdminType {
  174 + case int(protocolx.AdminTypePartner):
  175 + if partnerInfo, err = PartnerInfoService.FindOne(map[string]interface{}{"account": claim.Phone, "companyId": claim.CompanyId, "status": 1}); err != nil || partnerInfo == nil {
  176 + log.Error(err)
  177 + err = protocol.NewErrWithMessage(4140, err)
  178 + return
  179 + }
  180 + userId = partnerInfo.Id
  181 + break
  182 + case int(protocolx.AdminTypeManager):
  183 + if user, err = UsersRepository.FindOne(map[string]interface{}{"phone": claim.Phone, "companyId": claim.CompanyId, "status": 1}); err != nil || user == nil {
  184 + log.Error(err)
  185 + err = protocol.NewErrWithMessage(4140, err)
  186 + return
  187 + }
  188 + userId = user.Id
  189 + break
  190 + default:
  191 + err = protocol.NewErrWithMessage(4140, err)
  192 + return
  193 + }
  194 +
135 //oldAuth := userAuth.NewRedisUserAuth(userAuth.WithUserId(claim.UserId)) 195 //oldAuth := userAuth.NewRedisUserAuth(userAuth.WithUserId(claim.UserId))
136 //if err = oldAuth.Check(userAuth.NewOptions(userAuth.WithRefreshToken(request.RefreshToken))); err != nil { 196 //if err = oldAuth.Check(userAuth.NewOptions(userAuth.WithRefreshToken(request.RefreshToken))); err != nil {
137 // log.Error(err) 197 // log.Error(err)
138 // err = protocol.NewErrWithMessage(4140, err) 198 // err = protocol.NewErrWithMessage(4140, err)
139 // return 199 // return
140 //} 200 //}
141 - rsp.AccessToken, _ = utils.GenerateToken(claim.UserId, protocol.TokenExpire*time.Second)  
142 - rsp.RefreshToken, _ = utils.GenerateToken(claim.UserId, protocol.RefreshTokenExipre*time.Second) 201 + userClaim := utils.UserTokenClaims{
  202 + UserId: userId,
  203 + Phone: claim.Phone,
  204 + AdminType: claim.AdminType,
  205 + CompanyId: claim.CompanyId,
  206 + }
  207 + rsp.AccessToken, _ = utils.GenerateTokenWithClaim(userClaim, protocol.TokenExpire*time.Second)
  208 + rsp.RefreshToken, _ = utils.GenerateTokenWithClaim(userClaim, protocol.RefreshTokenExipre*time.Second)
143 rsp.ExpiresIn = protocol.TokenExpire 209 rsp.ExpiresIn = protocol.TokenExpire
144 210
145 //newAuth := userAuth.NewRedisUserAuth(userAuth.WithUserId(claim.UserId), 211 //newAuth := userAuth.NewRedisUserAuth(userAuth.WithUserId(claim.UserId),
@@ -149,6 +215,7 @@ func RefreshToken(request *protocol.RefreshTokenRequest) (rsp *protocol.RefreshT @@ -149,6 +215,7 @@ func RefreshToken(request *protocol.RefreshTokenRequest) (rsp *protocol.RefreshT
149 // log.Error(err) 215 // log.Error(err)
150 // return 216 // return
151 //} 217 //}
  218 + err = transactionContext.CommitTransaction()
152 return 219 return
153 } 220 }
154 221
@@ -192,3 +259,156 @@ func Revoke(header *protocol.RequestHeader, request *protocol.RevokeRequest) (rs @@ -192,3 +259,156 @@ func Revoke(header *protocol.RequestHeader, request *protocol.RevokeRequest) (rs
192 //} 259 //}
193 return 260 return
194 } 261 }
  262 +
  263 +func CenterCompanys(header *protocol.RequestHeader, request *protocolx.CenterCompanysRequest) (v interface{}, err error) {
  264 + var (
  265 + transactionContext, _ = factory.CreateTransactionContext(nil)
  266 + imInfo *domain.ImInfo
  267 + loginSvr = domain_service.NewPgLoginService(transactionContext)
  268 + )
  269 + phoneId, e := strconv.Atoi(request.Phone)
  270 + if e != nil {
  271 + log.Error(e)
  272 + e = protocol.NewErrWithMessage(2)
  273 + return
  274 + }
  275 + rsp := &protocolx.CenterCompanysResponse{}
  276 + if err = transactionContext.StartTransaction(); err != nil {
  277 + log.Error(err)
  278 + return nil, err
  279 + }
  280 + defer func() {
  281 + transactionContext.RollbackTransaction()
  282 + }()
  283 + loginSvr.Init(request.Phone)
  284 + if len(loginSvr.Users) == 0 && len(loginSvr.PartnerInfo) == 0 {
  285 + err = protocol.NewErrWithMessage(502, err) //账号不存在
  286 + return
  287 + }
  288 + switch request.GrantType {
  289 + case protocol.LoginByPassword:
  290 + if len(request.Password) == 0 {
  291 + err = protocol.NewCustomMessage(1, "密码不能为空!")
  292 + return
  293 + }
  294 + if loginSvr.ManagerLogin(request.Phone, request.Password) != nil && loginSvr.PartnerLogin(request.Phone, request.Password) != nil {
  295 + err = protocol.NewCustomMessage(1, "密码输入有误!")
  296 + return
  297 + }
  298 + break
  299 + case protocol.LoginBySmsCode:
  300 + if _, err = CheckSmsCode(request.Phone, request.Captcha); err != nil {
  301 + return
  302 + }
  303 + break
  304 + default:
  305 + err = protocol.NewCustomMessage(1, "登录方式不支持!")
  306 + break
  307 + }
  308 +
  309 + //获取统计信息
  310 + rsp.Partner, _ = loginSvr.PartnerStaticInfo()
  311 + rsp.Manager, _ = loginSvr.ManagerStaticInfo()
  312 + //没有有效人的时候
  313 + //if rsp.Partner ==nil && rsp.Manager ==nil{
  314 + // err = protocol.NewErrWithMessage(2002) //账号禁用
  315 + // return
  316 + //}
  317 +
  318 + var nickName string
  319 + if len(loginSvr.Users) > 0 {
  320 + nickName = loginSvr.Users[0].Name
  321 + } else if len(loginSvr.PartnerInfo) > 0 {
  322 + nickName = loginSvr.PartnerInfo[0].PartnerName
  323 + }
  324 + //初始化im信息
  325 + if imInfo, err = InitOrUpdateUserIMInfo(int64(phoneId), nickName, transactionContext); err != nil {
  326 + log.Error(err)
  327 + return
  328 + }
  329 +
  330 + rsp.CsAccountID = fmt.Sprintf("%v", imInfo.CustomerImId)
  331 + rsp.ImToken = imInfo.ImToken
  332 + rsp.Accid, _ = strconv.Atoi(imInfo.ImId)
  333 + rsp.Credentials, _ = utils.GenerateToken(int64(phoneId), request.Phone, protocol.RefreshTokenExipre*time.Second)
  334 +
  335 + err = transactionContext.CommitTransaction()
  336 + v = map[string]interface{}{"center": rsp}
  337 + return
  338 +}
  339 +
  340 +func Companys(header *protocol.RequestHeader, request *protocolx.CompanysRequest) (rsp *protocolx.CompanysResponse, err error) {
  341 + var (
  342 + transactionContext, _ = factory.CreateTransactionContext(nil)
  343 + loginSvr = domain_service.NewPgLoginService(transactionContext)
  344 + claim *utils.UserTokenClaims
  345 + )
  346 + rsp = &protocolx.CompanysResponse{}
  347 + if err = transactionContext.StartTransaction(); err != nil {
  348 + log.Error(err)
  349 + return nil, err
  350 + }
  351 + defer func() {
  352 + transactionContext.RollbackTransaction()
  353 + }()
  354 + if claim, err = utils.ParseJWTToken(request.Credentials); err != nil {
  355 + err = protocol.NewErrWithMessage(4139, err)
  356 + return
  357 + }
  358 + loginSvr.Init(claim.Phone)
  359 + rsp.Partner, _ = loginSvr.PartnerStaticInfo()
  360 + rsp.Manager, _ = loginSvr.ManagerStaticInfo()
  361 + err = transactionContext.CommitTransaction()
  362 + return
  363 +}
  364 +
  365 +func LoginV2(header *protocol.RequestHeader, request *protocol.LoginRequestV2) (rsp *protocol.LoginResponse, err error) {
  366 + var (
  367 + claim *utils.UserTokenClaims
  368 + transactionContext, _ = factory.CreateTransactionContext(nil)
  369 + PartnerInfoRepository, _ = factory.CreatePartnerInfoRepositoryIn(transactionContext)
  370 + UsersRepository, _ = factory.CreateUsersRepository(transactionContext)
  371 + userId int64
  372 + )
  373 + rsp = &protocol.LoginResponse{}
  374 + if err = transactionContext.StartTransaction(); err != nil {
  375 + return nil, err
  376 + }
  377 + defer func() {
  378 + transactionContext.RollbackTransaction()
  379 + }()
  380 + if claim, err = utils.ParseJWTToken(request.Credentials); err != nil {
  381 + err = protocol.NewErrWithMessage(4140, err)
  382 + return
  383 + }
  384 + switch request.IdType {
  385 + case int(protocolx.AdminTypePartner):
  386 + if p, e := PartnerInfoRepository.FindOne(map[string]interface{}{"account": claim.Phone, "companyId": request.Cid, "status": 1}); e == nil {
  387 + userId = p.Id
  388 + }
  389 + break
  390 + case int(protocolx.AdminTypeManager):
  391 + if p, e := UsersRepository.FindOne(map[string]interface{}{"phone": claim.Phone, "companyId": request.Cid, "status": 1}); e == nil {
  392 + userId = p.Id
  393 + }
  394 + break
  395 + default:
  396 + err = protocol.NewErrWithMessage(2, fmt.Errorf("idType :%v not in range (1,2)", request.IdType)) //用户类型有误
  397 + return
  398 + }
  399 + if userId == 0 {
  400 + err = protocol.NewErrWithMessage(502, err) //账号不存在
  401 + return
  402 + }
  403 + //根据simnum + cid
  404 + userClaims := utils.UserTokenClaims{
  405 + UserId: userId,
  406 + CompanyId: int64(request.Cid),
  407 + AdminType: request.IdType,
  408 + Phone: claim.Phone,
  409 + }
  410 + rsp.AuthCode, _ = utils.GenerateTokenWithClaim(userClaims, protocol.AuthCodeExpire*time.Second)
  411 +
  412 + err = transactionContext.CommitTransaction()
  413 + return
  414 +}
@@ -15,28 +15,29 @@ import ( @@ -15,28 +15,29 @@ import (
15 ) 15 )
16 16
17 // 更新用户 IM INFO 17 // 更新用户 IM INFO
18 -func InitOrUpdateUserIMInfo(partnerInfo *domain.PartnerInfo, ctx *transaction.TransactionContext) (err error) { 18 +func InitOrUpdateUserIMInfo(userId int64, name string, ctx *transaction.TransactionContext) (imInfo *domain.ImInfo, err error) {
19 var ( 19 var (
20 ImInfoRepository, _ = factory.CreateImInfoRepository(ctx) 20 ImInfoRepository, _ = factory.CreateImInfoRepository(ctx)
21 checkImRequest *protocol.CheckImRequest = &protocol.CheckImRequest{} 21 checkImRequest *protocol.CheckImRequest = &protocol.CheckImRequest{}
22 IsCreated = false 22 IsCreated = false
23 checkImResponse *protocol.CheckImResponse 23 checkImResponse *protocol.CheckImResponse
24 ) 24 )
25 - imInfo, e := ImInfoRepository.FindOne(map[string]interface{}{"user_id": partnerInfo.Id}) 25 + var errFind error
  26 + imInfo, errFind = ImInfoRepository.FindOne(map[string]interface{}{"user_id": userId})
26 // 异常 27 // 异常
27 - if e != nil && e != domain.QueryNoRow {  
28 - err = e 28 + if errFind != nil && errFind != domain.QueryNoRow {
  29 + err = errFind
29 return 30 return
30 } 31 }
31 // 不存在 32 // 不存在
32 - if e == domain.QueryNoRow { 33 + if errFind == domain.QueryNoRow {
33 imInfo = &domain.ImInfo{ 34 imInfo = &domain.ImInfo{
34 - UserId: partnerInfo.Id, 35 + UserId: userId,
35 CreateTime: time.Now(), 36 CreateTime: time.Now(),
36 } 37 }
37 } 38 }
38 // 已存在 39 // 已存在
39 - if e == nil && imInfo != nil { 40 + if errFind == nil && imInfo != nil {
40 IsCreated = true 41 IsCreated = true
41 } 42 }
42 43
@@ -47,7 +48,7 @@ func InitOrUpdateUserIMInfo(partnerInfo *domain.PartnerInfo, ctx *transaction.Tr @@ -47,7 +48,7 @@ func InitOrUpdateUserIMInfo(partnerInfo *domain.PartnerInfo, ctx *transaction.Tr
47 checkImRequest = &protocol.CheckImRequest{ 48 checkImRequest = &protocol.CheckImRequest{
48 UserId: imInfo.UserId, 49 UserId: imInfo.UserId,
49 ImId: imInfo.ImId, 50 ImId: imInfo.ImId,
50 - Uname: partnerInfo.PartnerName, 51 + Uname: name,
51 CustomerImId: fmt.Sprintf("%v", imInfo.CustomerImId), 52 CustomerImId: fmt.Sprintf("%v", imInfo.CustomerImId),
52 IsCreated: IsCreated, 53 IsCreated: IsCreated,
53 } 54 }
@@ -55,7 +56,7 @@ func InitOrUpdateUserIMInfo(partnerInfo *domain.PartnerInfo, ctx *transaction.Tr @@ -55,7 +56,7 @@ func InitOrUpdateUserIMInfo(partnerInfo *domain.PartnerInfo, ctx *transaction.Tr
55 return 56 return
56 } 57 }
57 if imInfo.CustomerImId == 0 { 58 if imInfo.CustomerImId == 0 {
58 - imInfo.CustomerImId = getRandomCustomerAccount(partnerInfo.Id, ctx) 59 + imInfo.CustomerImId = getRandomCustomerAccount(userId, ctx)
59 } 60 }
60 imInfo.ImToken = checkImResponse.ImToken 61 imInfo.ImToken = checkImResponse.ImToken
61 imInfo.UpdateTime = time.Now() 62 imInfo.UpdateTime = time.Now()
  1 +package company
  2 +
  3 +import (
  4 + "github.com/tiptok/gocomm/pkg/log"
  5 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/application/factory"
  6 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain"
  7 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg/transaction"
  8 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/utils"
  9 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/protocol"
  10 + protocolx "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/protocol/company"
  11 + "strings"
  12 +)
  13 +
  14 +func Property(header *protocol.RequestHeader, request *protocolx.PropertyRequest) (rsp *protocolx.PropertyResponse, err error) {
  15 + var (
  16 + transactionContext, _ = factory.CreateTransactionContext(nil)
  17 + )
  18 + rsp = &protocolx.PropertyResponse{}
  19 + if err = transactionContext.StartTransaction(); err != nil {
  20 + log.Error(err)
  21 + return nil, err
  22 + }
  23 + defer func() {
  24 + transactionContext.RollbackTransaction()
  25 + }()
  26 +
  27 + //用户查询区域
  28 + if (request.Action & 0x01) > 0 {
  29 + rsp.Districts, _ = getDistricts(header.UserId, transactionContext)
  30 + }
  31 + //查询合伙人类型
  32 + if (request.Action & 0x02) > 0 {
  33 + rsp.JoinWays, _ = getJoinWays(transactionContext)
  34 + }
  35 + err = transactionContext.CommitTransaction()
  36 + return
  37 +}
  38 +
  39 +func Partners(header *protocol.RequestHeader, request *protocolx.PartnersRequest) (rsp *protocolx.PartnersResponse, err error) {
  40 + var (
  41 + transactionContext, _ = factory.CreateTransactionContext(nil)
  42 + )
  43 + rsp = &protocolx.PartnersResponse{}
  44 + if err = transactionContext.StartTransaction(); err != nil {
  45 + log.Error(err)
  46 + return nil, err
  47 + }
  48 + defer func() {
  49 + transactionContext.RollbackTransaction()
  50 + }()
  51 + if rsp.Partners, err = getPartners(header.UserId, request, transactionContext); err != nil {
  52 + log.Error(err)
  53 + return
  54 + }
  55 + if rsp.Partners == nil {
  56 + rsp.Partners = []struct{}{}
  57 + }
  58 + err = transactionContext.CommitTransaction()
  59 + return
  60 +}
  61 +
  62 +func Statistics(header *protocol.RequestHeader, request *protocolx.StatisticsRequest) (rsp *protocolx.StatisticsResponse, err error) {
  63 + var (
  64 + transactionContext, _ = factory.CreateTransactionContext(nil)
  65 + )
  66 + rsp = &protocolx.StatisticsResponse{}
  67 + if err = transactionContext.StartTransaction(); err != nil {
  68 + log.Error(err)
  69 + return nil, err
  70 + }
  71 + defer func() {
  72 + transactionContext.RollbackTransaction()
  73 + }()
  74 + rsp.Statistics, err = getStatistics(header.UserId, transactionContext)
  75 + if err != nil {
  76 + log.Error(err)
  77 + return
  78 + }
  79 + err = transactionContext.CommitTransaction()
  80 + return
  81 +}
  82 +
  83 +// 获取区域列表
  84 +func getDistricts(userId int64, transactionContext *transaction.TransactionContext) (districts []protocolx.Districts, err error) {
  85 + var (
  86 + user *domain.Users
  87 + partnerInfos []*domain.PartnerInfo
  88 + UsersRepository, _ = factory.CreateUsersRepository(transactionContext)
  89 + PartnerInfoRepository, _ = factory.CreatePartnerInfoRepositoryIn(transactionContext)
  90 + )
  91 + if user, err = UsersRepository.FindOne(map[string]interface{}{"id": userId}); err != nil {
  92 + log.Error(err)
  93 + return
  94 + }
  95 + if user == nil || len(user.AccessPartners) == 0 {
  96 + return
  97 + }
  98 + if _, partnerInfos, err = PartnerInfoRepository.Find(map[string]interface{}{
  99 + "inPartnerIds": user.AccessPartnerIds(),
  100 + "sortByCreateTime": domain.ASC},
  101 + ); err != nil {
  102 + return
  103 + }
  104 + for i := range partnerInfos {
  105 + partner := partnerInfos[i]
  106 + include := false
  107 + if partner.RegionInfo == nil {
  108 + continue
  109 + }
  110 + for j := range districts {
  111 + if strings.TrimSpace(districts[j].Name) == strings.TrimSpace(partner.RegionInfo.RegionName) {
  112 + include = true
  113 + break
  114 + }
  115 + }
  116 + if !include {
  117 + districts = append(districts, protocolx.Districts{
  118 + Id: partner.RegionInfo.RegionId,
  119 + Name: partner.RegionInfo.RegionName,
  120 + })
  121 + }
  122 + }
  123 + return
  124 +}
  125 +
  126 +// 获取合伙人类型列表
  127 +func getJoinWays(transactionContext *transaction.TransactionContext) (joinWays []protocolx.JoinWays, err error) {
  128 + var (
  129 + CategoryInfoRepository, _ = factory.CreatePartnerCategoryInfoRepository(transactionContext)
  130 + categories []*domain.PartnerCategoryInfo
  131 + )
  132 + if _, categories, err = CategoryInfoRepository.Find(nil); err != nil && len(categories) == 0 {
  133 + return
  134 + }
  135 + for i := range categories {
  136 + c := categories[i]
  137 + joinWays = append(joinWays, protocolx.JoinWays{Type: c.Id, Name: c.Name})
  138 + }
  139 + return
  140 +}
  141 +
  142 +// 获取公司统计
  143 +func getStatistics(userId int64, transactionContext *transaction.TransactionContext) (interface{}, error) {
  144 + var (
  145 + UsersRepository, _ = factory.CreateUsersRepository(transactionContext)
  146 + PartnerInfoDao, _ = factory.CreatePartnerInfoDao(transactionContext)
  147 + OrderBaseDao, _ = factory.CreateOrderBaseDao(transactionContext)
  148 + BusinessBonusDao, _ = factory.CreateBusinessBonusDao(transactionContext)
  149 + //user *domain.Users
  150 + partnerIds []int64
  151 + )
  152 + if user, e := UsersRepository.FindOne(map[string]interface{}{"id": userId}); e != nil || user == nil {
  153 + return struct {
  154 + }{}, nil
  155 + } else {
  156 + partnerIds = user.AccessPartnerIds()
  157 + }
  158 + Statistics := make(map[string]interface{})
  159 + if count, e := PartnerInfoDao.PartnerStatic(map[string]interface{}{"inPartnerIds": partnerIds, "inPartnerCategory": domain.Career}); e == nil {
  160 + Statistics["careerCount"] = count
  161 + }
  162 + if count, e := PartnerInfoDao.PartnerStatic(map[string]interface{}{"inPartnerIds": partnerIds, "inPartnerCategory": domain.Business}); e == nil {
  163 + Statistics["businessCount"] = count
  164 + }
  165 + if count, e := PartnerInfoDao.PartnerStatic(map[string]interface{}{"inPartnerIds": partnerIds, "inPartnerCategory": domain.Develop}); e == nil {
  166 + Statistics["developCount"] = count
  167 + }
  168 + if count, e := PartnerInfoDao.PartnerStatic(map[string]interface{}{"inPartnerIds": partnerIds, "inPartnerCategory": domain.App}); e == nil {
  169 + Statistics["appCount"] = count
  170 + }
  171 + if bonus, e := OrderBaseDao.OrderBonusStatics(domain.OrderBonusQuery{InPartnerIds: partnerIds, OrderType: domain.OrderReal}); e == nil {
  172 + Statistics["careerOrdersMoney"] = bonus.TotalOrderAmount
  173 + Statistics["careerDividend"] = bonus.Bonus
  174 + }
  175 + if businessBonus, e := BusinessBonusDao.OrderBonusStatics(domain.OrderBonusQuery{InPartnerIds: partnerIds, IsDisable: 1}); e == nil {
  176 + Statistics["businessDividend"] = businessBonus.Bonus
  177 + Statistics["businessOrdersMoney"] = businessBonus.TotalOrderAmount
  178 + }
  179 + Statistics["developDividend"] = 0
  180 + Statistics["developOrdersMoney"] = 0
  181 + Statistics["appDividend"] = 0
  182 + Statistics["appOrdersMoney"] = 0
  183 + return Statistics, nil
  184 +}
  185 +
  186 +func getPartners(userId int64, request *protocolx.PartnersRequest, transactionContext *transaction.TransactionContext) (interface{}, error) {
  187 + var (
  188 + UsersRepository, _ = factory.CreateUsersRepository(transactionContext)
  189 + PartnerInfo, _ = factory.CreatePartnerInfoDao(transactionContext)
  190 + user *domain.Users
  191 + err error
  192 + PartnerCategoryInfoRepository, _ = factory.CreatePartnerCategoryInfoRepository(transactionContext)
  193 + )
  194 + if user, err = UsersRepository.FindOne(map[string]interface{}{"id": userId}); err != nil {
  195 + return nil, err
  196 + }
  197 + if len(user.AccessPartnerIds()) == 0 {
  198 + return nil, nil
  199 + }
  200 + mapCategoryInfo := make(map[int64]*domain.PartnerCategoryInfo)
  201 + if _, categories, e := PartnerCategoryInfoRepository.Find(nil); e == nil {
  202 + for i := range categories {
  203 + mapCategoryInfo[categories[i].Id] = categories[i]
  204 + }
  205 + }
  206 +
  207 + queryOption := make(map[string]interface{})
  208 +
  209 + if len(request.Districts) > 0 {
  210 + var districts []string
  211 + for i := 0; i < len(request.Districts); i++ {
  212 + districts = append(districts, request.Districts[i].Name)
  213 + }
  214 + queryOption["districts"] = districts
  215 + }
  216 + if len(request.JoinWays) > 0 {
  217 + var joinWays []int64
  218 + for i := 0; i < len(request.JoinWays); i++ {
  219 + joinWays = append(joinWays, request.JoinWays[i].Type)
  220 + }
  221 + queryOption["joinWays"] = joinWays
  222 + }
  223 + if request.StartTime > 0 {
  224 + queryOption["startTime"] = request.StartTime / 1000
  225 + }
  226 + if request.EndTime > 0 {
  227 + queryOption["endTime"] = request.EndTime / 1000
  228 + }
  229 + queryOption["limit"] = request.PageSize
  230 + queryOption["offset"] = request.PageSize * request.PageIndex
  231 +
  232 + queryOption["sortByBonus"] = domain.DESC
  233 + if request.SortBy != 0 {
  234 + queryOption["sortByBonus"] = domain.ASC
  235 + }
  236 +
  237 + if partners, e := PartnerInfo.Partners(user.AccessPartnerIds(), queryOption); e == nil {
  238 + var array []interface{}
  239 + for i := range partners {
  240 + mapPartners := make(map[string]interface{})
  241 + p := partners[i]
  242 + mapPartners["uid"] = p.Id
  243 + mapPartners["uname"] = p.PartnerName
  244 +
  245 + var joinWays []protocolx.JoinWays
  246 + for j := range p.PartnerCategoryInfos {
  247 + c := p.PartnerCategoryInfos[j]
  248 + if v, ok := mapCategoryInfo[c.Id]; ok {
  249 + joinWays = append(joinWays, protocolx.JoinWays{Type: v.Id, Name: v.Name})
  250 + }
  251 + }
  252 + mapPartners["joinWays"] = joinWays
  253 + if p.RegionInfo != nil {
  254 + mapPartners["district"] = protocolx.Districts{Id: p.RegionInfo.RegionId, Name: p.RegionInfo.RegionName}
  255 + }
  256 + mapPartners["cooperationTime"] = p.CooperateTime.Unix() * 1000
  257 + mapPartners["dividend"] = utils.Decimal(p.Bonus)
  258 + mapPartners["ordersCount"] = p.Total
  259 + mapPartners["ordersMoney"] = utils.Decimal(p.Amount)
  260 + array = append(array, mapPartners)
  261 + }
  262 + return array, nil
  263 + }
  264 + return nil, nil
  265 +}
@@ -12,10 +12,9 @@ import ( @@ -12,10 +12,9 @@ import (
12 // 分红统计 12 // 分红统计
13 func Statistics(header *protocol.RequestHeader, request *protocol.DividendStatisticsRequest) (rsp *protocol.DividendStatisticsResponse, err error) { 13 func Statistics(header *protocol.RequestHeader, request *protocol.DividendStatisticsRequest) (rsp *protocol.DividendStatisticsResponse, err error) {
14 var ( 14 var (
15 - transactionContext, _ = factory.CreateTransactionContext(nil)  
16 - OrderBaseResponsitory, _ = factory.CreateOrderBaseRepository(transactionContext)  
17 - //beginTime = time.Unix(request.StartTime/1000, 0)  
18 - //endTime = time.Unix(request.EndTime/1000, 0) 15 + transactionContext, _ = factory.CreateTransactionContext(nil)
  16 + OrderBaseResponsitory, _ = factory.CreateOrderBaseRepository(transactionContext)
  17 + BusinessBonusRepository, _ = factory.CreateBusinessBonusRepository(transactionContext)
19 ) 18 )
20 if err = transactionContext.StartTransaction(); err != nil { 19 if err = transactionContext.StartTransaction(); err != nil {
21 return nil, err 20 return nil, err
@@ -23,6 +22,8 @@ func Statistics(header *protocol.RequestHeader, request *protocol.DividendStatis @@ -23,6 +22,8 @@ func Statistics(header *protocol.RequestHeader, request *protocol.DividendStatis
23 defer func() { 22 defer func() {
24 transactionContext.RollbackTransaction() 23 transactionContext.RollbackTransaction()
25 }() 24 }()
  25 +
  26 + // 事业分红统计-查询订单
26 _, orderAll, e := OrderBaseResponsitory.Find(utils.ObjectJsonToMap(domain.OrderQueryOption{PartnerId: header.UserId, EndTime: time.Now(), SortByCreateTime: domain.DESC, OrderType: domain.OrderReal})) 27 _, orderAll, e := OrderBaseResponsitory.Find(utils.ObjectJsonToMap(domain.OrderQueryOption{PartnerId: header.UserId, EndTime: time.Now(), SortByCreateTime: domain.DESC, OrderType: domain.OrderReal}))
27 if e != nil { 28 if e != nil {
28 log.Error(e) 29 log.Error(e)
@@ -33,8 +34,16 @@ func Statistics(header *protocol.RequestHeader, request *protocol.DividendStatis @@ -33,8 +34,16 @@ func Statistics(header *protocol.RequestHeader, request *protocol.DividendStatis
33 orderBetween = append(orderBetween, orderAll[i]) 34 orderBetween = append(orderBetween, orderAll[i])
34 } 35 }
35 } 36 }
  37 + // 事业分红统计-所有订单统计
36 bonusAll := AllBonusStatics(orderAll, 0) 38 bonusAll := AllBonusStatics(orderAll, 0)
  39 + // 事业分红统计-季度订单统计
37 bonusQuarters := QuartersBonusStatics(orderBetween, 0) 40 bonusQuarters := QuartersBonusStatics(orderBetween, 0)
  41 +
  42 + // 业务分红统计
  43 + if bonus, e := BusinessBonusRepository.FindOne(map[string]interface{}{"partner_id": header.UserId, "isDisable": 1}); e == nil {
  44 + bonusAll.Receivable += bonus.Bonus
  45 + }
  46 +
38 rsp = &protocol.DividendStatisticsResponse{} 47 rsp = &protocol.DividendStatisticsResponse{}
39 rsp.Statistics = protocol.DividendStatistics{ 48 rsp.Statistics = protocol.DividendStatistics{
40 Received: bonusAll.Received, 49 Received: bonusAll.Received,
@@ -42,6 +51,7 @@ func Statistics(header *protocol.RequestHeader, request *protocol.DividendStatis @@ -42,6 +51,7 @@ func Statistics(header *protocol.RequestHeader, request *protocol.DividendStatis
42 Receivable: bonusAll.Receivable, 51 Receivable: bonusAll.Receivable,
43 Quarters: bonusQuarters, 52 Quarters: bonusQuarters,
44 } 53 }
  54 +
45 err = transactionContext.CommitTransaction() 55 err = transactionContext.CommitTransaction()
46 return 56 return
47 } 57 }
@@ -12,3 +12,7 @@ func CreatePartnerInfoDao(ctx *transaction.TransactionContext) (*dao.PartnerInfo @@ -12,3 +12,7 @@ func CreatePartnerInfoDao(ctx *transaction.TransactionContext) (*dao.PartnerInfo
12 func CreateOrderBaseDao(ctx *transaction.TransactionContext) (*dao.OrderBaseDao, error) { 12 func CreateOrderBaseDao(ctx *transaction.TransactionContext) (*dao.OrderBaseDao, error) {
13 return dao.NewOrderBaseDao(ctx) 13 return dao.NewOrderBaseDao(ctx)
14 } 14 }
  15 +
  16 +func CreateBusinessBonusDao(ctx *transaction.TransactionContext) (*dao.BusinessBonusDao, error) {
  17 + return dao.NewBusinessBonusDao(ctx)
  18 +}
@@ -56,3 +56,17 @@ func CreateImInfoRepository(transactionContext *transaction.TransactionContext) @@ -56,3 +56,17 @@ func CreateImInfoRepository(transactionContext *transaction.TransactionContext)
56 func CreateImCustomerServiceRepository(transactionContext *transaction.TransactionContext) (domain.ImCustomerServiceRepository, error) { 56 func CreateImCustomerServiceRepository(transactionContext *transaction.TransactionContext) (domain.ImCustomerServiceRepository, error) {
57 return repository.NewImCustomerServiceRepository(transactionContext) 57 return repository.NewImCustomerServiceRepository(transactionContext)
58 } 58 }
  59 +
  60 +// 合伙人类型
  61 +func CreatePartnerCategoryInfoRepository(transactionContext *transaction.TransactionContext) (domain.PartnerCategoryInfoRepository, error) {
  62 + return repository.NewPartnerCategoryInfoRepository(transactionContext)
  63 +}
  64 +
  65 +// 高管
  66 +func CreateUsersRepository(transactionContext *transaction.TransactionContext) (domain.UsersRepository, error) {
  67 + return repository.NewUsersRepository(transactionContext)
  68 +}
  69 +
  70 +func CreateBusinessBonusRepository(transactionContext *transaction.TransactionContext) (domain.BusinessBonusRepository, error) {
  71 + return repository.NewBusinessBonusRepository(transactionContext)
  72 +}
@@ -2,21 +2,243 @@ package order @@ -2,21 +2,243 @@ package order
2 2
3 import ( 3 import (
4 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/application/factory" 4 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/application/factory"
  5 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain"
  6 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/utils"
  7 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/log"
5 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/protocol" 8 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/protocol"
  9 + "time"
6 ) 10 )
7 11
8 -func Template(header *protocol.RequestHeader, request *protocol.OrderDetailRequest) (rsp *protocol.OrderDetailResponse, err error) { 12 +// 订单详情
  13 +func Detail(header *protocol.RequestHeader, request *protocol.OrderDetailRequest) (rsp *protocol.OrderDetailResponse, err error) {
9 var ( 14 var (
10 transactionContext, _ = factory.CreateTransactionContext(nil) 15 transactionContext, _ = factory.CreateTransactionContext(nil)
11 - //OrderResponsitory,_ =factory.CreateOrderRepository(transactionContext) 16 + OrderResponsitory, _ = factory.CreateOrderBaseRepository(transactionContext)
  17 + OrderDao, _ = factory.CreateOrderBaseDao(transactionContext)
  18 + order *domain.OrderBase
  19 + )
  20 + if err = transactionContext.StartTransaction(); err != nil {
  21 + return nil, err
  22 + }
  23 + defer func() {
  24 + transactionContext.RollbackTransaction()
  25 + }()
  26 + rsp = &protocol.OrderDetailResponse{}
  27 +
  28 + // 订单详情
  29 + if order, err = OrderResponsitory.FindOne(utils.ObjectJsonToMap(request)); err != nil {
  30 + log.Error(err)
  31 + return
  32 + }
  33 + rsp.Order = protocol.OrderDetail{
  34 + Id: order.Id,
  35 + OrderNo: order.OrderCode,
  36 + DeliveryNo: order.DeliveryCode,
  37 + OrderStatus: orderStatus(order),
  38 + CreateTime: order.CreateTime.Unix() * 1000,
  39 + UpdateTime: order.UpdateTime.Unix() * 1000,
  40 + OrderDistrict: map[string]interface{}{"id": order.RegionInfo.RegionId, "name": order.RegionInfo.RegionName},
  41 + Customer: protocol.Customer{Uname: order.Buyer.BuyerName, Phone: order.Buyer.ContactInfo},
  42 + Products: orderProducts(order),
  43 + Total: orderTotalStatic(order),
  44 + }
  45 +
  46 + // 更新已读(关联事件)
  47 + if header.UserId == order.PartnerId && order.UpdateTime.After(order.LastViewTime) {
  48 + if err = OrderDao.UpdateLastViewTime(order.Id, time.Now()); err != nil {
  49 + return
  50 + }
  51 + }
  52 +
  53 + err = transactionContext.CommitTransaction()
  54 + return
  55 +}
  56 +func orderStatus(order *domain.OrderBase) int {
  57 + var hasBonus = false
  58 + for i := range order.OrderGood {
  59 + good := order.OrderGood[i]
  60 + if good.BonusStatus == domain.BonusPaid {
  61 + hasBonus = true
  62 + break
  63 + }
  64 + }
  65 + if hasBonus {
  66 + if order.UseOrderCount >= 0 && order.UseOrderCount < order.PlanOrderCount {
  67 + return 3 // 已支付退货
  68 + }
  69 + return 2 // 已支付分红
  70 + }
  71 + if !hasBonus {
  72 + if order.UseOrderCount >= 0 && order.UseOrderCount < order.PlanOrderCount {
  73 + return 4 // 待支付退货
  74 + }
  75 + return 1
  76 + }
  77 + return 1
  78 +}
  79 +func orderProducts(order *domain.OrderBase) interface{} {
  80 + var products []map[string]interface{}
  81 + for i := range order.OrderGood {
  82 + good := order.OrderGood[i]
  83 + static := good.OrderBonusStatic()
  84 + item := make(map[string]interface{})
  85 + item["productName"] = good.GoodName
  86 + item["orderCount"] = good.PlanGoodNumber
  87 + item["orderAmount"] = good.PlanAmount
  88 + item["dividendPercent"] = good.PartnerBonusPercent
  89 + item["dividendReceivable"] = static.OrderTotalReceivable() //应收分红
  90 + item["dividendReceived"] = static.OrderBonusReceive() //已收分红
  91 + item["dividendUnReceive"] = static.OrderBonusWait() // 未收分红
  92 + item["dividendExpend"] = static.OrderBonusOutstanding() //分红支出
  93 + if len(good.Remark) > 0 {
  94 + item["orderUpdateReason"] = good.Remark
  95 + }
  96 + item["dividendStatus"] = good.Status()
  97 + if good.Status() > 2 {
  98 + item["countAdjust"] = good.UseGoodNumber
  99 + item["amountAdjust"] = good.UseAmount
  100 + }
  101 + products = append(products, item)
  102 + }
  103 + return products
  104 +}
  105 +func orderTotalStatic(order *domain.OrderBase) interface{} {
  106 + item := make(map[string]interface{})
  107 + static := order.OrderBonusStatic()
  108 + item["totalCount"] = order.PlanOrderCount
  109 + item["totalAmount"] = order.PlanOrderAmount
  110 + item["totalDividendReceivable"] = static.OrderTotalReceivable()
  111 + item["totalReceived"] = static.OrderBonusReceive()
  112 + item["totalUnReceive"] = static.OrderBonusWait()
  113 + item["totalExpend"] = static.OrderBonusOutstanding()
  114 + if order.UseOrderCount > 0 {
  115 + item["totalCountAdjust"] = order.UseOrderCount
  116 + item["totalAmountAdjust"] = order.UseOrderAmount
  117 + }
  118 + return item
  119 +}
  120 +
  121 +// 订单统计
  122 +func Statistics(header *protocol.RequestHeader, request *protocol.OrderStatisticsRequest) (rsp *protocol.OrderStatisticsResponse, err error) {
  123 + var (
  124 + transactionContext, _ = factory.CreateTransactionContext(nil)
  125 + OrderDao, _ = factory.CreateOrderBaseDao(transactionContext)
  126 + BusinessBonusRepository, _ = factory.CreateBusinessBonusRepository(transactionContext)
  127 + )
  128 + if err = transactionContext.StartTransaction(); err != nil {
  129 + return nil, err
  130 + }
  131 + defer func() {
  132 + transactionContext.RollbackTransaction()
  133 + }()
  134 + rsp = &protocol.OrderStatisticsResponse{Statistics: protocol.OrderStatics{}}
  135 +
  136 + // 当天订单/累计订单
  137 + if rsp.Statistics.TodayRealQuantity, rsp.Statistics.TodayRealMoney, err = OrderDao.OrderStatics(&domain.OrderStaticQuery{
  138 + BeginTime: utils.GetDayBegin().Unix() * 1000,
  139 + EndTime: utils.GetDayEnd().Unix() * 1000,
  140 + OrderType: domain.OrderReal,
  141 + PartnerId: header.UserId,
  142 + }); err != nil {
  143 + return
  144 + }
  145 + if rsp.Statistics.CumulativeQuantity, rsp.Statistics.CumulativeMoney, err = OrderDao.OrderStatics(&domain.OrderStaticQuery{
  146 + EndTime: time.Now().Unix() * 1000,
  147 + OrderType: domain.OrderReal,
  148 + PartnerId: header.UserId,
  149 + }); err != nil {
  150 + return
  151 + }
  152 + rsp.Statistics.TodayRealMoney = utils.Decimal(rsp.Statistics.TodayRealMoney)
  153 + rsp.Statistics.CumulativeMoney = utils.Decimal(rsp.Statistics.CumulativeMoney)
  154 +
  155 + //事业分红/业务分红
  156 + var careerBonus, businessBonus, total float64 //,developBonus,appBonus
  157 + if bonus, e := OrderDao.OrderBonusStatics(domain.OrderBonusQuery{PartnerId: header.UserId, OrderType: domain.OrderReal}); e == nil {
  158 + careerBonus = bonus.Bonus
  159 + total += careerBonus
  160 + }
  161 + if bonus, e := BusinessBonusRepository.FindOne(map[string]interface{}{"partner_id": header.UserId, "isDisable": 1}); e == nil {
  162 + businessBonus = bonus.Bonus
  163 + total += businessBonus
  164 + rsp.Statistics.BusinessMoney = bonus.Bonus
  165 + }
  166 + if total != 0 {
  167 + rsp.Statistics.CareerPercent = utils.DecimalToNumber(careerBonus * 100 / total)
  168 + rsp.Statistics.BusinessPercent = utils.DecimalToNumber(businessBonus * 100 / total)
  169 + }
  170 +
  171 + err = transactionContext.CommitTransaction()
  172 + return
  173 +}
12 174
  175 +// 订单列表
  176 +func List(header *protocol.RequestHeader, request *protocol.OrderListRequest) (rsp *protocol.OrderListResponse, err error) {
  177 + var (
  178 + transactionContext, _ = factory.CreateTransactionContext(nil)
  179 + OrderResponsitory, _ = factory.CreateOrderBaseRepository(transactionContext)
  180 + OrderDao, _ = factory.CreateOrderBaseDao(transactionContext)
  181 + orders []*domain.OrderBase
13 ) 182 )
  183 +
  184 + rsp = &protocol.OrderListResponse{
  185 + List: make([]*protocol.OrderListItem, 0),
  186 + }
14 if err = transactionContext.StartTransaction(); err != nil { 187 if err = transactionContext.StartTransaction(); err != nil {
15 return nil, err 188 return nil, err
16 } 189 }
17 defer func() { 190 defer func() {
18 transactionContext.RollbackTransaction() 191 transactionContext.RollbackTransaction()
19 }() 192 }()
  193 +
  194 + // 查询订单列表
  195 + queryOption := &domain.OrderQueryOption{
  196 + PartnerId: header.UserId,
  197 + Limit: request.PageSize,
  198 + Offset: request.PageSize * request.PageIndex,
  199 + SortByUpdateTime: domain.DESC,
  200 + }
  201 + if request.StartTime > 0 {
  202 + queryOption.BeginTime = time.Unix(request.StartTime/1000, 0)
  203 + }
  204 + if request.EndTime > 0 {
  205 + queryOption.EndTime = time.Unix(request.EndTime/1000, 0)
  206 + }
  207 + queryOption.OrderType = request.OrderType
  208 + _, orders, _ = OrderResponsitory.Find(utils.ObjectJsonToMap(queryOption))
  209 + if len(orders) != 0 {
  210 + for i := range orders {
  211 + rsp.List = append(rsp.List, DomainOrderToOrderListItem(orders[i]))
  212 + }
  213 + }
  214 +
  215 + // 查询统计数据
  216 + if request.PageIndex == 0 {
  217 + var (
  218 + cumulativeQuantity int
  219 + )
  220 + //累计实发订单
  221 + cumulativeQuantity, _, err = OrderDao.OrderStatics(&domain.OrderStaticQuery{
  222 + EndTime: time.Now().Unix() * 1000,
  223 + OrderType: domain.OrderReal,
  224 + PartnerId: header.UserId,
  225 + })
  226 + rsp.Total = cumulativeQuantity
  227 + }
  228 +
20 err = transactionContext.CommitTransaction() 229 err = transactionContext.CommitTransaction()
21 return 230 return
22 } 231 }
  232 +func DomainOrderToOrderListItem(order *domain.OrderBase) *protocol.OrderListItem {
  233 + bonusStatic := order.OrderBonusStatic()
  234 + return &protocol.OrderListItem{
  235 + Id: order.Id,
  236 + OrderType: order.OrderType,
  237 + OrderNo: order.OrderCode,
  238 + DeliveryNo: order.DeliveryCode,
  239 + OrderAmount: order.PlanOrderAmount,
  240 + UpdateTime: order.UpdateTime.Unix() * 1000,
  241 + MyDividend: bonusStatic.OrderTotalReceivable(),
  242 + IsRead: order.IsRead(),
  243 + }
  244 +}
1 -package order  
2 -  
3 -import (  
4 - "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/application/factory"  
5 - "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain"  
6 - "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/utils"  
7 - "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/log"  
8 - "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/protocol"  
9 - "time"  
10 -)  
11 -  
12 -// 订单详情  
13 -func Detail(header *protocol.RequestHeader, request *protocol.OrderDetailRequest) (rsp *protocol.OrderDetailResponse, err error) {  
14 - var (  
15 - transactionContext, _ = factory.CreateTransactionContext(nil)  
16 - OrderResponsitory, _ = factory.CreateOrderBaseRepository(transactionContext)  
17 - OrderDao, _ = factory.CreateOrderBaseDao(transactionContext)  
18 - order *domain.OrderBase  
19 - )  
20 - if err = transactionContext.StartTransaction(); err != nil {  
21 - return nil, err  
22 - }  
23 - defer func() {  
24 - transactionContext.RollbackTransaction()  
25 - }()  
26 -  
27 - rsp = &protocol.OrderDetailResponse{}  
28 - if order, err = OrderResponsitory.FindOne(utils.ObjectJsonToMap(request)); err != nil {  
29 - log.Error(err)  
30 - return  
31 - }  
32 - rsp.Order = protocol.OrderDetail{  
33 - Id: order.Id,  
34 - OrderNo: order.OrderCode,  
35 - DeliveryNo: order.DeliveryCode,  
36 - OrderStatus: orderStatus(order),  
37 - CreateTime: order.CreateTime.Unix() * 1000,  
38 - UpdateTime: order.UpdateTime.Unix() * 1000,  
39 - OrderDistrict: map[string]interface{}{"id": order.RegionInfo.RegionId, "name": order.RegionInfo.RegionName},  
40 - Customer: protocol.Customer{Uname: order.Buyer.BuyerName, Phone: order.Buyer.ContactInfo},  
41 - Products: orderProducts(order),  
42 - Total: orderTotalStatic(order),  
43 - }  
44 - if header.UserId == order.PartnerId && order.UpdateTime.After(order.LastViewTime) {  
45 - if err = OrderDao.UpdateLastViewTime(order.Id, time.Now()); err != nil {  
46 - return  
47 - }  
48 - }  
49 - err = transactionContext.CommitTransaction()  
50 - return  
51 -}  
52 -func orderStatus(order *domain.OrderBase) int {  
53 - var hasBonus = false  
54 - for i := range order.OrderGood {  
55 - good := order.OrderGood[i]  
56 - if good.BonusStatus == domain.BonusPaid {  
57 - hasBonus = true  
58 - break  
59 - }  
60 - }  
61 - if hasBonus {  
62 - if order.UseOrderCount >= 0 && order.UseOrderCount < order.PlanOrderCount {  
63 - return 3 // 已支付退货  
64 - }  
65 - return 2 // 已支付分红  
66 - }  
67 - if !hasBonus {  
68 - if order.UseOrderCount >= 0 && order.UseOrderCount < order.PlanOrderCount {  
69 - return 4 // 待支付退货  
70 - }  
71 - return 1  
72 - }  
73 - return 1  
74 -}  
75 -func orderProducts(order *domain.OrderBase) interface{} {  
76 - var products []map[string]interface{}  
77 - for i := range order.OrderGood {  
78 - good := order.OrderGood[i]  
79 - static := good.OrderBonusStatic()  
80 - item := make(map[string]interface{})  
81 - item["productName"] = good.GoodName  
82 - item["orderCount"] = good.PlanGoodNumber  
83 - item["orderAmount"] = good.PlanAmount  
84 - item["dividendPercent"] = good.PartnerBonusPercent  
85 - item["dividendReceivable"] = static.OrderTotalReceivable() //应收分红  
86 - item["dividendReceived"] = static.OrderBonusReceive() //已收分红  
87 - item["dividendUnReceive"] = static.OrderBonusWait() // 未收分红  
88 - item["dividendExpend"] = static.OrderBonusOutstanding() //分红支出  
89 - if len(good.Remark) > 0 {  
90 - item["orderUpdateReason"] = good.Remark  
91 - }  
92 - item["dividendStatus"] = good.Status()  
93 - if good.Status() > 2 {  
94 - item["countAdjust"] = good.UseGoodNumber  
95 - item["amountAdjust"] = good.UseAmount  
96 - }  
97 - products = append(products, item)  
98 - }  
99 - return products  
100 -}  
101 -func orderTotalStatic(order *domain.OrderBase) interface{} {  
102 - item := make(map[string]interface{})  
103 - static := order.OrderBonusStatic()  
104 - item["totalCount"] = order.PlanOrderCount  
105 - item["totalAmount"] = order.PlanOrderAmount  
106 - item["totalDividendReceivable"] = static.OrderTotalReceivable()  
107 - item["totalReceived"] = static.OrderBonusReceive()  
108 - item["totalUnReceive"] = static.OrderBonusWait()  
109 - item["totalExpend"] = static.OrderBonusOutstanding()  
110 - if order.UseOrderCount > 0 {  
111 - item["totalCountAdjust"] = order.UseOrderCount  
112 - item["totalAmountAdjust"] = order.UseOrderAmount  
113 - }  
114 - return item  
115 -}  
116 -  
117 -// 订单统计  
118 -func Statistics(header *protocol.RequestHeader, request *protocol.OrderStatisticsRequest) (rsp *protocol.OrderStatisticsResponse, err error) {  
119 - var (  
120 - transactionContext, _ = factory.CreateTransactionContext(nil)  
121 - OrderDao, _ = factory.CreateOrderBaseDao(transactionContext)  
122 - )  
123 - if err = transactionContext.StartTransaction(); err != nil {  
124 - return nil, err  
125 - }  
126 - defer func() {  
127 - transactionContext.RollbackTransaction()  
128 - }()  
129 - rsp = &protocol.OrderStatisticsResponse{Statistics: protocol.OrderStatics{}}  
130 - //if rsp.Statistics.TodayIntentionQuantity, rsp.Statistics.TodayIntentionMoney, err = OrderDao.OrderStatics(&domain.OrderStaticQuery{  
131 - // BeginTime: utils.GetDayBegin().Unix() * 1000,  
132 - // EndTime: utils.GetDayEnd().Unix() * 1000,  
133 - // OrderType: domain.OrderIntention,  
134 - // PartnerId: header.UserId,  
135 - //}); err != nil {  
136 - // return  
137 - //}  
138 - if rsp.Statistics.TodayRealQuantity, rsp.Statistics.TodayRealMoney, err = OrderDao.OrderStatics(&domain.OrderStaticQuery{  
139 - BeginTime: utils.GetDayBegin().Unix() * 1000,  
140 - EndTime: utils.GetDayEnd().Unix() * 1000,  
141 - OrderType: domain.OrderReal,  
142 - PartnerId: header.UserId,  
143 - }); err != nil {  
144 - return  
145 - }  
146 - if rsp.Statistics.CumulativeQuantity, rsp.Statistics.CumulativeMoney, err = OrderDao.OrderStatics(&domain.OrderStaticQuery{  
147 - EndTime: time.Now().Unix() * 1000,  
148 - OrderType: domain.OrderReal,  
149 - PartnerId: header.UserId,  
150 - }); err != nil {  
151 - return  
152 - }  
153 - rsp.Statistics.TodayRealMoney = utils.Decimal(rsp.Statistics.TodayRealMoney)  
154 - rsp.Statistics.CumulativeMoney = utils.Decimal(rsp.Statistics.CumulativeMoney)  
155 - err = transactionContext.CommitTransaction()  
156 - return  
157 -}  
158 -  
159 -// 订单列表  
160 -func List(header *protocol.RequestHeader, request *protocol.OrderListRequest) (rsp *protocol.OrderListResponse, err error) {  
161 - var (  
162 - transactionContext, _ = factory.CreateTransactionContext(nil)  
163 - OrderResponsitory, _ = factory.CreateOrderBaseRepository(transactionContext)  
164 - OrderDao, _ = factory.CreateOrderBaseDao(transactionContext)  
165 - orders []*domain.OrderBase  
166 - )  
167 -  
168 - rsp = &protocol.OrderListResponse{  
169 - List: make([]*protocol.OrderListItem, 0),  
170 - Statistics: make(map[string]interface{}),  
171 - }  
172 - if err = transactionContext.StartTransaction(); err != nil {  
173 - return nil, err  
174 - }  
175 - defer func() {  
176 - transactionContext.RollbackTransaction()  
177 - }()  
178 - queryOption := &domain.OrderQueryOption{  
179 - PartnerId: header.UserId,  
180 - Limit: request.PageSize,  
181 - Offset: request.PageSize * request.PageIndex,  
182 - SortByUpdateTime: domain.DESC,  
183 - }  
184 - if request.StartTime > 0 {  
185 - queryOption.BeginTime = time.Unix(request.StartTime/1000, 0)  
186 - }  
187 - if request.EndTime > 0 {  
188 - queryOption.EndTime = time.Unix(request.EndTime/1000, 0)  
189 - }  
190 - queryOption.OrderType = request.OrderType  
191 - _, orders, _ = OrderResponsitory.Find(utils.ObjectJsonToMap(queryOption))  
192 - //统计数据  
193 - if request.PageIndex == 0 {  
194 - var (  
195 - cumulativeQuantity int  
196 - )  
197 - //累计实发订单  
198 - cumulativeQuantity, _, err = OrderDao.OrderStatics(&domain.OrderStaticQuery{  
199 - EndTime: time.Now().Unix() * 1000,  
200 - OrderType: domain.OrderReal,  
201 - PartnerId: header.UserId,  
202 - })  
203 - rsp.Total = cumulativeQuantity  
204 - }  
205 -  
206 - if len(orders) == 0 {  
207 - return  
208 - }  
209 - for i := range orders {  
210 - rsp.List = append(rsp.List, DomainOrderToOrderListItem(orders[i]))  
211 - }  
212 -  
213 - err = transactionContext.CommitTransaction()  
214 - return  
215 -}  
216 -func DomainOrderToOrderListItem(order *domain.OrderBase) *protocol.OrderListItem {  
217 - bonusStatic := order.OrderBonusStatic()  
218 - return &protocol.OrderListItem{  
219 - Id: order.Id,  
220 - OrderType: order.OrderType,  
221 - OrderNo: order.OrderCode,  
222 - DeliveryNo: order.DeliveryCode,  
223 - OrderAmount: order.PlanOrderAmount,  
224 - UpdateTime: order.UpdateTime.Unix() * 1000,  
225 - MyDividend: bonusStatic.OrderTotalReceivable(),  
226 - IsRead: order.IsRead(),  
227 - }  
228 -}  
  1 +package partner
  2 +
  3 +import (
  4 + "fmt"
  5 + "github.com/tiptok/gocomm/pkg/log"
  6 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/application/factory"
  7 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain"
  8 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg/transaction"
  9 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/utils"
  10 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/protocol"
  11 + protocol_company "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/protocol/company"
  12 + protocolx "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/protocol/partner"
  13 +)
  14 +
  15 +func Detail(header *protocol.RequestHeader, request *protocolx.DetailRequest) (rsp *protocolx.DetailResponse, err error) {
  16 + var (
  17 + transactionContext, _ = factory.CreateTransactionContext(nil)
  18 + )
  19 + rsp = &protocolx.DetailResponse{}
  20 + if err = transactionContext.StartTransaction(); err != nil {
  21 + log.Error(err)
  22 + return nil, err
  23 + }
  24 + defer func() {
  25 + transactionContext.RollbackTransaction()
  26 + }()
  27 + if rsp.Partner, err = getDetail(request.Uid, transactionContext); err != nil {
  28 + return
  29 + }
  30 + err = transactionContext.CommitTransaction()
  31 + return
  32 +}
  33 +
  34 +func getDetail(userId int64, transactionContext *transaction.TransactionContext) (interface{}, error) {
  35 + var (
  36 + PartnerInfoRepository, _ = factory.CreatePartnerInfoRepositoryIn(transactionContext)
  37 + PartnerCategoryInfoRepository, _ = factory.CreatePartnerCategoryInfoRepository(transactionContext)
  38 + OrderBaseDao, _ = factory.CreateOrderBaseDao(transactionContext)
  39 + BusinessBonusDao, _ = factory.CreateBusinessBonusDao(transactionContext)
  40 + partner *domain.PartnerInfo
  41 + err error
  42 + )
  43 + if partner, err = PartnerInfoRepository.FindOne(map[string]interface{}{"id": userId}); err != nil {
  44 + log.Error(err)
  45 + return nil, err
  46 + }
  47 + p := protocolx.Partner{}
  48 +
  49 + p.PartnerName = partner.PartnerName
  50 + if partner.RegionInfo != nil {
  51 + p.District = protocol_company.Districts{
  52 + Id: partner.RegionInfo.RegionId,
  53 + Name: partner.RegionInfo.RegionName,
  54 + }
  55 + }
  56 + if len(partner.PartnerCategoryInfos) > 0 {
  57 + var cIds []int64
  58 + for i := range partner.PartnerCategoryInfos {
  59 + cIds = append(cIds, partner.PartnerCategoryInfos[i].Id)
  60 + }
  61 + _, categories, _ := PartnerCategoryInfoRepository.Find(map[string]interface{}{"inIds": cIds})
  62 + for i := range categories {
  63 + c := categories[i]
  64 + p.JoinWay = append(p.JoinWay, map[string]interface{}{"type": fmt.Sprintf("%v", c.Id), "name": c.Name})
  65 + }
  66 + }
  67 + p.CooperateTime = partner.CooperateTime.Unix() * 1000
  68 + if bonus, e := OrderBaseDao.OrderBonusStatics(domain.OrderBonusQuery{PartnerId: userId, OrderType: domain.OrderReal}); e == nil {
  69 + p.CareerOrdersCount = int(bonus.Total)
  70 + p.CareerOrdersMoney = utils.Decimal(bonus.TotalOrderAmount)
  71 + p.CareerDividend = utils.Decimal(bonus.Bonus)
  72 + }
  73 + if businessBonus, e := BusinessBonusDao.OrderBonusStatics(domain.OrderBonusQuery{PartnerId: userId, IsDisable: 1}); e == nil {
  74 + p.BusinessOrdersCount = int(businessBonus.Total)
  75 + p.BusinessOrdersMoney = utils.Decimal(businessBonus.TotalOrderAmount)
  76 + p.BusinessDividend = utils.Decimal(businessBonus.Bonus)
  77 + }
  78 + return p, nil
  79 +}
@@ -7,8 +7,13 @@ import ( @@ -7,8 +7,13 @@ import (
7 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/application/partnerInfo/query" 7 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/application/partnerInfo/query"
8 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/application/partnerInfo/service" 8 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/application/partnerInfo/service"
9 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain" 9 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain"
  10 + domain_service_i "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain/service"
  11 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/domain_service"
  12 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg/transaction"
  13 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/svr"
10 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/log" 14 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/log"
11 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/protocol" 15 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/protocol"
  16 + protocolx "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/protocol/auth"
12 "strconv" 17 "strconv"
13 "strings" 18 "strings"
14 ) 19 )
@@ -20,8 +25,10 @@ func UserInfo(header *protocol.RequestHeader, request *protocol.UserInfoRequest) @@ -20,8 +25,10 @@ func UserInfo(header *protocol.RequestHeader, request *protocol.UserInfoRequest)
20 transactionContext, _ = factory.CreateTransactionContext(nil) 25 transactionContext, _ = factory.CreateTransactionContext(nil)
21 CompanyResponsitory, _ = factory.CreateCompanyRepository(transactionContext) 26 CompanyResponsitory, _ = factory.CreateCompanyRepository(transactionContext)
22 PartnerInfoService, _ = factory.CreatePartnerInfoRepositoryIn(transactionContext) 27 PartnerInfoService, _ = factory.CreatePartnerInfoRepositoryIn(transactionContext)
  28 + UsersRepository, _ = factory.CreateUsersRepository(transactionContext)
23 ImInfoRepository, _ = factory.CreateImInfoRepository(transactionContext) 29 ImInfoRepository, _ = factory.CreateImInfoRepository(transactionContext)
24 company *domain.Company 30 company *domain.Company
  31 + user *domain.Users
25 ) 32 )
26 if err = transactionContext.StartTransaction(); err != nil { 33 if err = transactionContext.StartTransaction(); err != nil {
27 return nil, err 34 return nil, err
@@ -30,33 +37,71 @@ func UserInfo(header *protocol.RequestHeader, request *protocol.UserInfoRequest) @@ -30,33 +37,71 @@ func UserInfo(header *protocol.RequestHeader, request *protocol.UserInfoRequest)
30 transactionContext.RollbackTransaction() 37 transactionContext.RollbackTransaction()
31 }() 38 }()
32 rsp = &protocol.UserInfoResponse{} 39 rsp = &protocol.UserInfoResponse{}
33 - if partnerInfo, err = PartnerInfoService.FindOne(map[string]interface{}{"id": header.UserId}); err != nil {  
34 - err = protocol.NewErrWithMessage(502, err) //账号不存在  
35 - return 40 +
  41 + funcPartnerInfo := func() {
  42 + if partnerInfo, err = PartnerInfoService.FindOne(map[string]interface{}{"id": header.UserId}); err != nil {
  43 + err = protocol.NewErrWithMessage(502, err) //账号不存在
  44 + return
  45 + }
  46 + if company, err = CompanyResponsitory.FindOne(map[string]interface{}{"id": header.CompanyId}); err != nil {
  47 + return
  48 + }
  49 + rsp.User = protocol.User{
  50 + Id: partnerInfo.Id,
  51 + PartnerName: partnerInfo.PartnerName,
  52 + Phone: partnerInfo.Account,
  53 + CooperateCompany: protocol.Company{
  54 + Id: company.Id,
  55 + Name: company.Name,
  56 + Phone: company.Phone,
  57 + },
  58 + JoinWay: partnerInfo.PartnerCategoryInfo(),
  59 + District: map[string]interface{}{"id": partnerInfo.RegionInfo.RegionId, "name": partnerInfo.RegionInfo.RegionName},
  60 + SerialNo: partnerInfo.Id,
  61 + CooperateTime: partnerInfo.CooperateTime.Unix() * 1000,
  62 + }
  63 + if len(partnerInfo.Salesman) > 0 {
  64 + rsp.User.Salesman = map[string]interface{}{"uname": partnerInfo.Salesman[0].Name, "phone": partnerInfo.Salesman[0].Telephone}
  65 + } else {
  66 + rsp.User.Salesman = map[string]interface{}{}
  67 + }
36 } 68 }
37 - if company, err = CompanyResponsitory.FindOne(map[string]interface{}{"id": 1}); err != nil {  
38 - return 69 + funcManagerInfo := func() {
  70 + if user, err = UsersRepository.FindOne(map[string]interface{}{"id": header.UserId}); err != nil {
  71 + err = protocol.NewErrWithMessage(502, err) //账号不存在
  72 + return
  73 + }
  74 + if company, err = CompanyResponsitory.FindOne(map[string]interface{}{"id": header.CompanyId}); err != nil {
  75 + return
  76 + }
  77 + rsp.User = protocol.User{
  78 + Id: user.Id,
  79 + PartnerName: user.Name,
  80 + Phone: user.Phone,
  81 + CooperateCompany: protocol.Company{
  82 + Id: company.Id,
  83 + Name: company.Name,
  84 + Phone: company.Phone,
  85 + },
  86 + //JoinWay: partnerInfo.PartnerCategoryInfo(),
  87 + //District: map[string]interface{}{"id": partnerInfo.RegionInfo.RegionId, "name": partnerInfo.RegionInfo.RegionName},
  88 + //SerialNo: partnerInfo.Id,
  89 + //CooperateTime: partnerInfo.CooperateTime.Unix() * 1000,
  90 + }
  91 + }
  92 + switch header.AdminType {
  93 + case int(protocolx.AdminTypePartner):
  94 + funcPartnerInfo()
  95 + break
  96 + case int(protocolx.AdminTypeManager):
  97 + funcManagerInfo()
  98 + break
  99 + default:
  100 + funcPartnerInfo()
  101 + break
39 } 102 }
40 - rsp.User = protocol.User{  
41 - Id: partnerInfo.Id,  
42 - PartnerName: partnerInfo.PartnerName,  
43 - Phone: partnerInfo.Account,  
44 - CooperateCompany: protocol.Company{  
45 - Id: company.Id,  
46 - Name: company.Name,  
47 - Phone: company.Phone,  
48 - },  
49 - JoinWay: partnerInfo.PartnerCategoryInfo(),  
50 - District: map[string]interface{}{"id": partnerInfo.RegionInfo.RegionId, "name": partnerInfo.RegionInfo.RegionName},  
51 - SerialNo: partnerInfo.Id,  
52 - CooperateTime: partnerInfo.CooperateTime.Unix() * 1000,  
53 - }  
54 - if len(partnerInfo.Salesman) > 0 {  
55 - rsp.User.Salesman = map[string]interface{}{"uname": partnerInfo.Salesman[0].Name, "phone": partnerInfo.Salesman[0].Telephone}  
56 - } else {  
57 - rsp.User.Salesman = map[string]interface{}{}  
58 - }  
59 - if imInfo, e := ImInfoRepository.FindOne(map[string]interface{}{"user_id": partnerInfo.Id}); e == nil && imInfo != nil { 103 +
  104 + if imInfo, e := ImInfoRepository.FindOne(map[string]interface{}{"user_id": header.SimNum}); e == nil && imInfo != nil {
60 rsp.User.ImToken = imInfo.ImToken 105 rsp.User.ImToken = imInfo.ImToken
61 rsp.User.AccountID, _ = strconv.ParseInt(imInfo.ImId, 10, 64) 106 rsp.User.AccountID, _ = strconv.ParseInt(imInfo.ImId, 10, 64)
62 rsp.User.CsAccountID = fmt.Sprintf("%v", imInfo.CustomerImId) 107 rsp.User.CsAccountID = fmt.Sprintf("%v", imInfo.CustomerImId)
@@ -86,9 +131,7 @@ func CheckSmsCode(header *protocol.RequestHeader, request *protocol.CheckSmsCode @@ -86,9 +131,7 @@ func CheckSmsCode(header *protocol.RequestHeader, request *protocol.CheckSmsCode
86 func ChangePhone(header *protocol.RequestHeader, request *protocol.ChangePhoneRequest) (rsp *protocol.ChangePhoneResponse, err error) { 131 func ChangePhone(header *protocol.RequestHeader, request *protocol.ChangePhoneRequest) (rsp *protocol.ChangePhoneResponse, err error) {
87 var ( 132 var (
88 transactionContext, _ = factory.CreateTransactionContext(nil) 133 transactionContext, _ = factory.CreateTransactionContext(nil)
89 - PartnerInfoDao, _ = factory.CreatePartnerInfoDao(transactionContext)  
90 - PartnerInfoService, _ = factory.CreatePartnerInfoRepositoryIn(transactionContext)  
91 - partnerInfo *domain.PartnerInfo 134 + UserAuthService = CreateUserAuthService(header.AdminType, transactionContext)
92 ) 135 )
93 if err = transactionContext.StartTransaction(); err != nil { 136 if err = transactionContext.StartTransaction(); err != nil {
94 return nil, err 137 return nil, err
@@ -96,25 +139,10 @@ func ChangePhone(header *protocol.RequestHeader, request *protocol.ChangePhoneRe @@ -96,25 +139,10 @@ func ChangePhone(header *protocol.RequestHeader, request *protocol.ChangePhoneRe
96 defer func() { 139 defer func() {
97 transactionContext.RollbackTransaction() 140 transactionContext.RollbackTransaction()
98 }() 141 }()
99 - if partnerInfo, err = PartnerInfoService.FindOne(map[string]interface{}{"id": header.UserId}); err != nil {  
100 - err = protocol.NewErrWithMessage(502, err) //账号不存在  
101 - return  
102 - }  
103 - //验证新手机是否已经存在  
104 - if _, e := PartnerInfoService.FindOne(map[string]interface{}{"account": request.Phone}); e == nil {  
105 - err = protocol.NewErrWithMessage(2029, err) //账号已存在  
106 - return  
107 - }  
108 - if _, err = auth.CheckSmsCode(request.Phone, request.Captcha); err != nil {  
109 - log.Error(err)  
110 - return  
111 - }  
112 - if err = PartnerInfoDao.Update(map[string]interface{}{  
113 - "Id": partnerInfo.Id,  
114 - "Account": request.Phone,  
115 - }); err != nil { 142 + if err = UserAuthService.ChangeUserPhone(header.UserId, request.Phone, request.OldPhone); err != nil {
116 return 143 return
117 } 144 }
  145 + //TODO:修改完手机号 ,token失效,清理缓存
118 err = transactionContext.CommitTransaction() 146 err = transactionContext.CommitTransaction()
119 return 147 return
120 } 148 }
@@ -122,10 +150,8 @@ func ChangePhone(header *protocol.RequestHeader, request *protocol.ChangePhoneRe @@ -122,10 +150,8 @@ func ChangePhone(header *protocol.RequestHeader, request *protocol.ChangePhoneRe
122 //重置密码 150 //重置密码
123 func ResetPassword(header *protocol.RequestHeader, request *protocol.ResetPasswordRequest) (rsp *protocol.ResetPasswordResponse, err error) { 151 func ResetPassword(header *protocol.RequestHeader, request *protocol.ResetPasswordRequest) (rsp *protocol.ResetPasswordResponse, err error) {
124 var ( 152 var (
125 - partnerInfo *domain.PartnerInfo  
126 transactionContext, _ = factory.CreateTransactionContext(nil) 153 transactionContext, _ = factory.CreateTransactionContext(nil)
127 - PartnerInfoDao, _ = factory.CreatePartnerInfoDao(transactionContext)  
128 - PartnerInfoService, _ = factory.CreatePartnerInfoRepositoryIn(transactionContext) 154 + UserAuthService = CreateUserAuthService(header.AdminType, transactionContext)
129 ) 155 )
130 rsp = &protocol.ResetPasswordResponse{} 156 rsp = &protocol.ResetPasswordResponse{}
131 if err = transactionContext.StartTransaction(); err != nil { 157 if err = transactionContext.StartTransaction(); err != nil {
@@ -134,34 +160,9 @@ func ResetPassword(header *protocol.RequestHeader, request *protocol.ResetPasswo @@ -134,34 +160,9 @@ func ResetPassword(header *protocol.RequestHeader, request *protocol.ResetPasswo
134 defer func() { 160 defer func() {
135 transactionContext.RollbackTransaction() 161 transactionContext.RollbackTransaction()
136 }() 162 }()
137 - if len(request.NewPwd) < 6 {  
138 - err = protocol.NewErrWithMessage(2027)  
139 - return  
140 - }  
141 - if !strings.EqualFold(request.NewPwd, request.ConfirmPwd) {  
142 - err = protocol.NewErrWithMessage(2026)  
143 - return  
144 - }  
145 - if partnerInfo, err = PartnerInfoService.FindOne(map[string]interface{}{"id": header.UserId}); err != nil {  
146 - err = protocol.NewErrWithMessage(502, err) //账号不存在 163 + if err = UserAuthService.ResetUserPassword(header.UserId, fmt.Sprintf("%v", header.SimNum), request.NewPwd); err != nil {
147 return 164 return
148 } 165 }
149 - if err = PartnerInfoDao.Update(map[string]interface{}{  
150 - "Id": partnerInfo.Id,  
151 - "Password": request.ConfirmPwd,  
152 - }); err != nil {  
153 - return  
154 - }  
155 - //清除auth token  
156 - //auth := userAuth.NewRedisUserAuth(userAuth.WithUserId(header.UserId))  
157 - //if !auth.Exist() {  
158 - // return  
159 - //}  
160 - //if err = auth.RemoveAuth(); err != nil {  
161 - // log.Error(err)  
162 - // err = protocol.NewErrWithMessage(4140, err)  
163 - // return  
164 - //}  
165 err = transactionContext.CommitTransaction() 166 err = transactionContext.CommitTransaction()
166 return 167 return
167 } 168 }
@@ -169,10 +170,8 @@ func ResetPassword(header *protocol.RequestHeader, request *protocol.ResetPasswo @@ -169,10 +170,8 @@ func ResetPassword(header *protocol.RequestHeader, request *protocol.ResetPasswo
169 //修改密码 170 //修改密码
170 func ChangePassword(header *protocol.RequestHeader, request *protocol.ChangePasswordRequest) (rsp *protocol.ChangePasswordResponse, err error) { 171 func ChangePassword(header *protocol.RequestHeader, request *protocol.ChangePasswordRequest) (rsp *protocol.ChangePasswordResponse, err error) {
171 var ( 172 var (
172 - partnerInfo *domain.PartnerInfo  
173 transactionContext, _ = factory.CreateTransactionContext(nil) 173 transactionContext, _ = factory.CreateTransactionContext(nil)
174 - PartnerInfoDao, _ = factory.CreatePartnerInfoDao(transactionContext)  
175 - PartnerInfoService, _ = factory.CreatePartnerInfoRepositoryIn(transactionContext) 174 + UserAuthService = CreateUserAuthService(header.AdminType, transactionContext)
176 ) 175 )
177 if err = transactionContext.StartTransaction(); err != nil { 176 if err = transactionContext.StartTransaction(); err != nil {
178 return nil, err 177 return nil, err
@@ -181,43 +180,185 @@ func ChangePassword(header *protocol.RequestHeader, request *protocol.ChangePass @@ -181,43 +180,185 @@ func ChangePassword(header *protocol.RequestHeader, request *protocol.ChangePass
181 transactionContext.RollbackTransaction() 180 transactionContext.RollbackTransaction()
182 }() 181 }()
183 rsp = &protocol.ChangePasswordResponse{} 182 rsp = &protocol.ChangePasswordResponse{}
184 - if !strings.EqualFold(request.NewPwd, request.ConfirmPwd) {  
185 - err = protocol.NewErrWithMessage(2026) 183 + if err = UserAuthService.ChangeUserPassword(header.UserId, request.NewPwd, request.OldPwd, fmt.Sprintf("%v", header.SimNum)); err != nil {
  184 + err = protocol.NewCustomMessage(1, err.Error())
186 return 185 return
187 } 186 }
188 - if strings.EqualFold(request.NewPwd, request.OldPwd) {  
189 - err = protocol.NewErrWithMessage(2030)  
190 - return 187 + err = transactionContext.CommitTransaction()
  188 + return
  189 +}
  190 +
  191 +func UserInfoV2(header *protocol.RequestHeader, request *protocol.UserInfoRequest) (rsp interface{}, err error) {
  192 + var (
  193 + partnerInfo *domain.PartnerInfo
  194 + transactionContext, _ = factory.CreateTransactionContext(nil)
  195 + CompanyResponsitory, _ = factory.CreateCompanyRepository(transactionContext)
  196 + PartnerInfoService, _ = factory.CreatePartnerInfoRepositoryIn(transactionContext)
  197 + UsersRepository, _ = factory.CreateUsersRepository(transactionContext)
  198 + company *domain.Company
  199 + user *domain.Users
  200 + )
  201 + if err = transactionContext.StartTransaction(); err != nil {
  202 + return nil, err
191 } 203 }
192 - if len(request.NewPwd) < 6 {  
193 - err = protocol.NewErrWithMessage(2027)  
194 - return 204 + defer func() {
  205 + transactionContext.RollbackTransaction()
  206 + }()
  207 + rsp = &protocol.UserInfoResponse{}
  208 +
  209 + type xcompany struct {
  210 + Id int64 `json:"id"`
  211 + Name string `json:"name"`
  212 + Phone string `json:"phone"`
  213 + //合作区域
  214 + District interface{} `json:"district"`
  215 + //合作编码
  216 + SerialNo int64 `json:"serialNo"`
  217 + //合作时间
  218 + CooperateTime int64 `json:"cooperationTime"`
  219 + Salesman interface{} `json:"salesman"`
195 } 220 }
196 - if partnerInfo, err = PartnerInfoService.FindOne(map[string]interface{}{"id": header.UserId}); err != nil {  
197 - err = protocol.NewErrWithMessage(502, err) //账号不存在 221 + type xuser struct {
  222 + Id int64 `json:"uid"`
  223 + //用户名称
  224 + PartnerName string `json:"uname"`
  225 + //手机号
  226 + Phone string `json:"phone"`
  227 + //合作公司
  228 + CooperateCompany xcompany `json:"company"`
  229 + }
  230 + rspMap := make(map[string]interface{})
  231 + funcPartnerInfo := func() {
  232 + if partnerInfo, err = PartnerInfoService.FindOne(map[string]interface{}{"id": header.UserId}); err != nil {
  233 + err = protocol.NewErrWithMessage(502, err) //账号不存在
  234 + return
  235 + }
  236 + if company, err = CompanyResponsitory.FindOne(map[string]interface{}{"id": header.CompanyId}); err != nil {
  237 + return
  238 + }
  239 +
  240 + u := xuser{
  241 + Id: partnerInfo.Id,
  242 + PartnerName: partnerInfo.PartnerName,
  243 + Phone: partnerInfo.Account,
  244 + CooperateCompany: xcompany{
  245 + Id: company.Id,
  246 + Name: company.Name,
  247 + Phone: company.Phone,
  248 + SerialNo: partnerInfo.Id,
  249 + CooperateTime: partnerInfo.CooperateTime.Unix() * 1000,
  250 + //JoinWay: partnerInfo.PartnerCategoryInfo(),
  251 + District: map[string]interface{}{"id": partnerInfo.RegionInfo.RegionId, "name": partnerInfo.RegionInfo.RegionName},
  252 + },
  253 + }
  254 + if len(partnerInfo.Salesman) > 0 {
  255 + u.CooperateCompany.Salesman = map[string]interface{}{"uname": partnerInfo.Salesman[0].Name, "phone": partnerInfo.Salesman[0].Telephone}
  256 + } else {
  257 + u.CooperateCompany.Salesman = map[string]interface{}{}
  258 + }
  259 + rspMap["user"] = u
  260 + rsp = rspMap
  261 + }
  262 + funcManagerInfo := func() {
  263 + if user, err = UsersRepository.FindOne(map[string]interface{}{"id": header.UserId}); err != nil {
  264 + err = protocol.NewErrWithMessage(502, err) //账号不存在
  265 + return
  266 + }
  267 + if company, err = CompanyResponsitory.FindOne(map[string]interface{}{"id": header.CompanyId}); err != nil {
  268 + return
  269 + }
  270 + rspMap["user"] = xuser{
  271 + Id: user.Id,
  272 + PartnerName: user.Name,
  273 + Phone: user.Phone,
  274 + CooperateCompany: xcompany{
  275 + Id: company.Id,
  276 + Name: company.Name,
  277 + Phone: company.Phone,
  278 + },
  279 + }
  280 + rsp = rspMap
  281 + }
  282 + switch header.AdminType {
  283 + case int(protocolx.AdminTypePartner):
  284 + funcPartnerInfo()
  285 + break
  286 + case int(protocolx.AdminTypeManager):
  287 + funcManagerInfo()
  288 + break
  289 + default:
  290 + funcPartnerInfo()
  291 + break
  292 + }
  293 + err = transactionContext.CommitTransaction()
  294 + return
  295 +}
  296 +
  297 +func changeUserInfo(userId int64, phone, password string, transactionContext *transaction.TransactionContext) (err error) {
  298 + var (
  299 + ucenterApiGateway = svr.NewHttplibUCenterApiServiceGateway()
  300 + UsersRepository, _ = factory.CreateUsersRepository(transactionContext)
  301 + user *domain.Users
  302 + )
  303 + if user, err = UsersRepository.FindOne(map[string]interface{}{"id": userId}); err != nil || user == nil {
  304 + log.Error(err)
  305 + err = fmt.Errorf("用户不存在")
198 return 306 return
199 } 307 }
200 - if !strings.EqualFold(partnerInfo.Password, request.OldPwd) {  
201 - //密码不一致  
202 - err = protocol.NewErrWithMessage(2028, err) //账号不存在 308 + _, err = ucenterApiGateway.UpdateUser(user.OpenId, phone, password)
  309 + return
  310 +}
  311 +func changeUserPhone(userId int64, phone, oldPhone string, transactionContext *transaction.TransactionContext) (err error) {
  312 + var (
  313 + ucenterApiGateway = svr.NewHttplibUCenterApiServiceGateway()
  314 + UsersRepository, _ = factory.CreateUsersRepository(transactionContext)
  315 + user *domain.Users
  316 + )
  317 + if user, err = UsersRepository.FindOne(map[string]interface{}{"id": userId}); err != nil || user == nil {
  318 + log.Error(err)
  319 + err = fmt.Errorf("用户不存在")
203 return 320 return
204 } 321 }
205 - if err = PartnerInfoDao.Update(map[string]interface{}{  
206 - "Id": partnerInfo.Id,  
207 - "Password": request.ConfirmPwd,  
208 - }); err != nil { 322 + if newUser, e := UsersRepository.FindOne(map[string]interface{}{"phone": phone}); e == nil || newUser != nil {
  323 + err = protocol.NewErrWithMessage(2029, err)
209 return 324 return
210 } 325 }
211 - //清除auth token  
212 - //auth := userAuth.NewRedisUserAuth(userAuth.WithUserId(header.UserId))  
213 - //if !auth.Exist() {  
214 - // return 326 + _, err = ucenterApiGateway.ChangePhone(phone, oldPhone)
  327 + //if err != nil {
  328 + // _, err = transactionContext.PgTx.Exec("update users set phone=? where id=?", phone, userId)
215 //} 329 //}
216 - //if err = auth.RemoveAuth(); err != nil {  
217 - // log.Error(err)  
218 - // err = protocol.NewErrWithMessage(4140, err)  
219 - // return  
220 - //}  
221 - err = transactionContext.CommitTransaction()  
222 return 330 return
223 } 331 }
  332 +func changeUserPassword(userId int64, newPwd, oldPwd, phone string, transactionContext *transaction.TransactionContext) (err error) {
  333 + var (
  334 + ucenterApiGateway = svr.NewHttplibUCenterApiServiceGateway()
  335 + UsersRepository, _ = factory.CreateUsersRepository(transactionContext)
  336 + user *domain.Users
  337 + )
  338 + if user, err = UsersRepository.FindOne(map[string]interface{}{"id": userId}); err != nil || user == nil {
  339 + log.Error(err)
  340 + err = fmt.Errorf("用户不存在")
  341 + return
  342 + }
  343 + _, err = ucenterApiGateway.ChangePassword(phone, newPwd, oldPwd)
  344 + return
  345 +}
  346 +
  347 +func CreateUserAuthService(adminType int, transactionContext *transaction.TransactionContext) domain_service_i.UserAuthService {
  348 + if adminType == int(protocolx.AdminTypeManager) {
  349 + return domain_service.NewPgManagerAuthService(transactionContext)
  350 + }
  351 + return domain_service.NewPgPartnerAuthService(transactionContext)
  352 +}
  353 +
  354 +//TODO:修改密码/重置密码 清除uer_auth 缓存
  355 +//清除auth token
  356 +//auth := userAuth.NewRedisUserAuth(userAuth.WithUserId(header.UserId))
  357 +//if !auth.Exist() {
  358 +// return
  359 +//}
  360 +//if err = auth.RemoveAuth(); err != nil {
  361 +// log.Error(err)
  362 +// err = protocol.NewErrWithMessage(4140, err)
  363 +// return
  364 +//}
@@ -8,9 +8,20 @@ var LOG_LEVEL = "debug" @@ -8,9 +8,20 @@ var LOG_LEVEL = "debug"
8 var LOG_File = "app.log" 8 var LOG_File = "app.log"
9 9
10 var MMM_SMS_SERVICE_HOST = "https://sms.fjmaimaimai.com:9897" 10 var MMM_SMS_SERVICE_HOST = "https://sms.fjmaimaimai.com:9897"
  11 +var UCENTER_SERVICE_HOST = "https://suplus-ucenter-dev.fjmaimaimai.com"
  12 +var UCENTER_APP_KEY = "0c2c2a23dfc64ae230f5c54ab243ab52"
  13 +
  14 +var BUSINESS_ADMIN_SERVICE_HOST = "http://suplus-business-admin-dev.fjmaimaimai.com"
  15 +var BUSINESS_ADMIN_PLATFORM_ID = "25" //合伙人模块
11 16
12 func init() { 17 func init() {
13 if os.Getenv("LOG_LEVEL") != "" { 18 if os.Getenv("LOG_LEVEL") != "" {
14 LOG_LEVEL = os.Getenv("LOG_LEVEL") 19 LOG_LEVEL = os.Getenv("LOG_LEVEL")
15 } 20 }
  21 + if os.Getenv("UCENTER_SERVICE_HOST") != "" {
  22 + UCENTER_SERVICE_HOST = os.Getenv("UCENTER_SERVICE_HOST")
  23 + }
  24 + if os.Getenv("BUSINESS_ADMIN_SERVICE_HOST") != "" {
  25 + BUSINESS_ADMIN_SERVICE_HOST = os.Getenv("BUSINESS_ADMIN_SERVICE_HOST")
  26 + }
16 } 27 }
@@ -2,11 +2,11 @@ package constant @@ -2,11 +2,11 @@ package constant
2 2
3 import "os" 3 import "os"
4 4
5 -var POSTGRESQL_DB_NAME = "partner_dev" //partner  
6 -var POSTGRESQL_USER = "postgres" //  
7 -var POSTGRESQL_PASSWORD = "postgres_15432" //pgsql@123  
8 -var POSTGRESQL_HOST = "101.37.68.23" //127.0.0.1  
9 -var POSTGRESQL_PORT = "15432" //5432 5 +var POSTGRESQL_DB_NAME = "partner_dev" //partner
  6 +var POSTGRESQL_USER = "postgres" //
  7 +var POSTGRESQL_PASSWORD = "eagle1010" //pgsql@123
  8 +var POSTGRESQL_HOST = "114.55.200.59" //127.0.0.1
  9 +var POSTGRESQL_PORT = "31543" //5432
10 var DISABLE_CREATE_TABLE = false 10 var DISABLE_CREATE_TABLE = false
11 var DISABLE_SQL_GENERATE_PRINT = false 11 var DISABLE_SQL_GENERATE_PRINT = false
12 12
  1 +package domain
  2 +
  3 +import "time"
  4 +
  5 +// 业务分红信息
  6 +type BusinessBonus struct {
  7 + // 唯一标识
  8 + Id int64 `json:"id"`
  9 + // 公司编号
  10 + CompanyId int64 `json:"companyId"`
  11 + // 合伙人信息Id
  12 + PartnerInfoId int64 `json:"partnerInfoId"`
  13 + // 应收分红
  14 + Bonus float64 `json:"bonus"`
  15 + // 已收分红
  16 + BonusHas float64 `json:"bonusHas"`
  17 + // 未收分红
  18 + BonusNot float64 `json:"bonusNot"`
  19 + // 分红支出
  20 + BonusExpense float64 `json:"bonusExpense"`
  21 + // 是否关闭【0;否】【1:是】
  22 + IsDisable int8 `json:"isDisable"`
  23 + // 分红状态 1:待支付分红 2:已支付分红
  24 + BonusStatus int8 `json:"bonusStatus"`
  25 + // 创建时间
  26 + CreateAt time.Time `json:"createAt"`
  27 + // 更新时间
  28 + UpdateAt time.Time `json:"updateAt"`
  29 + // 删除时间
  30 + DeleteAt time.Time `json:"deleteAt"`
  31 +}
  32 +
  33 +type BusinessBonusRepository interface {
  34 + Save(dm *BusinessBonus) (*BusinessBonus, error)
  35 + Remove(dm *BusinessBonus) (*BusinessBonus, error)
  36 + FindOne(queryOptions map[string]interface{}) (*BusinessBonus, error)
  37 + Find(queryOptions map[string]interface{}) (int64, []*BusinessBonus, error)
  38 +}
  39 +
  40 +func (m *BusinessBonus) Identify() interface{} {
  41 + if m.Id == 0 {
  42 + return nil
  43 + }
  44 + return m.Id
  45 +}
1 -package domain  
2 -  
3 -type Company struct {  
4 - Id int64 `json:"id"`  
5 - Name string `json:"name"`  
6 - Phone string `json:"phone"`  
7 -}  
8 -  
9 -type CompanyRepository interface {  
10 - Save(dm *Company) (*Company, error)  
11 - Remove(dm *Company) (*Company, error)  
12 - FindOne(queryOptions map[string]interface{}) (*Company, error)  
13 - Find(queryOptions map[string]interface{}) (int64, []*Company, error)  
14 -}  
  1 +package domain
  2 +
  3 +import "time"
  4 +
  5 +// 公司信息
  6 +type Company struct {
  7 + // 唯一标识
  8 + Id int64 `json:"id"`
  9 + // 名称
  10 + Name string `json:"name"`
  11 + // 公司简称
  12 + Abbreviation string `json:"abbreviation"`
  13 + // 手机号码
  14 + Phone string `json:"phone"`
  15 + // 公司logo
  16 + Logo string `json:"logo"`
  17 + // 备注
  18 + Remarks string `json:"remarks"`
  19 + // 总后台的公司id
  20 + AdminCompanyId int `json:"adminCompanyId"`
  21 + // 状态 1正常 2禁用
  22 + Status int8 `json:"status"`
  23 + // 创建时间
  24 + CreateAt time.Time `json:"createAt"`
  25 + // 更新时间
  26 + UpdateAt time.Time `json:"updateAt"`
  27 + // 删除时间
  28 + DeleteAt time.Time `json:"deleteAt"`
  29 + // 是否开启合伙人模块,是否有效【1:有效】【2:无效】
  30 + Enable int8 `json:"enable"`
  31 +}
  32 +
  33 +type CompanyRepository interface {
  34 + Save(dm *Company) (*Company, error)
  35 + Remove(dm *Company) (*Company, error)
  36 + FindOne(queryOptions map[string]interface{}) (*Company, error)
  37 + Find(queryOptions map[string]interface{}) (int64, []*Company, error)
  38 +}
  39 +
  40 +func (m *Company) Identify() interface{} {
  41 + if m.Id == 0 {
  42 + return nil
  43 + }
  44 + return m.Id
  45 +}
@@ -9,6 +9,8 @@ import ( @@ -9,6 +9,8 @@ import (
9 type OrderBase struct { 9 type OrderBase struct {
10 //表id 10 //表id
11 Id int64 11 Id int64
  12 + // 公司id
  13 + CompanyId int64 `json:"companyId"`
12 //订单类型 1:实际订单 2:意向订单 14 //订单类型 1:实际订单 2:意向订单
13 OrderType int `pg:",notnull,default:1"` 15 OrderType int `pg:",notnull,default:1"`
14 //订单编号 16 //订单编号
@@ -4,6 +4,8 @@ package domain @@ -4,6 +4,8 @@ package domain
4 type OrderGood struct { 4 type OrderGood struct {
5 //货品id 5 //货品id
6 Id int64 6 Id int64
  7 + // 公司id
  8 + CompanyId int64 `json:"companyId"`
7 //所属订单id 9 //所属订单id
8 OrderId int64 10 OrderId int64
9 //货品名称 长度可能较长 11 //货品名称 长度可能较长
@@ -20,3 +20,24 @@ type DividendOrdersQuery struct { @@ -20,3 +20,24 @@ type DividendOrdersQuery struct {
20 StartTime int64 `json:"startTime" valid:"Required"` 20 StartTime int64 `json:"startTime" valid:"Required"`
21 EndTime int64 `json:"endTime" valid:"Required"` 21 EndTime int64 `json:"endTime" valid:"Required"`
22 } 22 }
  23 +
  24 +// 订单分红统计-查询
  25 +type OrderBonusQuery struct {
  26 + PartnerId int64 `json:"partnerId,omitempty"`
  27 + CompanyId int64 `json:"companyId,omitempty"`
  28 + InPartnerIds []int64 `json:"inPartnerIds,omitempty"`
  29 + IsDisable int `json:"isDisable,omitempty"`
  30 + OrderType int `json:"orderType,omitempty"`
  31 +}
  32 +
  33 +// 订单分红统计-应答
  34 +type OrderBonusResponse struct {
  35 + // 应收分红
  36 + Bonus float64 `json:"partnerId,omitempty"`
  37 + // 订单数量
  38 + Total int64 `json:"companyId,omitempty"`
  39 + // 分红支出
  40 + BonusExpense float64 `json:"bonusExpense,omitempty"`
  41 + // 订单金额
  42 + TotalOrderAmount float64 `json:"totalOrderAmount"`
  43 +}
  1 +package domain
  2 +
  3 +// 合伙人分类信息
  4 +type PartnerCategoryInfo struct {
  5 + // 唯一标识
  6 + Id int64 `json:"id"`
  7 + // 名称
  8 + Name string `json:"name"`
  9 +}
  10 +
  11 +type PartnerCategoryInfoRepository interface {
  12 + Save(dm *PartnerCategoryInfo) (*PartnerCategoryInfo, error)
  13 + Remove(dm *PartnerCategoryInfo) (*PartnerCategoryInfo, error)
  14 + FindOne(queryOptions map[string]interface{}) (*PartnerCategoryInfo, error)
  15 + Find(queryOptions map[string]interface{}) (int64, []*PartnerCategoryInfo, error)
  16 +}
  17 +
  18 +func (m *PartnerCategoryInfo) Identify() interface{} {
  19 + if m.Id == 0 {
  20 + return nil
  21 + }
  22 + return m.Id
  23 +}
  24 +
  25 +const (
  26 + Career = iota + 1
  27 + Business
  28 + Develop
  29 + App
  30 +)
@@ -12,6 +12,8 @@ type PartnerInfoRepository interface { @@ -12,6 +12,8 @@ type PartnerInfoRepository interface {
12 type PartnerInfo struct { 12 type PartnerInfo struct {
13 // 合伙人ID 13 // 合伙人ID
14 Id int64 `json:"id"` 14 Id int64 `json:"id"`
  15 + // 公司id
  16 + CompanyId int64 `json:"companyId"`
15 // 合伙人姓名 17 // 合伙人姓名
16 PartnerName string `json:"partnerName"` 18 PartnerName string `json:"partnerName"`
17 // 登录账号 19 // 登录账号
@@ -22,7 +24,6 @@ type PartnerInfo struct { @@ -22,7 +24,6 @@ type PartnerInfo struct {
22 Status int `json:"status"` 24 Status int `json:"status"`
23 // 合伙类别 (1.事业合伙人 2.业务合伙人 3.研发合伙人) 25 // 合伙类别 (1.事业合伙人 2.业务合伙人 3.研发合伙人)
24 PartnerCategory int `json:"partnerCategory"` 26 PartnerCategory int `json:"partnerCategory"`
25 -  
26 //所属区域信息 27 //所属区域信息
27 RegionInfo *RegionInfo `json:"regionId"` 28 RegionInfo *RegionInfo `json:"regionId"`
28 //合作时间 29 //合作时间
@@ -31,9 +32,10 @@ type PartnerInfo struct { @@ -31,9 +32,10 @@ type PartnerInfo struct {
31 CreateAt time.Time `json:"createAt"` 32 CreateAt time.Time `json:"createAt"`
32 //更新时间 33 //更新时间
33 UpdateAt time.Time `json:"updateAt"` 34 UpdateAt time.Time `json:"updateAt"`
34 -  
35 //关联业务员 35 //关联业务员
36 Salesman []*Salesman `json:"salesman"` 36 Salesman []*Salesman `json:"salesman"`
  37 + //合伙人分类信息
  38 + PartnerCategoryInfos []*PartnerCategoryInfo `partnerCategoryInfos`
37 } 39 }
38 40
39 func (m *PartnerInfo) Identify() interface{} { 41 func (m *PartnerInfo) Identify() interface{} {
@@ -86,7 +88,7 @@ func (m *PartnerInfo) PartnerCategoryInfo() *PartnerCategoryInfo { @@ -86,7 +88,7 @@ func (m *PartnerInfo) PartnerCategoryInfo() *PartnerCategoryInfo {
86 break 88 break
87 } 89 }
88 return &PartnerCategoryInfo{ 90 return &PartnerCategoryInfo{
89 - Id: m.PartnerCategory, 91 + Id: int64(m.PartnerCategory),
90 Name: name, 92 Name: name,
91 } 93 }
92 } 94 }
@@ -96,11 +98,6 @@ func (m *PartnerInfo) IsEnable() bool { @@ -96,11 +98,6 @@ func (m *PartnerInfo) IsEnable() bool {
96 return m.Status == 1 98 return m.Status == 1
97 } 99 }
98 100
99 -type PartnerCategoryInfo struct {  
100 - Id int `json:"id"`  
101 - Name string `json:"name"`  
102 -}  
103 -  
104 type RegionInfo struct { 101 type RegionInfo struct {
105 RegionId int `json:"regionId"` 102 RegionId int `json:"regionId"`
106 RegionName string `json:"regionName"` 103 RegionName string `json:"regionName"`
  1 +package domain
  2 +
  3 +type PartnerStatics struct {
  4 + PartnerInfo
  5 + // 订单金额
  6 + Amount float64 `json:"amount"`
  7 + // 分红
  8 + Bonus float64 `json:"bonus"`
  9 + // 分红支出
  10 + BonusExpense float64 `json:"bonus_expense"`
  11 + // 订单数
  12 + Total float64 `json:"total"`
  13 +}
  1 +package service
  2 +
  3 +type LoginService interface {
  4 +}
  1 +package service
  2 +
  3 +type UserAuthService interface {
  4 + ChangeUserPhone(userId int64, newPhone, oldPhone string) (err error)
  5 + ChangeUserPassword(userId int64, newPwd, oldPwd, phone string) (err error)
  6 + ResetUserPassword(userId int64, phone, password string) (err error)
  7 +}
  1 +package domain
  2 +
  3 +import "time"
  4 +
  5 +// 用户信息
  6 +type Users struct {
  7 + // 唯一标识
  8 + Id int64 `json:"id"`
  9 + // 公司id
  10 + CompanyId int64 `json:"companyId"`
  11 + // 统一用户中心 uid
  12 + OpenId int64 `json:"openId"`
  13 + // 名称
  14 + Name string `json:"name"`
  15 + // 性别:0保密 1男 2女
  16 + Sex int8 `json:"sex"`
  17 + // 员工工号
  18 + JobNum string `json:"jobNum"`
  19 + // 手机号码
  20 + Phone string `json:"phone"`
  21 + // 私人手机号码
  22 + PrivatePhone string `json:"privatePhone"`
  23 + // 邮箱
  24 + Email string `json:"email"`
  25 + // 分机号
  26 + ExtensionNum string `json:"extensionNum"`
  27 + // 入职时间
  28 + EntryTime time.Time `json:"entryTime"`
  29 + // 工作地点
  30 + Workspace string `json:"workspace"`
  31 + // 状态 1正常 2禁用
  32 + Status int8 `json:"status"`
  33 + // 手机号
  34 + Avatar string `json:"avatar"`
  35 + // 备注
  36 + Remarks string `json:"remarks"`
  37 + // 是否为当前公司主管 1 是2 否
  38 + ChargeStatus int8 `json:"chargeStatus"`
  39 + // 创建时间
  40 + CreateAt time.Time `json:"createAt"`
  41 + // 更新时间
  42 + UpdateAt time.Time `json:"updateAt"`
  43 + // 删除时间
  44 + DeleteAt time.Time `json:"deleteAt"`
  45 + // 可查看的合伙人信息
  46 + AccessPartners []*PartnerInfo
  47 + // 1普通用户 2主管理员
  48 + AdminType int8 `json:"adminType"`
  49 +}
  50 +
  51 +func (Users *Users) AccessPartnerIds() []int64 {
  52 + var partnerIds []int64
  53 + if Users == nil {
  54 + return partnerIds
  55 + }
  56 + for i := range Users.AccessPartners {
  57 + partnerIds = append(partnerIds, Users.AccessPartners[i].Id)
  58 + }
  59 + return partnerIds
  60 +}
  61 +
  62 +type UsersRepository interface {
  63 + Save(dm *Users) (*Users, error)
  64 + Remove(dm *Users) (*Users, error)
  65 + FindOne(queryOptions map[string]interface{}) (*Users, error)
  66 + Find(queryOptions map[string]interface{}) (int64, []*Users, error)
  67 +}
  68 +
  69 +func (m *Users) Identify() interface{} {
  70 + if m.Id == 0 {
  71 + return nil
  72 + }
  73 + return m.Id
  74 +}
  1 +package dao
  2 +
  3 +import (
  4 + "fmt"
  5 + "github.com/go-pg/pg/v10"
  6 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain"
  7 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg/models"
  8 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg/transaction"
  9 +)
  10 +
  11 +type BusinessBonusDao struct {
  12 + transactionContext *transaction.TransactionContext
  13 +}
  14 +
  15 +//订单分红统计
  16 +func (dao *BusinessBonusDao) OrderBonusStatics(option domain.OrderBonusQuery) (rsp domain.OrderBonusResponse, err error) {
  17 + rsp = domain.OrderBonusResponse{}
  18 + if option.PartnerId == 0 && option.CompanyId == 0 && len(option.InPartnerIds) == 0 {
  19 + return
  20 + }
  21 + tx := dao.transactionContext.PgTx
  22 + q := tx.Model(new(models.BusinessBonus))
  23 + q.ColumnExpr("count(*) count")
  24 + q.ColumnExpr("sum(bonus) bonus")
  25 + q.ColumnExpr("sum(bonus_expense) bonus_expense")
  26 + if option.PartnerId > 0 {
  27 + q.Where(`"business_bonus".partner_info_id =?`, option.PartnerId)
  28 + }
  29 + if option.CompanyId > 0 {
  30 + q.Where(`"business_bonus".company_id =?`, option.CompanyId)
  31 + }
  32 + if option.IsDisable > 0 {
  33 + q.Where(`"business_bonus".is_disable =?`, option.IsDisable)
  34 + }
  35 + if len(option.InPartnerIds) > 0 {
  36 + q.Where(`"business_bonus".partner_info_id in (?)`, pg.In(option.InPartnerIds))
  37 + }
  38 + err = q.Select(&rsp.Total, &rsp.Bonus, &rsp.BonusExpense)
  39 + return
  40 +}
  41 +
  42 +func NewBusinessBonusDao(transactionContext *transaction.TransactionContext) (*BusinessBonusDao, error) {
  43 + if transactionContext == nil {
  44 + return nil, fmt.Errorf("transactionContext参数不能为nil")
  45 + } else {
  46 + return &BusinessBonusDao{
  47 + transactionContext: transactionContext,
  48 + }, nil
  49 + }
  50 +}
@@ -2,6 +2,7 @@ package dao @@ -2,6 +2,7 @@ package dao
2 2
3 import ( 3 import (
4 "fmt" 4 "fmt"
  5 + "github.com/go-pg/pg/v10"
5 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain" 6 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain"
6 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg/models" 7 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg/models"
7 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg/transaction" 8 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg/transaction"
@@ -43,6 +44,34 @@ func (dao *OrderBaseDao) OrderStatics(option *domain.OrderStaticQuery) (count in @@ -43,6 +44,34 @@ func (dao *OrderBaseDao) OrderStatics(option *domain.OrderStaticQuery) (count in
43 return 44 return
44 } 45 }
45 46
  47 +//订单分红统计
  48 +func (dao *OrderBaseDao) OrderBonusStatics(option domain.OrderBonusQuery) (rsp domain.OrderBonusResponse, err error) {
  49 + rsp = domain.OrderBonusResponse{}
  50 + if option.PartnerId == 0 && option.CompanyId == 0 && len(option.InPartnerIds) == 0 {
  51 + return
  52 + }
  53 + tx := dao.transactionContext.PgTx
  54 + q := tx.Model(new(models.OrderBase))
  55 + q.ColumnExpr("count(*) count")
  56 + q.ColumnExpr("sum((case when use_order_count>0 then use_partner_bonus else plan_partner_bonus end)) bonus")
  57 + q.ColumnExpr("sum(partner_bonus_expense) bonus_expense")
  58 + q.ColumnExpr("sum(plan_order_amount) total_order_amount")
  59 + if option.PartnerId > 0 {
  60 + q.Where(`"order_base".partner_id =?`, option.PartnerId)
  61 + }
  62 + if option.CompanyId > 0 {
  63 + q.Where(`"order_base".company_id =?`, option.CompanyId)
  64 + }
  65 + if len(option.InPartnerIds) > 0 {
  66 + q.Where(`"order_base".partner_id in (?)`, pg.In(option.InPartnerIds))
  67 + }
  68 + if option.OrderType > 0 {
  69 + q.Where(`"order_base".order_type =?`, option.OrderType)
  70 + }
  71 + err = q.Select(&rsp.Total, &rsp.Bonus, &rsp.BonusExpense, &rsp.TotalOrderAmount)
  72 + return
  73 +}
  74 +
46 //分红订单 75 //分红订单
47 func (dao *OrderBaseDao) DividendOrders(option *domain.DividendOrdersQueryOption) (count int, domainOrders []*domain.OrderBase, err error) { 76 func (dao *OrderBaseDao) DividendOrders(option *domain.DividendOrdersQueryOption) (count int, domainOrders []*domain.OrderBase, err error) {
48 tx := dao.transactionContext.PgTx 77 tx := dao.transactionContext.PgTx
@@ -2,9 +2,13 @@ package dao @@ -2,9 +2,13 @@ package dao
2 2
3 import ( 3 import (
4 "fmt" 4 "fmt"
  5 + "github.com/go-pg/pg/v10"
  6 + "github.com/go-pg/pg/v10/orm"
  7 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain"
5 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg/models" 8 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg/models"
6 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg/transaction" 9 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg/transaction"
7 . "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/utils" 10 . "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/utils"
  11 + "strings"
8 ) 12 )
9 13
10 type PartnerInfoDao struct { 14 type PartnerInfoDao struct {
@@ -25,6 +29,107 @@ func (dao *PartnerInfoDao) Update(queryOptions map[string]interface{}) error { @@ -25,6 +29,107 @@ func (dao *PartnerInfoDao) Update(queryOptions map[string]interface{}) error {
25 return err 29 return err
26 } 30 }
27 31
  32 +func (dao *PartnerInfoDao) PartnerStatic(queryOptions map[string]interface{}) (count int, err error) {
  33 + tx := dao.transactionContext.PgTx
  34 + m := new(models.PartnerInfo)
  35 + query := NewQuery(tx.Model(m), queryOptions)
  36 +
  37 + query.ColumnExpr("count(*) count")
  38 + if inPartnerIds, ok := queryOptions["inPartnerIds"]; ok {
  39 + query.Where("id in (?)", pg.In(inPartnerIds.([]int64)))
  40 + }
  41 + if inPartnerCategory, ok := queryOptions["inPartnerCategory"]; ok {
  42 + query.Where(`partner_info.partner_category_infos @>'[{"id":?}]'`, inPartnerCategory)
  43 + }
  44 + // 多个合伙人类型
  45 + if inPartnerCategory, ok := queryOptions["inPartnerCategories"]; ok {
  46 + query.Query = query.WhereGroup(func(q *orm.Query) (*orm.Query, error) {
  47 + if arrayInPartnerCategory, ok := inPartnerCategory.([]int64); ok {
  48 + for i := range arrayInPartnerCategory {
  49 + q.WhereOr(`partner_info.partner_category_infos @>'[{"id":?}]')`, arrayInPartnerCategory[i])
  50 + }
  51 + }
  52 + return q, nil
  53 + })
  54 + }
  55 + err = query.Select(&count)
  56 + return
  57 +}
  58 +
  59 +func (dao *PartnerInfoDao) Partners(partnerIds []int64, queryOptions map[string]interface{}) (statics []*domain.PartnerStatics, err error) {
  60 + tx := dao.transactionContext.PgDd
  61 + var sql = strings.Builder{}
  62 + var filterPartners = strings.Builder{}
  63 +
  64 + if districts, ok := queryOptions["districts"]; ok {
  65 + districts, ok := districts.([]string)
  66 + if ok && len(districts) > 0 {
  67 + var filterDistricts = strings.Builder{}
  68 + for i := range districts {
  69 + filterDistricts.WriteString(fmt.Sprintf(` region_info @>'{"regionName":"%v"}'`, districts[i]))
  70 + if i != (len(districts) - 1) {
  71 + filterDistricts.WriteString(" or ")
  72 + }
  73 + }
  74 + filterPartners.WriteString(fmt.Sprintf(" and (%v)", filterDistricts.String()))
  75 + }
  76 + }
  77 + if joinWays, ok := queryOptions["joinWays"]; ok {
  78 + joinWays, ok := joinWays.([]int64)
  79 + if ok && len(joinWays) > 0 {
  80 + var filterJoinWays = strings.Builder{}
  81 + for i := range joinWays {
  82 + filterJoinWays.WriteString(fmt.Sprintf(` partner_category_infos @>'[{"id":%v}]'`, joinWays[i]))
  83 + if i != (len(joinWays) - 1) {
  84 + filterJoinWays.WriteString(" or ")
  85 + }
  86 + }
  87 + filterPartners.WriteString(fmt.Sprintf(" and (%v)", filterJoinWays.String()))
  88 + }
  89 + }
  90 + if startTime, ok := queryOptions["startTime"]; ok {
  91 + filterPartners.WriteString(fmt.Sprintf(" and cooperate_time>=to_timestamp(%v)", startTime))
  92 + }
  93 + if endTime, ok := queryOptions["endTime"]; ok {
  94 + filterPartners.WriteString(fmt.Sprintf(" and cooperate_time<to_timestamp(%v)", endTime))
  95 + }
  96 +
  97 + sql.WriteString(fmt.Sprintf(`
  98 +SELECT A.*,B.total,B.amount,COALESCE(B.bonus,0) bonus,B.bonus_expense
  99 +FROM
  100 +(
  101 + SELECT * FROM partner_info
  102 + WHERE (id in (?)) %v
  103 +)
  104 +A left join
  105 +(
  106 + SELECT partner_id,count(*) total,sum(amount) amount,sum(bonus) bonus,sum(bonus_expense) bonus_expense FROM
  107 + (
  108 + SELECT partner_id,
  109 + (case when use_order_count>0 then plan_order_amount else plan_order_amount end) amount,
  110 + (case when use_order_count>0 then use_partner_bonus else plan_partner_bonus end) bonus,
  111 + partner_bonus_expense bonus_expense FROM "order_base" AS "order_base"
  112 + WHERE (partner_id in (?)) and order_type =1
  113 + UNION ALL
  114 + SELECT partner_info_id partner_id,
  115 + 0 amount, bonus bonus, bonus_expense bonus_expense FROM business_bonus
  116 + WHERE (partner_info_id in (?)) and is_disable=1
  117 + ) B
  118 +GROUP BY partner_id
  119 +) B on A."id" = B.partner_id`, filterPartners.String()))
  120 + if sortByBonus, ok := queryOptions["sortByBonus"]; ok {
  121 + sql.WriteString(fmt.Sprintf(" \norder by bonus %v", sortByBonus))
  122 + }
  123 + if limit, ok := queryOptions["limit"]; ok {
  124 + sql.WriteString(fmt.Sprintf(" \nLIMIT %v", limit))
  125 + if offset, ok := queryOptions["offset"]; ok {
  126 + sql.WriteString(fmt.Sprintf(" \nOFFSET %v", offset))
  127 + }
  128 + }
  129 + _, err = tx.Query(&statics, sql.String(), pg.In(partnerIds), pg.In(partnerIds), pg.In(partnerIds))
  130 + return
  131 +}
  132 +
28 func NewPartnerInfoDao(transactionContext *transaction.TransactionContext) (*PartnerInfoDao, error) { 133 func NewPartnerInfoDao(transactionContext *transaction.TransactionContext) (*PartnerInfoDao, error) {
29 if transactionContext == nil { 134 if transactionContext == nil {
30 return nil, fmt.Errorf("transactionContext参数不能为nil") 135 return nil, fmt.Errorf("transactionContext参数不能为nil")
  1 +package dao
  2 +
  3 +import (
  4 + "fmt"
  5 + "github.com/go-pg/pg/v10"
  6 + "github.com/go-pg/pg/v10/orm"
  7 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain"
  8 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg/models"
  9 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg/transaction"
  10 + . "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/utils"
  11 +)
  12 +
  13 +type UsersDao struct {
  14 + transactionContext *transaction.TransactionContext
  15 +}
  16 +
  17 +func (dao *UsersDao) UserAccessPartners(queryOptions map[string]interface{}) ([]*domain.Users, error) {
  18 + tx := dao.transactionContext.PgTx
  19 + m := new(models.Users)
  20 + var users *domain.Users
  21 + query := NewQuery(tx.Model(m), queryOptions)
  22 + if inParterIds, ok := queryOptions["inParterIds"]; ok {
  23 + query.Relation("PartnerInfo", func(q *orm.Query) (*orm.Query, error) {
  24 + return q.Where("id in (?)", pg.In(inParterIds.([]int64))), nil
  25 + })
  26 + }
  27 + err := query.Select(&users)
  28 + return nil, err
  29 +}
  30 +
  31 +func NewUsersDao(transactionContext *transaction.TransactionContext) (*UsersDao, error) {
  32 + if transactionContext == nil {
  33 + return nil, fmt.Errorf("transactionContext参数不能为nil")
  34 + } else {
  35 + return &UsersDao{
  36 + transactionContext: transactionContext,
  37 + }, nil
  38 + }
  39 +}
  1 +package domain_service
  2 +
  3 +import (
  4 + "github.com/tiptok/gocomm/xa/eda"
  5 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain"
  6 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/dao"
  7 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg/transaction"
  8 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/repository"
  9 + http_gateway "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/svr"
  10 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/utils"
  11 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/log"
  12 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/protocol"
  13 + protocolx "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/protocol/auth"
  14 + "strings"
  15 +)
  16 +
  17 +type PgLoginService struct {
  18 + Phone string
  19 + eda.EventCenterPublisher
  20 + PartnerInfo []*domain.PartnerInfo
  21 + Users []*domain.Users
  22 + transactionContext *transaction.TransactionContext
  23 +}
  24 +
  25 +func (svr *PgLoginService) Init(phone string) (err error) {
  26 + var (
  27 + PartnerInfoService, _ = repository.NewPartnerInfoRepository(svr.transactionContext)
  28 + UsersRepository, _ = repository.NewUsersRepository(svr.transactionContext)
  29 + )
  30 + svr.Phone = phone
  31 + _, svr.PartnerInfo, err = PartnerInfoService.Find(map[string]interface{}{"account": phone, "status": 1, "sortByCreateTime": "ASC"})
  32 + _, svr.Users, err = UsersRepository.Find(map[string]interface{}{"phone": phone, "status": 1, "sortByCreateTime": "ASC"})
  33 + return nil
  34 +}
  35 +
  36 +//合伙人登录
  37 +func (svr *PgLoginService) PartnerLogin(phone string, password string) (err error) {
  38 + if len(svr.PartnerInfo) == 0 {
  39 + //子账号
  40 + err = protocol.NewErrWithMessage(502, err) //账号不存在
  41 + return
  42 + }
  43 + if !strings.EqualFold(svr.PartnerInfo[0].Password, password) {
  44 + err = protocol.NewCustomMessage(1, "密码输入有误!")
  45 + return
  46 + }
  47 + return
  48 +}
  49 +
  50 +//管理层登录
  51 +func (svr *PgLoginService) ManagerLogin(phone string, password string) (err error) {
  52 + if len(svr.Users) == 0 {
  53 + //子账号
  54 + err = protocol.NewErrWithMessage(502, err) //账号不存在
  55 + return
  56 + }
  57 + var openid int64
  58 + ucenerSvr := http_gateway.NewHttplibUCenterApiServiceGateway()
  59 + openid, err = ucenerSvr.ServerLogin(phone, password, 1)
  60 + if err == nil && openid > 0 {
  61 + _, err = svr.transactionContext.PgTx.Exec("update users set open_id=? where phone=?", openid, phone)
  62 + }
  63 + return
  64 +}
  65 +
  66 +//合伙人统计信息
  67 +func (svr *PgLoginService) PartnerStaticInfo() (interface{}, error) {
  68 + response := make(map[string]interface{})
  69 + response["id"] = protocolx.AdminTypePartner
  70 + response["name"] = protocolx.AdminTypePartnerName
  71 + if len(svr.PartnerInfo) == 0 {
  72 + response["companys"] = make([]struct{}, 0)
  73 + return response, nil
  74 + }
  75 + var (
  76 + OrderDao, _ = dao.NewOrderBaseDao(svr.transactionContext)
  77 + BusinessBonusDao, _ = dao.NewBusinessBonusDao(svr.transactionContext)
  78 + PartnerCategoryInfoRepository, _ = repository.NewPartnerCategoryInfoRepository(svr.transactionContext)
  79 + companyList []*domain.Company
  80 + allPartnerCategory []*domain.PartnerCategoryInfo
  81 + BusinessBonusRepository, _ = repository.NewBusinessBonusRepository(svr.transactionContext)
  82 + )
  83 + doGetCompanyIds := func() []int64 {
  84 + var companies []int64
  85 + for i := range svr.PartnerInfo {
  86 + companies = append(companies, svr.PartnerInfo[i].CompanyId)
  87 + }
  88 + return companies
  89 + }
  90 + doGetPartnerIds := func() []int64 {
  91 + var array []int64
  92 + for i := range svr.PartnerInfo {
  93 + array = append(array, svr.PartnerInfo[i].Id)
  94 + }
  95 + return array
  96 + }
  97 + companyList = svr.GetCompanyList(doGetCompanyIds)
  98 + if len(companyList) == 0 {
  99 + return response, nil
  100 + }
  101 + totalBonus, e := OrderDao.OrderBonusStatics(domain.OrderBonusQuery{InPartnerIds: doGetPartnerIds(), OrderType: domain.OrderReal})
  102 + if e != nil {
  103 + return response, e
  104 + }
  105 + if businessBonus, e := BusinessBonusDao.OrderBonusStatics(domain.OrderBonusQuery{InPartnerIds: doGetPartnerIds(), IsDisable: 1}); e == nil {
  106 + totalBonus.Bonus += businessBonus.Bonus
  107 + }
  108 + _, allPartnerCategory, e = PartnerCategoryInfoRepository.Find(map[string]interface{}{"sortById": domain.ASC})
  109 + var mapPartnerBussinessBonus = make(map[int64]*domain.BusinessBonus)
  110 + if _, bussinessBonus, e := BusinessBonusRepository.Find(map[string]interface{}{"inPartnerIds": doGetPartnerIds(), "isDisable": 1}); e == nil {
  111 + for _, v := range bussinessBonus {
  112 + mapPartnerBussinessBonus[v.PartnerInfoId] = v
  113 + }
  114 + }
  115 + if e != nil {
  116 + log.Error(e)
  117 + return response, e
  118 + }
  119 + var companys = make([]*Company, 0)
  120 + for i := range companyList {
  121 + c := companyList[i]
  122 + var partner *domain.PartnerInfo
  123 + for j := range svr.PartnerInfo {
  124 + if svr.PartnerInfo[j].CompanyId == c.Id {
  125 + partner = svr.PartnerInfo[j]
  126 + break
  127 + }
  128 + }
  129 + if partner == nil {
  130 + continue
  131 + }
  132 + bonus, _ := OrderDao.OrderBonusStatics(domain.OrderBonusQuery{PartnerId: partner.Id, OrderType: domain.OrderReal})
  133 + if v, ok := mapPartnerBussinessBonus[partner.Id]; ok {
  134 + bonus.Bonus += v.Bonus
  135 + }
  136 + item := &Company{
  137 + CompanyBase: newCompanyBase(c),
  138 + IncomePercent: computeBonusPercent(totalBonus.Bonus, bonus.Bonus*100),
  139 + DividendMoney: utils.Decimal(bonus.Bonus),
  140 + JoinWays: svr.GetJoinWays(allPartnerCategory, partner, bonus.Bonus),
  141 + }
  142 + companys = append(companys, item)
  143 + }
  144 +
  145 + response["companys"] = companys
  146 + return response, nil
  147 +}
  148 +func (svr *PgLoginService) ManagerStaticInfo() (interface{}, error) {
  149 + response := make(map[string]interface{})
  150 + response["id"] = protocolx.AdminTypeManager
  151 + response["name"] = protocolx.AdminTypeManagerName
  152 + if len(svr.Users) == 0 {
  153 + response["companys"] = make([]struct{}, 0)
  154 + return response, nil
  155 + }
  156 + var (
  157 + companyList []*domain.Company
  158 + //adminApiGateway = http_gateway.NewHttplibBusinessAdminApiServiceGateway()
  159 + )
  160 + doGetCompanyIds := func() []int64 {
  161 + var companies []int64
  162 + for i := range svr.Users {
  163 + companies = append(companies, svr.Users[i].CompanyId)
  164 + }
  165 + return companies
  166 + }
  167 + companyList = svr.GetCompanyList(doGetCompanyIds)
  168 + var companys = make([]protocol.CompanyBase, 0)
  169 + for i := range companyList {
  170 + c := companyList[i]
  171 +
  172 + //通过企业平台 校验模块权限
  173 + //var user *domain.Users
  174 + //for j := range svr.Users {
  175 + // if svr.Users[j].CompanyId == c.Id {
  176 + // user = svr.Users[j]
  177 + // break
  178 + // }
  179 + //}
  180 + //if user != nil {
  181 + // if code, e := adminApiGateway.UserAuth(user.Id, constant.BUSINESS_ADMIN_PLATFORM_ID); e != nil || code != 0 {
  182 + // log.Debug("【检查权限】", svr.Phone, "【公司】", c.Id, user.Id, code, e.Error())
  183 + // continue
  184 + // } else {
  185 + // log.Debug("【检查权限】", svr.Phone, "【公司】", c.Id, user.Id, code, e)
  186 + // }
  187 + //}
  188 + item := newCompanyBase(c)
  189 + companys = append(companys, item)
  190 + }
  191 +
  192 + response["companys"] = companys
  193 + return response, nil
  194 +}
  195 +func (svr *PgLoginService) GetCompanyList(funcGetCompanyIds func() []int64) []*domain.Company {
  196 + var (
  197 + CompanyRepository, _ = repository.NewCompanyRepository(svr.transactionContext)
  198 + companyList []*domain.Company
  199 + )
  200 + var companies []int64 = funcGetCompanyIds()
  201 + if len(companies) == 0 {
  202 + return companyList
  203 + }
  204 + if _, v, e := CompanyRepository.Find(map[string]interface{}{"inCompanyIds": companies, "status": 1, "sortByCreateTime": domain.ASC}); e != nil {
  205 + log.Error(e)
  206 + return companyList
  207 + } else {
  208 + companyList = v
  209 + }
  210 + return companyList
  211 +}
  212 +func (svr *PgLoginService) GetJoinWays(partnerCategory []*domain.PartnerCategoryInfo, partnerInfo *domain.PartnerInfo, bonus float64) []joinWay {
  213 + searchCategory := func(partnerCategory []*domain.PartnerCategoryInfo, id int64) *domain.PartnerCategoryInfo {
  214 + for i := range partnerCategory {
  215 + if partnerCategory[i].Id == id {
  216 + return partnerCategory[i]
  217 + }
  218 + }
  219 + return nil
  220 + }
  221 + //var (
  222 + // totalBonus float64
  223 + // businessBonus float64
  224 + // BusinessBonusRepository, _ = repository.NewBusinessBonusRepository(svr.transactionContext)
  225 + //)
  226 + //for i := range partnerInfo.PartnerCategoryInfos {
  227 + // c := partnerInfo.PartnerCategoryInfos[i]
  228 + // switch c.Id {
  229 + // case 1:
  230 + // totalBonus += bonus
  231 + // case 2:
  232 + // if one, e := BusinessBonusRepository.FindOne(map[string]interface{}{"partner_id": partnerInfo.Id}); e == nil {
  233 + // businessBonus = one.Bonus
  234 + // totalBonus += businessBonus
  235 + // }
  236 + // }
  237 + //}
  238 + var joinWays []joinWay
  239 + for i := range partnerCategory {
  240 + c := partnerCategory[i]
  241 + searchC := searchCategory(partnerInfo.PartnerCategoryInfos, c.Id)
  242 + if searchC != nil {
  243 + item := joinWay{
  244 + Type: int(c.Id),
  245 + Name: c.Name,
  246 + }
  247 + //if c.Id == 1 {
  248 + // item.Percent = computeBonusPercent(totalBonus, bonus) * 100
  249 + //} else if c.Id == 2 {
  250 + // item.Percent = computeBonusPercent(totalBonus, businessBonus) * 100
  251 + //}
  252 + joinWays = append(joinWays, item)
  253 + }
  254 + }
  255 +
  256 + for i := range joinWays {
  257 + joinWays[i].Percent = computeBonusPercent(float64(len(joinWays)), 1) * 100
  258 + }
  259 + return joinWays
  260 +}
  261 +func newCompanyBase(company *domain.Company) protocol.CompanyBase {
  262 + return protocol.CompanyBase{
  263 + Id: company.Id,
  264 + Name: company.Name,
  265 + ShortName: company.Abbreviation,
  266 + Image: protocol.NewImage(company.Logo),
  267 + Phone: company.Phone,
  268 + }
  269 +}
  270 +func computeBonusPercent(totalBonus float64, bonus float64) float64 {
  271 + if totalBonus == 0 {
  272 + return 0
  273 + }
  274 + return utils.Decimal(bonus / totalBonus)
  275 +}
  276 +
  277 +type Company struct {
  278 + protocol.CompanyBase
  279 + // 收入占比
  280 + IncomePercent float64 `json:"incomePercent"`
  281 + // 分红金额
  282 + DividendMoney float64 `json:"dividendMoney"`
  283 + JoinWays []joinWay `json:"joinWays"`
  284 +}
  285 +type incomeInfo struct {
  286 + // 收入占比
  287 + IncomePercent float64 `json:"incomePercent"`
  288 + // 分红金额
  289 + DividendMoney float64 `json:"dividendMoney"`
  290 +}
  291 +type joinWay struct {
  292 + Type int `json:"type"`
  293 + Name string `json:"name"`
  294 + Percent float64 `json:"percent"`
  295 +}
  296 +
  297 +func NewPgLoginService(ctx *transaction.TransactionContext) *PgLoginService {
  298 + return &PgLoginService{
  299 + transactionContext: ctx,
  300 + }
  301 +}
  1 +package domain_service
  2 +
  3 +import (
  4 + "fmt"
  5 + "github.com/tiptok/gocomm/xa/eda"
  6 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/application/factory"
  7 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain"
  8 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg/transaction"
  9 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/repository"
  10 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/svr"
  11 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/log"
  12 +)
  13 +
  14 +type PgManagerAuthService struct {
  15 + eda.EventCenterPublisher
  16 + transactionContext *transaction.TransactionContext
  17 +}
  18 +
  19 +func NewPgManagerAuthService(ctx *transaction.TransactionContext) *PgManagerAuthService {
  20 + return &PgManagerAuthService{
  21 + transactionContext: ctx,
  22 + }
  23 +}
  24 +
  25 +func (s *PgManagerAuthService) ChangeUserPhone(userId int64, newPhone, oldPhone string) (err error) {
  26 + var (
  27 + ucenterApiGateway = svr.NewHttplibUCenterApiServiceGateway()
  28 + UsersRepository, _ = repository.NewUsersRepository(s.transactionContext)
  29 + user *domain.Users
  30 + )
  31 + if user, err = UsersRepository.FindOne(map[string]interface{}{"id": userId}); err != nil || user == nil {
  32 + log.Error(err)
  33 + err = fmt.Errorf("用户不存在")
  34 + return
  35 + }
  36 + if newUser, e := UsersRepository.FindOne(map[string]interface{}{"phone": newPhone}); e == nil || newUser != nil {
  37 + err = fmt.Errorf("当前手机号已存在,请重新输入")
  38 + return
  39 + }
  40 + _, err = ucenterApiGateway.ChangePhone(newPhone, oldPhone)
  41 + if err == nil {
  42 + _, err = s.transactionContext.PgTx.Exec("update users set phone=? where phone=?", newPhone, oldPhone)
  43 + }
  44 + //event
  45 + return
  46 +}
  47 +func (s *PgManagerAuthService) ChangeUserPassword(userId int64, newPwd, oldPwd, phone string) (err error) {
  48 + var (
  49 + ucenterApiGateway = svr.NewHttplibUCenterApiServiceGateway()
  50 + UsersRepository, _ = factory.CreateUsersRepository(s.transactionContext)
  51 + user *domain.Users
  52 + )
  53 + if user, err = UsersRepository.FindOne(map[string]interface{}{"id": userId}); err != nil || user == nil {
  54 + log.Error(err)
  55 + err = fmt.Errorf("用户不存在")
  56 + return
  57 + }
  58 + _, err = ucenterApiGateway.ChangePassword(phone, newPwd, oldPwd)
  59 + return
  60 +}
  61 +func (s *PgManagerAuthService) ResetUserPassword(userId int64, phone, password string) (err error) {
  62 + var (
  63 + ucenterApiGateway = svr.NewHttplibUCenterApiServiceGateway()
  64 + UsersRepository, _ = factory.CreateUsersRepository(s.transactionContext)
  65 + user *domain.Users
  66 + )
  67 + if user, err = UsersRepository.FindOne(map[string]interface{}{"id": userId}); err != nil || user == nil {
  68 + log.Error(err)
  69 + err = fmt.Errorf("用户不存在")
  70 + return
  71 + }
  72 + _, err = ucenterApiGateway.UpdateUser(user.OpenId, phone, password)
  73 + return
  74 +}
  1 +package domain_service
  2 +
  3 +import (
  4 + "github.com/tiptok/gocomm/xa/eda"
  5 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain"
  6 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/dao"
  7 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg/transaction"
  8 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/repository"
  9 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/protocol"
  10 + "strings"
  11 +)
  12 +
  13 +type PgPartnerAuthService struct {
  14 + eda.EventCenterPublisher
  15 + transactionContext *transaction.TransactionContext
  16 +}
  17 +
  18 +func NewPgPartnerAuthService(ctx *transaction.TransactionContext) *PgPartnerAuthService {
  19 + return &PgPartnerAuthService{
  20 + transactionContext: ctx,
  21 + }
  22 +}
  23 +
  24 +func (s *PgPartnerAuthService) ChangeUserPhone(userId int64, newPhone, oldPhone string) (err error) {
  25 + var (
  26 + PartnerInfoDao, _ = dao.NewPartnerInfoDao(s.transactionContext)
  27 + PartnerInfoService, _ = repository.NewPartnerInfoRepository(s.transactionContext)
  28 + partnerInfo *domain.PartnerInfo
  29 + )
  30 + //验证新手机是否已经存在
  31 + if _, e := PartnerInfoService.FindOne(map[string]interface{}{"account": newPhone}); e == nil {
  32 + err = protocol.NewErrWithMessage(2029, err) //账号已存在
  33 + return
  34 + }
  35 + if partnerInfo, err = PartnerInfoService.FindOne(map[string]interface{}{"id": userId}); err != nil || (partnerInfo.Account != oldPhone) {
  36 + err = protocol.NewErrWithMessage(502, err) //账号不存在
  37 + return
  38 + }
  39 + if err = PartnerInfoDao.Update(map[string]interface{}{
  40 + "Id": userId,
  41 + "Account": newPhone,
  42 + }); err != nil {
  43 + return
  44 + }
  45 + return
  46 +}
  47 +func (s *PgPartnerAuthService) ChangeUserPassword(userId int64, newPwd, oldPwd, phone string) (err error) {
  48 + var (
  49 + partnerInfo *domain.PartnerInfo
  50 + PartnerInfoDao, _ = dao.NewPartnerInfoDao(s.transactionContext)
  51 + PartnerInfoService, _ = repository.NewPartnerInfoRepository(s.transactionContext)
  52 + )
  53 + if partnerInfo, err = PartnerInfoService.FindOne(map[string]interface{}{"id": userId}); err != nil {
  54 + err = protocol.NewErrWithMessage(502, err) //账号不存在
  55 + return
  56 + }
  57 + if !strings.EqualFold(partnerInfo.Password, oldPwd) {
  58 + //密码不一致
  59 + err = protocol.NewErrWithMessage(2028, err) //账号不存在
  60 + return
  61 + }
  62 + if err = PartnerInfoDao.Update(map[string]interface{}{
  63 + "Id": partnerInfo.Id,
  64 + "Password": newPwd,
  65 + }); err != nil {
  66 + return
  67 + }
  68 + return
  69 +}
  70 +func (s *PgPartnerAuthService) ResetUserPassword(userId int64, phone, password string) (err error) {
  71 + var (
  72 + partnerInfo *domain.PartnerInfo
  73 + PartnerInfoDao, _ = dao.NewPartnerInfoDao(s.transactionContext)
  74 + PartnerInfoService, _ = repository.NewPartnerInfoRepository(s.transactionContext)
  75 + )
  76 + if partnerInfo, err = PartnerInfoService.FindOne(map[string]interface{}{"id": userId}); err != nil {
  77 + err = protocol.NewErrWithMessage(502, err) //账号不存在
  78 + return
  79 + }
  80 + if err = PartnerInfoDao.Update(map[string]interface{}{
  81 + "Id": partnerInfo.Id,
  82 + "Password": password,
  83 + }); err != nil {
  84 + return
  85 + }
  86 + return
  87 +}
@@ -25,16 +25,16 @@ func init() { @@ -25,16 +25,16 @@ func init() {
25 //orm.RegisterTable((*models.OrderGood)(nil)) 25 //orm.RegisterTable((*models.OrderGood)(nil))
26 if !constant.DISABLE_CREATE_TABLE { 26 if !constant.DISABLE_CREATE_TABLE {
27 for _, model := range []interface{}{ 27 for _, model := range []interface{}{
28 - //(*models.Employee)(nil),  
29 (*models.PartnerInfo)(nil), 28 (*models.PartnerInfo)(nil),
30 - (*models.Order)(nil),  
31 - (*models.OrderPayment)(nil),  
32 (*models.PartnerSubAccount)(nil), 29 (*models.PartnerSubAccount)(nil),
33 (*models.Company)(nil), 30 (*models.Company)(nil),
34 (*models.OrderBase)(nil), 31 (*models.OrderBase)(nil),
35 (*models.OrderGood)(nil), 32 (*models.OrderGood)(nil),
36 (*models.ImInfo)(nil), 33 (*models.ImInfo)(nil),
37 (*models.ImCustomerService)(nil), 34 (*models.ImCustomerService)(nil),
  35 + (*models.BusinessBonus)(nil),
  36 + (*models.PartnerCategoryInfo)(nil),
  37 + (*models.Users)(nil),
38 } { 38 } {
39 err := DB.CreateTable(model, &orm.CreateTableOptions{ 39 err := DB.CreateTable(model, &orm.CreateTableOptions{
40 Temp: false, 40 Temp: false,
1 -package models  
2 -  
3 -type Company struct {  
4 - tableName struct{} `pg:"company"`  
5 - Id int64 `json:"id"`  
6 - Name string `json:"name"`  
7 - Phone string `json:"phone"`  
8 -}  
1 -package models  
2 -  
3 -import (  
4 - "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain"  
5 - "time"  
6 -)  
7 -  
8 -type Order struct {  
9 - tableName struct{} `pg:"order"`  
10 - //id  
11 - Id int64 `pg:",pk"`  
12 - //订单类型 1:实际订单 2:意向订单  
13 - OrderType int `pg:",notnull,default:1"`  
14 - //订单编号  
15 - OrderCode string `pg:",notnull`  
16 - //订单名称  
17 - OrderName string  
18 - //订单状态  
19 - OrderStatus int `pg:",notnull,default:1"`  
20 - //订单数量  
21 - OrderCount int  
22 - //实际订单数量  
23 - OrderActualCount int  
24 - //订单金额  
25 - OrderAmount float64  
26 - //订单实际金额  
27 - OrderActualAmount float64  
28 - //订单已支付金额(货款)  
29 - OrderPaymentAmount float64 `pg:",notnull,default:0"`  
30 - //订单区域信息  
31 - OrderRegionInfo *domain.RegionInfo  
32 -  
33 - Buyer *domain.Buyer  
34 - //合伙人编号  
35 - PartnerId int64  
36 - //合伙人分红百分比  
37 - PartnerBonusPercent float64  
38 - //业务员分红百分比  
39 - SalesmanBonusPercent float64  
40 -  
41 - //创建时间  
42 - CreateAt time.Time  
43 - //更新时间  
44 - UpdateAt time.Time  
45 -  
46 - //上一次查看时间 已读情况  
47 - LastViewTime time.Time  
48 - //订单更新理由  
49 - Reason string  
50 -}  
@@ -10,6 +10,8 @@ type OrderBase struct { @@ -10,6 +10,8 @@ type OrderBase struct {
10 tableName struct{} `pg:"order_base"` 10 tableName struct{} `pg:"order_base"`
11 //表id 11 //表id
12 Id int64 `pg:",pk"` 12 Id int64 `pg:",pk"`
  13 + // 公司id
  14 + CompanyId int64
13 //订单类型 1:实际订单 2:意向订单 15 //订单类型 1:实际订单 2:意向订单
14 OrderType int `pg:",notnull,default:1"` 16 OrderType int `pg:",notnull,default:1"`
15 //订单编号 17 //订单编号
@@ -5,6 +5,8 @@ type OrderGood struct { @@ -5,6 +5,8 @@ type OrderGood struct {
5 tableName struct{} `pg:"order_good"` 5 tableName struct{} `pg:"order_good"`
6 //货品id 6 //货品id
7 Id int64 `pg:",pk"` 7 Id int64 `pg:",pk"`
  8 + // 公司id
  9 + CompanyId int64
8 //所属订单id 10 //所属订单id
9 OrderId int64 11 OrderId int64
10 //货品名称 长度可能较长 12 //货品名称 长度可能较长
1 -package models  
2 -  
3 -import "time"  
4 -  
5 -type OrderPayment struct {  
6 - tableName struct{} `pg:"order_payment"`  
7 - //编号  
8 - Id int64 `pg:",pk"`  
9 - //订单编号  
10 - OrderId int64  
11 - //合伙人编号  
12 - PartnerId int64  
13 - //支付货款  
14 - PaymentAmount float64 `pg:",notnull,default:0"`  
15 - //分红金额  
16 - BonusAmount float64  
17 - //分红状态 1.等待支付分红 2.已支付分红  
18 - BonusStatus int `pg:",notnull,default:1"`  
19 - //创建时间  
20 - CreateAt time.Time  
21 - //更新时间  
22 - UpdateAt time.Time  
23 -}  
@@ -10,6 +10,8 @@ type PartnerInfo struct { @@ -10,6 +10,8 @@ type PartnerInfo struct {
10 tableName struct{} `pg:"partner_info"` 10 tableName struct{} `pg:"partner_info"`
11 // 合伙人ID 11 // 合伙人ID
12 Id int64 `pg:",pk"` 12 Id int64 `pg:",pk"`
  13 + // 公司id
  14 + CompanyId int64
13 // 合伙人姓名 15 // 合伙人姓名
14 PartnerName string 16 PartnerName string
15 // 登录账号 17 // 登录账号
@@ -32,4 +34,6 @@ type PartnerInfo struct { @@ -32,4 +34,6 @@ type PartnerInfo struct {
32 34
33 //关联业务员 35 //关联业务员
34 Salesman []*domain.Salesman 36 Salesman []*domain.Salesman
  37 + //合伙人分类信息
  38 + PartnerCategoryInfos []*PartnerCategoryInfo
35 } 39 }
  1 +package models
  2 +
  3 +import "time"
  4 +
  5 +// 业务分红信息
  6 +type BusinessBonus struct {
  7 + tableName struct{} `pg:"business_bonus"`
  8 + // 唯一标识
  9 + Id int64
  10 + // 公司编号
  11 + CompanyId int64
  12 + // 合伙人信息Id
  13 + PartnerInfoId int64
  14 + // 应收分红
  15 + Bonus float64
  16 + // 已收分红
  17 + BonusHas float64
  18 + // 未收分红
  19 + BonusNot float64
  20 + // 分红支出
  21 + BonusExpense float64
  22 + // 是否关闭【0;否】【1:是】
  23 + IsDisable int8
  24 + // 分红状态 1:待支付分红 2:已支付分红
  25 + BonusStatus int8
  26 + // 创建时间
  27 + CreateAt time.Time
  28 + // 更新时间
  29 + UpdateAt time.Time
  30 + // 删除时间
  31 + DeleteAt time.Time
  32 +}
  1 +package models
  2 +
  3 +import "time"
  4 +
  5 +// 公司信息
  6 +type Company struct {
  7 + tableName struct{} `pg:"company"`
  8 + // 唯一标识
  9 + Id int64
  10 + // 名称
  11 + Name string
  12 + // 公司简称
  13 + Abbreviation string
  14 + // 手机号码
  15 + Phone string
  16 + // 公司logo
  17 + Logo string
  18 + // 备注
  19 + Remarks string
  20 + // 总后台的公司id
  21 + AdminCompanyId int
  22 + // 状态 1正常 2禁用
  23 + Status int8
  24 + // 创建时间
  25 + CreateAt time.Time
  26 + // 更新时间
  27 + UpdateAt time.Time
  28 + // 删除时间
  29 + DeleteAt time.Time
  30 + // 是否开启合伙人模块,是否有效【1:有效】【2:无效】
  31 + Enable int8
  32 +}
  1 +package models
  2 +
  3 +// 合伙人分类信息
  4 +type PartnerCategoryInfo struct {
  5 + tableName struct{} `pg:"partner_category_info"`
  6 + // 唯一标识
  7 + Id int64
  8 + // 名称
  9 + Name string
  10 +}
  1 +package models
  2 +
  3 +import (
  4 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain"
  5 + "time"
  6 +)
  7 +
  8 +// 用户信息
  9 +type Users struct {
  10 + tableName struct{} `pg:"users"`
  11 + // 唯一标识
  12 + Id int64
  13 + // 公司id
  14 + CompanyId int64
  15 + // 统一用户中心 uid
  16 + OpenId int64
  17 + // 名称
  18 + Name string
  19 + // 性别:0保密 1男 2女
  20 + Sex int8
  21 + // 员工工号
  22 + JobNum string
  23 + // 手机号码
  24 + Phone string
  25 + // 私人手机号码
  26 + PrivatePhone string
  27 + // 邮箱
  28 + Email string
  29 + // 分机号
  30 + ExtensionNum string
  31 + // 入职时间
  32 + EntryTime time.Time
  33 + // 工作地点
  34 + Workspace string
  35 + // 状态 1正常 2禁用
  36 + Status int8
  37 + // 手机号
  38 + Avatar string
  39 + // 备注
  40 + Remarks string
  41 + // 是否为当前公司主管 1 是2 否
  42 + ChargeStatus int8
  43 + // 创建时间
  44 + CreateAt time.Time
  45 + // 更新时间
  46 + UpdateAt time.Time
  47 + // 删除时间
  48 + DeleteAt time.Time
  49 + // 可查看的合伙人信息
  50 + AccessPartners []*domain.PartnerInfo
  51 + // 1普通用户 2主管理员
  52 + AdminType int8
  53 +}
  1 +package repository
  2 +
  3 +import (
  4 + "fmt"
  5 + "github.com/go-pg/pg/v10"
  6 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain"
  7 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg/models"
  8 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg/transaction"
  9 + . "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/utils"
  10 +)
  11 +
  12 +type BusinessBonusRepository struct {
  13 + transactionContext *transaction.TransactionContext
  14 +}
  15 +
  16 +func (repository *BusinessBonusRepository) Save(dm *domain.BusinessBonus) (*domain.BusinessBonus, error) {
  17 + var (
  18 + err error
  19 + m = &models.BusinessBonus{}
  20 + tx = repository.transactionContext.PgTx
  21 + )
  22 + if err = GobModelTransform(m, dm); err != nil {
  23 + return nil, err
  24 + }
  25 + if dm.Identify() == nil {
  26 + if err = tx.Insert(m); err != nil {
  27 + return nil, err
  28 + }
  29 + return dm, nil
  30 + }
  31 + if err = tx.Update(m); err != nil {
  32 + return nil, err
  33 + }
  34 + return dm, nil
  35 +}
  36 +
  37 +func (repository *BusinessBonusRepository) Remove(BusinessBonus *domain.BusinessBonus) (*domain.BusinessBonus, error) {
  38 + var (
  39 + tx = repository.transactionContext.PgTx
  40 + BusinessBonusModel = &models.BusinessBonus{Id: BusinessBonus.Identify().(int64)}
  41 + )
  42 + if _, err := tx.Model(BusinessBonusModel).Where("id = ?", BusinessBonus.Id).Delete(); err != nil {
  43 + return BusinessBonus, err
  44 + }
  45 + return BusinessBonus, nil
  46 +}
  47 +
  48 +func (repository *BusinessBonusRepository) FindOne(queryOptions map[string]interface{}) (*domain.BusinessBonus, error) {
  49 + tx := repository.transactionContext.PgTx
  50 + BusinessBonusModel := new(models.BusinessBonus)
  51 + query := NewQuery(tx.Model(BusinessBonusModel), queryOptions)
  52 + query.SetWhere("id = ?", "id")
  53 + query.SetWhere("is_disable = ?", "isDisable")
  54 + query.SetWhere("partner_info_id = ?", "partner_id")
  55 + if err := query.First(); err != nil {
  56 + return nil, fmt.Errorf("query row not found")
  57 + }
  58 + if BusinessBonusModel.Id == 0 {
  59 + return nil, fmt.Errorf("query row not found")
  60 + }
  61 + return repository.transformPgModelToDomainModel(BusinessBonusModel)
  62 +}
  63 +
  64 +func (repository *BusinessBonusRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.BusinessBonus, error) {
  65 + tx := repository.transactionContext.PgTx
  66 + var BusinessBonusModels []*models.BusinessBonus
  67 + BusinessBonuss := make([]*domain.BusinessBonus, 0)
  68 + query := NewQuery(tx.Model(&BusinessBonusModels), queryOptions).
  69 + SetOrder("create_time", "sortByCreateTime").
  70 + SetOrder("update_time", "sortByUpdateTime").
  71 + SetWhere("is_disable = ?", "isDisable")
  72 + if v, ok := queryOptions["inPartnerIds"]; ok {
  73 + query.Where("partner_info_id in (?)", pg.In(v.([]int64)))
  74 + }
  75 + var err error
  76 + if query.AffectRow, err = query.SelectAndCount(); err != nil {
  77 + return 0, BusinessBonuss, err
  78 + }
  79 + for _, BusinessBonusModel := range BusinessBonusModels {
  80 + if BusinessBonus, err := repository.transformPgModelToDomainModel(BusinessBonusModel); err != nil {
  81 + return 0, BusinessBonuss, err
  82 + } else {
  83 + BusinessBonuss = append(BusinessBonuss, BusinessBonus)
  84 + }
  85 + }
  86 + return int64(query.AffectRow), BusinessBonuss, nil
  87 +}
  88 +
  89 +func (repository *BusinessBonusRepository) transformPgModelToDomainModel(BusinessBonusModel *models.BusinessBonus) (*domain.BusinessBonus, error) {
  90 + m := &domain.BusinessBonus{}
  91 + err := GobModelTransform(m, BusinessBonusModel)
  92 + return m, err
  93 +}
  94 +
  95 +func NewBusinessBonusRepository(transactionContext *transaction.TransactionContext) (*BusinessBonusRepository, error) {
  96 + if transactionContext == nil {
  97 + return nil, fmt.Errorf("transactionContext参数不能为nil")
  98 + }
  99 + return &BusinessBonusRepository{transactionContext: transactionContext}, nil
  100 +}
1 package repository 1 package repository
2 2
3 import ( 3 import (
  4 + "github.com/go-pg/pg/v10"
4 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain" 5 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain"
5 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg/models" 6 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg/models"
6 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg/transaction" 7 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg/transaction"
@@ -48,8 +49,10 @@ func (repository *CompanyRepository) FindOne(queryOptions map[string]interface{} @@ -48,8 +49,10 @@ func (repository *CompanyRepository) FindOne(queryOptions map[string]interface{}
48 CompanyModel := new(models.Company) 49 CompanyModel := new(models.Company)
49 query := NewQuery(tx.Model(CompanyModel), queryOptions) 50 query := NewQuery(tx.Model(CompanyModel), queryOptions)
50 query.SetWhere(`"company".id = ?`, "id") 51 query.SetWhere(`"company".id = ?`, "id")
  52 + query.SetWhere(`"company".status = ?`, "status")
  53 + query.SetWhere(`"company".enable = ?`, "enable")
51 if err := query.First(); err != nil { 54 if err := query.First(); err != nil {
52 - return nil, query.HandleError(err, "没有此订单") 55 + return nil, query.HandleError(err, "没有此公司")
53 } 56 }
54 if CompanyModel.Id == 0 { 57 if CompanyModel.Id == 0 {
55 return nil, nil 58 return nil, nil
@@ -62,6 +65,12 @@ func (repository *CompanyRepository) Find(queryOptions map[string]interface{}) ( @@ -62,6 +65,12 @@ func (repository *CompanyRepository) Find(queryOptions map[string]interface{}) (
62 var CompanyModels []*models.Company 65 var CompanyModels []*models.Company
63 Companys := make([]*domain.Company, 0) 66 Companys := make([]*domain.Company, 0)
64 query := NewQuery(tx.Model(&CompanyModels), queryOptions) 67 query := NewQuery(tx.Model(&CompanyModels), queryOptions)
  68 + if companies, ok := queryOptions["inCompanyIds"]; ok {
  69 + companyIds, _ := companies.([]int64)
  70 + query.Where("id in (?)", pg.In(companyIds))
  71 + }
  72 + query.SetWhere("status = ?", "status")
  73 + query.SetOrder(`create_at`, "sortByCreateTime")
65 var err error 74 var err error
66 if query.AffectRow, err = query.SelectAndCount(); err != nil { 75 if query.AffectRow, err = query.SelectAndCount(); err != nil {
67 return 0, Companys, err 76 return 0, Companys, err
  1 +package repository
  2 +
  3 +import (
  4 + "fmt"
  5 + "github.com/go-pg/pg/v10"
  6 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain"
  7 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg/models"
  8 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg/transaction"
  9 + . "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/utils"
  10 +)
  11 +
  12 +type PartnerCategoryInfoRepository struct {
  13 + transactionContext *transaction.TransactionContext
  14 +}
  15 +
  16 +func (repository *PartnerCategoryInfoRepository) Save(dm *domain.PartnerCategoryInfo) (*domain.PartnerCategoryInfo, error) {
  17 + var (
  18 + err error
  19 + m = &models.PartnerCategoryInfo{}
  20 + tx = repository.transactionContext.PgTx
  21 + )
  22 + if err = GobModelTransform(m, dm); err != nil {
  23 + return nil, err
  24 + }
  25 + if dm.Identify() == nil {
  26 + if err = tx.Insert(m); err != nil {
  27 + return nil, err
  28 + }
  29 + return dm, nil
  30 + }
  31 + if err = tx.Update(m); err != nil {
  32 + return nil, err
  33 + }
  34 + return dm, nil
  35 +}
  36 +
  37 +func (repository *PartnerCategoryInfoRepository) Remove(PartnerCategoryInfo *domain.PartnerCategoryInfo) (*domain.PartnerCategoryInfo, error) {
  38 + var (
  39 + tx = repository.transactionContext.PgTx
  40 + PartnerCategoryInfoModel = &models.PartnerCategoryInfo{Id: PartnerCategoryInfo.Identify().(int64)}
  41 + )
  42 + if _, err := tx.Model(PartnerCategoryInfoModel).Where("id = ?", PartnerCategoryInfo.Id).Delete(); err != nil {
  43 + return PartnerCategoryInfo, err
  44 + }
  45 + return PartnerCategoryInfo, nil
  46 +}
  47 +
  48 +func (repository *PartnerCategoryInfoRepository) FindOne(queryOptions map[string]interface{}) (*domain.PartnerCategoryInfo, error) {
  49 + tx := repository.transactionContext.PgTx
  50 + PartnerCategoryInfoModel := new(models.PartnerCategoryInfo)
  51 + query := NewQuery(tx.Model(PartnerCategoryInfoModel), queryOptions)
  52 + query.SetWhere("id = ?", "id")
  53 + if err := query.First(); err != nil {
  54 + return nil, fmt.Errorf("query row not found")
  55 + }
  56 + if PartnerCategoryInfoModel.Id == 0 {
  57 + return nil, fmt.Errorf("query row not found")
  58 + }
  59 + return repository.transformPgModelToDomainModel(PartnerCategoryInfoModel)
  60 +}
  61 +
  62 +func (repository *PartnerCategoryInfoRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.PartnerCategoryInfo, error) {
  63 + tx := repository.transactionContext.PgTx
  64 + var PartnerCategoryInfoModels []*models.PartnerCategoryInfo
  65 + PartnerCategoryInfos := make([]*domain.PartnerCategoryInfo, 0)
  66 + query := NewQuery(tx.Model(&PartnerCategoryInfoModels), queryOptions).
  67 + SetOrder("create_time", "sortByCreateTime").
  68 + SetOrder("update_time", "sortByUpdateTime").
  69 + SetOrder("id", "sortById")
  70 + if value, ok := queryOptions["inIds"]; ok {
  71 + query.Where("id in (?)", pg.In(value))
  72 + }
  73 + var err error
  74 + if query.AffectRow, err = query.SelectAndCount(); err != nil {
  75 + return 0, PartnerCategoryInfos, err
  76 + }
  77 + for _, PartnerCategoryInfoModel := range PartnerCategoryInfoModels {
  78 + if PartnerCategoryInfo, err := repository.transformPgModelToDomainModel(PartnerCategoryInfoModel); err != nil {
  79 + return 0, PartnerCategoryInfos, err
  80 + } else {
  81 + PartnerCategoryInfos = append(PartnerCategoryInfos, PartnerCategoryInfo)
  82 + }
  83 + }
  84 + return int64(query.AffectRow), PartnerCategoryInfos, nil
  85 +}
  86 +
  87 +func (repository *PartnerCategoryInfoRepository) transformPgModelToDomainModel(PartnerCategoryInfoModel *models.PartnerCategoryInfo) (*domain.PartnerCategoryInfo, error) {
  88 + m := &domain.PartnerCategoryInfo{}
  89 + err := GobModelTransform(m, PartnerCategoryInfoModel)
  90 + return m, err
  91 +}
  92 +
  93 +func NewPartnerCategoryInfoRepository(transactionContext *transaction.TransactionContext) (*PartnerCategoryInfoRepository, error) {
  94 + if transactionContext == nil {
  95 + return nil, fmt.Errorf("transactionContext参数不能为nil")
  96 + }
  97 + return &PartnerCategoryInfoRepository{transactionContext: transactionContext}, nil
  98 +}
1 package repository 1 package repository
2 2
3 import ( 3 import (
  4 + "github.com/go-pg/pg/v10"
  5 + "github.com/go-pg/pg/v10/orm"
4 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain" 6 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain"
5 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg/models" 7 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg/models"
6 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg/transaction" 8 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg/transaction"
@@ -53,6 +55,13 @@ func (repository *PartnerInfoRepository) FindOne(queryOptions map[string]interfa @@ -53,6 +55,13 @@ func (repository *PartnerInfoRepository) FindOne(queryOptions map[string]interfa
53 query := NewQuery(tx.Model(PartnerInfoModel), queryOptions) 55 query := NewQuery(tx.Model(PartnerInfoModel), queryOptions)
54 query.SetWhere("partner_info.id = ?", "id") 56 query.SetWhere("partner_info.id = ?", "id")
55 query.SetWhere("partner_info.account = ?", "account") 57 query.SetWhere("partner_info.account = ?", "account")
  58 + query.SetWhere("partner_info.status = ?", "status")
  59 + query.SetWhere("partner_info.company_id = ?", "companyId")
  60 + //if inParterIds,ok :=queryOptions["inParterIds"];ok{
  61 + // query.Relation("PartnerInfo", func(q *orm.Query) (*orm.Query, error) {
  62 + // return q.Where("id in (?)",pg.In(inParterIds.([]int64))),nil
  63 + // })
  64 + //}
56 if err := query.First(); err != nil { 65 if err := query.First(); err != nil {
57 return nil, query.HandleError(err, "没有此合伙人") 66 return nil, query.HandleError(err, "没有此合伙人")
58 } 67 }
@@ -74,6 +83,21 @@ func (repository *PartnerInfoRepository) Find(queryOptions map[string]interface{ @@ -74,6 +83,21 @@ func (repository *PartnerInfoRepository) Find(queryOptions map[string]interface{
74 SetLimit(). 83 SetLimit().
75 SetOrder("partner_info.create_at", "sortByCreateTime"). 84 SetOrder("partner_info.create_at", "sortByCreateTime").
76 SetOrder("partner_info.update_at", "sortByUpdateTime") 85 SetOrder("partner_info.update_at", "sortByUpdateTime")
  86 +
  87 + if inPartnerIds, ok := queryOptions["inPartnerIds"]; ok {
  88 + query.Where("id in (?)", pg.In(inPartnerIds.([]int64)))
  89 + }
  90 + // 合伙人类型
  91 + if inPartnerCategory, ok := queryOptions["inPartnerCategory"]; ok {
  92 + query.Query = query.WhereGroup(func(q *orm.Query) (*orm.Query, error) {
  93 + if arrayInPartnerCategory, ok := inPartnerCategory.([]int64); ok {
  94 + for i := range arrayInPartnerCategory {
  95 + q.WhereOr(`partner_info.partner_category_infos @>'[{"id":?}]')`, arrayInPartnerCategory[i])
  96 + }
  97 + }
  98 + return q, nil
  99 + })
  100 + }
77 var err error 101 var err error
78 if query.AffectRow, err = query.SelectAndCount(); err != nil { 102 if query.AffectRow, err = query.SelectAndCount(); err != nil {
79 return 0, PartnerInfos, err 103 return 0, PartnerInfos, err
  1 +package repository
  2 +
  3 +import (
  4 + "fmt"
  5 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain"
  6 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg/models"
  7 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg/transaction"
  8 + . "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/utils"
  9 +)
  10 +
  11 +type UsersRepository struct {
  12 + transactionContext *transaction.TransactionContext
  13 +}
  14 +
  15 +func (repository *UsersRepository) Save(dm *domain.Users) (*domain.Users, error) {
  16 + var (
  17 + err error
  18 + m = &models.Users{}
  19 + tx = repository.transactionContext.PgTx
  20 + )
  21 + if err = GobModelTransform(m, dm); err != nil {
  22 + return nil, err
  23 + }
  24 + if dm.Identify() == nil {
  25 + if err = tx.Insert(m); err != nil {
  26 + return nil, err
  27 + }
  28 + return dm, nil
  29 + }
  30 + if err = tx.Update(m); err != nil {
  31 + return nil, err
  32 + }
  33 + return dm, nil
  34 +}
  35 +
  36 +func (repository *UsersRepository) Remove(Users *domain.Users) (*domain.Users, error) {
  37 + var (
  38 + tx = repository.transactionContext.PgTx
  39 + UsersModel = &models.Users{Id: Users.Identify().(int64)}
  40 + )
  41 + if _, err := tx.Model(UsersModel).Where("id = ?", Users.Id).Delete(); err != nil {
  42 + return Users, err
  43 + }
  44 + return Users, nil
  45 +}
  46 +
  47 +func (repository *UsersRepository) FindOne(queryOptions map[string]interface{}) (*domain.Users, error) {
  48 + tx := repository.transactionContext.PgTx
  49 + UsersModel := new(models.Users)
  50 + query := NewQuery(tx.Model(UsersModel), queryOptions)
  51 + query.SetWhere("id = ?", "id")
  52 + query.SetWhere("status = ?", "status")
  53 + query.SetWhere("phone = ?", "phone")
  54 + query.SetWhere("company_id = ?", "companyId")
  55 + if err := query.First(); err != nil {
  56 + return nil, fmt.Errorf("query row not found")
  57 + }
  58 + if UsersModel.Id == 0 {
  59 + return nil, fmt.Errorf("query row not found")
  60 + }
  61 + return repository.transformPgModelToDomainModel(UsersModel)
  62 +}
  63 +
  64 +func (repository *UsersRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.Users, error) {
  65 + tx := repository.transactionContext.PgTx
  66 + var UsersModels []*models.Users
  67 + Userss := make([]*domain.Users, 0)
  68 + query := NewQuery(tx.Model(&UsersModels), queryOptions).
  69 + SetWhere("id = ?", "id").
  70 + SetWhere("phone = ?", "phone").
  71 + SetWhere("company_id = ?", "companyId").
  72 + SetWhere(`status = ?`, "status").
  73 + SetOrder("create_at", "sortByCreateTime").
  74 + SetOrder("update_at", "sortByUpdateTime")
  75 + var err error
  76 + if query.AffectRow, err = query.SelectAndCount(); err != nil {
  77 + return 0, Userss, err
  78 + }
  79 + for _, UsersModel := range UsersModels {
  80 + if Users, err := repository.transformPgModelToDomainModel(UsersModel); err != nil {
  81 + return 0, Userss, err
  82 + } else {
  83 + Userss = append(Userss, Users)
  84 + }
  85 + }
  86 + return int64(query.AffectRow), Userss, nil
  87 +}
  88 +
  89 +func (repository *UsersRepository) transformPgModelToDomainModel(UsersModel *models.Users) (*domain.Users, error) {
  90 + m := &domain.Users{}
  91 + err := GobModelTransform(m, UsersModel)
  92 + return m, err
  93 +}
  94 +
  95 +func NewUsersRepository(transactionContext *transaction.TransactionContext) (*UsersRepository, error) {
  96 + if transactionContext == nil {
  97 + return nil, fmt.Errorf("transactionContext参数不能为nil")
  98 + }
  99 + return &UsersRepository{transactionContext: transactionContext}, nil
  100 +}
  1 +package svr
  2 +
  3 +import (
  4 + "fmt"
  5 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/constant"
  6 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/log"
  7 + "strconv"
  8 + "strings"
  9 + "time"
  10 +)
  11 +
  12 +type HttplibBusinessAdminApiServiceGateway struct {
  13 + httplibBaseServiceGateway
  14 +}
  15 +
  16 +// 服务登录
  17 +func (serviceGateway *HttplibBusinessAdminApiServiceGateway) UserAuth(userId int64, platformId string) (int, error) {
  18 + url := strings.Join([]string{serviceGateway.baseURL, "auth", "get-user-auth"}, "/")
  19 + request := serviceGateway.createRequest(url, "post")
  20 + request.Header("appKey", constant.UCENTER_APP_KEY)
  21 + options := make(map[string]interface{})
  22 + options["userId"] = fmt.Sprintf("%v", userId)
  23 + options["platformId"] = fmt.Sprintf("%v", platformId)
  24 + request.JSONBody(options)
  25 + response := make(map[string]interface{})
  26 + err := request.ToJSON(&response)
  27 + if err != nil {
  28 + log.Error("Service Gateway Fail:", err)
  29 + return 0, err
  30 + }
  31 + return serviceGateway.handlerError(response)
  32 +}
  33 +
  34 +func (serviceGateway *HttplibBusinessAdminApiServiceGateway) handlerError(in map[string]interface{}) (int, error) {
  35 + var rspCode int
  36 + var err error
  37 + if code, ok := in["code"]; ok {
  38 + rspCode, _ = strconv.Atoi(fmt.Sprintf("%v", code))
  39 + } else {
  40 + err = fmt.Errorf("网关解析错误")
  41 + }
  42 + if msg, ok := in["msg"]; ok {
  43 + msg := msg.(string)
  44 + if rspCode != 0 && len(msg) > 0 {
  45 + err = fmt.Errorf(msg)
  46 + }
  47 + }
  48 + return rspCode, err
  49 +}
  50 +
  51 +func NewHttplibBusinessAdminApiServiceGateway() *HttplibBusinessAdminApiServiceGateway {
  52 + return &HttplibBusinessAdminApiServiceGateway{
  53 + httplibBaseServiceGateway: httplibBaseServiceGateway{
  54 + baseURL: constant.BUSINESS_ADMIN_SERVICE_HOST,
  55 + connectTimeout: 100 * time.Second,
  56 + readWriteTimeout: 30 * time.Second,
  57 + },
  58 + }
  59 +}
  1 +package svr
  2 +
  3 +import (
  4 + "fmt"
  5 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/constant"
  6 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/log"
  7 + "strconv"
  8 + "strings"
  9 + "time"
  10 +)
  11 +
  12 +type HttplibUCenterApiServiceGateway struct {
  13 + httplibBaseServiceGateway
  14 +}
  15 +
  16 +// 服务登录
  17 +func (serviceGateway *HttplibUCenterApiServiceGateway) ServerLogin(phone, password string, loginType int) (int64, error) {
  18 + url := strings.Join([]string{serviceGateway.baseURL, "auth", "serverLogin"}, "/")
  19 + request := serviceGateway.createRequest(url, "post")
  20 + request.Header("appKey", constant.UCENTER_APP_KEY)
  21 + options := make(map[string]interface{})
  22 + options["phone"] = strings.TrimSpace(phone)
  23 + options["password"] = strings.TrimSpace(password)
  24 + options["type"] = loginType
  25 + request.JSONBody(options)
  26 + response := make(map[string]interface{})
  27 + err := request.ToJSON(&response)
  28 + var openid int64
  29 + if err != nil {
  30 + log.Error("Service Gateway Fail:", err)
  31 + return 0, err
  32 + }
  33 + if data, ok := response["data"]; ok {
  34 + if data, ok := data.(map[string]interface{}); ok {
  35 + if data, ok := data["id"]; ok {
  36 + openid = int64(data.(float64))
  37 + //openid,err=strconv.ParseInt(fmt.Sprintf("%v",data.(float64)),10,64)
  38 + }
  39 + }
  40 + }
  41 + _, err = serviceGateway.handlerError(response)
  42 + return openid, err
  43 +}
  44 +
  45 +// 修改密码
  46 +func (serviceGateway *HttplibUCenterApiServiceGateway) UpdateUser(uid int64, phone, password string) (int, error) {
  47 + url := strings.Join([]string{serviceGateway.baseURL, "users", fmt.Sprintf("%v", uid)}, "/")
  48 + request := serviceGateway.createRequest(url, "put")
  49 + //request.Header("appKey", constant.UCENTER_APP_KEY)
  50 + options := make(map[string]interface{})
  51 + if len(phone) > 0 {
  52 + options["phone"] = strings.TrimSpace(phone)
  53 + }
  54 + if len(password) > 0 {
  55 + options["password"] = strings.TrimSpace(password)
  56 + }
  57 + request.JSONBody(options)
  58 + response := make(map[string]interface{})
  59 + err := request.ToJSON(&response)
  60 + if err != nil {
  61 + log.Error("Service Gateway Fail:", err)
  62 + return 0, err
  63 + }
  64 + return serviceGateway.handlerError(response)
  65 +}
  66 +func (serviceGateway *HttplibUCenterApiServiceGateway) ChangePassword(phone, newPwd, oldPwd string) (int, error) {
  67 + url := strings.Join([]string{serviceGateway.baseURL, "users", "changePassword"}, "/")
  68 + request := serviceGateway.createRequest(url, "post")
  69 + request.Header("appKey", constant.UCENTER_APP_KEY)
  70 + options := make(map[string]interface{})
  71 + options["phone"] = strings.TrimSpace(phone)
  72 + options["newPassword"] = strings.TrimSpace(newPwd)
  73 + //options["confirmPwd"] = strings.TrimSpace(confirmPwd)
  74 + options["password"] = strings.TrimSpace(oldPwd)
  75 + request.JSONBody(options)
  76 + response := make(map[string]interface{})
  77 + err := request.ToJSON(&response)
  78 + if err != nil {
  79 + log.Error("Service Gateway Fail:", err)
  80 + return 0, err
  81 + }
  82 + return serviceGateway.handlerError(response)
  83 +}
  84 +func (serviceGateway *HttplibUCenterApiServiceGateway) ChangePhone(newPhone, oldPhone string) (int, error) {
  85 + url := strings.Join([]string{serviceGateway.baseURL, "user", "change-phone"}, "/")
  86 + request := serviceGateway.createRequest(url, "post")
  87 + options := make(map[string]interface{})
  88 + options["phone"] = strings.TrimSpace(newPhone)
  89 + options["oldPhone"] = strings.TrimSpace(oldPhone)
  90 + request.JSONBody(options)
  91 + response := make(map[string]interface{})
  92 + err := request.ToJSON(&response)
  93 + if err != nil {
  94 + log.Error("Service Gateway Fail:", err)
  95 + return 0, err
  96 + }
  97 + return serviceGateway.handlerError(response)
  98 +}
  99 +
  100 +func (serviceGateway *HttplibUCenterApiServiceGateway) handlerError(in map[string]interface{}) (int, error) {
  101 + var rspCode int
  102 + var err error
  103 + if code, ok := in["code"]; ok {
  104 + rspCode, _ = strconv.Atoi(fmt.Sprintf("%v", code))
  105 + } else {
  106 + err = fmt.Errorf("网关解析错误")
  107 + }
  108 + if msg, ok := in["msg"]; ok {
  109 + msg := msg.(string)
  110 + if rspCode != 0 && len(msg) > 0 {
  111 + err = fmt.Errorf(msg)
  112 + }
  113 + }
  114 + return rspCode, err
  115 +}
  116 +
  117 +func NewHttplibUCenterApiServiceGateway() *HttplibUCenterApiServiceGateway {
  118 + return &HttplibUCenterApiServiceGateway{
  119 + httplibBaseServiceGateway: httplibBaseServiceGateway{
  120 + baseURL: constant.UCENTER_SERVICE_HOST,
  121 + connectTimeout: 100 * time.Second,
  122 + readWriteTimeout: 30 * time.Second,
  123 + },
  124 + }
  125 +}
@@ -6,7 +6,10 @@ import ( @@ -6,7 +6,10 @@ import (
6 ) 6 )
7 7
8 type UserTokenClaims struct { 8 type UserTokenClaims struct {
9 - UserId int64 `json:"userId"` 9 + UserId int64 `json:"userId"`
  10 + CompanyId int64 `json:"companyId"`
  11 + AdminType int `json:"adminType"` //用户类型 1:合伙人 2:高管
  12 + Phone string `json:"phone"`
10 jwt.StandardClaims 13 jwt.StandardClaims
11 } 14 }
12 15
@@ -22,10 +25,14 @@ func ParseJWTToken(token string) (*UserTokenClaims, error) { @@ -22,10 +25,14 @@ func ParseJWTToken(token string) (*UserTokenClaims, error) {
22 } 25 }
23 if tokenClaims != nil { 26 if tokenClaims != nil {
24 if claim, ok := tokenClaims.Claims.(*UserTokenClaims); ok && tokenClaims.Valid { 27 if claim, ok := tokenClaims.Claims.(*UserTokenClaims); ok && tokenClaims.Valid {
  28 + // TODO:版本兼容
  29 + //if claim.CompanyId==0{
  30 + // claim.CompanyId = 1
  31 + // claim.AdminType = 1
  32 + //}
25 return claim, nil 33 return claim, nil
26 } 34 }
27 } 35 }
28 -  
29 return nil, err 36 return nil, err
30 } 37 }
31 38
@@ -33,11 +40,49 @@ func ParseJWTToken(token string) (*UserTokenClaims, error) { @@ -33,11 +40,49 @@ func ParseJWTToken(token string) (*UserTokenClaims, error) {
33 //@uid 用户变化 40 //@uid 用户变化
34 //@password 密码 41 //@password 密码
35 //@expire 过期时长 42 //@expire 过期时长
36 -func GenerateToken(uid int64, expire time.Duration) (string, error) { 43 +func GenerateToken(uid int64, phone string, expire time.Duration) (string, error) {
37 now := time.Now() 44 now := time.Now()
38 expireTime := now.Add(expire) 45 expireTime := now.Add(expire)
39 claims := UserTokenClaims{ 46 claims := UserTokenClaims{
40 UserId: uid, 47 UserId: uid,
  48 + Phone: phone,
  49 + StandardClaims: jwt.StandardClaims{
  50 + ExpiresAt: expireTime.Unix(),
  51 + Issuer: "jwt",
  52 + },
  53 + }
  54 +
  55 + tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
  56 + token, err := tokenClaims.SignedString(jwtSecret)
  57 + return token, err
  58 +}
  59 +
  60 +func GenerateTokenWithAdminType(uid int64, phone string, adminType int, expire time.Duration) (string, error) {
  61 + now := time.Now()
  62 + expireTime := now.Add(expire)
  63 + claims := UserTokenClaims{
  64 + UserId: uid,
  65 + Phone: phone,
  66 + AdminType: adminType,
  67 + StandardClaims: jwt.StandardClaims{
  68 + ExpiresAt: expireTime.Unix(),
  69 + Issuer: "jwt",
  70 + },
  71 + }
  72 +
  73 + tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
  74 + token, err := tokenClaims.SignedString(jwtSecret)
  75 + return token, err
  76 +}
  77 +
  78 +func GenerateTokenWithClaim(claim UserTokenClaims, expire time.Duration) (string, error) {
  79 + now := time.Now()
  80 + expireTime := now.Add(expire)
  81 + claims := UserTokenClaims{
  82 + UserId: claim.UserId,
  83 + Phone: claim.Phone,
  84 + CompanyId: claim.CompanyId,
  85 + AdminType: claim.AdminType,
41 StandardClaims: jwt.StandardClaims{ 86 StandardClaims: jwt.StandardClaims{
42 ExpiresAt: expireTime.Unix(), 87 ExpiresAt: expireTime.Unix(),
43 Issuer: "jwt", 88 Issuer: "jwt",
@@ -11,4 +11,7 @@ func init() { @@ -11,4 +11,7 @@ func init() {
11 beego.InsertFilter("/*", beego.BeforeExec, middleware.CreateRequestBodyFilter()) 11 beego.InsertFilter("/*", beego.BeforeExec, middleware.CreateRequestBodyFilter())
12 beego.InsertFilter("/*", beego.BeforeExec, middleware.CreateRequstLogFilter(Logger)) 12 beego.InsertFilter("/*", beego.BeforeExec, middleware.CreateRequstLogFilter(Logger))
13 beego.InsertFilter("/*", beego.AfterExec, middleware.CreateResponseLogFilter(Logger), false) 13 beego.InsertFilter("/*", beego.AfterExec, middleware.CreateResponseLogFilter(Logger), false)
  14 +
  15 + beego.InsertFilter("/v1", beego.BeforeExec, middleware.CheckJWTToken)
  16 + beego.InsertFilter("/v2", beego.BeforeExec, middleware.CheckJWTToken)
14 } 17 }
@@ -4,6 +4,7 @@ import ( @@ -4,6 +4,7 @@ import (
4 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/application/auth" 4 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/application/auth"
5 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/log" 5 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/log"
6 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/protocol" 6 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/protocol"
  7 + protocolx "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/protocol/auth"
7 "time" 8 "time"
8 ) 9 )
9 10
@@ -163,3 +164,83 @@ func (this *AuthController) AuthCheckSmsCode() { @@ -163,3 +164,83 @@ func (this *AuthController) AuthCheckSmsCode() {
163 err = CacheSms.Put(request.Phone, rsp.CaptchaCertificate, 5*time.Minute) 164 err = CacheSms.Put(request.Phone, rsp.CaptchaCertificate, 5*time.Minute)
164 msg = protocol.NewReturnResponse(rsp, err) 165 msg = protocol.NewReturnResponse(rsp, err)
165 } 166 }
  167 +
  168 +// CenterCompanys
  169 +// 获取统一用户中心公司(登录凭证)
  170 +func (this *AuthController) CenterCompanys() {
  171 + var msg *protocol.ResponseMessage
  172 + defer func() {
  173 + this.Resp(msg)
  174 + }()
  175 + var request *protocolx.CenterCompanysRequest
  176 + if err := this.JsonUnmarshal(&request); err != nil {
  177 + msg = protocol.BadRequestParam(1)
  178 + return
  179 + }
  180 + if b, m := this.Valid(request); !b {
  181 + msg = m
  182 + return
  183 + }
  184 + header := this.GetRequestHeader(this.Ctx)
  185 + data, err := auth.CenterCompanys(header, request)
  186 + if err != nil {
  187 + log.Error(err)
  188 + }
  189 + msg = protocol.NewReturnResponse(data, err)
  190 +}
  191 +
  192 +// Companys
  193 +// 测试
  194 +func (this *AuthController) Companys() {
  195 + var msg *protocol.ResponseMessage
  196 + defer func() {
  197 + this.Resp(msg)
  198 + }()
  199 + var request *protocolx.CompanysRequest
  200 + if err := this.JsonUnmarshal(&request); err != nil {
  201 + msg = protocol.BadRequestParam(1)
  202 + return
  203 + }
  204 + if b, m := this.Valid(request); !b {
  205 + msg = m
  206 + return
  207 + }
  208 + if request.ClientId != clientId {
  209 + msg = protocol.NewResponseMessage(101, "clientId无效")
  210 + return
  211 + }
  212 + header := this.GetRequestHeader(this.Ctx)
  213 + data, err := auth.Companys(header, request)
  214 + if err != nil {
  215 + log.Error(err)
  216 + }
  217 + msg = protocol.NewReturnResponse(data, err)
  218 +}
  219 +
  220 +// LoginV2
  221 +// @router /loginV2 [post]
  222 +func (this *AuthController) LoginV2() {
  223 + var msg *protocol.ResponseMessage
  224 + defer func() {
  225 + this.Resp(msg)
  226 + }()
  227 + var request *protocol.LoginRequestV2
  228 + if err := this.JsonUnmarshal(&request); err != nil {
  229 + msg = protocol.BadRequestParam(1)
  230 + return
  231 + }
  232 + if b, m := this.Valid(request); !b {
  233 + msg = m
  234 + return
  235 + }
  236 + if request.ClientId != clientId {
  237 + msg = protocol.NewResponseMessage(101, "clientId无效")
  238 + return
  239 + }
  240 + header := this.GetRequestHeader(this.Ctx)
  241 + data, err := auth.LoginV2(header, request)
  242 + if err != nil {
  243 + log.Error(err)
  244 + }
  245 + msg = protocol.NewReturnResponse(data, err)
  246 +}
@@ -7,6 +7,7 @@ import ( @@ -7,6 +7,7 @@ import (
7 "github.com/astaxie/beego/context" 7 "github.com/astaxie/beego/context"
8 "github.com/astaxie/beego/validation" 8 "github.com/astaxie/beego/validation"
9 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/utils" 9 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/utils"
  10 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/log"
10 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/protocol" 11 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/protocol"
11 "strconv" 12 "strconv"
12 ) 13 )
@@ -41,6 +42,7 @@ func (controller *BaseController) Valid(obj interface{}) (result bool, msg *prot @@ -41,6 +42,7 @@ func (controller *BaseController) Valid(obj interface{}) (result bool, msg *prot
41 valid := validation.Validation{} 42 valid := validation.Validation{}
42 result, err = valid.Valid(obj) 43 result, err = valid.Valid(obj)
43 if err != nil { 44 if err != nil {
  45 + log.Error(err)
44 } 46 }
45 if !result { 47 if !result {
46 msg = protocol.BadRequestParam(2) 48 msg = protocol.BadRequestParam(2)
@@ -80,6 +82,9 @@ func (this *BaseController) GetRequestHeader(ctx *context.Context) *protocol.Req @@ -80,6 +82,9 @@ func (this *BaseController) GetRequestHeader(ctx *context.Context) *protocol.Req
80 if len(h.AccessToken) > 0 { 82 if len(h.AccessToken) > 0 {
81 if claim, err := utils.ParseJWTToken(h.AccessToken); err == nil { 83 if claim, err := utils.ParseJWTToken(h.AccessToken); err == nil {
82 h.UserId = claim.UserId 84 h.UserId = claim.UserId
  85 + h.CompanyId = claim.CompanyId
  86 + h.AdminType = claim.AdminType
  87 + h.SimNum, _ = strconv.Atoi(claim.Phone)
83 } 88 }
84 } 89 }
85 return h 90 return h
  1 +package controllers
  2 +
  3 +import (
  4 + "github.com/tiptok/gocomm/pkg/log"
  5 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/application/company"
  6 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/protocol"
  7 + protocolx "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/protocol/company"
  8 +)
  9 +
  10 +type CompanyController struct {
  11 + BaseController
  12 +}
  13 +
  14 +// Property
  15 +// 测试
  16 +func (this *CompanyController) Property() {
  17 + var msg *protocol.ResponseMessage
  18 + defer func() {
  19 + this.Resp(msg)
  20 + }()
  21 + var request *protocolx.PropertyRequest
  22 + if err := this.JsonUnmarshal(&request); err != nil {
  23 + msg = protocol.BadRequestParam(1)
  24 + return
  25 + }
  26 + if b, m := this.Valid(request); !b {
  27 + msg = m
  28 + return
  29 + }
  30 + header := this.GetRequestHeader(this.Ctx)
  31 + data, err := company.Property(header, request)
  32 + if err != nil {
  33 + log.Error(err)
  34 + }
  35 + msg = protocol.NewReturnResponse(data, err)
  36 +}
  37 +
  38 +// Partners
  39 +// 测试
  40 +func (this *CompanyController) Partners() {
  41 + var msg *protocol.ResponseMessage
  42 + defer func() {
  43 + this.Resp(msg)
  44 + }()
  45 + var request *protocolx.PartnersRequest
  46 + if err := this.JsonUnmarshal(&request); err != nil {
  47 + msg = protocol.BadRequestParam(1)
  48 + return
  49 + }
  50 + if b, m := this.Valid(request); !b {
  51 + msg = m
  52 + return
  53 + }
  54 + header := this.GetRequestHeader(this.Ctx)
  55 + data, err := company.Partners(header, request)
  56 + if err != nil {
  57 + log.Error(err)
  58 + }
  59 + msg = protocol.NewReturnResponse(data, err)
  60 +}
  61 +
  62 +// Statistics
  63 +// 测试
  64 +func (this *CompanyController) Statistics() {
  65 + var msg *protocol.ResponseMessage
  66 + defer func() {
  67 + this.Resp(msg)
  68 + }()
  69 + var request *protocolx.StatisticsRequest
  70 + if err := this.JsonUnmarshal(&request); err != nil {
  71 + msg = protocol.BadRequestParam(1)
  72 + return
  73 + }
  74 + if b, m := this.Valid(request); !b {
  75 + msg = m
  76 + return
  77 + }
  78 + header := this.GetRequestHeader(this.Ctx)
  79 + data, err := company.Statistics(header, request)
  80 + if err != nil {
  81 + log.Error(err)
  82 + }
  83 + msg = protocol.NewReturnResponse(data, err)
  84 +}
  1 +package controllers
  2 +
  3 +import (
  4 + "github.com/tiptok/gocomm/pkg/log"
  5 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/application/partner"
  6 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/protocol"
  7 + protocolx "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/protocol/partner"
  8 +)
  9 +
  10 +type PartnerController struct {
  11 + BaseController
  12 +}
  13 +
  14 +// Detail
  15 +// 测试
  16 +func (this *PartnerController) Detail() {
  17 + var msg *protocol.ResponseMessage
  18 + defer func() {
  19 + this.Resp(msg)
  20 + }()
  21 + var request *protocolx.DetailRequest
  22 + if err := this.JsonUnmarshal(&request); err != nil {
  23 + msg = protocol.BadRequestParam(1)
  24 + return
  25 + }
  26 + if b, m := this.Valid(request); !b {
  27 + msg = m
  28 + return
  29 + }
  30 + header := this.GetRequestHeader(this.Ctx)
  31 + data, err := partner.Detail(header, request)
  32 + if err != nil {
  33 + log.Error(err)
  34 + }
  35 + msg = protocol.NewReturnResponse(data, err)
  36 +}
@@ -105,6 +105,15 @@ func (this *UserController) ResetPassword() { @@ -105,6 +105,15 @@ func (this *UserController) ResetPassword() {
105 msg = m 105 msg = m
106 return 106 return
107 } 107 }
  108 + if len(request.NewPwd) < 6 {
  109 + msg = protocol.BadRequestParam(2027)
  110 + return
  111 + }
  112 + if !strings.EqualFold(request.NewPwd, request.ConfirmPwd) {
  113 + msg = protocol.BadRequestParam(2026)
  114 + return
  115 + }
  116 +
108 if !CacheSms.IsExist(request.Phone) { 117 if !CacheSms.IsExist(request.Phone) {
109 msg = protocol.NewMesage(1009) //验证码失效 118 msg = protocol.NewMesage(1009) //验证码失效
110 return 119 return
@@ -118,6 +127,7 @@ func (this *UserController) ResetPassword() { @@ -118,6 +127,7 @@ func (this *UserController) ResetPassword() {
118 msg = protocol.NewMesage(1013) //验证码不一致 127 msg = protocol.NewMesage(1013) //验证码不一致
119 return 128 return
120 } 129 }
  130 +
121 header := this.GetRequestHeader(this.Ctx) 131 header := this.GetRequestHeader(this.Ctx)
122 data, err := user.ResetPassword(header, request) 132 data, err := user.ResetPassword(header, request)
123 if err == nil { 133 if err == nil {
@@ -139,10 +149,24 @@ func (this *UserController) ChangePassword() { @@ -139,10 +149,24 @@ func (this *UserController) ChangePassword() {
139 msg = protocol.BadRequestParam(1) 149 msg = protocol.BadRequestParam(1)
140 return 150 return
141 } 151 }
  152 +
142 if b, m := this.Valid(request); !b { 153 if b, m := this.Valid(request); !b {
143 msg = m 154 msg = m
144 return 155 return
145 } 156 }
  157 + if strings.EqualFold(request.NewPwd, request.OldPwd) {
  158 + msg = protocol.BadRequestParam(2030)
  159 + return
  160 + }
  161 + if len(request.NewPwd) < 6 {
  162 + msg = protocol.BadRequestParam(2027)
  163 + return
  164 + }
  165 + if !strings.EqualFold(request.NewPwd, request.ConfirmPwd) {
  166 + msg = protocol.BadRequestParam(2026)
  167 + return
  168 + }
  169 +
146 header := this.GetRequestHeader(this.Ctx) 170 header := this.GetRequestHeader(this.Ctx)
147 data, err := user.ChangePassword(header, request) 171 data, err := user.ChangePassword(header, request)
148 if err == nil { 172 if err == nil {
@@ -151,3 +175,23 @@ func (this *UserController) ChangePassword() { @@ -151,3 +175,23 @@ func (this *UserController) ChangePassword() {
151 } 175 }
152 msg = protocol.NewReturnResponse(data, err) 176 msg = protocol.NewReturnResponse(data, err)
153 } 177 }
  178 +
  179 +//UserInfo
  180 +//@router /userInfo [post]
  181 +func (this *UserController) UserInfoV2() {
  182 + var msg *protocol.ResponseMessage
  183 + defer func() {
  184 + this.Resp(msg)
  185 + }()
  186 + var request *protocol.UserInfoRequest
  187 + if err := this.JsonUnmarshal(&request); err != nil {
  188 + msg = protocol.BadRequestParam(2)
  189 + return
  190 + }
  191 + if b, m := this.Valid(request); !b {
  192 + msg = m
  193 + return
  194 + }
  195 + header := this.GetRequestHeader(this.Ctx)
  196 + msg = protocol.NewReturnResponse(user.UserInfoV2(header, request))
  197 +}
@@ -16,7 +16,10 @@ func CheckJWTToken(ctx *context.Context) { @@ -16,7 +16,10 @@ func CheckJWTToken(ctx *context.Context) {
16 if strings.HasSuffix(ctx.Request.RequestURI, "login") || 16 if strings.HasSuffix(ctx.Request.RequestURI, "login") ||
17 strings.HasSuffix(ctx.Request.RequestURI, "accessToken") || 17 strings.HasSuffix(ctx.Request.RequestURI, "accessToken") ||
18 strings.HasSuffix(ctx.Request.RequestURI, "refreshToken") || 18 strings.HasSuffix(ctx.Request.RequestURI, "refreshToken") ||
19 - strings.HasSuffix(ctx.Request.RequestURI, "smsCode") { 19 + strings.HasSuffix(ctx.Request.RequestURI, "smsCode") ||
  20 + strings.HasSuffix(ctx.Request.RequestURI, "centerCompanys") ||
  21 + strings.HasSuffix(ctx.Request.RequestURI, "companys") ||
  22 + strings.HasSuffix(ctx.Request.RequestURI, "loginV2") {
20 return 23 return
21 } 24 }
22 defer func() { 25 defer func() {
@@ -3,11 +3,10 @@ package routers @@ -3,11 +3,10 @@ package routers
3 import ( 3 import (
4 "github.com/astaxie/beego" 4 "github.com/astaxie/beego"
5 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/port/appsvr/controllers" 5 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/port/appsvr/controllers"
6 - "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/port/appsvr/middleware"  
7 ) 6 )
8 7
9 func init() { 8 func init() {
10 - nsV1 := beego.NewNamespace("v1", beego.NSBefore(middleware.CheckJWTToken)) //beego.NSNamespace("auth", beego.NSInclude(&controllers.AuthController{})) 9 + nsV1 := beego.NewNamespace("v1") //, beego.NSBefore(middleware.CheckJWTToken)
11 nsV1.Router("/auth/login", &controllers.AuthController{}, "Post:Login") 10 nsV1.Router("/auth/login", &controllers.AuthController{}, "Post:Login")
12 nsV1.Router("/auth/smsCode", &controllers.AuthController{}, "Post:SmsCode") 11 nsV1.Router("/auth/smsCode", &controllers.AuthController{}, "Post:SmsCode")
13 nsV1.Router("/auth/accessToken", &controllers.AuthController{}, "Post:AccessToken") 12 nsV1.Router("/auth/accessToken", &controllers.AuthController{}, "Post:AccessToken")
@@ -15,6 +14,8 @@ func init() { @@ -15,6 +14,8 @@ func init() {
15 nsV1.Router("/auth/revoke", &controllers.AuthController{}, "Post:Revoke") 14 nsV1.Router("/auth/revoke", &controllers.AuthController{}, "Post:Revoke")
16 nsV1.Router("/auth/updateDevice", &controllers.AuthController{}, "Post:UpdateDevice") 15 nsV1.Router("/auth/updateDevice", &controllers.AuthController{}, "Post:UpdateDevice")
17 nsV1.Router("/auth/checkSmsCode", &controllers.AuthController{}, "Post:AuthCheckSmsCode") 16 nsV1.Router("/auth/checkSmsCode", &controllers.AuthController{}, "Post:AuthCheckSmsCode")
  17 + nsV1.Router("/auth/centerCompanys", &controllers.AuthController{}, "post:CenterCompanys")
  18 + nsV1.Router("/auth/companys", &controllers.AuthController{}, "post:Companys")
18 19
19 nsV1.Router("/user/userInfo", &controllers.UserController{}, "Post:UserInfo") 20 nsV1.Router("/user/userInfo", &controllers.UserController{}, "Post:UserInfo")
20 nsV1.Router("/user/checkSmsCode", &controllers.UserController{}, "Post:CheckSmsCode") 21 nsV1.Router("/user/checkSmsCode", &controllers.UserController{}, "Post:CheckSmsCode")
@@ -29,5 +30,20 @@ func init() { @@ -29,5 +30,20 @@ func init() {
29 30
30 nsV1.Router("/dividend/statistics", &controllers.DividendController{}, "Post:DividendStatistics") 31 nsV1.Router("/dividend/statistics", &controllers.DividendController{}, "Post:DividendStatistics")
31 nsV1.Router("/dividend/orders", &controllers.DividendController{}, "Post:DividendOrders") 32 nsV1.Router("/dividend/orders", &controllers.DividendController{}, "Post:DividendOrders")
  33 +
  34 + nsV1.Router("/company/property", &controllers.CompanyController{}, "post:Property")
  35 + nsV1.Router("/company/partners", &controllers.CompanyController{}, "post:Partners")
  36 + nsV1.Router("/company/statistics", &controllers.CompanyController{}, "post:Statistics")
  37 +
  38 + nsV1.Router("/partner/detail", &controllers.PartnerController{}, "post:Detail")
32 beego.AddNamespace(nsV1) 39 beego.AddNamespace(nsV1)
  40 +
  41 + InitV2()
  42 +}
  43 +
  44 +func InitV2() {
  45 + nsV2 := beego.NewNamespace("v2") // ,, beego.NSBefore(middleware.CheckJWTToken)
  46 + nsV2.Router("/auth/login", &controllers.AuthController{}, "Post:LoginV2")
  47 + nsV2.Router("/user/userInfo", &controllers.UserController{}, "Post:UserInfoV2")
  48 + beego.AddNamespace(nsV2)
33 } 49 }
  1 +package controllers
  2 +
  3 +import (
  4 + "github.com/astaxie/beego/validation"
  5 + "github.com/gin-gonic/gin"
  6 + "github.com/tiptok/gocomm/pkg/mygin"
  7 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/utils"
  8 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/protocol"
  9 + "strconv"
  10 +)
  11 +
  12 +type BaseController struct {
  13 + mygin.BaseController
  14 +}
  15 +
  16 +func (this *BaseController) Resp(c *gin.Context, httpCode int, rsp *protocol.ResponseMessage) {
  17 + c.Set("outputData", rsp)
  18 + c.JSON(httpCode, rsp)
  19 + //c.Abort()
  20 +}
  21 +
  22 +func (controller *BaseController) Valid(obj interface{}) (result bool, msg *protocol.ResponseMessage) {
  23 + /*校验*/
  24 + var err error
  25 + valid := validation.Validation{}
  26 + result, err = valid.Valid(obj)
  27 + if err != nil {
  28 + }
  29 + if !result {
  30 + msg = protocol.BadRequestParam(2)
  31 + return
  32 + }
  33 +
  34 + return
  35 +}
  36 +
  37 +//获取请求头信息
  38 +func (this *BaseController) GetRequestHeader(c *gin.Context) *protocol.RequestHeader {
  39 + h := &protocol.RequestHeader{}
  40 +
  41 + h.AccessToken = c.Query("x-mmm-accesstoken")
  42 + h.AppProject = c.Query("x-mmm-appproject")
  43 + h.DeviceType, _ = strconv.Atoi(c.Query("x-mmm-devicetype"))
  44 + h.Sign = c.Query("x-mmm-sign")
  45 + h.Uuid = c.Query("x-mmm-uuid")
  46 + h.TimeStamp = c.Query("x-mmm-timestamp")
  47 + h.Version = c.Query("x-mmm-version")
  48 + h.UserId, _ = strconv.ParseInt(c.Query("x-mmm-id"), 10, 64)
  49 +
  50 + if len(h.AccessToken) > 0 {
  51 + if claim, err := utils.ParseJWTToken(h.AccessToken); err == nil {
  52 + h.UserId = claim.UserId
  53 + }
  54 + }
  55 + return h
  56 +}
  1 +package controllers
  2 +
  3 +import (
  4 + "github.com/gin-gonic/gin"
  5 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/application/order"
  6 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain"
  7 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/protocol"
  8 + "net/http"
  9 + "time"
  10 +)
  11 +
  12 +type OrderController struct {
  13 + BaseController
  14 +}
  15 +
  16 +//OrderStatistics 订单统计
  17 +// @router /statistics [post]
  18 +func (this *OrderController) Statistics(c *gin.Context) {
  19 + var msg *protocol.ResponseMessage
  20 + defer func() {
  21 + this.Resp(c, http.StatusOK, msg)
  22 + }()
  23 + var request *protocol.OrderStatisticsRequest
  24 + if err := c.ShouldBind(&request); err != nil {
  25 + msg = protocol.BadRequestParam(1)
  26 + return
  27 + }
  28 + if b, m := this.Valid(request); !b {
  29 + msg = m
  30 + return
  31 + }
  32 + header := this.GetRequestHeader(c)
  33 + msg = protocol.NewReturnResponse(order.Statistics(header, request))
  34 +}
  35 +
  36 +//OrderDetail 订单详情
  37 +// @router /orderDetail [post]
  38 +func (this *OrderController) OrderDetail(c *gin.Context) {
  39 + var msg *protocol.ResponseMessage
  40 + defer func() {
  41 + this.Resp(c, http.StatusOK, msg)
  42 + }()
  43 + var request *protocol.OrderDetailRequest
  44 + if err := c.ShouldBind(&request); err != nil {
  45 + msg = protocol.BadRequestParam(1)
  46 + return
  47 + }
  48 + if b, m := this.Valid(request); !b {
  49 + msg = m
  50 + return
  51 + }
  52 + header := this.GetRequestHeader(c)
  53 + msg = protocol.NewReturnResponse(order.Detail(header, request))
  54 +}
  55 +
  56 +//OrderList
  57 +func (this *OrderController) OrderList(c *gin.Context) {
  58 + var msg *protocol.ResponseMessage
  59 + defer func() {
  60 + this.Resp(c, http.StatusOK, msg)
  61 + }()
  62 + var request *protocol.OrderListRequest
  63 + if err := c.ShouldBind(&request); err != nil {
  64 + msg = protocol.BadRequestParam(1)
  65 + return
  66 + }
  67 + if b, m := this.Valid(request); !b {
  68 + msg = m
  69 + return
  70 + }
  71 + request.OrderType = domain.OrderReal
  72 + header := this.GetRequestHeader(c)
  73 + msg = protocol.NewReturnResponse(order.List(header, request))
  74 +}
  75 +
  76 +//OrderList
  77 +func (this *OrderController) Intentions(c *gin.Context) {
  78 + var msg *protocol.ResponseMessage
  79 + defer func() {
  80 + this.Resp(c, http.StatusOK, msg)
  81 + }()
  82 + var request *protocol.OrderListRequest
  83 + if err := c.ShouldBind(&request); err != nil {
  84 + msg = protocol.BadRequestParam(1)
  85 + return
  86 + }
  87 + if b, m := this.Valid(request); !b {
  88 + msg = m
  89 + return
  90 + }
  91 + request.EndTime = time.Now().Unix() * 1000
  92 + request.OrderType = domain.OrderIntention
  93 + header := this.GetRequestHeader(c)
  94 + msg = protocol.NewReturnResponse(order.List(header, request))
  95 +}
  1 +package ginsvr
  2 +
  3 +import (
  4 + "github.com/gin-gonic/gin/ginS"
  5 + _ "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/port/ginsvr/routers"
  6 +)
  7 +
  8 +func Run() {
  9 + ginS.Run(":8080")
  10 +}
  1 +package middleware
  2 +
  3 +import (
  4 + "encoding/json"
  5 + "fmt"
  6 + "github.com/gin-gonic/gin"
  7 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/log"
  8 + "io/ioutil"
  9 + "net/http"
  10 + "time"
  11 +)
  12 +
  13 +func CreateRequstLogFilter() gin.HandlerFunc {
  14 + return func(ctx *gin.Context) {
  15 + requestId := fmt.Sprintf("%v.%v", ctx.Request.Method, ctx.Request.RequestURI)
  16 + ctx.Set("requestId", requestId)
  17 + var body string = "{}"
  18 + if _, ok := ctx.Get("requestBody"); ok {
  19 + data, _ := ctx.Get("requestBody")
  20 + body = string(data.([]byte))
  21 + }
  22 + start := time.Now()
  23 + ctx.Next()
  24 + end := time.Now()
  25 + latency := end.Sub(start)
  26 +
  27 + v, _ := ctx.Get("outputData")
  28 + rspBody, _ := json.Marshal(v)
  29 + if len(rspBody) > 500 {
  30 + rspBody = rspBody[:500]
  31 + }
  32 + log.Debug(fmt.Sprintf("====>Recv User:%v | %v | %s | %v | \nAuth=%v \nReqBody:%s \nRspBody:%v", ctx.Query("UserId"), ctx.ClientIP(), requestId, latency, ctx.Query("x-mmm-accesstoken"), body, string(rspBody)))
  33 + }
  34 +}
  35 +
  36 +func CreateResponseLogFilter() func(ctx *gin.Context) {
  37 + return func(ctx *gin.Context) {
  38 + requestId, _ := ctx.Get("requestId")
  39 + v, _ := ctx.Get("outputData")
  40 + body, _ := json.Marshal(v)
  41 + if len(body) > 1000 {
  42 + body = body[:1000]
  43 + }
  44 + log.Debug(fmt.Sprintf("<====Send RequestId:%v BodyData:%s", requestId, body))
  45 + }
  46 +}
  47 +
  48 +func CreateRequestBodyFilter() func(ctx *gin.Context) {
  49 + return func(ctx *gin.Context) {
  50 + if ctx.Request.Method == http.MethodPost || ctx.Request.Method == http.MethodPut {
  51 + body, _ := ioutil.ReadAll(ctx.Request.Body)
  52 + if len(body) == 0 {
  53 + body = []byte("{}")
  54 + }
  55 + ctx.Set("requestBody", body)
  56 + ctx.Request.Body.Close()
  57 + }
  58 + }
  59 +}
  1 +package routers
  2 +
  3 +import (
  4 + "github.com/gin-gonic/gin/ginS"
  5 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/port/ginsvr/controllers"
  6 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/port/ginsvr/middleware"
  7 +)
  8 +
  9 +func init() {
  10 + //ginS.Use(middleware.CreateRequestBodyFilter())
  11 + ginS.Use(middleware.CreateRequstLogFilter())
  12 +
  13 + order := &controllers.OrderController{}
  14 + ginS.POST("/order/statistics", order.Statistics)
  15 + ginS.POST("/order/details", order.OrderDetail)
  16 + ginS.POST("/order/list", order.OrderList)
  17 + ginS.POST("/order/intentions", order.Intentions)
  18 +}
@@ -5,9 +5,9 @@ const ( @@ -5,9 +5,9 @@ const (
5 LoginBySmsCode = "signInCaptcha" 5 LoginBySmsCode = "signInCaptcha"
6 ) 6 )
7 7
8 -const AuthCodeExpire = 60 * 15 8 +const AuthCodeExpire = 60 * 15 //15分钟过期
9 9
10 -const TokenExpire = 60 * 60 * 2 10 +const TokenExpire = 60 * 60 * 2 //两个小时过期
11 const RefreshTokenExipre = 3600 * 24 * 30 * 1 //刷新token 一个月过期 11 const RefreshTokenExipre = 3600 * 24 * 30 * 1 //刷新token 一个月过期
12 12
13 //const TokenExpire = 30 13 //const TokenExpire = 30
@@ -25,6 +25,13 @@ type LoginResponse struct { @@ -25,6 +25,13 @@ type LoginResponse struct {
25 AuthCode string `json:"authCode"` 25 AuthCode string `json:"authCode"`
26 } 26 }
27 27
  28 +type LoginRequestV2 struct {
  29 + Cid int `json:"cid"`
  30 + IdType int `json:"idType"`
  31 + Credentials string `json:"credentials"` // 登录类型 1:密码 2:验证码
  32 + ClientId string `json:"clientId"`
  33 +}
  34 +
28 //JWT用户信息 35 //JWT用户信息
29 type JWTUserInfo struct { 36 type JWTUserInfo struct {
30 UserId string `json:"id"` //用户id 37 UserId string `json:"id"` //用户id
  1 +package auth
  2 +
  3 +import "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/protocol"
  4 +
  5 +type CenterCompanysRequest protocol.LoginRequest
  1 +package auth
  2 +
  3 +type CenterCompanysResponse struct {
  4 + Accid int `json:"accid"` //网易云信ID
  5 + ImToken string `json:"imToken"` //网易云信Token
  6 + CsAccountID string `json:"csAccountID"` //系统分配客服ID
  7 + Credentials string `json:"credentials"` //登录凭证
  8 + Partner interface{} `json:"partner"` //合伙人对象
  9 + Manager interface{} `json:"manager"` //高管对象
  10 +}
  1 +package auth
  2 +
  3 +type CompanysRequest struct {
  4 + // 客户端密钥
  5 + ClientId string `json:"clientId"`
  6 + // 登录凭证
  7 + Credentials string `json:"credentials"`
  8 +}
  1 +package auth
  2 +
  3 +type CompanysResponse struct {
  4 + Partner interface{} `json:"partner"` //合伙人对象
  5 + Manager interface{} `json:"manager"` //高管对象
  6 +}
  1 +package auth
  2 +
  3 +type AdminType int
  4 +
  5 +var (
  6 + AdminTypePartner AdminType = 1
  7 + AdminTypeManager AdminType = 2
  8 +)
  9 +
  10 +var (
  11 + AdminTypePartnerName string = "合伙人"
  12 + AdminTypeManagerName string = "企业高管"
  13 +)
  1 +package company
  2 +
  3 +type PartnersRequest struct {
  4 + // 页码索引(0开始)
  5 + PageIndex int `json:"pageIndex"`
  6 + // 每页数量
  7 + PageSize int `json:"pageSize" valid:"Required"`
  8 + // 起始时间戳
  9 + StartTime int64 `json:"startTime"`
  10 + // 结束时间戳
  11 + EndTime int64 `json:"endTime"`
  12 + // 区域(空或不传,即所有区域)
  13 + Districts []Districts `json:"districts"`
  14 + // 合作类型(空或不传,即所有类型)
  15 + JoinWays []JoinWays `json:"joinWays"`
  16 + // 分红排序(0.从多到少 1.从少到多)
  17 + SortBy int `json:"sortBy"`
  18 +}
  1 +package company
  2 +
  3 +type PartnersResponse struct {
  4 + // 唯一标识
  5 + Partners interface{} `json:"partners"`
  6 +}
  1 +package company
  2 +
  3 +type PropertyRequest struct {
  4 + // 企业属性请求动作(0x1区域、0x2合伙类型)
  5 + Action int `json:"action"`
  6 +}
  1 +package company
  2 +
  3 +type PropertyResponse struct {
  4 + // 唯一标识
  5 + Districts []Districts `json:"districts"`
  6 + JoinWays []JoinWays `json:"joinWays"`
  7 +}
  8 +
  9 +// 区域
  10 +type Districts struct {
  11 + Id int `json:"id"`
  12 + Name string `json:"name"`
  13 +}
  14 +
  15 +// 合作类型
  16 +type JoinWays struct {
  17 + Type int64 `json:"type"`
  18 + Name string `json:"name"`
  19 +}
  1 +package company
  2 +
  3 +type StatisticsRequest struct {
  4 + // 唯一标识
  5 + Id int64 `json:"id"`
  6 +}
  1 +package company
  2 +
  3 +type StatisticsResponse struct {
  4 + // 统计对象
  5 + Statistics interface{} `json:"statistics"`
  6 +}
@@ -54,6 +54,13 @@ type OrderStatics struct { @@ -54,6 +54,13 @@ type OrderStatics struct {
54 TodayRealMoney float64 `json:"todayRealMoney"` //今日新增实发订单金额 54 TodayRealMoney float64 `json:"todayRealMoney"` //今日新增实发订单金额
55 CumulativeQuantity int `json:"cumulativeQuantity"` //累计实发订单 55 CumulativeQuantity int `json:"cumulativeQuantity"` //累计实发订单
56 CumulativeMoney float64 `json:"cumulativeMoney"` //累计实发订单金额 56 CumulativeMoney float64 `json:"cumulativeMoney"` //累计实发订单金额
  57 +
  58 + //v0.3.0 新增加
  59 + CareerPercent float64 `json:"careerPercent"` // 事业占比
  60 + BusinessPercent float64 `json:"businessPercent"` // 业务占比
  61 + DevelopPercent float64 `json:"developPercent"` // 研发占比
  62 + AppPercent float64 `json:"appPercent"` // 研发占比
  63 + BusinessMoney float64 `json:"businessMoney"` // 业务分红累计
57 } 64 }
58 65
59 /*OrderList */ 66 /*OrderList */
  1 +package partner
  2 +
  3 +type DetailRequest struct {
  4 + // 唯一标识
  5 + Uid int64 `json:"uid" valid:"Required"`
  6 +}
  1 +package partner
  2 +
  3 +type DetailResponse struct {
  4 + Partner interface{} `json:"partner"`
  5 +}
  6 +
  7 +type Partner struct {
  8 + //用户名称
  9 + PartnerName string `json:"uname"`
  10 + //合作区域
  11 + District interface{} `json:"district"`
  12 + // 合伙类别 (1.研发合伙人 2.业务合伙人 3.事业)
  13 + JoinWay []interface{} `json:"joinWays"`
  14 + //合作时间
  15 + CooperateTime int64 `json:"cooperationTime"`
  16 +
  17 + CareerOrdersCount int `json:"careerOrdersCount"`
  18 + CareerOrdersMoney float64 `json:"careerOrdersMoney"`
  19 + CareerDividend float64 `json:"careerDividend"`
  20 +
  21 + BusinessOrdersCount int `json:"businessOrdersCount"`
  22 + BusinessOrdersMoney float64 `json:"businessOrdersMoney"`
  23 + BusinessDividend float64 `json:"businessDividend"`
  24 +
  25 + DevelopOrdersCount int `json:"developOrdersCount"`
  26 + DevelopOrdersMoney float64 `json:"developOrdersMoney"`
  27 + DevelopDividend float64 `json:"developDividend"`
  28 +
  29 + ApplicationOrdersCount int `json:"applicationOrdersCount"`
  30 + ApplicationOrdersMoney float64 `json:"applicationOrdersMoney"`
  31 + ApplicationDividend float64 `json:"applicationDividend"`
  32 +}
@@ -9,8 +9,11 @@ type RequestHeader struct { @@ -9,8 +9,11 @@ type RequestHeader struct {
9 AppProject string 9 AppProject string
10 AccessToken string 10 AccessToken string
11 Uid int64 //用户基本信息Id 11 Uid int64 //用户基本信息Id
12 - CompanyId int64  
13 - UserId int64 //UserId 唯一标识,唯一关联所有用户信息(=user_company.id) 12 +
  13 + CompanyId int64 //公司编号
  14 + UserId int64 //UserId 唯一标识,(类型是合伙人对应表partner_info.id,类型是高层对应表users.id)
  15 + AdminType int //合伙人:1 高管:2
  16 + SimNum int
14 17
15 requestId string //请求编号 md5 18 requestId string //请求编号 md5
16 reqIndex int64 //请求链序号 19 reqIndex int64 //请求链序号
  1 +package protocol
  2 +
  3 +type CompanyBase struct {
  4 + Id int64 `json:"id"`
  5 + Name string `json:"name"`
  6 + ShortName string `json:"shortName"`
  7 + Image interface{} `json:"image"`
  8 + Phone string `json:"phone"`
  9 +}
  10 +
  11 +type Image struct {
  12 + Path string `json:"path"`
  13 +}
  14 +
  15 +func NewImage(path string) Image {
  16 + return Image{
  17 + Path: path,
  18 + }
  19 +}