user.go 14 KB

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