view_user.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. // Copyright 2019 getensh.com. All rights reserved.
  2. // Use of this source code is governed by getensh.com.
  3. package model
  4. import (
  5. "cp-organization-management/errors"
  6. "fmt"
  7. "time"
  8. "encoding/json"
  9. "github.com/jaryhe/gopkgs/logger"
  10. "github.com/jaryhe/gopkgs/util"
  11. "github.com/jinzhu/gorm"
  12. "go.uber.org/zap"
  13. )
  14. type ViewUser struct {
  15. Id int64 `json:"id" gorm:"primary_key"`
  16. Username string `json:"username" gorm:"username;comment:'用户名';not null;default:''"`
  17. Passowrd string `json:"passowrd" gorm:"passowrd;comment:'密码';not null;default:''"`
  18. Phone string `json:"phone" gorm:"phone;commnet:'手机号';not null;default:''"`
  19. Email string `json:"email" gorm:"email;commnet:'电子邮件';not null;default:''"`
  20. IsSuperUser bool `json:"is_super_user" gorm:"is_super_user;commnet:'是否是超级账号,超级账号不能删除';not null;default:0"`
  21. GroupId int64 `json:"group_id" gorm:"group_id;commnet:'权限组id';not null;default:0"`
  22. //Zones string `json:"zones" gorm:"zones;commnet:'管辖区域列表';not null;default:''"`
  23. CreatedAt time.Time `json:"created_at" gorm:"created_at"`
  24. UpdatedAt time.Time `json:"updated_at" gorm:"updated_at"`
  25. Name string `json:"name" gorm:"name"`
  26. table string `json:"table"`
  27. ZoneCode string `json:"zone_code" gorm:"zone_code"`
  28. ZoneName string `json:"zone_name" gorm:"zone_name"`
  29. ZoneLevel int `json:"zone_level" gorm:"zone_level"`
  30. }
  31. func (p *ViewUser) TableName() string {
  32. return p.table
  33. }
  34. func NewViewUser(database string) *ViewUser {
  35. return &ViewUser{table: fmt.Sprintf("%s.%s", database, "view_user")}
  36. }
  37. func (p *ViewUser) CreateTable(db *gorm.DB) error {
  38. err := db.CreateTable(p).Error
  39. if err != nil {
  40. logger.Error("mysql",
  41. zap.String("sql", "create table "+p.TableName()),
  42. zap.String("fields", ""),
  43. zap.String("error", err.Error()))
  44. }
  45. return nil
  46. }
  47. func (p *ViewUser) Find(db *gorm.DB, where map[string]interface{}) error {
  48. err := db.Table(p.TableName()).Where(where).Find(p).Error
  49. if err != nil {
  50. fields, _ := util.MarshalToString(where)
  51. logger.Error("mysql",
  52. zap.String("sql", "select from "+p.TableName()),
  53. zap.String("fields", fields),
  54. zap.String("error", err.Error()))
  55. }
  56. return err
  57. }
  58. func (p *ViewUser) Last(db *gorm.DB) error {
  59. err := db.Table(p.TableName()).Last(p).Error
  60. if err != nil {
  61. logger.Error("mysql",
  62. zap.String("sql", "select last from "+p.TableName()),
  63. zap.String("fields", ""),
  64. zap.String("error", err.Error()))
  65. }
  66. return err
  67. }
  68. // Insert 插入一条记录
  69. func (p *ViewUser) Insert(db *gorm.DB) error {
  70. timeNow := time.Now()
  71. p.CreatedAt = timeNow
  72. p.UpdatedAt = timeNow
  73. err := db.Create(p).Error
  74. if err != nil {
  75. fields, _ := util.MarshalToString(*p)
  76. logger.Error("mysql",
  77. zap.String("sql", "insert into "+p.TableName()),
  78. zap.String("fields", fields),
  79. zap.String("error", err.Error()))
  80. }
  81. return err
  82. }
  83. func (p *ViewUser) Delete(db *gorm.DB, filter map[string]interface{}) error {
  84. err := db.Where(filter).Delete(p).Error
  85. if err != nil {
  86. fields, _ := util.MarshalToString(filter)
  87. logger.Error("mysql",
  88. zap.String("sql", "delete from "+p.TableName()),
  89. zap.String("fields", fields),
  90. zap.String("error", err.Error()))
  91. }
  92. return err
  93. }
  94. func (p *ViewUser) Save(db *gorm.DB) error {
  95. p.UpdatedAt = time.Now()
  96. err := db.Save(p).Error
  97. if err != nil {
  98. fields, _ := util.MarshalToString(*p)
  99. logger.Error("mysql",
  100. zap.String("sql", "save "+p.TableName()),
  101. zap.String("fields", fields),
  102. zap.String("error", err.Error()))
  103. }
  104. return err
  105. }
  106. func (p *ViewUser) Update(db *gorm.DB) error {
  107. p.UpdatedAt = time.Now()
  108. err := db.Model(p).Updates(p).Error
  109. if err != nil {
  110. fields, _ := util.MarshalToString(*p)
  111. logger.Error("mysql",
  112. zap.String("sql", "update "+p.TableName()),
  113. zap.String("fields", fields),
  114. zap.String("error", err.Error()))
  115. }
  116. return err
  117. }
  118. // 通过结构体变量更新字段值, gorm库会忽略零值字段。就是字段值等于0, nil, "", false这些值会被忽略掉,不会更新。如果想更新零值,可以使用map类型替代结构体。
  119. func (p *ViewUser) UpdateSome(db *gorm.DB, filed map[string]interface{}) error {
  120. if filed == nil {
  121. return errors.ParamsError
  122. }
  123. filed["updated_at"] = time.Now()
  124. err := db.Model(p).Updates(filed).Error
  125. if err != nil {
  126. fields, _ := util.MarshalToString(filed)
  127. logger.Error("mysql",
  128. zap.String("sql", "update "+p.TableName()),
  129. zap.String("fields", fields),
  130. zap.String("error", err.Error()))
  131. }
  132. return err
  133. }
  134. func (p *ViewUser) UpdateWithAffectRows(db *gorm.DB, where map[string]interface{}, values map[string]interface{}) (int64, error) {
  135. cond, val, err := whereBuild(where)
  136. if err != nil {
  137. return 0, err
  138. }
  139. r := db.Table(p.TableName()).Where(cond, val...).Updates(values)
  140. if r.Error != nil {
  141. fields, _ := json.Marshal(where)
  142. updateValues, _ := json.Marshal(values)
  143. logger.Error("mysql",
  144. zap.String("sql", "update "+p.TableName()),
  145. zap.String("fields", string(fields)),
  146. zap.String("values", string(updateValues)),
  147. zap.String("error", err.Error()))
  148. return 0, errors.DataBaseError
  149. }
  150. return r.RowsAffected, err
  151. }
  152. func (p *ViewUser) QueryAll(db *gorm.DB, filter map[string]interface{}, out interface{}) error {
  153. err := db.Table(p.TableName()).Where(filter).Find(out).Error
  154. if err != nil {
  155. fields, _ := util.MarshalToString(filter)
  156. logger.Error("mysql",
  157. zap.String("sql", "select from "+p.TableName()),
  158. zap.String("fields", fields),
  159. zap.String("error", err.Error()))
  160. }
  161. return err
  162. }
  163. func (p *ViewUser) List(db *gorm.DB, limit, offset int, out interface{}) error {
  164. err := db.Table(p.TableName()).Limit(limit).Offset(offset).Find(out).Error
  165. if err != nil {
  166. logger.Error("mysql",
  167. zap.String("sql", "select from "+p.TableName()),
  168. zap.String("fields", ""),
  169. zap.String("error", err.Error()))
  170. }
  171. return err
  172. }
  173. func (p *ViewUser) Count(db *gorm.DB, where map[string]interface{}, group string) (int64, error) {
  174. cond, val, err := whereBuild(where)
  175. if err != nil {
  176. return 0, err
  177. }
  178. ret := int64(0)
  179. err = db.Table(p.TableName()).Where(cond, val...).Group(group).Count(&ret).Error
  180. if err != nil {
  181. fields, _ := json.Marshal(where)
  182. logger.Error("mysql",
  183. zap.String("sql", "select count from "+p.TableName()),
  184. zap.String("fields", string(fields)),
  185. zap.String("error", err.Error()))
  186. return ret, errors.DataBaseError
  187. }
  188. return ret, err
  189. }
  190. func (p *ViewUser) CountOr(db *gorm.DB, where map[string]interface{}, or map[string]interface{}, group string) (int64, error) {
  191. cond, val, err := whereBuildAndOr(where, or)
  192. if err != nil {
  193. return 0, err
  194. }
  195. ret := int64(0)
  196. err = db.Table(p.TableName()).Where(cond, val...).Group(group).Count(&ret).Error
  197. if err != nil {
  198. fields, _ := json.Marshal(where)
  199. logger.Error("mysql",
  200. zap.String("sql", "select count from "+p.TableName()),
  201. zap.String("fields", string(fields)),
  202. zap.String("error", err.Error()))
  203. return ret, errors.DataBaseError
  204. }
  205. return ret, err
  206. }
  207. func (p *ViewUser) ListNew(db *gorm.DB, where map[string]interface{}, limit, offset int64, group string) (list []ViewUser, err error) {
  208. cond, val, err := whereBuild(where)
  209. if err != nil {
  210. return list, err
  211. }
  212. err = db.Table(p.TableName()).Where(cond, val...).Group(group).Limit(limit).Offset(offset).Find(&list).Error
  213. if err != nil {
  214. logger.Error("mysql",
  215. zap.String("sql", "select * from "+p.TableName()),
  216. zap.String("error", err.Error()))
  217. return list, errors.DataBaseError
  218. }
  219. return list, err
  220. }
  221. func (p *ViewUser) ListOr(db *gorm.DB, where map[string]interface{}, or map[string]interface{}, limit, offset int64, group string) (list []ViewUser, err error) {
  222. cond, val, err := whereBuildAndOr(where, or)
  223. if err != nil {
  224. return list, err
  225. }
  226. err = db.Table(p.TableName()).Where(cond, val...).Group(group).Limit(limit).Offset(offset).Find(&list).Error
  227. if err != nil {
  228. logger.Error("mysql",
  229. zap.String("sql", "select * from "+p.TableName()),
  230. zap.String("error", err.Error()))
  231. return list, errors.DataBaseError
  232. }
  233. return list, err
  234. }
  235. type UserListReq struct {
  236. Uid int64
  237. Limit int64
  238. Offset int64
  239. Filter string
  240. LoginUserSubZoneUserIds []int64
  241. LoginUserSubZone []string
  242. ZoneFilterUserIds []int64
  243. ParentIds string
  244. }
  245. type UserListItem struct {
  246. Id int64
  247. Name string
  248. Username string
  249. Phone string
  250. Email string
  251. Zones string
  252. }
  253. func userListSql(req *UserListReq, tablename string) (string, string, []interface{}) {
  254. where := ""
  255. args := []interface{}{}
  256. whereArray1 := []string{}
  257. whereArray2 := []string{}
  258. sql := fmt.Sprintf("select *, group_concat(zone_name) as zones from %s", tablename)
  259. whereArray1 = append(whereArray1, fmt.Sprintf("pids like '%s%%'", req.ParentIds))
  260. if len(req.LoginUserSubZoneUserIds) > 0 {
  261. whereArray1 = append(whereArray1, fmt.Sprintf("(id in (?) and zone_code in(?))"))
  262. args = append(args, req.LoginUserSubZoneUserIds)
  263. args = append(args, req.LoginUserSubZone)
  264. }
  265. countSql := fmt.Sprintf("select 1 from %s", tablename)
  266. whereArray2 = append(whereArray2, fmt.Sprintf("is_super_user=0"))
  267. whereArray2 = append(whereArray2, fmt.Sprintf("id<>%d", req.Uid))
  268. if req.Filter != "" {
  269. whereArray2 = append(whereArray2, fmt.Sprintf("(username like '%%%s%%' or name like '%%%s%%')", req.Filter, req.Filter))
  270. }
  271. if len(req.ZoneFilterUserIds) > 0 {
  272. whereArray2 = append(whereArray2, fmt.Sprintf("id in(?)"))
  273. args = append(args, req.ZoneFilterUserIds)
  274. }
  275. //whereArray = append(whereArray, fmt.Sprintf())
  276. for _, v := range whereArray1 {
  277. if where == "" {
  278. where = fmt.Sprintf("%s", v)
  279. continue
  280. }
  281. where = fmt.Sprintf("%s or %s", where, v)
  282. }
  283. where = fmt.Sprintf("where (%s)", where)
  284. for _, v := range whereArray2 {
  285. where = fmt.Sprintf("%s and %s", where, v)
  286. }
  287. sql = fmt.Sprintf("%s %s group by id limit %d offset %d", sql, where, req.Limit, req.Offset)
  288. countSql = fmt.Sprintf("%s %s group by id", countSql, where)
  289. countSql = fmt.Sprintf("select count(1) as count from (%s) as b", countSql)
  290. return countSql, sql, args
  291. }
  292. type ResultCount struct {
  293. Count int64
  294. }
  295. func (p *ViewUser)UserList(db *gorm.DB, req *UserListReq) ([]UserListItem, int64, error) {
  296. countSql, sql, args := userListSql(req, p.TableName())
  297. array := []ResultCount{}
  298. ret := []UserListItem{}
  299. var err error
  300. err = db.Raw(countSql, args...).Scan(&array).Error
  301. if err != nil {
  302. logger.Error("mysql",
  303. zap.String("sql", countSql),
  304. zap.String("error", err.Error()))
  305. return nil, 0, errors.DataBaseError
  306. }
  307. if len(array) == 0 {
  308. return nil, 0, nil
  309. }
  310. if array[0].Count == 0 {
  311. return nil, 0, nil
  312. }
  313. err = db.Raw(sql, args...).Scan(&ret).Error
  314. if err != nil {
  315. logger.Error("mysql",
  316. zap.String("sql", sql),
  317. zap.String("error", err.Error()))
  318. return nil, array[0].Count, errors.DataBaseError
  319. }
  320. return ret, array[0].Count, nil
  321. }
  322. func (p *ViewUser) GetUserIdBySubZones(db *gorm.DB, topLevel int, zones []string) ([]int64, error) {
  323. sql := fmt.Sprintf("select * from %s where not exists (select id from %s where zone_level <= %d) and zone_code in(?) group by id", p.TableName(), p.TableName(), topLevel)
  324. array := []ViewUser{}
  325. err := db.Raw(sql, zones).Scan(&array).Error
  326. if err != nil {
  327. logger.Error("mysql",
  328. zap.String("sql", sql),
  329. zap.String("error", err.Error()))
  330. return nil, errors.DataBaseError
  331. }
  332. ret := []int64{}
  333. for _, v := range array {
  334. ret = append(ret, v.Id)
  335. }
  336. return ret, nil
  337. }
  338. /*
  339. func Test(db *gorm.DB) {
  340. dbname := utils.GetDbName("001")
  341. // createViewSql := fmt.Sprintf("CREATE VIEW `%s`.`view_user` AS select t1.*, t2.zone_code from %s.t_rbac_user as t1 left join %s.t_user_zone as t2 on t1.id=t2.user_id;", dbname, dbname, dbname)
  342. // err := db.Exec(createViewSql).Error
  343. // fmt.Printf("%v\n", err)
  344. //return
  345. p := NewViewUser(dbname)
  346. where := map[string]interface{}{
  347. "zone_code in":[]string{"1", "2"},
  348. }
  349. cond, val, _ := whereBuild(where)
  350. list := []ViewUser{}
  351. db.Table(p.TableName()).Where(cond, val...).Group("").Limit(1).Offset(0).Find(&list)
  352. fmt.Printf("%v\n", list)
  353. var ret int64
  354. db.Table(p.TableName()).Where(cond, val...).Group("").Count(&ret)
  355. fmt.Printf("%v\n", ret)
  356. }
  357. */