123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360 |
- package db
- import (
- "context"
- "fmt"
- "github.com/caixw/lib.go/conv"
- "github.com/sirupsen/logrus"
- "gorm.io/gorm"
- "reflect"
- "time"
- "youngee_m_api/consts"
- "youngee_m_api/model/common_model"
- "youngee_m_api/model/gorm_model"
- "youngee_m_api/model/http_model"
- "youngee_m_api/pack"
- "youngee_m_api/util"
- )
- //GetUser 查找用户,查不到返回空
- func GetUser(ctx context.Context, User string) (*gorm_model.YounggeeUser, error) {
- db := GetReadDB(ctx)
- user := &gorm_model.YounggeeUser{}
- err := db.Model(user).Where("user = ?", User).First(user).Error
- if err != nil {
- if err == gorm.ErrRecordNotFound {
- fmt.Println("record not found")
- return nil, nil
- }
- return nil, err
- }
- return user, nil
- }
- //GetUserByID 查不到返回空
- func GetUserByID(ctx context.Context, ID int64) (*gorm_model.YounggeeUser, error) {
- db := GetReadDB(ctx)
- user := &gorm_model.YounggeeUser{}
- err := db.Model(user).Where("id = ?", ID).First(user).Error
- if err != nil {
- if err == gorm.ErrRecordNotFound {
- fmt.Println("record not found")
- return nil, nil
- }
- return nil, err
- }
- return user, nil
- }
- // GetAllUser 查找所有用户
- func GetAllUser(ctx context.Context) ([]string, error) {
- db := GetReadDB(ctx)
- db = db.Debug().Model([]gorm_model.YounggeeUser{}).Where("role = ? or role = ?", "1", "2")
- var user []gorm_model.YounggeeUser
- db.Find(&user)
- var total int64
- if err := db.Count(&total).Error; err != nil {
- logrus.WithContext(ctx).Errorf("[GetAllUser] error query mysql total, err:%+v", err)
- return nil, err
- }
- var userList []string
- for _, User := range user {
- userList = append(userList, User.User)
- }
- return userList, nil
- }
- // GetUserList 获取员工用户列表
- func GetUserList(ctx context.Context, pageNum, pageSize int32) (*http_model.UserListData, error) {
- db := GetReadDB(ctx)
- db = db.Debug().Model([]gorm_model.YounggeeUser{}).Where("role = ? or role = ?", "1", "2")
- var user []gorm_model.YounggeeUser
- // 查询总数
- var total int64
- if err := db.Count(&total).Error; err != nil {
- logrus.WithContext(ctx).Errorf("[GetUserList] error query mysql total, err:%+v", err)
- return nil, err
- }
- // 查询该页数据
- limit := pageSize
- offset := pageSize * pageNum // assert pageNum start with 0
- err := db.Order("created_at desc").Limit(int(limit)).Offset(int(offset)).Find(&user).Error
- if err != nil {
- logrus.WithContext(ctx).Errorf("[GetUserList] error query mysql find, err:%+v", err)
- return nil, err
- }
- userList := new(http_model.UserListData)
- userList.UserListPreview = pack.MGormUserListToHttpUserListPreview(user)
- userList.Total = conv.MustString(total, "")
- return userList, nil
- }
- func UpdateUserInfo(ctx context.Context, req *http_model.UpdateUserInfoRequest) (string, error) {
- db := GetReadDB(ctx)
- user, username, role, password, email, phone := req.User, req.Username, req.Role, req.Password, req.Email, req.Phone
- db = db.Debug().Model([]gorm_model.YounggeeUser{}).Where("user = ?", user)
- err := db.Updates(map[string]interface{}{
- "username": username, "password": password, "email": email, "phone": phone, "role": role}).Error
- if err != nil {
- return "", err
- }
- return "更新成功", nil
- }
- func CreateUser(ctx context.Context, req *http_model.CreateUserRequest) (string, error) {
- db := GetReadDB(ctx)
- username, role, password, email, phone := req.Username, req.Role, req.Password, req.Email, req.Phone
- var IsUserPhone gorm_model.YounggeeUser
- err := db.Debug().Where(" phone = ?", req.Phone).First(&IsUserPhone).Error
- if err == nil {
- return "手机号已存在,不能再次创建", nil
- }
- var user gorm_model.YounggeeUser
- var userInfo gorm_model.YounggeeUser
- getMonth := time.Now().Format("01") //获取月
- getDay := time.Now().Day() //获取日
- dayString := ""
- if getDay < 10 {
- dayString = conv.MustString(getDay, "")
- dayString = "0" + dayString
- } else {
- dayString = conv.MustString(getDay, "")
- }
- monthAndDay := conv.MustString(getMonth, "") + dayString
- err = db.Debug().Where(fmt.Sprintf(" user like '%s%%'", monthAndDay)).Last(&userInfo).Error
- num := 1
- if userInfo.User != "" {
- num = conv.MustInt(userInfo.User[4:6], 0)
- num = num + 1 //获取日
- } else {
- num = 1
- }
- numString := ""
- if num < 10 {
- numString = conv.MustString(num, "")
- numString = "0" + numString
- } else {
- numString = conv.MustString(num, "")
- }
- user.Username = username
- user.RealName = username
- user.User = monthAndDay + numString
- user.Role = role
- user.Password = password
- user.Email = email
- user.Phone = phone
- user.LastLoginTime = time.Now()
- user.CreatedAt = time.Now()
- user.UpdatedAt = time.Now()
- err = db.Debug().Create(&user).Error
- if err != nil {
- return "创建失败", err
- }
- return "创建成功", nil
- }
- func DisabledUser(ctx context.Context, user string) (string, error) {
- db := GetReadDB(ctx)
- err := db.Debug().Model(gorm_model.YounggeeUser{}).Where("user = ?", user).Update("user_state", "0").Error
- if err != nil {
- logrus.WithContext(ctx).Errorf("[DisabledUser] error Update mysql find, err:%+v", err)
- return "禁用失败", err
- }
- return "账号已禁止使用", nil
- }
- func GetEnterpriseUserList(ctx context.Context, pageSize, pageNum int32, conditions *common_model.EnterpriseUserConditions) ([]*http_model.EnterpriseUserPreview, int64, error) {
- db := GetReadDB(ctx)
- // 查询user表信息,筛选出企业用户
- db = db.Debug().Model([]gorm_model.YounggeeUser{}).Where("role = ? ", "3")
- // 根据 查询条件过滤
- conditionType := reflect.TypeOf(conditions).Elem()
- conditionValue := reflect.ValueOf(conditions).Elem()
- for i := 0; i < conditionType.NumField(); i++ {
- field := conditionType.Field(i)
- tag := field.Tag.Get("condition")
- value := conditionValue.FieldByName(field.Name)
- if !util.IsBlank(value) && tag != "created_at" {
- db = db.Where(fmt.Sprintf("%s = ?", tag), value.Interface())
- } else if tag == "created_at" && value.Interface() != nil {
- db = db.Where(fmt.Sprintf("created_at like '%s%%'", value.Interface()))
- }
- }
- var users []gorm_model.YounggeeUser
- var totalUser int64
- if err := db.Count(&totalUser).Error; err != nil {
- logrus.WithContext(ctx).Errorf("[GetEnterpriseUserList] error query mysql total, err:%+v", err)
- return nil, 0, err
- }
- db.Order("user").Find(&users)
- // 查询 用户自增的id
- var userIds []int64
- userMap := make(map[int64]gorm_model.YounggeeUser)
- for _, user := range users {
- userIds = append(userIds, user.ID)
- userMap[user.ID] = user
- }
- db1 := GetReadDB(ctx)
- var enterprises []gorm_model.Enterprise
- db1 = db1.Debug().Model(gorm_model.Enterprise{}).Where("user_id IN ?", userIds).Find(&enterprises)
- // 查询该页数据
- limit := pageSize
- offset := pageSize * pageNum // assert pageNum start with 0
- err := db.Order("user").Limit(int(limit)).Offset(int(offset)).Error
- if err != nil {
- logrus.WithContext(ctx).Errorf("[GetEnterpriseUserList] error query mysql total, err:%+v", err)
- return nil, 0, err
- }
- enterpriseMap := make(map[int64]gorm_model.Enterprise)
- for _, enterprise := range enterprises {
- enterpriseMap[enterprise.UserID] = enterprise
- }
- var enterpriseUsers []*http_model.EnterpriseUser
- for _, userId := range userIds {
- enterpriseUser := new(http_model.EnterpriseUser)
- _, ok1 := userMap[userId]
- _, ok2 := enterpriseMap[userId]
- if ok1 && ok2 {
- enterpriseUser.Enterprise = enterpriseMap[userId]
- enterpriseUser.YoungeeUser = userMap[userId]
- }
- enterpriseUsers = append(enterpriseUsers, enterpriseUser)
- }
- var enterpriseUserDatas []*http_model.EnterpriseUserPreview
- enterpriseUserDatas = pack.EnterpriseUserToEnterpriseUserData(enterpriseUsers)
- return enterpriseUserDatas, totalUser, nil
- }
- func GetCreatorList(ctx context.Context, pageSize, pageNum int32, conditions *common_model.CreatorListConditions) ([]*http_model.CreatorListPreview, int64, error) {
- db := GetReadDB(ctx)
- db = db.Debug().Model(gorm_model.YoungeeTalentInfo{})
- // 根据 条件过滤
- conditionType := reflect.TypeOf(conditions).Elem()
- conditionValue := reflect.ValueOf(conditions).Elem()
- for i := 0; i < conditionType.NumField(); i++ {
- field := conditionType.Field(i)
- tag := field.Tag.Get("condition")
- value := conditionValue.FieldByName(field.Name)
- if !util.IsBlank(value) && tag != "create_date" {
- db = db.Where(fmt.Sprintf("%s = ?", tag), value.Interface())
- } else if tag == "create_date" && value.Interface() != nil {
- db = db.Where(fmt.Sprintf("create_date like '%s%%'", value.Interface()))
- }
- }
- // 查询总数
- var total int64
- var talentList []gorm_model.YoungeeTalentInfo
- if err := db.Count(&total).Error; err != nil {
- logrus.WithContext(ctx).Errorf("[GetCreatorList] error query mysql total, err:%+v", err)
- return nil, 0, err
- }
- // 查询该页数据
- limit := pageSize
- offset := pageSize * pageNum // assert pageNum start with 0
- err := db.Order("id").Limit(int(limit)).Offset(int(offset)).Find(&talentList).Error
- if err != nil {
- logrus.WithContext(ctx).Errorf("[GetCreatorList] error query mysql total, err:%+v", err)
- return nil, 0, err
- }
- var CreatorList []*http_model.CreatorListPreview
- CreatorList = pack.TalentListToCreatorListData(talentList)
- return CreatorList, total, nil
- }
- func AccountInfo(ctx context.Context, pageSize, pageNum int32, conditions *common_model.AccountInfoConditions) ([]*http_model.AccountInfoData, int64, error) {
- db := GetReadDB(ctx)
- db = db.Debug().Model(gorm_model.YoungeePlatformAccountInfo{})
- // 根据 条件过滤
- conditionType := reflect.TypeOf(conditions).Elem()
- conditionValue := reflect.ValueOf(conditions).Elem()
- for i := 0; i < conditionType.NumField(); i++ {
- field := conditionType.Field(i)
- tag := field.Tag.Get("condition")
- value := conditionValue.FieldByName(field.Name)
- if !util.IsBlank(value) && tag != "bind_date" && tag != "fans_low" && tag != "fans_high" {
- db = db.Where(fmt.Sprintf("%s = ?", tag), value.Interface())
- } else if tag == "bind_date" && value.Interface() != nil {
- db = db.Where(fmt.Sprintf("bind_date like '%s%%'", value.Interface()))
- }
- if !util.IsBlank(value) && tag == "fans_low" {
- db = db.Where(fmt.Sprintf("%s >= ?", "fans_count"), value.Interface())
- }
- if !util.IsBlank(value) && tag == "fans_high" {
- db = db.Where(fmt.Sprintf("%s <= ?", "fans_count"), value.Interface())
- }
- }
- db = db.Debug().Where("deleted = ?", 0)
- var total int64
- if err := db.Count(&total).Error; err != nil {
- logrus.WithContext(ctx).Errorf("[GetAccountInfo] error query mysql total, err:%+v", err)
- return nil, 0, err
- }
- var PlatformAccountInfos []*gorm_model.YoungeePlatformAccountInfo
- // 查询该页数据
- limit := pageSize
- offset := pageSize * pageNum // assert pageNum start with 0
- err := db.Order("bind_date desc").Limit(int(limit)).Offset(int(offset)).Find(&PlatformAccountInfos).Error
- if err != nil {
- logrus.WithContext(ctx).Errorf("[GetAccountInfo] error query mysql total, err:%+v", err)
- return nil, 0, err
- }
- phoneMap := map[string]string{}
- for _, PlatformAccountInfo := range PlatformAccountInfos {
- if _, ok := phoneMap[PlatformAccountInfo.TalentID]; !ok {
- phoneMap[PlatformAccountInfo.TalentID] = getPhoneByTalentID(ctx, PlatformAccountInfo.TalentID)
- }
- }
- var accountInfoDatas []*http_model.AccountInfoData
- for _, PlatformAccountInfo := range PlatformAccountInfos {
- accountInfo := new(http_model.AccountInfoData)
- accountInfo.BindDate = conv.MustString(PlatformAccountInfo.BindDate, "")[0:19]
- accountInfo.Platform = consts.GetProjectPlatform(PlatformAccountInfo.PlatformID)
- accountInfo.PlatformNickname = PlatformAccountInfo.PlatformNickname
- accountInfo.TalentId = PlatformAccountInfo.TalentID
- accountInfo.Phone = phoneMap[PlatformAccountInfo.TalentID]
- accountInfo.Fans = util.GetNumString(PlatformAccountInfo.FansCount)
- accountInfo.HomePageUrl = PlatformAccountInfo.HomePageUrl
- accountInfo.HomePageCaptureUrl = PlatformAccountInfo.HomePageCaptureUrl
- accountInfoDatas = append(accountInfoDatas, accountInfo)
- }
- return accountInfoDatas, total, nil
- }
- func getPhoneByTalentID(ctx context.Context, talentID string) string {
- db := GetReadDB(ctx)
- talentInfo := gorm_model.YoungeeTalentInfo{}
- err := db.Debug().Where("id = ?", talentID).First(&talentInfo).Error
- if err != nil {
- if err == gorm.ErrRecordNotFound {
- return ""
- } else {
- return ""
- }
- }
- return talentInfo.TalentPhoneNumber
- }
- func DeleteAccount(ctx context.Context, PlatformID, PlatformNickname, TalentId string) error {
- db := GetReadDB(ctx)
- accountInfo := gorm_model.YoungeePlatformAccountInfo{}
- db = db.Debug().Where("talent_id = ? "+
- "AND platform_nickname = ? "+
- "AND platform_id = ?",
- TalentId, PlatformNickname, PlatformID).First(&accountInfo)
- err := db.Update("deleted", 1).Error
- if err != nil {
- logrus.WithContext(ctx).Errorf("[user db] call DeleteAccount error,err:%+v", err)
- return err
- }
- return nil
- }
|