作者 yangfu

Merge remote-tracking branch 'origin/test'

正在显示 76 个修改的文件 包含 3631 行增加520 行删除

要显示太多修改。

为保证性能只显示 76 of 76+ 个文件。

@@ -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,25 @@ spec: @@ -74,6 +74,25 @@ 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
  84 + - name: REDIS_HOST
  85 + valueFrom:
  86 + configMapKeyRef:
  87 + name: suplus-config
  88 + key: redis.ip
  89 + - name: REDIS_PORT
  90 + valueFrom:
  91 + configMapKeyRef:
  92 + name: suplus-config
  93 + key: redis.port
  94 + - name: REDIS_AUTH
  95 + value: ""
77 volumes: 96 volumes:
78 - name: accesslogs 97 - name: accesslogs
79 emptyDir: {} 98 emptyDir: {}
@@ -74,6 +74,25 @@ spec: @@ -74,6 +74,25 @@ 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
  84 + - name: REDIS_HOST
  85 + valueFrom:
  86 + configMapKeyRef:
  87 + name: suplus-config
  88 + key: redis.ip
  89 + - name: REDIS_PORT
  90 + valueFrom:
  91 + configMapKeyRef:
  92 + name: suplus-config
  93 + key: redis.port
  94 + - name: REDIS_AUTH
  95 + value: ""
77 volumes: 96 volumes:
78 - name: accesslogs 97 - name: accesslogs
79 emptyDir: {} 98 emptyDir: {}
@@ -74,6 +74,25 @@ spec: @@ -74,6 +74,25 @@ 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
  84 + - name: REDIS_HOST
  85 + valueFrom:
  86 + configMapKeyRef:
  87 + name: suplus-config
  88 + key: redis.ip
  89 + - name: REDIS_PORT
  90 + valueFrom:
  91 + configMapKeyRef:
  92 + name: suplus-config
  93 + key: redis.port
  94 + - name: REDIS_AUTH
  95 + value: ""
77 volumes: 96 volumes:
78 - name: accesslogs 97 - name: accesslogs
79 emptyDir: {} 98 emptyDir: {}
@@ -5,9 +5,10 @@ go 1.14 @@ -5,9 +5,10 @@ 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
8 github.com/go-pg/pg/v10 v10.0.0-beta.2 9 github.com/go-pg/pg/v10 v10.0.0-beta.2
9 github.com/linmadan/egglib-go v0.0.0-20191217144343-ca4539f95bf9 10 github.com/linmadan/egglib-go v0.0.0-20191217144343-ca4539f95bf9
10 github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644 // indirect 11 github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644 // indirect
11 github.com/shopspring/decimal v1.2.0 12 github.com/shopspring/decimal v1.2.0
12 - github.com/tiptok/gocomm v1.0.0 13 + github.com/tiptok/gocomm v1.0.1
13 ) 14 )
@@ -2,11 +2,13 @@ package main @@ -2,11 +2,13 @@ package main
2 2
3 import ( 3 import (
4 "github.com/astaxie/beego" 4 "github.com/astaxie/beego"
  5 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/application/event"
5 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/constant" 6 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/constant"
6 _ "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/constant" 7 _ "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/constant"
7 _ "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg" 8 _ "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg"
8 _ "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/redis" 9 _ "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/redis"
9 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/log" 10 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/log"
  11 + //"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/port/ginsvr"
10 _ "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/port/appsvr" 12 _ "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/port/appsvr"
11 ) 13 )
12 14
@@ -15,6 +17,11 @@ func main() { @@ -15,6 +17,11 @@ func main() {
15 log.Info("app stop!") 17 log.Info("app stop!")
16 }() 18 }()
17 log.Info("app start!") 19 log.Info("app start!")
18 - log.Info(constant.POSTGRESQL_HOST, constant.POSTGRESQL_DB_NAME) 20 + log.Info(constant.POSTGRESQL_DB_NAME)
  21 + //ginsvr.Run()
  22 +
  23 + //注册事件
  24 + event.InitEventCenter()
  25 +
19 beego.Run() 26 beego.Run()
20 } 27 }
@@ -2,11 +2,19 @@ package auth @@ -2,11 +2,19 @@ package auth
2 2
3 import ( 3 import (
4 "fmt" 4 "fmt"
  5 + "github.com/tiptok/gocomm/xa/eda"
5 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/application/factory" 6 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/application/factory"
  7 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/application/userAuth"
  8 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/constant"
6 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain" 9 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain"
  10 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain/event"
  11 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/domain_service"
  12 + http_gateway "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/svr"
7 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/utils" 13 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/utils"
8 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/log" 14 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/log"
9 "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"
  17 + "strconv"
10 "strings" 18 "strings"
11 "time" 19 "time"
12 ) 20 )
@@ -66,9 +74,15 @@ func Login(header *protocol.RequestHeader, request *protocol.LoginRequest) (rsp @@ -66,9 +74,15 @@ func Login(header *protocol.RequestHeader, request *protocol.LoginRequest) (rsp
66 err = protocol.NewCustomMessage(1, "登录方式不支持!") 74 err = protocol.NewCustomMessage(1, "登录方式不支持!")
67 break 75 break
68 } 76 }
69 - rsp.AuthCode, _ = utils.GenerateToken(partnerInfo.Id, protocol.AuthCodeExpire*time.Second) 77 + userClaim := utils.UserTokenClaims{
  78 + UserId: partnerInfo.Id,
  79 + Phone: partnerInfo.Account,
  80 + AdminType: int(protocolx.AdminTypePartner),
  81 + CompanyId: 1, //默认公司
  82 + }
  83 + rsp.AuthCode, _ = utils.GenerateTokenWithClaim(userClaim, protocol.AuthCodeExpire*time.Second)
70 84
71 - if err = InitOrUpdateUserIMInfo(partnerInfo, transactionContext); err != nil { 85 + if _, err = InitOrUpdateUserIMInfo(partnerInfo.Id, partnerInfo.PartnerName, transactionContext); err != nil {
72 log.Error(err) 86 log.Error(err)
73 return 87 return
74 } 88 }
@@ -105,24 +119,45 @@ func AccessToken(request *protocol.AccessTokenRequest) (rsp *protocol.AccessToke @@ -105,24 +119,45 @@ func AccessToken(request *protocol.AccessTokenRequest) (rsp *protocol.AccessToke
105 err = protocol.NewErrWithMessage(1, fmt.Errorf("jwt authCode (%v) valid", request.AuthCode)) 119 err = protocol.NewErrWithMessage(1, fmt.Errorf("jwt authCode (%v) valid", request.AuthCode))
106 return 120 return
107 } 121 }
108 - rsp.AccessToken, _ = utils.GenerateToken(claim.UserId, protocol.TokenExpire*time.Second)  
109 - rsp.RefreshToken, _ = utils.GenerateToken(claim.UserId, protocol.RefreshTokenExipre*time.Second) 122 + userClaims := utils.UserTokenClaims{
  123 + UserId: claim.UserId,
  124 + CompanyId: claim.CompanyId,
  125 + AdminType: claim.AdminType,
  126 + Phone: claim.Phone,
  127 + }
  128 + rsp.AccessToken, _ = utils.GenerateTokenWithClaim(userClaims, protocol.TokenExpire*time.Second)
  129 + rsp.RefreshToken, _ = utils.GenerateTokenWithClaim(userClaims, protocol.RefreshTokenExipre*time.Second)
110 rsp.ExpiresIn = protocol.TokenExpire 130 rsp.ExpiresIn = protocol.TokenExpire
111 131
112 - //auth := userAuth.NewRedisUserAuth(userAuth.WithUserId(claim.UserId),  
113 - // userAuth.WithAccessToken(rsp.AccessToken),  
114 - // userAuth.WithRefreshToken(rsp.RefreshToken))  
115 - //if err = auth.AddAuth(); err != nil {  
116 - // log.Error(err)  
117 - // return  
118 - //} 132 + eda.Publish(&event.AccessTokenEvent{
  133 + UserPhone: claim.Phone,
  134 + AccessToken: rsp.AccessToken,
  135 + RefreshToken: rsp.RefreshToken,
  136 + })
