user.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  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.Model([]gorm_model.YounggeeUser{}).Where("role = ? ", "3")
  161. if conditions.User != "" {
  162. userId := GetUserIDByEnterpriseID(ctx, conditions.User)
  163. db = db.Where("id = ?", userId)
  164. }
  165. // 根据 查询条件过滤
  166. conditionType := reflect.TypeOf(conditions).Elem()
  167. conditionValue := reflect.ValueOf(conditions).Elem()
  168. for i := 0; i < conditionType.NumField(); i++ {
  169. field := conditionType.Field(i)
  170. tag := field.Tag.Get("condition")
  171. value := conditionValue.FieldByName(field.Name)
  172. if !util.IsBlank(value) && tag != "created_at" && tag != "username" && tag != "user" {
  173. db = db.Debug().Where(fmt.Sprintf("%s = ?", tag), value.Interface())
  174. } else if tag == "created_at" && value.Interface() != nil {
  175. db = db.Where(fmt.Sprintf("created_at like '%s%%'", value.Interface()))
  176. } else if tag == "username" && value.Interface() != nil {
  177. db = db.Debug().Where(fmt.Sprintf("username like '%%%s%%'", value.Interface()))
  178. }
  179. }
  180. var totalUser int64
  181. if err := db.Count(&totalUser).Error; err != nil {
  182. logrus.WithContext(ctx).Errorf("[GetEnterpriseUserList] error query mysql total, err:%+v", err)
  183. return nil, 0, err
  184. }
  185. var users []gorm_model.YounggeeUser
  186. // 查询该页数据
  187. limit := pageSize
  188. offset := pageSize * pageNum // assert pageNum start with 0
  189. err := db.Order("created_at desc").Limit(int(limit)).Offset(int(offset)).Find(&users).Error
  190. if err != nil {
  191. logrus.WithContext(ctx).Errorf("[GetEnterpriseUserList] error query mysql total, err:%+v", err)
  192. return nil, 0, err
  193. }
  194. // 查询 用户自增的id
  195. var userIds []int64
  196. userMap := make(map[int64]gorm_model.YounggeeUser)
  197. for _, user := range users {
  198. userIds = append(userIds, user.ID)
  199. userMap[user.ID] = user
  200. }
  201. db1 := GetReadDB(ctx)
  202. var enterprises []gorm_model.Enterprise
  203. db1 = db1.Model(gorm_model.Enterprise{}).Where("user_id IN ?", userIds).Find(&enterprises)
  204. enterpriseMap := make(map[int64]gorm_model.Enterprise)
  205. for _, enterprise := range enterprises {
  206. enterpriseMap[enterprise.UserID] = enterprise
  207. }
  208. var enterpriseUsers []*http_model.EnterpriseUser
  209. for _, userId := range userIds {
  210. enterpriseUser := new(http_model.EnterpriseUser)
  211. _, ok1 := userMap[userId]
  212. _, ok2 := enterpriseMap[userId]
  213. if ok1 && ok2 {
  214. enterpriseUser.Enterprise = enterpriseMap[userId]
  215. enterpriseUser.YoungeeUser = userMap[userId]
  216. }
  217. enterpriseUsers = append(enterpriseUsers, enterpriseUser)
  218. }
  219. var enterpriseUserDatas []*http_model.EnterpriseUserPreview
  220. enterpriseUserDatas = pack.EnterpriseUserToEnterpriseUserData(enterpriseUsers)
  221. return enterpriseUserDatas, totalUser, nil
  222. }
  223. func GetCreatorList(ctx context.Context, pageSize, pageNum int32, conditions *common_model.CreatorListConditions) ([]*http_model.CreatorListPreview, int64, error) {
  224. db := GetReadDB(ctx)
  225. db = db.Debug().Model(gorm_model.YoungeeTalentInfo{}).Where("in_blacklist = ?", conditions.InBlacklist)
  226. // 根据 条件过滤
  227. conditionType := reflect.TypeOf(conditions).Elem()
  228. conditionValue := reflect.ValueOf(conditions).Elem()
  229. for i := 0; i < conditionType.NumField(); i++ {
  230. field := conditionType.Field(i)
  231. tag := field.Tag.Get("condition")
  232. value := conditionValue.FieldByName(field.Name)
  233. if !util.IsBlank(value) && tag != "create_date" && tag != "talent_wx_nickname" && tag != "id" {
  234. db = db.Debug().Where(fmt.Sprintf("%s = ?", tag), value.Interface())
  235. } else if tag == "create_date" && value.Interface() != nil {
  236. db = db.Where(fmt.Sprintf("create_date like '%s%%'", value.Interface()))
  237. } else if tag == "talent_wx_nickname" && value.Interface() != nil {
  238. db = db.Where(fmt.Sprintf("talent_wx_nickname like '%%%s%%'", value.Interface()))
  239. } else if tag == "id" && value.Interface() != nil {
  240. db = db.Where(fmt.Sprintf("id like '%%%s%%'", value.Interface()))
  241. }
  242. }
  243. // 查询总数
  244. var total int64
  245. var talentList []gorm_model.YoungeeTalentInfo
  246. if err := db.Count(&total).Error; err != nil {
  247. logrus.WithContext(ctx).Errorf("[GetCreatorList] error query mysql total, err:%+v", err)
  248. return nil, 0, err
  249. }
  250. // 查询该页数据
  251. limit := pageSize
  252. offset := pageSize * pageNum // assert pageNum start with 0
  253. err := db.Order("create_date desc").Limit(int(limit)).Offset(int(offset)).Find(&talentList).Error
  254. if err != nil {
  255. logrus.WithContext(ctx).Errorf("[GetCreatorList] error query mysql total, err:%+v", err)
  256. return nil, 0, err
  257. }
  258. var CreatorList []*http_model.CreatorListPreview
  259. CreatorList = pack.TalentListToCreatorListData(talentList)
  260. return CreatorList, total, nil
  261. }
  262. func AccountInfo(ctx context.Context, pageSize, pageNum int32, conditions *common_model.AccountInfoConditions) ([]*http_model.AccountInfoData, int64, error) {
  263. db := GetReadDB(ctx)
  264. db = db.Debug().Model(gorm_model.YoungeePlatformAccountInfo{})
  265. // 根据 条件过滤
  266. conditionType := reflect.TypeOf(conditions).Elem()
  267. conditionValue := reflect.ValueOf(conditions).Elem()
  268. for i := 0; i < conditionType.NumField(); i++ {
  269. field := conditionType.Field(i)
  270. tag := field.Tag.Get("condition")
  271. value := conditionValue.FieldByName(field.Name)
  272. if !util.IsBlank(value) && tag != "bind_date" && tag != "fans_low" && tag != "fans_high" && tag != "platform_nickname" {
  273. db = db.Where(fmt.Sprintf("%s = ?", tag), value.Interface())
  274. } else if tag == "bind_date" && value.Interface() != nil {
  275. db = db.Where(fmt.Sprintf("bind_date like '%s%%'", value.Interface()))
  276. }
  277. if !util.IsBlank(value) && tag == "fans_low" {
  278. db = db.Where(fmt.Sprintf("%s >= ?", "fans_count"), value.Interface())
  279. }
  280. if !util.IsBlank(value) && tag == "fans_high" {
  281. db = db.Where(fmt.Sprintf("%s <= ?", "fans_count"), value.Interface())
  282. }
  283. if !util.IsBlank(value) && tag == "platform_nickname" {
  284. db = db.Where(fmt.Sprintf("platform_nickname like '%%%s%%'", value.Interface()))
  285. }
  286. }
  287. db = db.Debug().Where("deleted = ?", 0)
  288. var total int64
  289. if err := db.Count(&total).Error; err != nil {
  290. logrus.WithContext(ctx).Errorf("[GetAccountInfo] error query mysql total, err:%+v", err)
  291. return nil, 0, err
  292. }
  293. var PlatformAccountInfos []*gorm_model.YoungeePlatformAccountInfo
  294. // 查询该页数据
  295. limit := pageSize
  296. offset := pageSize * pageNum // assert pageNum start with 0
  297. err := db.Order("bind_date desc").Limit(int(limit)).Offset(int(offset)).Find(&PlatformAccountInfos).Error
  298. if err != nil {
  299. logrus.WithContext(ctx).Errorf("[GetAccountInfo] error query mysql total, err:%+v", err)
  300. return nil, 0, err
  301. }
  302. phoneMap := map[string]string{}
  303. for _, PlatformAccountInfo := range PlatformAccountInfos {
  304. if _, ok := phoneMap[PlatformAccountInfo.TalentID]; !ok {
  305. phoneMap[PlatformAccountInfo.TalentID] = getPhoneByTalentID(ctx, PlatformAccountInfo.TalentID)
  306. }
  307. }
  308. var accountInfoDatas []*http_model.AccountInfoData
  309. for _, PlatformAccountInfo := range PlatformAccountInfos {
  310. accountInfo := new(http_model.AccountInfoData)
  311. accountInfo.BindDate = conv.MustString(PlatformAccountInfo.BindDate, "")[0:19]
  312. accountInfo.Platform = consts.GetProjectPlatform(PlatformAccountInfo.PlatformID)
  313. accountInfo.PlatformNickname = PlatformAccountInfo.PlatformNickname
  314. accountInfo.PlatformType = PlatformAccountInfo.PlatformType
  315. accountInfo.TalentId = PlatformAccountInfo.TalentID
  316. accountInfo.Phone = phoneMap[PlatformAccountInfo.TalentID]
  317. accountInfo.Fans = util.GetNumString(PlatformAccountInfo.FansCount)
  318. accountInfo.HomePageUrl = PlatformAccountInfo.HomePageUrl
  319. accountInfo.HomePageCaptureUrl = PlatformAccountInfo.HomePageCaptureUrl
  320. accountInfoDatas = append(accountInfoDatas, accountInfo)
  321. }
  322. return accountInfoDatas, total, nil
  323. }
  324. func getPhoneByTalentID(ctx context.Context, talentID string) string {
  325. db := GetReadDB(ctx)
  326. //talentInfo := gorm_model.YoungeeTalentInfo{}
  327. phoneNumber := ""
  328. err := db.Debug().Model(&gorm_model.YoungeeTalentDeliveryAddress{}).Select("phone_number").Where("talent_id = ?", talentID).First(&phoneNumber).Error
  329. if err != nil {
  330. if err == gorm.ErrRecordNotFound {
  331. return ""
  332. } else {
  333. return ""
  334. }
  335. }
  336. return phoneNumber
  337. }
  338. func DeleteAccount(ctx context.Context, PlatformID, PlatformNickname, TalentId string) error {
  339. db := GetReadDB(ctx)
  340. accountInfo := gorm_model.YoungeePlatformAccountInfo{}
  341. db = db.Debug().Where("talent_id = ? "+
  342. "AND platform_nickname = ? "+
  343. "AND platform_id = ?",
  344. TalentId, PlatformNickname, PlatformID).Find(&accountInfo)
  345. err := CreateMessage(context.Background(), 15, 2, accountInfo.TalentID, "")
  346. if err != nil {
  347. logrus.WithContext(context.Background()).Errorf("[user db] call CreateMessageByTaskId error,err:%+v", err)
  348. }
  349. err = db.Delete(&accountInfo).Error
  350. if err != nil {
  351. logrus.WithContext(ctx).Errorf("[user db] call DeleteAccount error,err:%+v", err)
  352. return err
  353. }
  354. return nil
  355. }
  356. func GetEnterpriseIds(ctx context.Context) (*http_model.EnterPriseIds, error) {
  357. var enterpriseIds []string
  358. db := GetReadDB(ctx)
  359. err := db.Model(gorm_model.Enterprise{}).Select("enterprise_id").Find(&enterpriseIds).Error
  360. if err != nil {
  361. logrus.WithContext(ctx).Errorf("[user db] call GetEnterpriseIds error,err:%+v", err)
  362. return nil, err
  363. }
  364. EnterpriseIds := http_model.EnterPriseIds{}
  365. EnterpriseIds.EnterPriseIds = enterpriseIds
  366. return &EnterpriseIds, nil
  367. }
  368. func ModifyAccInfo(ctx context.Context, req *http_model.ModifyAccInfoRequest) error {
  369. db := GetReadDB(ctx)
  370. return db.Model(gorm_model.YoungeePlatformAccountInfo{}).Where("account_id = ?", req.AccountId).Updates(
  371. gorm_model.YoungeePlatformAccountInfo{
  372. FansCount: req.Fans,
  373. PlatformNickname: req.PlatformNickname,
  374. HomePageUrl: req.HomePageUrl,
  375. HomePageCaptureUrl: req.HomePageCaptureUrl,
  376. UpdatedPerson: 1,
  377. UpdatedAdminID: req.User,
  378. }).Error
  379. }
  380. // 拉黑创作者
  381. func Block(ctx context.Context, data http_model.BlockRequest) error {
  382. err := Black(ctx, data.ID, data.InBlacklist)
  383. if err != nil {
  384. logrus.WithContext(ctx).Errorf("[project] call ChangeProjectStatus error,err:%+v", err)
  385. return err
  386. }
  387. return nil
  388. }
  389. func Black(ctx context.Context, ID string, InBlacklist uint) error {
  390. db := GetReadDB(ctx)
  391. talentInfo := gorm_model.YoungeeTalentInfo{}
  392. if err := db.Debug().Model(&talentInfo).
  393. Where("id = ?", ID).
  394. //Updates(gorm_model.YoungeeTalentInfo{InBlacklist: InBlacklist}). //这种方法置0不生效
  395. UpdateColumn("in_blacklist", InBlacklist).
  396. Error; err != nil {
  397. logrus.WithContext(ctx).Errorf("[ChangeProjectStatus] error query mysql total, err:%+v", err)
  398. return err
  399. }
  400. return nil
  401. }