Xingyu Xian 7 ヶ月 前
コミット
f79366cc48

+ 38 - 0
db/job.go

@@ -36,3 +36,41 @@ func DeleteJob(ctx context.Context, job gorm_model.YounggeeJob) error {
 	}
 	return nil
 }
+
+// FindJobByEnterpriseId 按商家ID查找岗位信息
+func FindJobByEnterpriseId(ctx context.Context, job gorm_model.YounggeeJob) ([]*gorm_model.YounggeeJob, error) {
+	db := GetReadDB(ctx)
+	var Jobs []*gorm_model.YounggeeJob
+	whereCondition := gorm_model.YounggeeJob{EnterpriseId: job.EnterpriseId}
+	err := db.Model(gorm_model.YounggeeJob{}).Where(whereCondition).Find(&Jobs).Error
+	if err != nil {
+		return nil, err
+	}
+	return Jobs, nil
+}
+
+// FindJobByJobId 按照岗位Id查找岗位信息
+func FindJobByJobId(ctx context.Context, jobId int) (*gorm_model.YounggeeJob, error) {
+	db := GetReadDB(ctx)
+	var Job *gorm_model.YounggeeJob
+	whereCondition := gorm_model.YounggeeJob{JobId: jobId}
+	err := db.Model(gorm_model.YounggeeJob{}).Where(whereCondition).Find(&Job).Error
+	if err != nil {
+		return nil, err
+	}
+	return Job, nil
+}
+
+/*
+func GetRewardStrategyBySelectionId(ctx context.Context, SelectionId string) ([]*gorm_model.RewardStrategy, error) {
+	db := GetReadDB(ctx)
+	var RewardStrategys []*gorm_model.RewardStrategy
+	err := db.Model(gorm_model.RewardStrategy{}).Where("selection_id = ?", SelectionId).Find(&RewardStrategys).Error
+	if err != nil {
+		logrus.WithContext(ctx).Errorf("[GetRewardStrategyBySelectionId] error query, err:%+v", err)
+		return nil, err
+	}
+	return RewardStrategys, nil
+}
+
+*/

+ 1 - 0
db/selection.go