119 return 137 return
120 } 138 }
121 139
122 func RefreshToken(request *protocol.RefreshTokenRequest) (rsp *protocol.RefreshTokenResponse, err error) { 140 func RefreshToken(request *protocol.RefreshTokenRequest) (rsp *protocol.RefreshTokenResponse, err error) {
123 var ( 141 var (
124 - claim *utils.UserTokenClaims 142 + claim *utils.UserTokenClaims
  143 + transactionContext, _ = factory.CreateTransactionContext(nil)
  144 + PartnerInfoService, _ = factory.CreatePartnerInfoRepositoryIn(transactionContext)
  145 + UsersRepository, _ = factory.CreateUsersRepository(transactionContext)
  146 + CompanyRepository, _ = factory.CreateCompanyRepository(transactionContext)
  147 +
  148 + partnerInfo *domain.PartnerInfo
  149 + user *domain.Users
  150 + company *domain.Company
  151 + userId int64
125 ) 152 )
  153 +
  154 + if err = transactionContext.StartTransaction(); err != nil {
  155 + return nil, err
  156 + }
  157 + defer func() {
  158 + transactionContext.RollbackTransaction()
  159 + }()
  160 +
126 rsp = &protocol.RefreshTokenResponse{} 161 rsp = &protocol.RefreshTokenResponse{}
127 if claim, err = utils.ParseJWTToken(request.RefreshToken); err != nil { 162 if claim, err = utils.ParseJWTToken(request.RefreshToken); err != nil {
128 err = protocol.NewErrWithMessage(4140, err) 163 err = protocol.NewErrWithMessage(4140, err)
@@ -132,23 +167,58 @@ func RefreshToken(request *protocol.RefreshTokenRequest) (rsp *protocol.RefreshT @@ -132,23 +167,58 @@ func RefreshToken(request *protocol.RefreshTokenRequest) (rsp *protocol.RefreshT
132 err = protocol.NewErrWithMessage(1, fmt.Errorf("jwt refrshToken (%v) valid", request.RefreshToken)) 167 err = protocol.NewErrWithMessage(1, fmt.Errorf("jwt refrshToken (%v) valid", request.RefreshToken))
133 return 168 return
134 } 169 }
135 - //oldAuth := userAuth.NewRedisUserAuth(userAuth.WithUserId(claim.UserId))  
136 - //if err = oldAuth.Check(userAuth.NewOptions(userAuth.WithRefreshToken(request.RefreshToken))); err != nil {  
137 - // log.Error(err)  
138 - // err = protocol.NewErrWithMessage(4140, err)  
139 - // return  
140 - //}  
141 - rsp.AccessToken, _ = utils.GenerateToken(claim.UserId, protocol.TokenExpire*time.Second)  
142 - rsp.RefreshToken, _ = utils.GenerateToken(claim.UserId, protocol.RefreshTokenExipre*time.Second) 170 + if company, err = CompanyRepository.FindOne(map[string]interface{}{"id": claim.CompanyId, "status": 1, "enable": 1}); err != nil || company == nil {
  171 + log.Error(err)
  172 + err = protocol.NewErrWithMessage(4140, err)
  173 + return
  174 + }
  175 +
  176 + switch claim.AdminType {
  177 + case int(protocolx.AdminTypePartner):
  178 + if partnerInfo, err = PartnerInfoService.FindOne(map[string]interface{}{"account": claim.Phone, "companyId": claim.CompanyId, "status": 1}); err != nil || partnerInfo == nil {
  179 + log.Error(err)
  180 + err = protocol.NewErrWithMessage(4140, err)
  181 + return
  182 + }
  183 + userId = partnerInfo.Id
  184 + break
  185 + case int(protocolx.AdminTypeManager):
  186 + if user, err = UsersRepository.FindOne(map[string]interface{}{"phone": claim.Phone, "companyId": claim.CompanyId, "status": 1}); err != nil || user == nil {
  187 + log.Error(err)
  188 + err = protocol.NewErrWithMessage(4140, err)
  189 + return
  190 + }
  191 + userId = user.Id
  192 + break
  193 + default:
  194 + err = protocol.NewErrWithMessage(4140, err)
  195 + return
  196 + }
  197 +
  198 + userClaim := utils.UserTokenClaims{
  199 + UserId: userId,
  200 + Phone: claim.Phone,
  201 + AdminType: claim.AdminType,
  202 + CompanyId: claim.CompanyId,
  203 + }
  204 + rsp.AccessToken, _ = utils.GenerateTokenWithClaim(userClaim, protocol.TokenExpire*time.Second)
  205 + rsp.RefreshToken, _ = utils.GenerateTokenWithClaim(userClaim, protocol.RefreshTokenExipre*time.Second)
143 rsp.ExpiresIn = protocol.TokenExpire 206 rsp.ExpiresIn = protocol.TokenExpire
144 207
145 - //newAuth := userAuth.NewRedisUserAuth(userAuth.WithUserId(claim.UserId),  
146 - // userAuth.WithAccessToken(rsp.AccessToken),  
147 - // userAuth.WithRefreshToken(rsp.RefreshToken))  
148 - //if err = newAuth.AddAuth(); err != nil {  
149 - // log.Error(err)  
150 - // return  
151 - //} 208 + if err = eda.Publish(&event.RefreshTokenEvent{
  209 + UserPhone: claim.Phone,
  210 + AccessToken: rsp.AccessToken,
  211 + RefreshToken: rsp.RefreshToken,
  212 + OldRefreshToken: request.RefreshToken,
  213 + OldAccessToken: "",
  214 + }); err != nil {
  215 + log.Error(err)
  216 + rsp.RefreshToken = ""
  217 + rsp.AccessToken = ""
  218 + err = protocol.NewErrWithMessage(4140, err)
  219 + return
  220 + }
  221 + err = transactionContext.CommitTransaction()
152 return 222 return
153 } 223 }
154 224
@@ -192,3 +262,234 @@ func Revoke(header *protocol.RequestHeader, request *protocol.RevokeRequest) (rs @@ -192,3 +262,234 @@ func Revoke(header *protocol.RequestHeader, request *protocol.RevokeRequest) (rs
192 //} 262 //}
193 return 263 return
194 } 264 }
  265 +
  266 +//注销登录
  267 +func UCenterRevoke(header *protocol.RequestHeader, userId int64) (rsp *protocol.RevokeResponse, err error) {
  268 + var (
  269 + transactionContext, _ = factory.CreateTransactionContext(nil)
  270 + UsersRepository, _ = factory.CreateUsersRepository(transactionContext)
  271 + user *domain.Users
  272 + )
  273 +
  274 + rsp = &protocol.RevokeResponse{}
  275 + if err = transactionContext.StartTransaction(); err != nil {
  276 + return nil, err
  277 + }
  278 + defer func() {
  279 + transactionContext.RollbackTransaction()
  280 + }()
  281 +
  282 + if user, err = UsersRepository.FindOne(map[string]interface{}{"openId": userId}); err != nil {
  283 + log.Error(err)
  284 + err = nil
  285 + return
  286 + }
  287 + id, _ := strconv.Atoi(user.Phone)
  288 + auth := userAuth.NewRedisUserAuth(userAuth.WithUserId(int64(id)))
  289 + if !auth.Exist() {
  290 + return
  291 + }
  292 + if err = auth.RemoveAuth(); err != nil {
  293 + log.Error(err)
  294 + return
  295 + }
  296 + err = transactionContext.CommitTransaction()
  297 + return
  298 +}
  299 +
  300 +func CenterCompanys(header *protocol.RequestHeader, request *protocolx.CenterCompanysRequest) (v interface{}, err error) {
  301 + var (
  302 + transactionContext, _ = factory.CreateTransactionContext(nil)
  303 + imInfo *domain.ImInfo
  304 + loginSvr = domain_service.NewPgLoginService(transactionContext)
  305 + )
  306 + phoneId, e := strconv.Atoi(request.Phone)
  307 + if e != nil {
  308 + log.Error(e)
  309 + e = protocol.NewErrWithMessage(2)
  310 + return
  311 + }
  312 + rsp := &protocolx.CenterCompanysResponse{}
  313 + if err = transactionContext.StartTransaction(); err != nil {
  314 + log.Error(err)
  315 + return nil, err
  316 + }
  317 + defer func() {
  318 + transactionContext.RollbackTransaction()
  319 + }()
  320 + loginSvr.Init(request.Phone)
  321 + if len(loginSvr.Users) == 0 && len(loginSvr.PartnerInfo) == 0 {
  322 + err = protocol.NewErrWithMessage(10001)
  323 + return
  324 + }
  325 + switch request.GrantType {
  326 + case protocol.LoginByPassword:
  327 + if len(request.Password) == 0 {
  328 + err = protocol.NewCustomMessage(1, "密码不能为空!")
  329 + return
  330 + }
  331 + if loginSvr.ManagerLogin(request.Phone, request.Password) != nil && loginSvr.PartnerLogin(request.Phone, request.Password) != nil {
  332 + err = protocol.NewCustomMessage(1, "密码输入有误!")
  333 + return
  334 + }
  335 + break
  336 + case protocol.LoginBySmsCode:
  337 + if _, err = CheckSmsCode(request.Phone, request.Captcha); err != nil {
  338 + return
  339 + }
  340 + break
  341 + case protocol.LoginByCredentials:
  342 + if _, err = utils.ParseJWTToken(request.Credentials); err != nil {
  343 + err = protocol.NewErrWithMessage(4140, err)
  344 + return
  345 + }
  346 + default:
  347 + err = protocol.NewCustomMessage(1, "登录方式不支持!")
  348 + break
  349 + }
  350 +
  351 + //获取统计信息
  352 + rsp.Partner, _ = loginSvr.PartnerStaticInfo()
  353 + rsp.Manager, _ = loginSvr.ManagerStaticInfo()
  354 + //没有有效人的时候
  355 + if !loginSvr.AvailableCompany {
  356 + err = protocol.NewErrWithMessage(10008) //账号禁用
  357 + return
  358 + }
  359 +
  360 + var nickName string
  361 + if len(loginSvr.Users) > 0 {
  362 + nickName = loginSvr.Users[0].Name
  363 + } else if len(loginSvr.PartnerInfo) > 0 {
  364 + nickName = loginSvr.PartnerInfo[0].PartnerName
  365 + }
  366 + //初始化im信息
  367 + if imInfo, err = InitOrUpdateUserIMInfo(int64(phoneId), nickName, transactionContext); err != nil {
  368 + log.Error(err)
  369 + return
  370 + }
  371 +
  372 + rsp.CsAccountID = fmt.Sprintf("%v", imInfo.CustomerImId)
  373 + rsp.ImToken = imInfo.ImToken
  374 + rsp.Accid, _ = strconv.Atoi(imInfo.ImId)
  375 + rsp.Phone = request.Phone
  376 + rsp.Credentials, _ = utils.GenerateToken(int64(phoneId), request.Phone, protocol.RefreshTokenExipre*time.Second)
  377 +
  378 + err = transactionContext.CommitTransaction()
  379 + v = map[string]interface{}{"center": rsp}
  380 + return
  381 +}
  382 +
  383 +func Companys(header *protocol.RequestHeader, request *protocolx.CompanysRequest) (rsp *protocolx.CompanysResponse, err error) {
  384 + var (
  385 + transactionContext, _ = factory.CreateTransactionContext(nil)
  386 + loginSvr = domain_service.NewPgLoginService(transactionContext)
  387 + claim *utils.UserTokenClaims
  388 + )
  389 + rsp = &protocolx.CompanysResponse{}
  390 + if err = transactionContext.StartTransaction(); err != nil {
  391 + log.Error(err)
  392 + return nil, err
  393 + }
  394 + defer func() {
  395 + transactionContext.RollbackTransaction()
  396 + }()
  397 + if claim, err = utils.ParseJWTToken(request.Credentials); err != nil {
  398 + err = protocol.NewErrWithMessage(4140, err)
  399 + return
  400 + }
  401 + loginSvr.Init(claim.Phone)
  402 + rsp.Partner, _ = loginSvr.PartnerStaticInfo()
  403 + rsp.Manager, _ = loginSvr.ManagerStaticInfo()
  404 + //没有有效人的时候
  405 + if !loginSvr.AvailableCompany {
  406 + err = protocol.NewErrWithMessage(4140, err) //账号禁用
  407 + return
  408 + }
  409 + err = transactionContext.CommitTransaction()
  410 + return
  411 +}
  412 +
  413 +func LoginV2(header *protocol.RequestHeader, request *protocol.LoginRequestV2) (rsp *protocol.LoginResponse, err error) {
  414 + var (
  415 + claim *utils.UserTokenClaims
  416 + transactionContext, _ = factory.CreateTransactionContext(nil)
  417 + PartnerInfoRepository, _ = factory.CreatePartnerInfoRepositoryIn(transactionContext)
  418 + UsersRepository, _ = factory.CreateUsersRepository(transactionContext)
  419 + CompanyRepository, _ = factory.CreateCompanyRepository(transactionContext)
  420 + userId int64
  421 + adminApiGateway = http_gateway.NewHttplibBusinessAdminApiServiceGateway()
  422 + )
  423 + rsp = &protocol.LoginResponse{}
  424 + if err = transactionContext.StartTransaction(); err != nil {
  425 + return nil, err
  426 + }
  427 + defer func() {
  428 + transactionContext.RollbackTransaction()
  429 + }()
  430 + if claim, err = utils.ParseJWTToken(request.Credentials); err != nil {
  431 + err = protocol.NewErrWithMessage(4140, err)
  432 + return
  433 + }
  434 + if company, e := CompanyRepository.FindOne(map[string]interface{}{"id": request.Cid, "enable": 1}); e != nil || company == nil {
  435 + err = protocol.NewErrWithMessage(10007, err)
  436 + return
  437 + }
  438 + switch request.IdType {
  439 + case int(protocolx.AdminTypePartner):
  440 + if p, e := PartnerInfoRepository.FindOne(map[string]interface{}{"account": claim.Phone, "companyId": request.Cid, "deleteAtIsNull": true}); e == nil {
  441 + userId = p.Id
  442 + if !p.IsEnable() {
  443 + err = protocol.NewErrWithMessage(10006, err) //当前账号已被禁用
  444 + return
  445 + }
  446 + }
  447 + //TODO:验证公司模块权限
  448 + if _, adminUsers, e := UsersRepository.Find(map[string]interface{}{"inCompanyIds": []int64{int64(request.Cid)}, "adminType": 2}); e == nil {
  449 + if len(adminUsers) > 0 {
  450 + au := adminUsers[0]
  451 + if code, e := adminApiGateway.UserAuth(au.Id, constant.BUSINESS_ADMIN_PLATFORM_ID); e != nil || code != 0 {
  452 + log.Debug("【合伙人检查权限】", claim.Phone, "【公司】", request.Cid, au.Id, code, e.Error())
  453 + err = protocol.NewErrWithMessage(10008, err) // 抱歉,企业管理员未帮您开通权限
  454 + return
  455 + }
  456 + }
  457 + }
  458 + break
  459 + case int(protocolx.AdminTypeManager):
  460 + if p, e := UsersRepository.FindOne(map[string]interface{}{"phone": claim.Phone, "companyId": request.Cid, "deleteAtIsNull": true}); e == nil {
  461 + userId = p.Id
  462 + if !p.IsEnable() {
  463 + err = protocol.NewErrWithMessage(10006, err) //当前账号已被禁用
  464 + return
  465 + }
  466 + }
  467 + //校验模块权限
  468 + if userId != 0 {
  469 + if code, e := adminApiGateway.UserAuth(userId, constant.BUSINESS_ADMIN_PLATFORM_ID); e != nil || code != 0 {
  470 + log.Debug("【检查权限】", userId, "【公司】", request.Cid, "【错误】:", code, e.Error())
  471 + err = protocol.NewErrWithMessage(10008, err) // 抱歉,企业管理员未帮您开通权限
  472 + return
  473 + }
  474 + }
  475 + break
  476 + default:
  477 + err = protocol.NewErrWithMessage(2, fmt.Errorf("idType :%v not in range (1,2)", request.IdType)) //用户类型有误
  478 + return
  479 + }
  480 + if userId == 0 {
  481 + err = protocol.NewErrWithMessage(10001, err) //账号不存在
  482 + return
  483 + }
  484 + //根据simnum + cid
  485 + userClaims := utils.UserTokenClaims{
  486 + UserId: userId,
  487 + CompanyId: int64(request.Cid),
  488 + AdminType: request.IdType,
  489 + Phone: claim.Phone,
  490 + }
  491 + rsp.AuthCode, _ = utils.GenerateTokenWithClaim(userClaims, protocol.AuthCodeExpire*time.Second)
  492 +
  493 + err = transactionContext.CommitTransaction()
  494 + return
  495 +}
