作者 yangfu

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

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