@@ -251,6 +251,7 @@ func UpdateSelectionSettleMoney(ctx context.Context, selectionID string, payMone
 func GetSelectionInfoList(ctx context.Context, pageNum, pageSize int64, conditions http_model.SelectionSquareCondition) ([]*http_model.SelectionBriefInfo, int64, error) {
 	db := GetReadDB(ctx)
 	db = db.Debug().Model(gorm_model.YounggeeSelectionInfo{}).Where("selection_status>2")
+	fmt.Println("conditions: ", conditions)
 
 	conditionType := reflect.TypeOf(&conditions).Elem()
 	conditionValue := reflect.ValueOf(&conditions).Elem()

+ 1 - 1
db/sub_account.go

@@ -43,7 +43,7 @@ func FindSubAccountByPhone(ctx context.Context, phone string) (*gorm_model.Young
 	db := GetReadDB(ctx)
 	var total int64
 	var subAccount *gorm_model.YounggeeSubAccount
-	whereCondition := gorm_model.YounggeeSubAccount{PhoneNumber: phone}
+	whereCondition := gorm_model.YounggeeSubAccount{PhoneNumber: phone, SubAccountType: 1}
 	err := db.Model(gorm_model.YounggeeSubAccount{}).Where(whereCondition).Find(&subAccount).Count(&total).Error
 	if err != nil {
 		return nil, err

+ 18 - 4
db/user.go

@@ -3,9 +3,8 @@ package db
 import (
 	"context"
 	"fmt"
-	"youngee_b_api/model/gorm_model"
-
 	"gorm.io/gorm"
+	"youngee_b_api/model/gorm_model"
 )
 
 func CreateUser(ctx context.Context, user gorm_model.YounggeeUser) (*int64, error) {
@@ -17,11 +16,26 @@ func CreateUser(ctx context.Context, user gorm_model.YounggeeUser) (*int64, erro
 	return &user.ID, nil
 }
 
-// GetUserByPhone 查不到返回空 根据手机号在User表中查用户数据
+// GetUserByPhone 查不到返回空 根据手机号在User表中查商家用户数据
 func GetUserByPhone(ctx context.Context, phone string) (*gorm_model.YounggeeUser, error) {
 	db := GetReadDB(ctx)
 	user := &gorm_model.YounggeeUser{}
-	err := db.Model(user).Where("phone = ?", phone).First(user).Error
+	err := db.Model(user).Where("phone = ? AND role = 3", phone).First(user).Error
+	if err != nil {
+		if err == gorm.ErrRecordNotFound {
+			fmt.Println("record not found")
+			return nil, nil
+		}
+		return nil, err
+	}
+	return user, nil
+}
+
+// GetSubUserByPhone 根据手机号在user表中查找子账号用户
+func GetSubUserByPhone(ctx context.Context, phone string) (*gorm_model.YounggeeUser, error) {
+	db := GetReadDB(ctx)
+	user := &gorm_model.YounggeeUser{}
+	err := db.Model(user).Where("phone = ? AND role = 4", phone).First(user).Error
 	if err != nil {
 		if err == gorm.ErrRecordNotFound {
 			fmt.Println("record not found")

+ 3 - 0
handler/addNewSubAccount.go

@@ -39,10 +39,12 @@ func (h *AddNewSubAccountHandler) run() {
 	// fmt.Println("AddNewSubAccountHandler Running")
 	newSubAccount := http_model.AddNewSubAccountRequest{}
 	newSubAccount = *h.req
+	// 1. 验证码校验
 	tag, err := service.LoginAuth.SubAccountAuthCode(h.ctx, newSubAccount.PhoneNumber, newSubAccount.Code)
 	if err != nil {
 		fmt.Println(err)
 	}
+	// 2. 校验通过则创建样叽用户和子账号
 	if tag == "1" {
 		err := service.SubAccount.CreateSubAccount(h.ctx, newSubAccount)
 		if err != nil {
@@ -52,6 +54,7 @@ func (h *AddNewSubAccountHandler) run() {
 			h.resp.Message = "成功创建子账号"
 		}
 	} else {
+		// 验证码校验不通过的返回值
 		h.resp.Message = tag
 	}
 	return

+ 4 - 4
handler/code_login.go

@@ -57,15 +57,15 @@ func (h *CodeLoginHandler) getResponse() interface{} {
 }
 
 func (h *CodeLoginHandler) run() {
-	token, err := service.LoginAuth.AuthCode(h.ctx, h.req.Phone, h.req.Code)
+	msg, userData, err := service.LoginAuth.AuthCode(h.ctx, h.req.Phone, h.req.Code)
 	if err != nil {
 		logrus.Errorf("[CodeLoginHandler] call AuthCode err:%+v\n", err)
-		util.HandlerPackErrorResp(h.resp, consts.ErrorInternal, token)
+		util.HandlerPackErrorResp(h.resp, consts.ErrorInternal, msg)
 		log.Info("login fail,req:%+v", h.req)
 		return
 	}
-	data := http_model.CodeLoginData{}
-	data.Token = token
+	var data *http_model.CodeLoginData
+	data = userData
 	// h.resp.Message = "登陆成功"
 	h.resp.Data = data
 }

+ 2 - 0
model/gorm_model/sub_account.go

@@ -7,6 +7,8 @@ type YounggeeSubAccount struct {
 	JobId          int    `gorm:"column:job_id"`                                    // 岗位ID
 	EnterpriseId   string `gorm:"column:enterprise_id"`                             // 所属商家账号ID
 	AccountStatus  int    `gorm:"column:account_status"`                            // 账号状态,1为正常,2为停用
+	UserId         int    `gorm:"column:user_id"`                                   // 用户表中ID
+	SubAccountType int    `gorm:"column:sub_account_type"`                          // 子账号类型,1为商家端子账号,2为管理后台子账号
 }
 
 func (m *YounggeeSubAccount) TableName() string {

+ 7 - 1
model/http_model/code_login.go

@@ -6,7 +6,13 @@ type CodeLoginRequest struct {
 }
 
 type CodeLoginData struct {
-	Token string `json:"token"`
+	Token                string `json:"token"`                 // Token
+	Role                 string `json:"role"`                  // 角色 1,超级管理员; 2,管理员;3,企业用户; 4. 企业子账号;5. 管理后台子账号
+	JobName              string `json:"job_name"`              // 岗位名称
+	WorkshopPermission   string `json:"workshop_permission"`   // 工作台权限
+	TaskcenterPermission string `json:"taskcenter_permission"` // 任务中心权限
+	CooperatePermission  string `json:"cooperate_permission"`  // 推广合作权限
+	FinancialPermission  string `json:"financial_Permission"`  // 财务结算权限
 }
 
 func NewCodeLoginRequest() *CodeLoginRequest {

+ 1 - 1
model/redis_model/auth.go

@@ -1,6 +1,6 @@
 package redis_model
 
-// redis 存放的企业用户信息Session
+// Auth redis 存放的企业用户信息Session
 type Auth struct {
 	Phone        string `json:"phone"`
 	ID           int64  `json:"id"`        // 用户表id

+ 13 - 0
model/redis_model/subAccountAuth.go

@@ -0,0 +1,13 @@
+package redis_model
+
+// SubAccountAuth redis 存放的企业子账号用户信息Session
+type SubAccountAuth struct {
+	Phone          string `json:"phone"`            // 电话号码
+	ID             int64  `json:"id"`               // 用户表id
+	User           string `json:"user"`             // 账号
+	Username       string `json:"username"`         // 后台用户名
+	SubAccountName string `json:"sub_account_name"` // 子账号名称
+	Role           string `json:"role"`             // 角色 1,超级管理员; 2,管理员;3,企业用户; 4. 企业子账号;5. 管理后台子账号
+	Token          string `json:"token"`            // Token
+	EnterpriseID   string `json:"enterprise_id"`    // 企业ID
+}

+ 89 - 36
service/login_auth.go

@@ -10,6 +10,8 @@ import (
 	"time"
 	"youngee_b_api/consts"
 	"youngee_b_api/db"
+	"youngee_b_api/model/gorm_model"
+	"youngee_b_api/model/http_model"
 	"youngee_b_api/model/redis_model"
 	"youngee_b_api/model/system_model"
 	"youngee_b_api/redis"
@@ -49,59 +51,110 @@ func (l *loginAuth) AuthToken(ctx context.Context, token string) (*redis_model.A
 }
 
 // AuthCode 判断此手机号是否有账号存在 鉴定验证码 用户信息存入redis 并返回Token
-func (l *loginAuth) AuthCode(ctx context.Context, phone string, code string) (string, error) {
+func (l *loginAuth) AuthCode(ctx context.Context, phone string, code string) (string, *http_model.CodeLoginData, error) {
+	var userData *gorm_model.YounggeeUser
 	user, err := db.GetUserByPhone(ctx, phone)
 	fmt.Println("login_auth", user, err)
 	if err != nil {
 		// 数据库操作错误
-		return "", err
+		return "", nil, err
 	} else if user == nil {
-		// 账号不存在,则注册账号
-		_, err = Enterprise.CreateEnterprise(ctx, phone)
-		if err != nil {
-			return "账号创建失败", err
-		}
-		user, err = db.GetUserByPhone(ctx, phone)
-		fmt.Println("login_auth", user, err)
-		if err != nil {
-			return "", err
+		user, err := db.GetSubUserByPhone(ctx, phone)
+
+		fmt.Println("子账号存在")
+		if user == nil {
+			fmt.Println("子账号也不存在")
+			// 账号不存在,则默认注册商家账号
+			_, err = Enterprise.CreateEnterprise(ctx, phone)
+			if err != nil {
+				return "账号创建失败", nil, err
+			}
+			user, err = db.GetUserByPhone(ctx, phone)
+			userData = user
+			fmt.Println("login_auth", user, err)
+			if err != nil {
+				return "", nil, err
+			}
+		} else {
+			userData = user
 		}
-	} else if string(user.Role) != consts.BRole {
-		// 账号权限有误
-		logrus.Debugf("[AuthCode] auth fail,phone:%+v", phone)
-		return "权限错误,请登录企业账号", errors.New("auth fail")
+	} else if user != nil {
+		userData = user
 	}
 	vcode, err := l.getSessionCode(ctx, phone)
 	if err != nil {
-		return "", err
+		return "", nil, err
 	}
 	fmt.Printf("缓存的验证码 vcode: %v,实际填入的 code:%v", vcode, code)
 	if vcode != code {
 		// 验证码错误
 		logrus.Debugf("[AuthCode] auth fail,phone:%+v", phone)
-		return "验证码有误", errors.New("auth fail")
+		return "验证码有误", nil, errors.New("auth fail")
 	}
 	token := l.getToken(ctx, phone)
-	enterprise, err := db.GetEnterpriseByUID(ctx, user.ID)
-	if err != nil {
-		return "", err
-	}
-	auth := &redis_model.Auth{
-		Phone:        phone,
-		ID:           user.ID,
-		User:         user.User,
-		Username:     user.Username,
-		RealName:     user.RealName,
-		Role:         user.Role,
-		Email:        user.Email,
-		Token:        token,
-		EnterpriseID: enterprise.EnterpriseID,
+
+	var jobData *gorm_model.YounggeeJob
+
+	// 若为商家用户
+	if string(userData.Role) == consts.BRole {
+		fmt.Println("商家主账号")
+		enterprise, err := db.GetEnterpriseByUID(ctx, userData.ID)
+		if err != nil {
+			return "", nil, err
+		}
+		auth := &redis_model.Auth{
+			Phone:        phone,
+			ID:           userData.ID,
+			User:         userData.User,
+			Username:     userData.Username,
+			RealName:     userData.RealName,
+			Role:         userData.Role,
+			Email:        userData.Email,
+			Token:        token,
+			EnterpriseID: enterprise.EnterpriseID,
+		}
+		if err := l.setSession(ctx, phone, auth); err != nil {
+			fmt.Printf("setSession error\n")
+			return "", nil, err
+		}
+	} else {
+		// 若为商家子账号
+		fmt.Printf("商家子账号")
+		subaccount, err := db.FindSubAccountByPhone(ctx, phone)
+		if err != nil {
+			return "", nil, err
+		}
+		auth := &redis_model.Auth{
+			Phone:        phone,
+			ID:           userData.ID,
+			User:         userData.User,
+			Username:     userData.Username,
+			RealName:     userData.RealName,
+			Role:         userData.Role,
+			Email:        userData.Email,
+			Token:        token,
+			EnterpriseID: subaccount.EnterpriseId,
+		}
+
+		job, err := db.FindJobByJobId(ctx, subaccount.JobId)
+		jobData = job
+		if err := l.setSession(ctx, phone, auth); err != nil {
+			fmt.Printf("setSession error\n")
+			return "", nil, err
+		}
 	}
-	if err := l.setSession(ctx, phone, auth); err != nil {
-		fmt.Printf("setSession error\n")
-		return "", err
+
+	loginUserData := http_model.CodeLoginData{
+		Token:                token,
+		Role:                 userData.Role,
+		JobName:              jobData.JobName,
+		WorkshopPermission:   jobData.WorkshopPermission,
+		CooperatePermission:  jobData.CooperatePermission,
+		FinancialPermission:  jobData.FinancialPermission,
+		TaskcenterPermission: jobData.TaskcenterPermission,
 	}
-	return token, nil
+
+	return "", &loginUserData, nil
 }
 
 // func (l *loginAuth) AuthPassword(ctx context.Context, phone string, password string) (string, error) {
@@ -221,7 +274,7 @@ func (l *loginAuth) SubAccountAuthCode(ctx context.Context, phone string, code s
 				return "验证码有误", errors.New("auth fail")
 			}
 			return "1", err
-		} else if string(user.Role) != consts.BRole {
+		} else if string(user.Role) == consts.BRole {
 			if user.AuthStatus == 1 {
 				// 被商家主账户注册,未认证,则可以注册
 				vcode, err := l.getSessionCode(ctx, phoneNumber)

+ 26 - 3
service/sub_account.go

@@ -2,6 +2,9 @@ package service
 
 import (
 	"context"
+	"fmt"
+	log "github.com/sirupsen/logrus"
+	"time"
 	"youngee_b_api/db"
 	"youngee_b_api/model/gorm_model"
 	"youngee_b_api/model/http_model"
@@ -14,16 +17,36 @@ type subaccount struct {
 
 // CreateSubAccount 新增子账号
 func (*subaccount) CreateSubAccount(ctx context.Context, request http_model.AddNewSubAccountRequest) error {
+	user := gorm_model.YounggeeUser{
+		Phone:         request.PhoneNumber,
+		User:          "1002",
+		Username:      request.PhoneNumber,
+		Password:      "1002",
+		RealName:      "",
+		Role:          "4",
+		Email:         "",
+		LastLoginTime: time.Now().UTC().Local(),
+	}
+	userId, err := db.CreateUser(ctx, user)
+	if err != nil {
+		log.Infof("[CreateEnterpriseSubUser] fail,err:%+v", err)
+		return err
+	}
+	fmt.Println("userId: ", userId)
+	var curr = int(*userId)
+
 	var newSubAccount = gorm_model.YounggeeSubAccount{
 		PhoneNumber:    request.PhoneNumber,
 		SubAccountName: request.SubAccountName,
 		JobId:          request.JobId,
 		EnterpriseId:   request.EnterpriseId,
 		AccountStatus:  1,
+		UserId:         curr,
+		SubAccountType: 1,
 	}
-	err := db.CreateSubAccount(ctx, newSubAccount)
-	if err != nil {
-		return err
+	err1 := db.CreateSubAccount(ctx, newSubAccount)
+	if err1 != nil {
+		return err1
 	}
 	return nil
 }