@@ -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 + Statistics["totalCount"] = len(partnerIds)
  184 + return Statistics, nil
  185 +}
  186 +
  187 +func getPartners(userId int64, request *protocolx.PartnersRequest, transactionContext *transaction.TransactionContext) (interface{}, error) {
  188 + var (
  189 + UsersRepository, _ = factory.CreateUsersRepository(transactionContext)
  190 + PartnerInfo, _ = factory.CreatePartnerInfoDao(transactionContext)
  191 + user *domain.Users
  192 + err error
  193 + PartnerCategoryInfoRepository, _ = factory.CreatePartnerCategoryInfoRepository(transactionContext)
  194 + )
  195 + if user, err = UsersRepository.FindOne(map[string]interface{}{"id": userId}); err != nil {
  196 + return nil, err
  197 + }
  198 + if len(user.AccessPartnerIds()) == 0 {
  199 + return nil, nil
  200 + }
  201 + mapCategoryInfo := make(map[int64]*domain.PartnerCategoryInfo)
  202 + if _, categories, e := PartnerCategoryInfoRepository.Find(nil); e == nil {
  203 + for i := range categories {
  204 + mapCategoryInfo[categories[i].Id] = categories[i]
  205 + }
  206 + }
  207 +
  208 + queryOption := make(map[string]interface{})
  209 +
  210 + if len(request.Districts) > 0 {
  211 + var districts []string
  212 + for i := 0; i < len(request.Districts); i++ {
  213 + districts = append(districts, request.Districts[i].Name)
  214 + }
  215 + queryOption["districts"] = districts
  216 + }
  217 + if len(request.JoinWays) > 0 {
  218 + var joinWays []int64
  219 + for i := 0; i < len(request.JoinWays); i++ {
  220 + joinWays = append(joinWays, request.JoinWays[i].Type)
  221 + }
  222 + queryOption["joinWays"] = joinWays
  223 + }
  224 + if request.StartTime > 0 {
  225 + queryOption["startTime"] = request.StartTime / 1000
  226 + }
  227 + if request.EndTime > 0 {
  228 + queryOption["endTime"] = request.EndTime / 1000
  229 + }
  230 + queryOption["limit"] = request.PageSize
  231 + queryOption["offset"] = request.PageSize * request.PageIndex
  232 +
  233 + queryOption["sortByBonus"] = domain.DESC
  234 + if request.SortBy != 0 {
  235 + queryOption["sortByBonus"] = domain.ASC
  236 + }
  237 +
  238 + if partners, e := PartnerInfo.Partners(user.AccessPartnerIds(), queryOption); e == nil {
  239 + var array []interface{}
  240 + for i := range partners {
  241 + mapPartners := make(map[string]interface{})
  242 + p := partners[i]
  243 + mapPartners["uid"] = p.Id
  244 + mapPartners["uname"] = p.PartnerName
  245 +
  246 + var joinWays []protocolx.JoinWays
  247 + for j := range p.PartnerCategoryInfos {
  248 + c := p.PartnerCategoryInfos[j]
  249 + if v, ok := mapCategoryInfo[c.Id]; ok {
  250 + joinWays = append(joinWays, protocolx.JoinWays{Type: v.Id, Name: v.Name})
  251 + }
  252 + }
  253 + mapPartners["joinWays"] = joinWays
  254 + if p.RegionInfo != nil {
  255 + mapPartners["district"] = protocolx.Districts{Id: p.RegionInfo.RegionId, Name: p.RegionInfo.RegionName}
  256 + }
  257 + mapPartners["cooperationTime"] = p.CooperateTime.Unix() * 1000
  258 + mapPartners["dividend"] = utils.Decimal(p.Bonus)
  259 + mapPartners["ordersCount"] = p.Total
  260 + mapPartners["ordersMoney"] = utils.Decimal(p.Amount)
  261 + array = append(array, mapPartners)
  262 + }
  263 + return array, nil
  264 + }
  265 + return nil, nil
  266 +}
@@ -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,24 @@ func Statistics(header *protocol.RequestHeader, request *protocol.DividendStatis @@ -33,8 +34,24 @@ 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 + bonusAll.Received += bonus.BonusHas
  46 + bonusAll.Outstanding += bonus.BonusNot
  47 + if bonus.UpdateAt.Unix() >= (request.StartTime/1000) && bonus.UpdateAt.Unix() < (request.EndTime/1000) {
  48 + q := quarter(bonus.UpdateAt)
  49 + bonusQuarters[q].Receivable += bonus.Bonus
  50 + bonusQuarters[q].Received += bonus.BonusHas
  51 + bonusQuarters[q].Outstanding += bonus.BonusNot
  52 + }
  53 + }
  54 +
38 rsp = &protocol.DividendStatisticsResponse{} 55 rsp = &protocol.DividendStatisticsResponse{}
39 rsp.Statistics = protocol.DividendStatistics{ 56 rsp.Statistics = protocol.DividendStatistics{
40 Received: bonusAll.Received, 57 Received: bonusAll.Received,
@@ -42,6 +59,7 @@ func Statistics(header *protocol.RequestHeader, request *protocol.DividendStatis @@ -42,6 +59,7 @@ func Statistics(header *protocol.RequestHeader, request *protocol.DividendStatis
42 Receivable: bonusAll.Receivable, 59 Receivable: bonusAll.Receivable,
43 Quarters: bonusQuarters, 60 Quarters: bonusQuarters,
44 } 61 }
  62 +
45 err = transactionContext.CommitTransaction() 63 err = transactionContext.CommitTransaction()
46 return 64 return
47 } 65 }
  1 +package event
  2 +
  3 +import (
  4 + "github.com/tiptok/gocomm/xa/eda"
  5 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/application/event/subscriber"
  6 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain/event"
  7 +)
  8 +
  9 +func InitEventCenter() {
  10 + eda.RegisterSubscribe(&event.AccessTokenEvent{}, &subscriber.AuthCacheSubscribe{})
  11 + eda.RegisterSubscribe(&event.RefreshTokenEvent{}, &subscriber.AuthCacheSubscribe{})
  12 +}
  1 +package subscriber
  2 +
  3 +import (
  4 + "github.com/tiptok/gocomm/xa/eda"
  5 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/application/userAuth"
  6 + devent "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain/event"
  7 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/log"
  8 + "strconv"
  9 +)
  10 +
  11 +type AuthCacheSubscribe struct {
  12 +}
  13 +
  14 +func (s *AuthCacheSubscribe) HandleEvent(event eda.Event) error {
  15 + switch event.EventType() {
  16 + case devent.ACCESS_TOKEN_EVENT:
  17 + e, _ := event.(*devent.AccessTokenEvent)
  18 + return s.addAuth(e.UserPhone, e.AccessToken, e.RefreshToken)
  19 + case devent.REFRESH_TOKEN_EVENT:
  20 + e, _ := event.(*devent.RefreshTokenEvent)
  21 + if err := s.removeAuth(e.UserPhone, e.OldAccessToken, e.OldRefreshToken); err != nil {
  22 + return err
  23 + }
  24 + return s.addAuth(e.UserPhone, e.AccessToken, e.RefreshToken)
  25 + default:
  26 + break
  27 + }
  28 + return nil
  29 +}
  30 +
  31 +func (s *AuthCacheSubscribe) addAuth(phone, accessToken, refreshToken string) error {
  32 + userPhone, _ := strconv.Atoi(phone)
  33 + auth := userAuth.NewRedisUserAuth(userAuth.WithUserId(int64(userPhone)),
  34 + userAuth.WithAccessToken(accessToken),
  35 + userAuth.WithRefreshToken(refreshToken))
  36 + if err := auth.AddAuth(); err != nil {
  37 + log.Error(err)
  38 + return err
  39 + }
  40 + return nil
  41 +}
  42 +
  43 +func (s *AuthCacheSubscribe) removeAuth(phone, accessToken, refreshToken string) error {
  44 + userPhone, _ := strconv.Atoi(phone)
  45 + oldAuth := userAuth.NewRedisUserAuth(userAuth.WithUserId(int64(userPhone)))
  46 + if err := oldAuth.Check(
  47 + userAuth.NewOptions(
  48 + userAuth.WithRefreshToken(refreshToken),
  49 + userAuth.WithAccessToken(accessToken),
  50 + )); err != nil {
  51 + log.Error(err)
  52 + return err
  53 + }
  54 + return nil
  55 +}
