user.go 16 KB

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