user.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. package db
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/caixw/lib.go/conv"
  6. "github.com/sirupsen/logrus"
  7. "gorm.io/gorm"
  8. "reflect"
  9. "time"
  10. "youngee_m_api/consts"
  11. "youngee_m_api/model/common_model"
  12. "youngee_m_api/model/gorm_model"
  13. "youngee_m_api/model/http_model"
  14. "youngee_m_api/pack"
  15. "youngee_m_api/util"
  16. )
  17. //GetUser 查找用户,查不到返回空
  18. func GetUser(ctx context.Context, User string) (*gorm_model.YounggeeUser, error) {
  19. db := GetReadDB(ctx)
  20. user := &gorm_model.YounggeeUser{}
  21. err := db.Model(user).Where("user = ?", User).First(user).Error
  22. if err != nil {
  23. if err == gorm.ErrRecordNotFound {
  24. fmt.Println("record not found")
  25. return nil, nil
  26. }
  27. return nil, err
  28. }
  29. return user, nil
  30. }
  31. //GetUserByID 查不到返回空
  32. func GetUserByID(ctx context.Context, ID int64) (*gorm_model.YounggeeUser, error) {
  33. db := GetReadDB(ctx)
  34. user := &gorm_model.YounggeeUser{}
  35. err := db.Model(user).Where("id = ?", ID).First(user).Error
  36. if err != nil {
  37. if err == gorm.ErrRecordNotFound {
  38. fmt.Println("record not found")
  39. return nil, nil
  40. }
  41. return nil, err
  42. }
  43. return user, nil
  44. }
  45. // GetAllUser 查找所有用户
  46. func GetAllUser(ctx context.Context) ([]string, error) {
  47. db := GetReadDB(ctx)
  48. db = db.Debug().Model([]gorm_model.YounggeeUser{}).Where("role = ? or role = ?", "1", "2")
  49. var user []gorm_model.YounggeeUser
  50. db.Find(&user)
  51. var total int64
  52. if err := db.Count(&total).Error; err != nil {
  53. logrus.WithContext(ctx).Errorf("[GetAllUser] error query mysql total, err:%+v", err)
  54. return nil, err
  55. }
  56. var userList []string
  57. for _, User := range user {
  58. userList = append(userList, User.User)
  59. }
  60. return userList, nil
  61. }
  62. // GetUserList 获取员工用户列表
  63. func GetUserList(ctx context.Context, pageNum, pageSize int32) (*http_model.UserListData, error) {
  64. db := GetReadDB(ctx)
  65. db = db.Debug().Model([]gorm_model.YounggeeUser{}).Where("role = ? or role = ?", "1", "2")
  66. var user []gorm_model.YounggeeUser
  67. // 查询总数
  68. var total int64
  69. if err := db.Count(&total).Error; err != nil {
  70. logrus.WithContext(ctx).Errorf("[GetUserList] error query mysql total, err:%+v", err)
  71. return nil, err
  72. }
  73. // 查询该页数据
  74. limit := pageSize
  75. offset := pageSize * pageNum // assert pageNum start with 0
  76. err := db.Order("created_at desc").Limit(int(limit)).Offset(int(offset)).Find(&user).Error
  77. if err != nil {
  78. logrus.WithContext(ctx).Errorf("[GetUserList] error query mysql find, err:%+v", err)
  79. return nil, err
  80. }
  81. userList := new(http_model.UserListData)
  82. userList.UserListPreview = pack.MGormUserListToHttpUserListPreview(user)
  83. userList.Total = conv.MustString(total, "")
  84. return userList, nil
  85. }
  86. func UpdateUserInfo(ctx context.Context, req *http_model.UpdateUserInfoRequest) (string, error) {
  87. db := GetReadDB(ctx)
  88. user, username, role, password, email, phone := req.User, req.Username, req.Role, req.Password, req.Email, req.Phone
  89. db = db.Debug().Model([]gorm_model.YounggeeUser{}).Where("user = ?", user)
  90. err := db.Updates(map[string]interface{}{
  91. "username": username, "password": password, "email": email, "phone": phone, "role": role}).Error
  92. if err != nil {
  93. return "", err
  94. }
  95. return "更新成功", nil
  96. }
  97. func CreateUser(ctx context.Context, req *http_model.CreateUserRequest) (string, error) {
  98. db := GetReadDB(ctx)
  99. username, role, password, email, phone := req.Username, req.Role, req.Password, req.Email, req.Phone
  100. var IsUserPhone gorm_model.YounggeeUser
  101. err := db.Debug().Where(" phone = ?", req.Phone).First(&IsUserPhone).Error
  102. if err == nil {
  103. return "手机号已存在,不能再次创建", nil
  104. }
  105. var user gorm_model.YounggeeUser
  106. var userInfo gorm_model.YounggeeUser
  107. getMonth := time.Now().Format("01") //获取月
  108. getDay := time.Now().Day() //获取日
  109. dayString := ""
  110. if getDay < 10 {
  111. dayString = conv.MustString(getDay, "")
  112. dayString = "0" + dayString
  113. } else {
  114. dayString = conv.MustString(getDay, "")
  115. }
  116. monthAndDay := conv.MustString(getMonth, "") + dayString
  117. err = db.Debug().Where(fmt.Sprintf(" user like '%s%%'", monthAndDay)).Last(&userInfo).Error
  118. num := 1
  119. if userInfo.User != "" {
  120. num = conv.MustInt(userInfo.User[4:6], 0)
  121. num = num + 1 //获取日
  122. } else {
  123. num = 1
  124. }
  125. numString := ""
  126. if num < 10 {
  127. numString = conv.MustString(num, "")
  128. numString = "0" + numString
  129. } else {
  130. numString = conv.MustString(num, "")
  131. }
  132. user.Username = username
  133. user.RealName = username
  134. user.User = monthAndDay + numString
  135. user.Role = role
  136. user.Password = password
  137. user.Email = email
  138. user.Phone = phone
  139. user.LastLoginTime = time.Now()
  140. user.CreatedAt = time.Now()
  141. user.UpdatedAt = time.Now()
  142. err = db.Debug().Create(&user).Error
  143. if err != nil {
  144. return "创建失败", err
  145. }
  146. return "创建成功", nil
  147. }
  148. func DisabledUser(ctx context.Context, user string) (string, error) {
  149. db := GetReadDB(ctx)
  150. err := db.Debug().Model(gorm_model.YounggeeUser{}).Where("user = ?", user).Update("user_state", "0").Error
  151. if err != nil {
  152. logrus.WithContext(ctx).Errorf("[DisabledUser] error Update mysql find, err:%+v", err)
  153. return "禁用失败", err
  154. }
  155. return "账号已禁止使用", nil
  156. }
  157. func GetEnterpriseUserList(ctx context.Context, pageSize, pageNum int32, conditions *common_model.EnterpriseUserConditions) ([]*http_model.EnterpriseUserPreview, int64, error) {
  158. db := GetReadDB(ctx)
  159. // 查询user表信息,筛选出企业用户
  160. db = db.Debug().Model([]gorm_model.YounggeeUser{}).Where("role = ? ", "3")
  161. // 根据 查询条件过滤
  162. conditionType := reflect.TypeOf(conditions).Elem()
  163. conditionValue := reflect.ValueOf(conditions).Elem()
  164. for i := 0; i < conditionType.NumField(); i++ {
  165. field := conditionType.Field(i)
  166. tag := field.Tag.Get("condition")
  167. value := conditionValue.FieldByName(field.Name)
  168. if !util.IsBlank(value) && tag != "created_at" {
  169. db = db.Where(fmt.Sprintf("%s = ?", tag), value.Interface())
  170. } else if tag == "created_at" && value.Interface() != nil {
  171. db = db.Where(fmt.Sprintf("created_at like '%s%%'", value.Interface()))
  172. }
  173. }
  174. var users []gorm_model.YounggeeUser
  175. var totalUser int64
  176. if err := db.Count(&totalUser).Error; err != nil {
  177. logrus.WithContext(ctx).Errorf("[GetEnterpriseUserList] error query mysql total, err:%+v", err)
  178. return nil, 0, err
  179. }
  180. db.Order("user").Find(&users)
  181. // 查询 用户自增的id
  182. var userIds []int64
  183. userMap := make(map[int64]gorm_model.YounggeeUser)
  184. for _, user := range users {
  185. userIds = append(userIds, user.ID)
  186. userMap[user.ID] = user
  187. }
  188. db1 := GetReadDB(ctx)
  189. var enterprises []gorm_model.Enterprise
  190. db1 = db1.Debug().Model(gorm_model.Enterprise{}).Where("user_id IN ?", userIds).Find(&enterprises)
  191. // 查询该页数据
  192. limit := pageSize
  193. offset := pageSize * pageNum // assert pageNum start with 0
  194. err := db.Order("user").Limit(int(limit)).Offset(int(offset)).Error
  195. if err != nil {
  196. logrus.WithContext(ctx).Errorf("[GetEnterpriseUserList] error query mysql total, err:%+v", err)
  197. return nil, 0, err
  198. }
  199. enterpriseMap := make(map[int64]gorm_model.Enterprise)
  200. for _, enterprise := range enterprises {
  201. enterpriseMap[enterprise.UserID] = enterprise
  202. }
  203. var enterpriseUsers []*http_model.EnterpriseUser
  204. for _, userId := range userIds {
  205. enterpriseUser := new(http_model.EnterpriseUser)
  206. _, ok1 := userMap[userId]
  207. _, ok2 := enterpriseMap[userId]
  208. if ok1 && ok2 {
  209. enterpriseUser.Enterprise = enterpriseMap[userId]
  210. enterpriseUser.YoungeeUser = userMap[userId]
  211. }
  212. enterpriseUsers = append(enterpriseUsers, enterpriseUser)
  213. }
  214. var enterpriseUserDatas []*http_model.EnterpriseUserPreview
  215. enterpriseUserDatas = pack.EnterpriseUserToEnterpriseUserData(enterpriseUsers)
  216. return enterpriseUserDatas, totalUser, nil
  217. }
  218. func GetCreatorList(ctx context.Context, pageSize, pageNum int32, conditions *common_model.CreatorListConditions) ([]*http_model.CreatorListPreview, int64, error) {
  219. db := GetReadDB(ctx)
  220. db = db.Debug().Model(gorm_model.YoungeeTalentInfo{})
  221. // 根据 条件过滤
  222. conditionType := reflect.TypeOf(conditions).Elem()
  223. conditionValue := reflect.ValueOf(conditions).Elem()
  224. for i := 0; i < conditionType.NumField(); i++ {
  225. field := conditionType.Field(i)
  226. tag := field.Tag.Get("condition")
  227. value := conditionValue.FieldByName(field.Name)
  228. if !util.IsBlank(value) && tag != "create_date" {
  229. db = db.Where(fmt.Sprintf("%s = ?", tag), value.Interface())
  230. } else if tag == "create_date" && value.Interface() != nil {
  231. db = db.Where(fmt.Sprintf("create_date like '%s%%'", value.Interface()))
  232. }
  233. }
  234. // 查询总数
  235. var total int64
  236. var talentList []gorm_model.YoungeeTalentInfo
  237. if err := db.Count(&total).Error; err != nil {
  238. logrus.WithContext(ctx).Errorf("[GetCreatorList] error query mysql total, err:%+v", err)
  239. return nil, 0, err
  240. }
  241. // 查询该页数据
  242. limit := pageSize
  243. offset := pageSize * pageNum // assert pageNum start with 0
  244. err := db.Order("id").Limit(int(limit)).Offset(int(offset)).Find(&talentList).Error
  245. if err != nil {
  246. logrus.WithContext(ctx).Errorf("[GetCreatorList] error query mysql total, err:%+v", err)
  247. return nil, 0, err
  248. }
  249. var CreatorList []*http_model.CreatorListPreview
  250. CreatorList = pack.TalentListToCreatorListData(talentList)
  251. return CreatorList, total, nil
  252. }
  253. func AccountInfo(ctx context.Context, pageSize, pageNum int32, conditions *common_model.AccountInfoConditions) ([]*http_model.AccountInfoData, int64, error) {
  254. db := GetReadDB(ctx)
  255. db = db.Debug().Model(gorm_model.YoungeePlatformAccountInfo{})
  256. // 根据 条件过滤
  257. conditionType := reflect.TypeOf(conditions).Elem()
  258. conditionValue := reflect.ValueOf(conditions).Elem()
  259. for i := 0; i < conditionType.NumField(); i++ {
  260. field := conditionType.Field(i)
  261. tag := field.Tag.Get("condition")
  262. value := conditionValue.FieldByName(field.Name)
  263. if !util.IsBlank(value) && tag != "bind_date" && tag != "fans_low" && tag != "fans_high" {
  264. db = db.Where(fmt.Sprintf("%s = ?", tag), value.Interface())
  265. } else if tag == "bind_date" && value.Interface() != nil {
  266. db = db.Where(fmt.Sprintf("bind_date like '%s%%'", value.Interface()))
  267. }
  268. if !util.IsBlank(value) && tag == "fans_low" {
  269. db = db.Where(fmt.Sprintf("%s >= ?", "fans_count"), value.Interface())
  270. }
  271. if !util.IsBlank(value) && tag == "fans_high" {
  272. db = db.Where(fmt.Sprintf("%s <= ?", "fans_count"), value.Interface())
  273. }
  274. }
  275. db = db.Debug().Where("deleted = ?", 0)
  276. var total int64
  277. if err := db.Count(&total).Error; err != nil {
  278. logrus.WithContext(ctx).Errorf("[GetAccountInfo] error query mysql total, err:%+v", err)
  279. return nil, 0, err
  280. }
  281. var PlatformAccountInfos []*gorm_model.YoungeePlatformAccountInfo
  282. // 查询该页数据
  283. limit := pageSize
  284. offset := pageSize * pageNum // assert pageNum start with 0
  285. err := db.Order("bind_date desc").Limit(int(limit)).Offset(int(offset)).Find(&PlatformAccountInfos).Error
  286. if err != nil {
  287. logrus.WithContext(ctx).Errorf("[GetAccountInfo] error query mysql total, err:%+v", err)
  288. return nil, 0, err
  289. }
  290. phoneMap := map[string]string{}
  291. for _, PlatformAccountInfo := range PlatformAccountInfos {
  292. if _, ok := phoneMap[PlatformAccountInfo.TalentID]; !ok {
  293. phoneMap[PlatformAccountInfo.TalentID] = getPhoneByTalentID(ctx, PlatformAccountInfo.TalentID)
  294. }
  295. }
  296. var accountInfoDatas []*http_model.AccountInfoData
  297. for _, PlatformAccountInfo := range PlatformAccountInfos {
  298. accountInfo := new(http_model.AccountInfoData)
  299. accountInfo.BindDate = conv.MustString(PlatformAccountInfo.BindDate, "")[0:19]
  300. accountInfo.Platform = consts.GetProjectPlatform(PlatformAccountInfo.PlatformID)
  301. accountInfo.PlatformNickname = PlatformAccountInfo.PlatformNickname
  302. accountInfo.TalentId = PlatformAccountInfo.TalentID
  303. accountInfo.Phone = phoneMap[PlatformAccountInfo.TalentID]
  304. accountInfo.Fans = util.GetNumString(PlatformAccountInfo.FansCount)
  305. accountInfo.HomePageUrl = PlatformAccountInfo.HomePageUrl
  306. accountInfo.HomePageCaptureUrl = PlatformAccountInfo.HomePageCaptureUrl
  307. accountInfoDatas = append(accountInfoDatas, accountInfo)
  308. }
  309. return accountInfoDatas, total, nil
  310. }
  311. func getPhoneByTalentID(ctx context.Context, talentID string) string {
  312. db := GetReadDB(ctx)
  313. talentInfo := gorm_model.YoungeeTalentInfo{}
  314. err := db.Debug().Where("id = ?", talentID).First(&talentInfo).Error
  315. if err != nil {
  316. if err == gorm.ErrRecordNotFound {
  317. return ""
  318. } else {
  319. return ""
  320. }
  321. }
  322. return talentInfo.TalentPhoneNumber
  323. }
  324. func DeleteAccount(ctx context.Context, PlatformID, PlatformNickname, TalentId string) error {
  325. db := GetReadDB(ctx)
  326. accountInfo := gorm_model.YoungeePlatformAccountInfo{}
  327. db = db.Debug().Where("talent_id = ? "+
  328. "AND platform_nickname = ? "+
  329. "AND platform_id = ?",
  330. TalentId, PlatformNickname, PlatformID).First(&accountInfo)
  331. err := db.Update("deleted", 1).Error
  332. if err != nil {
  333. logrus.WithContext(ctx).Errorf("[user db] call DeleteAccount error,err:%+v", err)
  334. return err
  335. }
  336. return nil
  337. }