@@ -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 +}
1 package order 1 package order
2 2
3 import ( 3 import (
  4 + "github.com/tiptok/gocomm/xtime"
4 "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"
  7 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/utils"
  8 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/log"
5 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/protocol" 9 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/protocol"
  10 + "time"
6 ) 11 )
7 12
8 -func Template(header *protocol.RequestHeader, request *protocol.OrderDetailRequest) (rsp *protocol.OrderDetailResponse, err error) { 13 +// 订单详情
  14 +func Detail(header *protocol.RequestHeader, request *protocol.OrderDetailRequest) (rsp *protocol.OrderDetailResponse, err error) {
9 var ( 15 var (
10 transactionContext, _ = factory.CreateTransactionContext(nil) 16 transactionContext, _ = factory.CreateTransactionContext(nil)
11 - //OrderResponsitory,_ =factory.CreateOrderRepository(transactionContext) 17 + OrderResponsitory, _ = factory.CreateOrderBaseRepository(transactionContext)
  18 + OrderDao, _ = factory.CreateOrderBaseDao(transactionContext)
  19 + order *domain.OrderBase
  20 + )
  21 + if err = transactionContext.StartTransaction(); err != nil {
  22 + return nil, err
  23 + }
  24 + defer func() {
  25 + transactionContext.RollbackTransaction()
  26 + }()
  27 + rsp = &protocol.OrderDetailResponse{}
  28 +
  29 + // 订单详情
  30 + if order, err = OrderResponsitory.FindOne(utils.ObjectJsonToMap(request)); err != nil {
  31 + log.Error(err)
  32 + return
  33 + }
  34 + rsp.Order = protocol.OrderDetail{
  35 + Id: order.Id,
  36 + OrderNo: order.OrderCode,
  37 + DeliveryNo: order.DeliveryCode,
  38 + OrderStatus: orderStatus(order),
  39 + CreateTime: order.CreateTime.Unix() * 1000,
  40 + UpdateTime: order.UpdateTime.Unix() * 1000,
  41 + OrderDistrict: map[string]interface{}{"id": order.RegionInfo.RegionId, "name": order.RegionInfo.RegionName},
  42 + Customer: protocol.Customer{Uname: order.Buyer.BuyerName, Phone: order.Buyer.ContactInfo},
  43 + Products: orderProducts(order),
  44 + Total: orderTotalStatic(order),
  45 + }
  46 +
  47 + // 更新已读(关联事件)
  48 + if header.UserId == order.PartnerId && order.UpdateTime.After(order.LastViewTime) {
  49 + if err = OrderDao.UpdateLastViewTime(order.Id, time.Now()); err != nil {
  50 + return
  51 + }
  52 + }
  53 +
  54 + err = transactionContext.CommitTransaction()
  55 + return
  56 +}
  57 +func orderStatus(order *domain.OrderBase) int {
  58 + var hasBonus = false
  59 + for i := range order.OrderGood {
  60 + good := order.OrderGood[i]
  61 + if good.BonusStatus == domain.BonusPaid {
  62 + hasBonus = true
  63 + break
  64 + }
  65 + }
  66 + if hasBonus {
  67 + if order.UseOrderCount >= 0 && order.UseOrderCount < order.PlanOrderCount {
  68 + return 3 // 已支付退货
  69 + }
  70 + return 2 // 已支付分红
  71 + }
  72 + if !hasBonus {
  73 + if order.UseOrderCount >= 0 && order.UseOrderCount < order.PlanOrderCount {
  74 + return 4 // 待支付退货
  75 + }
  76 + return 1
  77 + }
  78 + return 1
  79 +}
  80 +func orderProducts(order *domain.OrderBase) interface{} {
  81 + var products []map[string]interface{}
  82 + for i := range order.OrderGood {
  83 + good := order.OrderGood[i]
  84 + static := good.OrderBonusStatic()
  85 + item := make(map[string]interface{})
  86 + item["productName"] = good.GoodName
  87 + item["orderCount"] = good.PlanGoodNumber
  88 + item["orderAmount"] = good.PlanAmount
  89 + item["dividendPercent"] = good.PartnerBonusPercent
  90 + item["dividendReceivable"] = static.OrderTotalReceivable() //应收分红
  91 + item["dividendReceived"] = static.OrderBonusReceive() //已收分红
  92 + item["dividendUnReceive"] = static.OrderBonusWait() // 未收分红
  93 + item["dividendExpend"] = static.OrderBonusOutstanding() //分红支出
  94 + if len(good.Remark) > 0 {
  95 + item["orderUpdateReason"] = good.Remark
  96 + }
  97 + item["dividendStatus"] = good.Status()
  98 + if good.Status() > 2 {
  99 + item["countAdjust"] = good.UseGoodNumber
  100 + item["amountAdjust"] = good.UseAmount
  101 + }
  102 + products = append(products, item)
  103 + }
  104 + return products
  105 +}
  106 +func orderTotalStatic(order *domain.OrderBase) interface{} {
  107 + item := make(map[string]interface{})
  108 + static := order.OrderBonusStatic()
  109 + item["totalCount"] = order.PlanOrderCount
  110 + item["totalAmount"] = order.PlanOrderAmount
  111 + item["totalDividendReceivable"] = static.OrderTotalReceivable()
  112 + item["totalReceived"] = static.OrderBonusReceive()
  113 + item["totalUnReceive"] = static.OrderBonusWait()
  114 + item["totalExpend"] = static.OrderBonusOutstanding()
  115 + if order.UseOrderCount > 0 {
  116 + item["totalCountAdjust"] = order.UseOrderCount
  117 + item["totalAmountAdjust"] = order.UseOrderAmount
  118 + }
  119 + return item
  120 +}
12 121
  122 +// 订单统计
  123 +func Statistics(header *protocol.RequestHeader, request *protocol.OrderStatisticsRequest) (rsp *protocol.OrderStatisticsResponse, err error) {
  124 + var (
  125 + transactionContext, _ = factory.CreateTransactionContext(nil)
  126 + OrderDao, _ = factory.CreateOrderBaseDao(transactionContext)
  127 + BusinessBonusRepository, _ = factory.CreateBusinessBonusRepository(transactionContext)
13 ) 128 )
14 if err = transactionContext.StartTransaction(); err != nil { 129 if err = transactionContext.StartTransaction(); err != nil {
15 return nil, err 130 return nil, err
@@ -17,6 +132,122 @@ func Template(header *protocol.RequestHeader, request *protocol.OrderDetailReque @@ -17,6 +132,122 @@ func Template(header *protocol.RequestHeader, request *protocol.OrderDetailReque
17 defer func() { 132 defer func() {
18 transactionContext.RollbackTransaction() 133 transactionContext.RollbackTransaction()
19 }() 134 }()
  135 + rsp = &protocol.OrderStatisticsResponse{Statistics: protocol.OrderStatics{}}
  136 +
  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 +
  156 + //事业分红/业务分红
  157 + var careerBonus, businessBonus, total float64 //,developBonus,appBonus
  158 + if bonus, e := OrderDao.OrderBonusStatics(domain.OrderBonusQuery{PartnerId: header.UserId, OrderType: domain.OrderReal}); e == nil {
  159 + careerBonus = bonus.Bonus
  160 + total += careerBonus
  161 + }
  162 + if bonus, e := BusinessBonusRepository.FindOne(map[string]interface{}{"partner_id": header.UserId, "isDisable": 1}); e == nil {
  163 + businessBonus = bonus.Bonus
  164 + total += businessBonus
  165 + rsp.Statistics.BusinessMoney = bonus.Bonus
  166 + }
  167 + if total != 0 {
  168 + rsp.Statistics.CareerPercent = utils.DecimalToNumber(careerBonus * 100 / total)
  169 + rsp.Statistics.BusinessPercent = utils.DecimalToNumber(businessBonus * 100 / total)
  170 + }
  171 +
20 err = transactionContext.CommitTransaction() 172 err = transactionContext.CommitTransaction()
21 return 173 return
22 } 174 }
  175 +
  176 +// 订单列表
  177 +func List(header *protocol.RequestHeader, request *protocol.OrderListRequest) (rsp *protocol.OrderListResponse, err error) {
  178 + var (
  179 + transactionContext, _ = factory.CreateTransactionContext(nil)
  180 + OrderResponsitory, _ = factory.CreateOrderBaseRepository(transactionContext)
  181 + OrderDao, _ = factory.CreateOrderBaseDao(transactionContext)
  182 + orders []*domain.OrderBase
  183 + total int64
  184 + )
  185 +
  186 + rsp = &protocol.OrderListResponse{
  187 + List: make([]*protocol.OrderListItem, 0),
  188 + }
  189 + if err = transactionContext.StartTransaction(); err != nil {
  190 + return nil, err
  191 + }
  192 + defer func() {
  193 + transactionContext.RollbackTransaction()
  194 + }()
  195 +
  196 + // 查询订单列表
  197 + queryOption := &domain.OrderQueryOption{
  198 + PartnerId: header.UserId,
  199 + Limit: request.PageSize,
  200 + Offset: request.PageSize * request.PageIndex,
  201 + SortByUpdateTime: domain.DESC,
  202 + }
  203 + if request.StartTime > 0 {
  204 + queryOption.BeginTime = time.Unix(request.StartTime/1000, 0)
  205 + }
  206 + if request.EndTime > 0 {
  207 + queryOption.EndTime = time.Unix(request.EndTime/1000, 0)
  208 + }
  209 + queryOption.OrderType = request.OrderType
  210 + total, orders, _ = OrderResponsitory.Find(utils.ObjectJsonToMap(queryOption))
  211 + if len(orders) != 0 {
  212 + for i := range orders {
  213 + rsp.List = append(rsp.List, DomainOrderToOrderListItem(orders[i]))
  214 + }
  215 + }
  216 +
  217 + // 查询统计数据
  218 + if request.PageIndex == 0 {
  219 + var (
  220 + cumulativeQuantity int
  221 + )
  222 + //累计实发订单
  223 + cumulativeQuantity, _, err = OrderDao.OrderStatics(&domain.OrderStaticQuery{
  224 + EndTime: time.Now().Unix() * 1000,
  225 + OrderType: domain.OrderReal,
  226 + PartnerId: header.UserId,
  227 + })
  228 + rsp.Total = cumulativeQuantity
  229 + }
  230 + // 今天累计数量特殊处理,不需要返回所有订单总数(因为要复用rsp.Total字段)
  231 + if request.StartTime > 0 && request.EndTime > 0 {
  232 + zero := time.Time(xtime.XTime(time.Now()).DayBefore(0)).Unix()
  233 + if request.StartTime == (zero * 1000) {
  234 + rsp.Total = int(total)
  235 + }
  236 + }
  237 +
  238 + err = transactionContext.CommitTransaction()
  239 + return
  240 +}
  241 +func DomainOrderToOrderListItem(order *domain.OrderBase) *protocol.OrderListItem {
  242 + bonusStatic := order.OrderBonusStatic()
  243 + return &protocol.OrderListItem{
  244 + Id: order.Id,
  245 + OrderType: order.OrderType,
  246 + OrderNo: order.OrderCode,
  247 + DeliveryNo: order.DeliveryCode,
  248 + OrderAmount: order.PlanOrderAmount,
  249 + UpdateTime: order.UpdateTime.Unix() * 1000,
  250 + MyDividend: bonusStatic.OrderTotalReceivable(),
  251 + IsRead: order.IsRead(),
  252 + }
  253 +}
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,12 @@ import ( @@ -7,8 +7,12 @@ 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"
10 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/log" 13 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/log"
11 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/protocol" 14 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/protocol"
  15 + protocolx "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/protocol/auth"
12 "strconv" 16 "strconv"
13 "strings" 17 "strings"
14 ) 18 )
@@ -20,8 +24,10 @@ func UserInfo(header *protocol.RequestHeader, request *protocol.UserInfoRequest) @@ -20,8 +24,10 @@ func UserInfo(header *protocol.RequestHeader, request *protocol.UserInfoRequest)
20 transactionContext, _ = factory.CreateTransactionContext(nil) 24 transactionContext, _ = factory.CreateTransactionContext(nil)
21 CompanyResponsitory, _ = factory.CreateCompanyRepository(transactionContext) 25 CompanyResponsitory, _ = factory.CreateCompanyRepository(transactionContext)
22 PartnerInfoService, _ = factory.CreatePartnerInfoRepositoryIn(transactionContext) 26 PartnerInfoService, _ = factory.CreatePartnerInfoRepositoryIn(transactionContext)
  27 + UsersRepository, _ = factory.CreateUsersRepository(transactionContext)
23 ImInfoRepository, _ = factory.CreateImInfoRepository(transactionContext) 28 ImInfoRepository, _ = factory.CreateImInfoRepository(transactionContext)
24 company *domain.Company 29 company *domain.Company
  30 + user *domain.Users
25 ) 31 )
26 if err = transactionContext.StartTransaction(); err != nil { 32 if err = transactionContext.StartTransaction(); err != nil {
27 return nil, err 33 return nil, err
@@ -30,33 +36,71 @@ func UserInfo(header *protocol.RequestHeader, request *protocol.UserInfoRequest) @@ -30,33 +36,71 @@ func UserInfo(header *protocol.RequestHeader, request *protocol.UserInfoRequest)
30 transactionContext.RollbackTransaction() 36 transactionContext.RollbackTransaction()
31 }() 37 }()
32 rsp = &protocol.UserInfoResponse{} 38 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 39 +
  40 + funcPartnerInfo := func() {
  41 + if partnerInfo, err = PartnerInfoService.FindOne(map[string]interface{}{"id": header.UserId}); err != nil {
  42 + err = protocol.NewErrWithMessage(502, err) //账号不存在
  43 + return
  44 + }
  45 + if company, err = CompanyResponsitory.FindOne(map[string]interface{}{"id": header.CompanyId}); err != nil {
  46 + return
  47 + }
  48 + rsp.User = protocol.User{
  49 + Id: partnerInfo.Id,
  50 + PartnerName: partnerInfo.PartnerName,
  51 + Phone: partnerInfo.Account,
  52 + CooperateCompany: protocol.Company{
  53 + Id: company.Id,
  54 + Name: company.Name,
  55 + Phone: company.Phone,
  56 + },
  57 + JoinWay: partnerInfo.PartnerCategoryInfo(),
  58 + District: map[string]interface{}{"id": partnerInfo.RegionInfo.RegionId, "name": partnerInfo.RegionInfo.RegionName},
  59 + SerialNo: partnerInfo.Id,
  60 + CooperateTime: partnerInfo.CooperateTime.Unix() * 1000,
  61 + }
  62 + if len(partnerInfo.Salesman) > 0 {
  63 + rsp.User.Salesman = map[string]interface{}{"uname": partnerInfo.Salesman[0].Name, "phone": partnerInfo.Salesman[0].Telephone}
  64 + } else {
  65 + rsp.User.Salesman = map[string]interface{}{}
  66 + }
36 } 67 }
37 - if company, err = CompanyResponsitory.FindOne(map[string]interface{}{"id": 1}); err != nil {  
38 - return 68 + funcManagerInfo := func() {
  69 + if user, err = UsersRepository.FindOne(map[string]interface{}{"id": header.UserId}); err != nil {
  70 + err = protocol.NewErrWithMessage(502, err) //账号不存在
  71 + return
  72 + }
  73 + if company, err = CompanyResponsitory.FindOne(map[string]interface{}{"id": header.CompanyId}); err != nil {
  74 + return
  75 + }
  76 + rsp.User = protocol.User{
  77 + Id: user.Id,
  78 + PartnerName: user.Name,
  79 + Phone: user.Phone,
  80 + CooperateCompany: protocol.Company{
  81 + Id: company.Id,
  82 + Name: company.Name,
  83 + Phone: company.Phone,
  84 + },
  85 + //JoinWay: partnerInfo.PartnerCategoryInfo(),
  86 + //District: map[string]interface{}{"id": partnerInfo.RegionInfo.RegionId, "name": partnerInfo.RegionInfo.RegionName},
  87 + //SerialNo: partnerInfo.Id,
  88 + //CooperateTime: partnerInfo.CooperateTime.Unix() * 1000,
  89 + }
39 } 90 }
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 { 91 + switch header.AdminType {
  92 + case int(protocolx.AdminTypePartner):
  93 + funcPartnerInfo()
  94 + break
  95 + case int(protocolx.AdminTypeManager):
  96 + funcManagerInfo()
  97 + break
  98 + default:
  99 + funcPartnerInfo()
  100 + break
  101 + }
  102 +
  103 + if imInfo, e := ImInfoRepository.FindOne(map[string]interface{}{"user_id": header.SimNum}); e == nil && imInfo != nil {
60 rsp.User.ImToken = imInfo.ImToken 104 rsp.User.ImToken = imInfo.ImToken
61 rsp.User.AccountID, _ = strconv.ParseInt(imInfo.ImId, 10, 64) 105 rsp.User.AccountID, _ = strconv.ParseInt(imInfo.ImId, 10, 64)
62 rsp.User.CsAccountID = fmt.Sprintf("%v", imInfo.CustomerImId) 106 rsp.User.CsAccountID = fmt.Sprintf("%v", imInfo.CustomerImId)
@@ -86,9 +130,7 @@ func CheckSmsCode(header *protocol.RequestHeader, request *protocol.CheckSmsCode @@ -86,9 +130,7 @@ func CheckSmsCode(header *protocol.RequestHeader, request *protocol.CheckSmsCode
86 func ChangePhone(header *protocol.RequestHeader, request *protocol.ChangePhoneRequest) (rsp *protocol.ChangePhoneResponse, err error) { 130 func ChangePhone(header *protocol.RequestHeader, request *protocol.ChangePhoneRequest) (rsp *protocol.ChangePhoneResponse, err error) {
87 var ( 131 var (
88 transactionContext, _ = factory.CreateTransactionContext(nil) 132 transactionContext, _ = factory.CreateTransactionContext(nil)
89 - PartnerInfoDao, _ = factory.CreatePartnerInfoDao(transactionContext)  
90 - PartnerInfoService, _ = factory.CreatePartnerInfoRepositoryIn(transactionContext)  
91 - partnerInfo *domain.PartnerInfo 133 + UserAuthService = CreateUserAuthService(header.AdminType, transactionContext)
92 ) 134 )
93 if err = transactionContext.StartTransaction(); err != nil { 135 if err = transactionContext.StartTransaction(); err != nil {
94 return nil, err 136 return nil, err
@@ -96,23 +138,8 @@ func ChangePhone(header *protocol.RequestHeader, request *protocol.ChangePhoneRe @@ -96,23 +138,8 @@ func ChangePhone(header *protocol.RequestHeader, request *protocol.ChangePhoneRe
96 defer func() { 138 defer func() {
97 transactionContext.RollbackTransaction() 139 transactionContext.RollbackTransaction()
98 }() 140 }()
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 { 141 + if err = UserAuthService.ChangeUserPhone(header.UserId, request.Phone, request.OldPhone); err != nil {
  142 + err = protocol.NewCustomMessage(1, err.Error())
116 return 143 return
117 } 144 }
118 err = transactionContext.CommitTransaction() 145 err = transactionContext.CommitTransaction()
@@ -122,10 +149,8 @@ func ChangePhone(header *protocol.RequestHeader, request *protocol.ChangePhoneRe @@ -122,10 +149,8 @@ func ChangePhone(header *protocol.RequestHeader, request *protocol.ChangePhoneRe
122 //重置密码 149 //重置密码
123 func ResetPassword(header *protocol.RequestHeader, request *protocol.ResetPasswordRequest) (rsp *protocol.ResetPasswordResponse, err error) { 150 func ResetPassword(header *protocol.RequestHeader, request *protocol.ResetPasswordRequest) (rsp *protocol.ResetPasswordResponse, err error) {
124 var ( 151 var (
125 - partnerInfo *domain.PartnerInfo  
126 transactionContext, _ = factory.CreateTransactionContext(nil) 152 transactionContext, _ = factory.CreateTransactionContext(nil)
127 - PartnerInfoDao, _ = factory.CreatePartnerInfoDao(transactionContext)  
128 - PartnerInfoService, _ = factory.CreatePartnerInfoRepositoryIn(transactionContext) 153 + UserAuthService = CreateUserAuthService(header.AdminType, transactionContext)
129 ) 154 )
130 rsp = &protocol.ResetPasswordResponse{} 155 rsp = &protocol.ResetPasswordResponse{}
131 if err = transactionContext.StartTransaction(); err != nil { 156 if err = transactionContext.StartTransaction(); err != nil {
@@ -134,34 +159,10 @@ func ResetPassword(header *protocol.RequestHeader, request *protocol.ResetPasswo @@ -134,34 +159,10 @@ func ResetPassword(header *protocol.RequestHeader, request *protocol.ResetPasswo
134 defer func() { 159 defer func() {
135 transactionContext.RollbackTransaction() 160 transactionContext.RollbackTransaction()
136 }() 161 }()
137 - if len(request.NewPwd) < 6 {  
138 - err = protocol.NewErrWithMessage(2027) 162 + if err = UserAuthService.ResetUserPassword(header.UserId, request.Phone, request.NewPwd); err != nil {
  163 + err = protocol.NewCustomMessage(1, err.Error())
139 return 164 return
140 } 165 }
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) //账号不存在  
147 - return  
148 - }  
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,124 @@ func ChangePassword(header *protocol.RequestHeader, request *protocol.ChangePass @@ -181,43 +180,124 @@ 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, request.Phone); 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) //账号不存在  
198 - return 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"`
199 } 229 }
200 - if !strings.EqualFold(partnerInfo.Password, request.OldPwd) {  
201 - //密码不一致  
202 - err = protocol.NewErrWithMessage(2028, err) //账号不存在  
203 - return 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
204 } 261 }
205 - if err = PartnerInfoDao.Update(map[string]interface{}{  
206 - "Id": partnerInfo.Id,  
207 - "Password": request.ConfirmPwd,  
208 - }); err != nil {  
209 - return 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
210 } 292 }
211 - //清除auth token  
212 - //auth := userAuth.NewRedisUserAuth(userAuth.WithUserId(header.UserId))  
213 - //if !auth.Exist() {  
214 - // return  
215 - //}  
216 - //if err = auth.RemoveAuth(); err != nil {  
217 - // log.Error(err)  
218 - // err = protocol.NewErrWithMessage(4140, err)  
219 - // return  
220 - //}  
221 err = transactionContext.CommitTransaction() 293 err = transactionContext.CommitTransaction()
222 return 294 return
223 } 295 }
  296 +
  297 +func CreateUserAuthService(adminType int, transactionContext *transaction.TransactionContext) domain_service_i.UserAuthService {
  298 + return domain_service.NewPgAuthService(transactionContext)
  299 + //if adminType == int(protocolx.AdminTypeManager) {
  300 + // return domain_service.NewPgManagerAuthService(transactionContext)
  301 + //}
  302 + //return domain_service.NewPgPartnerAuthService(transactionContext)
  303 +}
@@ -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
@@ -9,6 +9,7 @@ var REDIS_AUTH = "123456" @@ -9,6 +9,7 @@ var REDIS_AUTH = "123456"
9 func init() { 9 func init() {
10 if os.Getenv("REDIS_HOST") != "" { 10 if os.Getenv("REDIS_HOST") != "" {
11 REDIS_HOST = os.Getenv("REDIS_HOST") 11 REDIS_HOST = os.Getenv("REDIS_HOST")
  12 + REDIS_AUTH = os.Getenv("REDIS_AUTH")
12 } 13 }
13 if os.Getenv("REDIS_PORT") != "" { 14 if os.Getenv("REDIS_PORT") != "" {
14 REDIS_PORT = os.Getenv("REDIS_PORT") 15 REDIS_PORT = os.Getenv("REDIS_PORT")
  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 +}
  1 +package event
  2 +
  3 +const ACCESS_TOKEN_EVENT = "access_token_event"
  4 +
  5 +type AccessTokenEvent struct {
  6 + UserPhone string
  7 + AccessToken string
  8 + RefreshToken string
  9 +}
  10 +
  11 +func (event *AccessTokenEvent) EventType() string {
  12 + return ACCESS_TOKEN_EVENT
  13 +}
  1 +package event
  2 +
  3 +const REFRESH_TOKEN_EVENT = "refresh_token_event"
  4 +
  5 +type RefreshTokenEvent struct {
  6 + UserPhone string
  7 + AccessToken string
  8 + RefreshToken string
  9 +
  10 + OldAccessToken string
  11 + OldRefreshToken string
  12 +}
  13 +
  14 +func (event *RefreshTokenEvent) EventType() string {
  15 + return REFRESH_TOKEN_EVENT
  16 +}
@@ -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 +//账号是否有效
  70 +func (m *Users) IsEnable() bool {
  71 + return m.Status == 1
  72 +}
  73 +
  74 +func (m *Users) Identify() interface{} {
  75 + if m.Id == 0 {
  76 + return nil
  77 + }
  78 + return m.Id
  79 +}
  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 {
@@ -18,13 +22,117 @@ func (dao *PartnerInfoDao) Update(queryOptions map[string]interface{}) error { @@ -18,13 +22,117 @@ func (dao *PartnerInfoDao) Update(queryOptions map[string]interface{}) error {
18 query.SetUpdate(`account=?`, "Account") 22 query.SetUpdate(`account=?`, "Account")
19 query.SetUpdate(`password=?`, "Password") 23 query.SetUpdate(`password=?`, "Password")
20 query.SetWhere(`id=?`, "Id") 24 query.SetWhere(`id=?`, "Id")
  25 + query.SetWhere(`account=?`, "oldAccount")
21 if _, ok := queryOptions["Id"]; !ok { 26 if _, ok := queryOptions["Id"]; !ok {
22 - return fmt.Errorf(`error: miss param "Id"`) 27 + if _, ok := queryOptions["oldAccount"]; !ok {
  28 + return fmt.Errorf(`error: miss param "Id"`)
  29 + }
23 } 30 }
24 _, err := query.Update() 31 _, err := query.Update()
25 return err 32 return err
26 } 33 }
27 34
  35 +func (dao *PartnerInfoDao) PartnerStatic(queryOptions map[string]interface{}) (count int, err error) {
  36 + tx := dao.transactionContext.PgTx
  37 + m := new(models.PartnerInfo)
  38 + query := NewQuery(tx.Model(m), queryOptions)
  39 +
  40 + query.ColumnExpr("count(*) count")
  41 + if inPartnerIds, ok := queryOptions["inPartnerIds"]; ok {
  42 + query.Where("id in (?)", pg.In(inPartnerIds.([]int64)))
  43 + }
  44 + if inPartnerCategory, ok := queryOptions["inPartnerCategory"]; ok {
  45 + query.Where(`partner_info.partner_category_infos @>'[{"id":?}]'`, inPartnerCategory)
  46 + }
  47 + // 多个合伙人类型
  48 + if inPartnerCategory, ok := queryOptions["inPartnerCategories"]; ok {
  49 + query.Query = query.WhereGroup(func(q *orm.Query) (*orm.Query, error) {
  50 + if arrayInPartnerCategory, ok := inPartnerCategory.([]int64); ok {
  51 + for i := range arrayInPartnerCategory {
  52 + q.WhereOr(`partner_info.partner_category_infos @>'[{"id":?}]')`, arrayInPartnerCategory[i])
  53 + }
  54 + }
  55 + return q, nil
  56 + })
  57 + }
  58 + err = query.Select(&count)
  59 + return
  60 +}
  61 +
  62 +func (dao *PartnerInfoDao) Partners(partnerIds []int64, queryOptions map[string]interface{}) (statics []*domain.PartnerStatics, err error) {
  63 + tx := dao.transactionContext.PgDd
  64 + var sql = strings.Builder{}
  65 + var filterPartners = strings.Builder{}
  66 +
  67 + if districts, ok := queryOptions["districts"]; ok {
  68 + districts, ok := districts.([]string)
  69 + if ok && len(districts) > 0 {
  70 + var filterDistricts = strings.Builder{}
  71 + for i := range districts {
  72 + filterDistricts.WriteString(fmt.Sprintf(` region_info @>'{"regionName":"%v"}'`, districts[i]))
  73 + if i != (len(districts) - 1) {
  74 + filterDistricts.WriteString(" or ")
  75 + }
  76 + }
  77 + filterPartners.WriteString(fmt.Sprintf(" and (%v)", filterDistricts.String()))
  78 + }
  79 + }
  80 + if joinWays, ok := queryOptions["joinWays"]; ok {
  81 + joinWays, ok := joinWays.([]int64)
  82 + if ok && len(joinWays) > 0 {
  83 + var filterJoinWays = strings.Builder{}
  84 + for i := range joinWays {
  85 + filterJoinWays.WriteString(fmt.Sprintf(` partner_category_infos @>'[{"id":%v}]'`, joinWays[i]))
  86 + if i != (len(joinWays) - 1) {
  87 + filterJoinWays.WriteString(" or ")
  88 + }
  89 + }
  90 + filterPartners.WriteString(fmt.Sprintf(" and (%v)", filterJoinWays.String()))
  91 + }
  92 + }
  93 + if startTime, ok := queryOptions["startTime"]; ok {
  94 + filterPartners.WriteString(fmt.Sprintf(" and cooperate_time>=to_timestamp(%v)", startTime))
  95 + }
  96 + if endTime, ok := queryOptions["endTime"]; ok {
  97 + filterPartners.WriteString(fmt.Sprintf(" and cooperate_time<to_timestamp(%v)", endTime))
  98 + }
  99 +
  100 + sql.WriteString(fmt.Sprintf(`
  101 +SELECT A.*,B.total,B.amount,COALESCE(B.bonus,0) bonus,B.bonus_expense
  102 +FROM
  103 +(
  104 + SELECT * FROM partner_info
  105 + WHERE (id in (?)) %v
  106 +)
  107 +A left join
  108 +(
  109 + SELECT partner_id,count(*) total,sum(amount) amount,sum(bonus) bonus,sum(bonus_expense) bonus_expense FROM
  110 + (
  111 + SELECT partner_id,
  112 + plan_order_amount amount,
  113 + (case when use_order_count>=0 then use_partner_bonus else plan_partner_bonus end) bonus,
  114 + partner_bonus_expense bonus_expense FROM "order_base" AS "order_base"
  115 + WHERE (partner_id in (?)) and order_type =1
  116 + UNION ALL
  117 + SELECT partner_info_id partner_id,
  118 + 0 amount, bonus bonus, bonus_expense bonus_expense FROM business_bonus
  119 + WHERE (partner_info_id in (?)) and is_disable=1
  120 + ) B
  121 +GROUP BY partner_id
  122 +) B on A."id" = B.partner_id`, filterPartners.String()))
  123 + if sortByBonus, ok := queryOptions["sortByBonus"]; ok {
  124 + sql.WriteString(fmt.Sprintf(" \norder by bonus %v", sortByBonus))
  125 + }
  126 + if limit, ok := queryOptions["limit"]; ok {
  127 + sql.WriteString(fmt.Sprintf(" \nLIMIT %v", limit))
  128 + if offset, ok := queryOptions["offset"]; ok {
  129 + sql.WriteString(fmt.Sprintf(" \nOFFSET %v", offset))
  130 + }
  131 + }
  132 + _, err = tx.Query(&statics, sql.String(), pg.In(partnerIds), pg.In(partnerIds), pg.In(partnerIds))
  133 + return
  134 +}
  135 +
28 func NewPartnerInfoDao(transactionContext *transaction.TransactionContext) (*PartnerInfoDao, error) { 136 func NewPartnerInfoDao(transactionContext *transaction.TransactionContext) (*PartnerInfoDao, error) {
29 if transactionContext == nil { 137 if transactionContext == nil {
30 return nil, fmt.Errorf("transactionContext参数不能为nil") 138 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/infrastructure/pg/transaction"
  6 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/log"
  7 +)
  8 +
  9 +type PgAuthService struct {
  10 + eda.EventCenterPublisher
  11 + //transactionContext *transaction.TransactionContext
  12 + manager *PgManagerAuthService
  13 + partner *PgPartnerAuthService
  14 +}
  15 +
  16 +func NewPgAuthService(ctx *transaction.TransactionContext) *PgAuthService {
  17 + return &PgAuthService{
  18 + manager: NewPgManagerAuthService(ctx),
  19 + partner: NewPgPartnerAuthService(ctx),
  20 + }
  21 +}
  22 +
  23 +func (s *PgAuthService) ChangeUserPhone(userId int64, newPhone, oldPhone string) (err error) {
  24 + errPartner := s.partner.ChangeUserPhone(userId, newPhone, oldPhone)
  25 + errManager := s.manager.ChangeUserPhone(userId, newPhone, oldPhone)
  26 + return errResolve(errPartner, errManager)
  27 +}
  28 +func (s *PgAuthService) ChangeUserPassword(userId int64, newPwd, oldPwd, phone string) (err error) {
  29 + errPartner := s.partner.ChangeUserPassword(userId, newPwd, oldPwd, phone)
  30 + errManager := s.manager.ChangeUserPassword(userId, newPwd, oldPwd, phone)
  31 + return errResolve(errPartner, errManager)
  32 +}
  33 +func (s *PgAuthService) ResetUserPassword(userId int64, phone, password string) (err error) {
  34 + errPartner := s.partner.ResetUserPassword(userId, phone, password)
  35 + errManager := s.manager.ResetUserPassword(userId, phone, password)
  36 + return errResolve(errPartner, errManager)
  37 +}
  38 +
  39 +func errResolve(errPartner, errManager error) (err error) {
  40 + if errPartner != nil {
  41 + log.Error("partner:", errPartner)
  42 + }
  43 + if errManager != nil {
  44 + log.Error("mannager:", errManager)
  45 + }
  46 + if errPartner != nil && errManager != nil {
  47 + err = errPartner
  48 + if err == errUserNotFound && errManager != errUserNotFound {
  49 + err = errManager
  50 + }
  51 + return
  52 + }
  53 + return
  54 +}
  1 +package domain_service
  2 +
  3 +import (
  4 + "github.com/tiptok/gocomm/xa/eda"
  5 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/constant"
  6 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain"
  7 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/dao"
  8 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg/transaction"
  9 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/repository"
  10 + http_gateway "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/svr"
  11 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/utils"
  12 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/log"
  13 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/protocol"
  14 + protocolx "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/protocol/auth"
  15 + "strings"
  16 +)
  17 +
  18 +type PgLoginService struct {
  19 + Phone string
  20 + eda.EventCenterPublisher
  21 + PartnerInfo []*domain.PartnerInfo
  22 + Users []*domain.Users
  23 + transactionContext *transaction.TransactionContext
  24 + AvailableCompany bool
  25 +}
  26 +
  27 +func (svr *PgLoginService) Init(phone string) (err error) {
  28 + var (
  29 + PartnerInfoService, _ = repository.NewPartnerInfoRepository(svr.transactionContext)
  30 + UsersRepository, _ = repository.NewUsersRepository(svr.transactionContext)
  31 + )
  32 + svr.Phone = phone
  33 + _, svr.PartnerInfo, err = PartnerInfoService.Find(map[string]interface{}{"account": phone, "status": 1, "sortByCreateTime": "ASC"})
  34 + _, svr.Users, err = UsersRepository.Find(map[string]interface{}{"phone": phone, "status": 1, "sortByCreateTime": "ASC", "deleteAtIsNull": true})
  35 + return nil
  36 +}
  37 +
  38 +//合伙人登录
  39 +func (svr *PgLoginService) PartnerLogin(phone string, password string) (err error) {
  40 + if len(svr.PartnerInfo) == 0 {
  41 + //子账号
  42 + err = protocol.NewErrWithMessage(502, err) //账号不存在
  43 + return
  44 + }
  45 + if !strings.EqualFold(svr.PartnerInfo[0].Password, password) {
  46 + err = protocol.NewCustomMessage(1, "密码输入有误!")
  47 + return
  48 + }
  49 + return
  50 +}
  51 +
  52 +//管理层登录
  53 +func (svr *PgLoginService) ManagerLogin(phone string, password string) (err error) {
  54 + if len(svr.Users) == 0 {
  55 + //子账号
  56 + err = protocol.NewErrWithMessage(502, err) //账号不存在
  57 + return
  58 + }
  59 + var openid int64
  60 + ucenerSvr := http_gateway.NewHttplibUCenterApiServiceGateway()
  61 + openid, err = ucenerSvr.ServerLogin(phone, password, 1)
  62 + if err == nil && openid > 0 {
  63 + _, err = svr.transactionContext.PgTx.Exec("update users set open_id=? where phone=?", openid, phone)
  64 + }
  65 + return
  66 +}
  67 +
  68 +//合伙人统计信息
  69 +func (svr *PgLoginService) PartnerStaticInfo() (interface{}, error) {
  70 + response := make(map[string]interface{})
  71 + response["id"] = protocolx.AdminTypePartner
  72 + response["name"] = protocolx.AdminTypePartnerName
  73 + if len(svr.PartnerInfo) == 0 {
  74 + response["companys"] = make([]struct{}, 0)
  75 + return response, nil
  76 + }
  77 + var (
  78 + OrderDao, _ = dao.NewOrderBaseDao(svr.transactionContext)
  79 + BusinessBonusDao, _ = dao.NewBusinessBonusDao(svr.transactionContext)
  80 + PartnerCategoryInfoRepository, _ = repository.NewPartnerCategoryInfoRepository(svr.transactionContext)
  81 + companyList []*domain.Company
  82 + allPartnerCategory []*domain.PartnerCategoryInfo
  83 + BusinessBonusRepository, _ = repository.NewBusinessBonusRepository(svr.transactionContext)
  84 + UsersRepository, _ = repository.NewUsersRepository(svr.transactionContext)
  85 + adminApiGateway = http_gateway.NewHttplibBusinessAdminApiServiceGateway()
  86 + )
  87 + doGetCompanyIds := func() []int64 {
  88 + var companies []int64
  89 + for i := range svr.PartnerInfo {
  90 + companies = append(companies, svr.PartnerInfo[i].CompanyId)
  91 + }
  92 + return companies
  93 + }
  94 + doGetPartnerIds := func() []int64 {
  95 + var array []int64
  96 + for i := range svr.PartnerInfo {
  97 + array = append(array, svr.PartnerInfo[i].Id)
  98 + }
  99 + return array
  100 + }
  101 + companyList = svr.GetCompanyList(doGetCompanyIds)
  102 + if len(companyList) == 0 {
  103 + return response, nil
  104 + }
  105 + totalBonus, e := OrderDao.OrderBonusStatics(domain.OrderBonusQuery{InPartnerIds: doGetPartnerIds(), OrderType: domain.OrderReal})
  106 + if e != nil {
  107 + return response, e
  108 + }
  109 + if businessBonus, e := BusinessBonusDao.OrderBonusStatics(domain.OrderBonusQuery{InPartnerIds: doGetPartnerIds(), IsDisable: 1}); e == nil {
  110 + totalBonus.Bonus += businessBonus.Bonus
  111 + }
  112 + _, allPartnerCategory, e = PartnerCategoryInfoRepository.Find(map[string]interface{}{"sortById": domain.ASC})
  113 + var mapPartnerBussinessBonus = make(map[int64]*domain.BusinessBonus)
  114 + if _, bussinessBonus, e := BusinessBonusRepository.Find(map[string]interface{}{"inPartnerIds": doGetPartnerIds(), "isDisable": 1}); e == nil {
  115 + for _, v := range bussinessBonus {
  116 + mapPartnerBussinessBonus[v.PartnerInfoId] = v
  117 + }
  118 + }
  119 + if e != nil {
  120 + log.Error(e)
  121 + return response, e
  122 + }
  123 + var mapCompanyAdminUsers map[int64]*domain.Users = make(map[int64]*domain.Users) //key:company_id value:domain.users
  124 + if _, adminUsers, e := UsersRepository.Find(map[string]interface{}{"inCompanyIds": doGetCompanyIds(), "adminType": 2}); e == nil {
  125 + for i := range adminUsers {
  126 + mapCompanyAdminUsers[adminUsers[i].CompanyId] = adminUsers[i]
  127 + }
  128 + }
  129 + var companys = make([]*Company, 0)
  130 + for i := range companyList {
  131 + c := companyList[i]
  132 + var partner *domain.PartnerInfo
  133 + for j := range svr.PartnerInfo {
  134 + if svr.PartnerInfo[j].CompanyId == c.Id {
  135 + partner = svr.PartnerInfo[j]
  136 + break
  137 + }
  138 + }
  139 + if partner == nil {
  140 + continue
  141 + }
  142 + if au, ok := mapCompanyAdminUsers[partner.CompanyId]; ok {
  143 + if code, e := adminApiGateway.UserAuth(au.Id, constant.BUSINESS_ADMIN_PLATFORM_ID); e != nil || code != 0 {
  144 + log.Debug("【合伙人检查权限】", svr.Phone, "【公司】", c.Id, au.Id, code, e.Error())
  145 + continue
  146 + } else {
  147 + log.Debug("【合伙人检查权限】", svr.Phone, "【公司】", c.Id, au.Id, code, e)
  148 + }
  149 + } else {
  150 + log.Debug("【合伙人检查权限】", svr.Phone, "【公司】", c.Id, partner.Id, "公司管理员不存在")
  151 + continue
  152 + }
  153 +
  154 + bonus, _ := OrderDao.OrderBonusStatics(domain.OrderBonusQuery{PartnerId: partner.Id, OrderType: domain.OrderReal})
  155 + if v, ok := mapPartnerBussinessBonus[partner.Id]; ok {
  156 + bonus.Bonus += v.Bonus
  157 + }
  158 + item := &Company{
  159 + CompanyBase: newCompanyBase(c),
  160 + IncomePercent: computeBonusPercent(totalBonus.Bonus, bonus.Bonus*100),
  161 + DividendMoney: utils.Decimal(bonus.Bonus),
  162 + JoinWays: svr.GetJoinWays(allPartnerCategory, partner, bonus.Bonus),
  163 + }
  164 + companys = append(companys, item)
  165 + }
  166 + if len(companys) > 0 {
  167 + svr.AvailableCompany = true
  168 + }
  169 +
  170 + response["companys"] = companys
  171 + return response, nil
  172 +}
  173 +func (svr *PgLoginService) ManagerStaticInfo() (interface{}, error) {
  174 + response := make(map[string]interface{})
  175 + response["id"] = protocolx.AdminTypeManager
  176 + response["name"] = protocolx.AdminTypeManagerName
  177 + if len(svr.Users) == 0 {
  178 + response["companys"] = make([]struct{}, 0)
  179 + return response, nil
  180 + }
  181 + var (
  182 + companyList []*domain.Company
  183 + adminApiGateway = http_gateway.NewHttplibBusinessAdminApiServiceGateway()
  184 + )
  185 + doGetCompanyIds := func() []int64 {
  186 + var companies []int64
  187 + for i := range svr.Users {
  188 + companies = append(companies, svr.Users[i].CompanyId)
  189 + }
  190 + return companies
  191 + }
  192 + companyList = svr.GetCompanyList(doGetCompanyIds)
  193 + var companys = make([]protocol.CompanyBase, 0)
  194 + for i := range companyList {
  195 + c := companyList[i]
  196 +
  197 + if constant.POSTGRESQL_DB_NAME != "partner_dev1" {
  198 + //通过企业平台 校验模块权限
  199 + var user *domain.Users
  200 + for j := range svr.Users {
  201 + if svr.Users[j].CompanyId == c.Id {
  202 + user = svr.Users[j]
  203 + break
  204 + }
  205 + }
  206 + if user != nil {
  207 + if code, e := adminApiGateway.UserAuth(user.Id, constant.BUSINESS_ADMIN_PLATFORM_ID); e != nil || code != 0 {
  208 + log.Debug("【检查权限】", svr.Phone, "【公司】", c.Id, user.Id, code, e.Error())
  209 + continue
  210 + } else {
  211 + log.Debug("【检查权限】", svr.Phone, "【公司】", c.Id, user.Id, code, e)
  212 + }
  213 + }
  214 + }
  215 + item := newCompanyBase(c)
  216 + companys = append(companys, item)
  217 + }
  218 + if len(companys) > 0 {
  219 + svr.AvailableCompany = true
  220 + }
  221 +
  222 + response["companys"] = companys
  223 + return response, nil
  224 +}
  225 +func (svr *PgLoginService) GetCompanyList(funcGetCompanyIds func() []int64) []*domain.Company {
  226 + var (
  227 + CompanyRepository, _ = repository.NewCompanyRepository(svr.transactionContext)
  228 + companyList []*domain.Company
  229 + )
  230 + var companies []int64 = funcGetCompanyIds()
  231 + if len(companies) == 0 {
  232 + return companyList
  233 + }
  234 + if _, v, e := CompanyRepository.Find(map[string]interface{}{"inCompanyIds": companies, "enable": 1, "sortByCreateTime": domain.DESC}); e != nil {
  235 + log.Error(e)
  236 + return companyList
  237 + } else {
  238 + companyList = v
  239 + }
  240 + return companyList
  241 +}
  242 +func (svr *PgLoginService) GetJoinWays(partnerCategory []*domain.PartnerCategoryInfo, partnerInfo *domain.PartnerInfo, bonus float64) []joinWay {
  243 + searchCategory := func(partnerCategory []*domain.PartnerCategoryInfo, id int64) *domain.PartnerCategoryInfo {
  244 + for i := range partnerCategory {
  245 + if partnerCategory[i].Id == id {
  246 + return partnerCategory[i]
  247 + }
  248 + }
  249 + return nil
  250 + }
  251 + var joinWays []joinWay
  252 + for i := range partnerCategory {
  253 + c := partnerCategory[i]
  254 + searchC := searchCategory(partnerInfo.PartnerCategoryInfos, c.Id)
  255 + if searchC != nil {
  256 + item := joinWay{
  257 + Type: int(c.Id),
  258 + Name: c.Name,
  259 + }
  260 + joinWays = append(joinWays, item)
  261 + }
  262 + }
  263 +
  264 + for i := range joinWays {
  265 + joinWays[i].Percent = computeBonusPercent(float64(len(joinWays)), 1) * 100
  266 + }
  267 + return joinWays
  268 +}
  269 +func newCompanyBase(company *domain.Company) protocol.CompanyBase {
  270 + return protocol.CompanyBase{
  271 + Id: company.Id,
  272 + Name: company.Name,
  273 + ShortName: company.Abbreviation,
  274 + Image: protocol.NewImage(company.Logo),
  275 + Phone: company.Phone,
  276 + }
  277 +}
  278 +func computeBonusPercent(totalBonus float64, bonus float64) float64 {
  279 + if totalBonus == 0 {
  280 + return 0
  281 + }
  282 + return utils.Decimal(bonus / totalBonus)
  283 +}
  284 +
  285 +type Company struct {
  286 + protocol.CompanyBase
  287 + // 收入占比
  288 + IncomePercent float64 `json:"incomePercent"`
  289 + // 分红金额
  290 + DividendMoney float64 `json:"dividendMoney"`
  291 + JoinWays []joinWay `json:"joinWays"`
  292 +}
  293 +type incomeInfo struct {
  294 + // 收入占比
  295 + IncomePercent float64 `json:"incomePercent"`
  296 + // 分红金额
  297 + DividendMoney float64 `json:"dividendMoney"`
  298 +}
  299 +type joinWay struct {
  300 + Type int `json:"type"`
  301 + Name string `json:"name"`
  302 + Percent float64 `json:"percent"`
  303 +}
  304 +
  305 +func NewPgLoginService(ctx *transaction.TransactionContext) *PgLoginService {
  306 + return &PgLoginService{
  307 + transactionContext: ctx,
  308 + AvailableCompany: false,
  309 + }
  310 +}
  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 +var errUserNotFound = fmt.Errorf("用户不存在")
  15 +
  16 +type PgManagerAuthService struct {
  17 + eda.EventCenterPublisher
  18 + transactionContext *transaction.TransactionContext
  19 +}
  20 +
  21 +func NewPgManagerAuthService(ctx *transaction.TransactionContext) *PgManagerAuthService {
  22 + return &PgManagerAuthService{
  23 + transactionContext: ctx,
  24 + }
  25 +}
  26 +
  27 +func (s *PgManagerAuthService) ChangeUserPhone(userId int64, newPhone, oldPhone string) (err error) {
  28 + var (
  29 + ucenterApiGateway = svr.NewHttplibUCenterApiServiceGateway()
  30 + UsersRepository, _ = repository.NewUsersRepository(s.transactionContext)
  31 + user *domain.Users
  32 + )
  33 + if user, err = UsersRepository.FindOne(map[string]interface{}{"phone": oldPhone}); err != nil || user == nil {
  34 + log.Error(err)
  35 + err = errUserNotFound
  36 + return
  37 + }
  38 + if newUser, e := UsersRepository.FindOne(map[string]interface{}{"phone": newPhone}); e == nil || newUser != nil {
  39 + err = fmt.Errorf("当前手机号已存在,请重新输入")
  40 + return
  41 + }
  42 + _, err = ucenterApiGateway.ChangePhone(newPhone, oldPhone)
  43 + if err == nil {
  44 + _, err = s.transactionContext.PgTx.Exec("update users set phone=? where phone=?", newPhone, oldPhone)
  45 + }
  46 + //event
  47 + return
  48 +}
  49 +func (s *PgManagerAuthService) ChangeUserPassword(userId int64, newPwd, oldPwd, phone string) (err error) {
  50 + var (
  51 + ucenterApiGateway = svr.NewHttplibUCenterApiServiceGateway()
  52 + UsersRepository, _ = factory.CreateUsersRepository(s.transactionContext)
  53 + user *domain.Users
  54 + )
  55 + if user, err = UsersRepository.FindOne(map[string]interface{}{"phone": phone}); err != nil || user == nil {
  56 + log.Error(err)
  57 + err = fmt.Errorf("用户不存在")
  58 + return
  59 + }
  60 + _, err = ucenterApiGateway.ChangePassword(phone, newPwd, oldPwd)
  61 + return
  62 +}
  63 +func (s *PgManagerAuthService) ResetUserPassword(userId int64, phone, password string) (err error) {
  64 + var (
  65 + ucenterApiGateway = svr.NewHttplibUCenterApiServiceGateway()
  66 + UsersRepository, _ = factory.CreateUsersRepository(s.transactionContext)
  67 + user *domain.Users
  68 + )
  69 + if user, err = UsersRepository.FindOne(map[string]interface{}{"phone": phone}); err != nil || user == nil {
  70 + log.Error(err)
  71 + err = fmt.Errorf("用户不存在")
  72 + return
  73 + }
  74 + _, err = ucenterApiGateway.UpdateUser(user.OpenId, phone, password)
  75 + return
  76 +}
  1 +package domain_service
  2 +
  3 +import (
  4 + "fmt"
  5 + "github.com/tiptok/gocomm/xa/eda"
  6 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain"
  7 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/dao"
  8 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg/transaction"
  9 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/repository"
  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 + if partnerInfo, err = PartnerInfoService.FindOne(map[string]interface{}{"account": oldPhone}); err != nil || (partnerInfo.Account != oldPhone) {
  31 + err = errUserNotFound //账号不存在
  32 + return
  33 + }
  34 + //验证新手机是否已经存在
  35 + if _, e := PartnerInfoService.FindOne(map[string]interface{}{"account": newPhone}); e == nil {
  36 + err = fmt.Errorf("当前手机号已存在,请重新输入") //账号已存在
  37 + return
  38 + }
  39 + if err = PartnerInfoDao.Update(map[string]interface{}{
  40 + "oldAccount": oldPhone,
  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{}{"account": phone}); err != nil {
  54 + err = errUserNotFound //账号不存在
  55 + return
  56 + }
  57 + if !strings.EqualFold(partnerInfo.Password, oldPwd) {
  58 + err = fmt.Errorf("旧密码不正确") //账号不存在
  59 + return
  60 + }
  61 + if err = PartnerInfoDao.Update(map[string]interface{}{
  62 + "oldAccount": phone,
  63 + "Password": newPwd,
  64 + }); err != nil {
  65 + return
  66 + }
  67 + return
  68 +}
  69 +func (s *PgPartnerAuthService) ResetUserPassword(userId int64, phone, password string) (err error) {
  70 + var (
  71 + //partnerInfo *domain.PartnerInfo
  72 + PartnerInfoDao, _ = dao.NewPartnerInfoDao(s.transactionContext)
  73 + PartnerInfoService, _ = repository.NewPartnerInfoRepository(s.transactionContext)
  74 + )
  75 + if _, err = PartnerInfoService.FindOne(map[string]interface{}{"account": phone}); err != nil {
  76 + err = errUserNotFound //账号不存在
  77 + return
  78 + }
  79 + if err = PartnerInfoDao.Update(map[string]interface{}{
  80 + "oldAccount": phone,
  81 + "Password": password,
  82 + }); err != nil {
  83 + return
  84 + }
  85 + return
  86 +}
@@ -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,13 @@ func (repository *CompanyRepository) Find(queryOptions map[string]interface{}) ( @@ -62,6 +65,13 @@ 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.SetWhere(`enable = ?`, "enable")
  74 + query.SetOrder(`create_at`, "sortByCreateTime")
65 var err error 75 var err error
66 if query.AffectRow, err = query.SelectAndCount(); err != nil { 76 if query.AffectRow, err = query.SelectAndCount(); err != nil {
67 return 0, Companys, err 77 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 + "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 UsersRepository struct {
  13 + transactionContext *transaction.TransactionContext
  14 +}
  15 +
  16 +func (repository *UsersRepository) Save(dm *domain.Users) (*domain.Users, error) {
  17 + var (
  18 + err error
  19 + m = &models.Users{}
  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 *UsersRepository) Remove(Users *domain.Users) (*domain.Users, error) {
  38 + var (
  39 + tx = repository.transactionContext.PgTx
  40 + UsersModel = &models.Users{Id: Users.Identify().(int64)}
  41 + )
  42 + if _, err := tx.Model(UsersModel).Where("id = ?", Users.Id).Delete(); err != nil {
  43 + return Users, err
  44 + }
  45 + return Users, nil
  46 +}
  47 +
  48 +func (repository *UsersRepository) FindOne(queryOptions map[string]interface{}) (*domain.Users, error) {
  49 + tx := repository.transactionContext.PgTx
  50 + UsersModel := new(models.Users)
  51 + query := NewQuery(tx.Model(UsersModel), queryOptions)
  52 + query.SetWhere("id = ?", "id")
  53 + query.SetWhere("open_id = ?", "openId")
  54 + query.SetWhere("status = ?", "status")
  55 + query.SetWhere("phone = ?", "phone")
  56 + query.SetWhere("company_id = ?", "companyId")
  57 + query.SetWhere(`delete_at is null`, "deleteAtIsNull")
  58 + if err := query.First(); err != nil {
  59 + return nil, fmt.Errorf("query row not found")
  60 + }
  61 + if UsersModel.Id == 0 {
  62 + return nil, fmt.Errorf("query row not found")
  63 + }
  64 + return repository.transformPgModelToDomainModel(UsersModel)
  65 +}
  66 +
  67 +func (repository *UsersRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.Users, error) {
  68 + tx := repository.transactionContext.PgTx
  69 + var UsersModels []*models.Users
  70 + Userss := make([]*domain.Users, 0)
  71 + query := NewQuery(tx.Model(&UsersModels), queryOptions).
  72 + SetWhere("id = ?", "id").
  73 + SetWhere("phone = ?", "phone").
  74 + SetWhere("company_id = ?", "companyId").
  75 + SetWhere(`status = ?`, "status").
  76 + SetWhere(`delete_at is null`, "deleteAtIsNull").
  77 + SetOrder("create_at", "sortByCreateTime").
  78 + SetOrder("update_at", "sortByUpdateTime")
  79 +
  80 + if v, ok := queryOptions["inCompanyIds"]; ok {
  81 + query.Where("company_id in (?)", pg.In(v))
  82 + }
  83 + query.SetWhere("admin_type=?", "adminType")
  84 + var err error
  85 + if query.AffectRow, err = query.SelectAndCount(); err != nil {
  86 + return 0, Userss, err
  87 + }
  88 + for _, UsersModel := range UsersModels {
  89 + if Users, err := repository.transformPgModelToDomainModel(UsersModel); err != nil {
  90 + return 0, Userss, err
  91 + } else {
  92 + Userss = append(Userss, Users)
  93 + }
  94 + }
  95 + return int64(query.AffectRow), Userss, nil
  96 +}
  97 +
  98 +func (repository *UsersRepository) transformPgModelToDomainModel(UsersModel *models.Users) (*domain.Users, error) {
  99 + m := &domain.Users{}
  100 + err := GobModelTransform(m, UsersModel)
  101 + return m, err
  102 +}
  103 +
  104 +func NewUsersRepository(transactionContext *transaction.TransactionContext) (*UsersRepository, error) {
  105 + if transactionContext == nil {
  106 + return nil, fmt.Errorf("transactionContext参数不能为nil")
  107 + }
  108 + return &UsersRepository{transactionContext: transactionContext}, nil
  109 +}
  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",
@@ -9,6 +9,10 @@ import ( @@ -9,6 +9,10 @@ import (
9 9
10 func init() { 10 func init() {
11 beego.InsertFilter("/*", beego.BeforeExec, middleware.CreateRequestBodyFilter()) 11 beego.InsertFilter("/*", beego.BeforeExec, middleware.CreateRequestBodyFilter())
  12 +
  13 + beego.InsertFilter("/v1/*", beego.BeforeExec, middleware.CheckJWTToken)
  14 + beego.InsertFilter("/v2/*", beego.BeforeExec, middleware.CheckJWTToken)
  15 +
12 beego.InsertFilter("/*", beego.BeforeExec, middleware.CreateRequstLogFilter(Logger)) 16 beego.InsertFilter("/*", beego.BeforeExec, middleware.CreateRequstLogFilter(Logger))
13 beego.InsertFilter("/*", beego.AfterExec, middleware.CreateResponseLogFilter(Logger), false) 17 beego.InsertFilter("/*", beego.AfterExec, middleware.CreateResponseLogFilter(Logger), false)
14 } 18 }
@@ -4,6 +4,8 @@ import ( @@ -4,6 +4,8 @@ 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"
  8 + "strconv"
7 "time" 9 "time"
8 ) 10 )
9 11
@@ -163,3 +165,110 @@ func (this *AuthController) AuthCheckSmsCode() { @@ -163,3 +165,110 @@ func (this *AuthController) AuthCheckSmsCode() {
163 err = CacheSms.Put(request.Phone, rsp.CaptchaCertificate, 5*time.Minute) 165 err = CacheSms.Put(request.Phone, rsp.CaptchaCertificate, 5*time.Minute)
164 msg = protocol.NewReturnResponse(rsp, err) 166 msg = protocol.NewReturnResponse(rsp, err)
165 } 167 }
  168 +
  169 +// CenterCompanys
  170 +// 获取统一用户中心公司(登录凭证)
  171 +func (this *AuthController) CenterCompanys() {
  172 + var msg *protocol.ResponseMessage
  173 + defer func() {
  174 + this.Resp(msg)
  175 + }()
  176 + var request *protocolx.CenterCompanysRequest
  177 + if err := this.JsonUnmarshal(&request); err != nil {
  178 + msg = protocol.BadRequestParam(1)
  179 + return
  180 + }
  181 + if b, m := this.Valid(request); !b {
  182 + msg = m
  183 + return
  184 + }
  185 + header := this.GetRequestHeader(this.Ctx)
  186 + data, err := auth.CenterCompanys(header, request)
  187 + if err != nil {
  188 + log.Error(err)
  189 + }
  190 + msg = protocol.NewReturnResponse(data, err)
  191 +}
  192 +
  193 +// Companys
  194 +// 测试
  195 +func (this *AuthController) Companys() {
  196 + var msg *protocol.ResponseMessage
  197 + defer func() {
  198 + this.Resp(msg)
  199 + }()
  200 + var request *protocolx.CompanysRequest
  201 + if err := this.JsonUnmarshal(&request); err != nil {
  202 + msg = protocol.BadRequestParam(1)
  203 + return
  204 + }
  205 + if b, m := this.Valid(request); !b {
  206 + msg = m
  207 + return
  208 + }
  209 + if request.ClientId != clientId {
  210 + msg = protocol.NewResponseMessage(101, "clientId无效")
  211 + return
  212 + }
  213 + header := this.GetRequestHeader(this.Ctx)
  214 + data, err := auth.Companys(header, request)
  215 + if err != nil {
  216 + log.Error(err)
  217 + }
  218 + msg = protocol.NewReturnResponse(data, err)
  219 +}
  220 +
  221 +// LoginV2
  222 +// @router /loginV2 [post]
  223 +func (this *AuthController) LoginV2() {
  224 + var msg *protocol.ResponseMessage
  225 + defer func() {
  226 + this.Resp(msg)
  227 + }()
  228 + var request *protocol.LoginRequestV2
  229 + if err := this.JsonUnmarshal(&request); err != nil {
  230 + msg = protocol.BadRequestParam(1)
  231 + return
  232 + }
  233 + if b, m := this.Valid(request); !b {
  234 + msg = m
  235 + return
  236 + }
  237 + if request.ClientId != clientId {
  238 + msg = protocol.NewResponseMessage(101, "clientId无效")
  239 + return
  240 + }
  241 + header := this.GetRequestHeader(this.Ctx)
  242 + data, err := auth.LoginV2(header, request)
  243 + if err != nil {
  244 + log.Error(err)
  245 + }
  246 + msg = protocol.NewReturnResponse(data, err)
  247 +}
  248 +
  249 +//Revoke
  250 +//@router /ucenter/user/revoke [post]
  251 +func (this *AuthController) UCenterRevoke() {
  252 + var msg *protocol.ResponseMessage
  253 + defer func() {
  254 + this.Resp(msg)
  255 + }()
  256 + type reqParam struct {
  257 + UserId string `json:"id"`
  258 + }
  259 + var request *reqParam
  260 + if err := this.JsonUnmarshal(&request); err != nil {
  261 + log.Error(err)
  262 + msg = protocol.BadRequestParam(1)
  263 + return
  264 + }
  265 + if b, m := this.Valid(request); !b {
  266 + msg = m
  267 + return
  268 + }
  269 + uid, e := strconv.Atoi(request.UserId)
  270 + if e != nil {
  271 + log.Error(e, request.UserId)
  272 + }
  273 + msg = protocol.NewReturnResponse(auth.UCenterRevoke(nil, int64(uid)))
  274 +}
@@ -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 +}
@@ -2,8 +2,10 @@ package middleware @@ -2,8 +2,10 @@ package middleware
2 2
3 import ( 3 import (
4 "github.com/astaxie/beego/context" 4 "github.com/astaxie/beego/context"
  5 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/application/userAuth"
5 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/utils" 6 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/utils"
6 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/protocol" 7 "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/protocol"
  8 + "strconv"
7 "strings" 9 "strings"
8 ) 10 )
9 11
@@ -16,7 +18,14 @@ func CheckJWTToken(ctx *context.Context) { @@ -16,7 +18,14 @@ func CheckJWTToken(ctx *context.Context) {
16 if strings.HasSuffix(ctx.Request.RequestURI, "login") || 18 if strings.HasSuffix(ctx.Request.RequestURI, "login") ||
17 strings.HasSuffix(ctx.Request.RequestURI, "accessToken") || 19 strings.HasSuffix(ctx.Request.RequestURI, "accessToken") ||
18 strings.HasSuffix(ctx.Request.RequestURI, "refreshToken") || 20 strings.HasSuffix(ctx.Request.RequestURI, "refreshToken") ||
19 - strings.HasSuffix(ctx.Request.RequestURI, "smsCode") { 21 + strings.HasSuffix(ctx.Request.RequestURI, "smsCode") ||
  22 + strings.HasSuffix(ctx.Request.RequestURI, "centerCompanys") ||
  23 + strings.HasSuffix(ctx.Request.RequestURI, "companys") ||
  24 + strings.HasSuffix(ctx.Request.RequestURI, "loginV2") ||
  25 + strings.HasSuffix(ctx.Request.RequestURI, "checkSmsCode") ||
  26 + strings.HasSuffix(ctx.Request.RequestURI, "changePhone") ||
  27 + strings.HasSuffix(ctx.Request.RequestURI, "resetPassword") ||
  28 + strings.HasSuffix(ctx.Request.RequestURI, "changePassword") {
20 return 29 return
21 } 30 }
22 defer func() { 31 defer func() {
@@ -30,15 +39,16 @@ func CheckJWTToken(ctx *context.Context) { @@ -30,15 +39,16 @@ func CheckJWTToken(ctx *context.Context) {
30 } else { 39 } else {
31 ctx.Input.SetData("UserId", u.UserId) 40 ctx.Input.SetData("UserId", u.UserId)
32 41
33 - //valid token  
34 - //tokenAuth := userAuth.NewRedisUserAuth(userAuth.WithUserId(u.UserId))  
35 - //err := tokenAuth.Check(  
36 - // userAuth.NewOptions(userAuth.WithAccessToken(token)),  
37 - //)  
38 - //if err != nil {  
39 - // msg = protocol.NewMesage(4141)  
40 - // return  
41 - //} 42 + // valid token
  43 + userPhone, _ := strconv.Atoi(u.Phone)
  44 + tokenAuth := userAuth.NewRedisUserAuth(userAuth.WithUserId(int64(userPhone)))
  45 + err := tokenAuth.Check(
  46 + userAuth.NewOptions(userAuth.WithAccessToken(token)),
  47 + )
  48 + if err != nil {
  49 + msg = protocol.NewMesage(4141)
  50 + return
  51 + }
42 } 52 }
43 return 53 return
44 } 54 }
  1 +package routers
  2 +
  3 +import (
  4 + "github.com/astaxie/beego"
  5 + "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/port/appsvr/controllers"
  6 +)
  7 +
  8 +func init() {
  9 + beego.Router("ucenter/user/revoke", &controllers.AuthController{}, "Post:UCenterRevoke")
  10 +}
@@ -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 +}
1 package protocol 1 package protocol
2 2
3 const ( 3 const (
4 - LoginByPassword = "signInPassword"  
5 - LoginBySmsCode = "signInCaptcha" 4 + LoginByPassword = "signInPassword"
  5 + LoginBySmsCode = "signInCaptcha"
  6 + LoginByCredentials = "signInCredentials"
6 ) 7 )
7 8
8 -const AuthCodeExpire = 60 * 15 9 +const AuthCodeExpire = 60 * 15 //15分钟过期
9 10
10 -const TokenExpire = 60 * 60 * 2 11 +const TokenExpire = 60 * 60 * 2 //两个小时过期
11 const RefreshTokenExipre = 3600 * 24 * 30 * 1 //刷新token 一个月过期 12 const RefreshTokenExipre = 3600 * 24 * 30 * 1 //刷新token 一个月过期
12 13
13 //const TokenExpire = 30 14 //const TokenExpire = 30
@@ -15,16 +16,24 @@ const RefreshTokenExipre = 3600 * 24 * 30 * 1 //刷新token 一个月过期 @@ -15,16 +16,24 @@ const RefreshTokenExipre = 3600 * 24 * 30 * 1 //刷新token 一个月过期
15 16
16 /*Login */ 17 /*Login */
17 type LoginRequest struct { 18 type LoginRequest struct {
18 - Phone string `json:"phone" valid:"Required;"`  
19 - Password string `json:"password"`  
20 - Captcha string `json:"captcha"`  
21 - GrantType string `json:"grantType"` // 登录类型 1:密码 2:验证码  
22 - ClientId string `json:"clientId"` 19 + Phone string `json:"phone" valid:"Required;"`
  20 + Password string `json:"password"`
  21 + Captcha string `json:"captcha"`
  22 + GrantType string `json:"grantType"` // 登录类型 1:密码 2:验证码
  23 + ClientId string `json:"clientId"`
  24 + Credentials string `json:"credentials"` //凭证登录
23 } 25 }
24 type LoginResponse struct { 26 type LoginResponse struct {
25 AuthCode string `json:"authCode"` 27 AuthCode string `json:"authCode"`
26 } 28 }
27 29
  30 +type LoginRequestV2 struct {
  31 + Cid int `json:"cid"`
  32 + IdType int `json:"idType"`
  33 + Credentials string `json:"credentials"` // 登录类型 1:密码 2:验证码
  34 + ClientId string `json:"clientId"`
  35 +}
  36 +
28 //JWT用户信息 37 //JWT用户信息
29 type JWTUserInfo struct { 38 type JWTUserInfo struct {
30 UserId string `json:"id"` //用户id 39 UserId string `json:"id"` //用户id
@@ -33,7 +42,7 @@ type JWTUserInfo struct { @@ -33,7 +42,7 @@ type JWTUserInfo struct {
33 42
34 /*SmsCode*/ 43 /*SmsCode*/
35 type SmsCodeRequest struct { 44 type SmsCodeRequest struct {
36 - Phone string `json:"phone" valid:"Required;Mobile"` 45 + Phone string `json:"phone" valid:"Required"`
37 Content string `json:"-"` 46 Content string `json:"-"`
38 SendType string `json:"send_type"` //sms_login_code sms_change_mobile 47 SendType string `json:"send_type"` //sms_login_code sms_change_mobile
39 48