role_service.go 34KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016
  1. package service
  2. import (
  3. "XT_New/models"
  4. "XT_New/utils"
  5. "database/sql"
  6. "encoding/json"
  7. "fmt"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "github.com/jinzhu/gorm"
  12. )
  13. func GetRoles(orgID int64, appID int64, page int, count int) ([]*models.Role, int, error) {
  14. var roles []*models.Role
  15. var totalCount int
  16. err := readUserDb.Model(&models.Role{}).
  17. Where("org_id = ? AND app_id = ?", orgID, appID).
  18. Count(&totalCount).
  19. Order("ctime asc").Limit(count).Offset((page - 1) * count).
  20. Find(&roles).
  21. Error
  22. if err != nil {
  23. if err == gorm.ErrRecordNotFound {
  24. return make([]*models.Role, 0), 0, nil
  25. } else {
  26. return nil, 0, err
  27. }
  28. }
  29. return roles, totalCount, nil
  30. }
  31. func GetAppRole(orgID int64, appID int64, adminUserID int64) (*models.App_Role, error) {
  32. var appRole models.App_Role
  33. err := readUserDb.Model(models.App_Role{}).Preload("AdminUser", "status = 1").Where("org_id = ? and app_id = ? and admin_user_id = ?", orgID, appID, adminUserID).First(&appRole).Error
  34. if err != nil {
  35. if err == gorm.ErrRecordNotFound {
  36. return nil, nil
  37. } else {
  38. return nil, err
  39. }
  40. }
  41. if len(appRole.RoleIds) > 0 {
  42. role_ids := strings.Split(appRole.RoleIds, ",")
  43. for _, item := range role_ids {
  44. id, _ := strconv.ParseInt(item, 10, 64)
  45. if id != 0 {
  46. role, _ := GetRoleByRoleID(id)
  47. if role != nil {
  48. if role.IsSystem == 1 && role.RoleName == "子管理员" {
  49. appRole.IsSubSuperAdmin = true
  50. }
  51. }
  52. }
  53. }
  54. }
  55. return &appRole, nil
  56. }
  57. func CreateRole(adminUserID int64, orgID int64, appID int64, name string, intro string) (*models.Role, error) {
  58. role := models.Role{
  59. RoleName: name,
  60. RoleIntro: intro,
  61. Creator: adminUserID,
  62. OrgId: orgID,
  63. AppId: appID,
  64. IsSuperAdmin: false,
  65. Status: 1,
  66. CreateTime: time.Now().Unix(),
  67. ModifyTime: time.Now().Unix(),
  68. }
  69. tx := writeUserDb.Begin()
  70. if err := tx.Create(&role).Error; err != nil {
  71. tx.Rollback()
  72. return nil, err
  73. }
  74. tx.Commit()
  75. return &role, nil
  76. }
  77. func GetRoleByRoleID(roleID int64) (*models.Role, error) {
  78. var role models.Role
  79. err := readUserDb.Model(&models.Role{}).Where("id = ?", roleID).First(&role).Error
  80. if err != nil {
  81. if err == gorm.ErrRecordNotFound {
  82. return nil, nil
  83. }
  84. return nil, err
  85. } else {
  86. return &role, nil
  87. }
  88. }
  89. func ModifyRole(role *models.Role) error {
  90. tx := writeUserDb.Begin()
  91. if err := tx.Save(role).Error; err != nil {
  92. tx.Rollback()
  93. return err
  94. }
  95. return tx.Commit().Error
  96. }
  97. // 拥有xx角色的管理员的数量
  98. func RoleAdminUserCount(orgID int64, appID int64, roleID int64) (int, error) {
  99. var count int
  100. err := readUserDb.Model(models.App_Role{}).
  101. Where("org_id = ? AND app_id = ? AND role_id = ? AND status = 1", orgID, appID, roleID).
  102. Count(&count).
  103. Error
  104. if err != nil {
  105. return 0, err
  106. } else {
  107. return count, nil
  108. }
  109. }
  110. type AdminUserManageViewModel struct {
  111. AdminUserId int `gorm:"admin_user_id" json:"user_id"`
  112. UserName string `gorm:"user_name" json:"user_name"`
  113. RoleName string `gorm:"role_name" json:"role_name"`
  114. UserTitle int `gorm:"user_title" json:"user_title"`
  115. Ip string `gorm:"ip" json:"ip"`
  116. Ctime int64 `gorm:"ctime" json:"last_login_time"`
  117. Status int `gorm:"status" json:"status"`
  118. Avatar string `gorm:"avatar" json:"avatar"`
  119. RoleIds string `gorm:"role_ids" json:"role_ids"`
  120. // LastLoginTimeStr string `gorm:"-" json:"last_login_time_formatted"`
  121. TitleName string `gorm:"-" json:"title_name"`
  122. IsSubSuperAdmin bool `gorm:"-" json:"is_sub_super_admin"`
  123. //mobile string `gorm:"-" json:"mobile"`
  124. Sort int `gorm:"sort" json:"sort"`
  125. IsMark int `gorm:"is_mark" json:"is_mark"`
  126. UserType int `gorm:"user_type" json:"user_type"`
  127. DoctorNumber string `gorm:"column:doctor_number" json:"doctor_number" form:"doctor_number"`
  128. }
  129. func GetAdminUsersAndLoginInfo(orgID int64, appID int64, page int, count int) ([]*AdminUserManageViewModel, int, error) {
  130. if count <= 0 {
  131. return []*AdminUserManageViewModel{}, 0, nil
  132. }
  133. if page < 1 {
  134. page = 1
  135. }
  136. var viewModels []*AdminUserManageViewModel = make([]*AdminUserManageViewModel, 0)
  137. rows, err := readUserDb.Raw("SELECT u_a_r.admin_user_id, u_a_r.user_name,u_a_r.doctor_number, u_a_r.user_title, u_l.ip, u_l.ctime, u_a_r.status,u_a_r.avatar,u_a_r.role_ids,u_a_r.sort,u_a_r.is_mark,u_a_r.user_type FROM sgj_user_admin_role AS u_a_r LEFT JOIN (SELECT * FROM (SELECT admin_user_id, org_id, app_id, ip, ctime FROM sgj_user_admin_login_log WHERE org_id = ? AND app_id = ? ORDER BY ctime DESC) AS t GROUP BY admin_user_id) AS u_l ON u_a_r.org_id = u_l.org_id AND u_a_r.app_id = u_l.app_id AND u_a_r.admin_user_id = u_l.admin_user_id WHERE u_a_r.org_id = ? AND u_a_r.app_id = ? GROUP BY u_a_r.admin_user_id LIMIT ? OFFSET ?;", orgID, appID, orgID, appID, count, (page-1)*count).Rows()
  138. defer rows.Close()
  139. if err != nil {
  140. if err == gorm.ErrRecordNotFound {
  141. return viewModels, 0, nil
  142. } else {
  143. return nil, 0, err
  144. }
  145. }
  146. for rows.Next() {
  147. var viewModel AdminUserManageViewModel
  148. readUserDb.ScanRows(rows, &viewModel)
  149. title, _ := models.UserTitle[viewModel.UserTitle]
  150. viewModel.TitleName = title
  151. // if viewModel.Ctime == 0 {
  152. // viewModel.LastLoginTimeStr = ""
  153. // } else {
  154. // loginTime := time.Unix(viewModel.Ctime, 0)
  155. // viewModel.LastLoginTimeStr = loginTime.Format("2006-01-02 15:04")
  156. // }
  157. viewModels = append(viewModels, &viewModel)
  158. }
  159. for _, item := range viewModels {
  160. if len(item.RoleIds) > 0 {
  161. ids := strings.Split(item.RoleIds, ",")
  162. for _, id := range ids {
  163. id, _ := strconv.ParseInt(id, 10, 64)
  164. if id != 0 {
  165. role, _ := GetRoleByRoleID(id)
  166. if role != nil {
  167. if role.IsSystem == 1 && role.RoleName == "子管理员" {
  168. item.IsSubSuperAdmin = true
  169. }
  170. if len(item.RoleName) == 0 {
  171. item.RoleName = role.RoleName
  172. } else {
  173. item.RoleName = item.RoleName + "," + role.RoleName
  174. }
  175. }
  176. }
  177. }
  178. }
  179. //admin, _ := GetAdminUserByUserID(int64(item.AdminUserId))
  180. //item.mobile = admin.Mobile
  181. }
  182. total := 0
  183. //readUserDb.Table("sgj_user_admin_role as u_a_r").Joins("join sgj_user_role as u_r on u_r.org_id = u_a_r.org_id AND u_r.app_id = u_a_r.app_id AND u_r.id = u_a_r.role_id").Where("u_a_r.org_id = ? AND u_a_r.app_id = ?", orgID, appID).Count(&total)
  184. return viewModels, total, nil
  185. }
  186. func GetValidRoleCount(orgID int64, appID int64, superAdminUserID int64) (int, error) {
  187. var count int
  188. err := readUserDb.Model(models.Role{}).
  189. Where("org_id = ? AND app_id = ? AND creator = ? AND is_super_admin = 0 AND status = 1", orgID, appID, superAdminUserID).
  190. Count(&count).
  191. Error
  192. if err != nil {
  193. return 0, err
  194. } else {
  195. return count, nil
  196. }
  197. }
  198. func GetAllValidRoles(orgID int64, appID int64) ([]*models.Role, error) {
  199. var roles []*models.Role
  200. err := readUserDb.Model(models.Role{}).
  201. Where("org_id = ? AND app_id = ? AND status = 1", orgID, appID).
  202. Order("number desc,ctime").
  203. Find(&roles).
  204. Error
  205. if err != nil {
  206. if err == gorm.ErrRecordNotFound {
  207. return make([]*models.Role, 0), nil
  208. } else {
  209. return nil, err
  210. }
  211. }
  212. return roles, nil
  213. }
  214. func IsRoleExist(orgID int64, appID int64, roleID int64) (bool, error) {
  215. var count int
  216. err := readUserDb.Model(models.Role{}).Where("org_id = ? AND app_id = ? AND id = ? AND status = 1", orgID, appID, roleID).Count(&count).Error
  217. if err != nil {
  218. return false, err
  219. } else {
  220. return count > 0, nil
  221. }
  222. }
  223. type AdminUserEditViewModel struct {
  224. AdminUserId int64 `gorm:"admin_user_id" json:"user_id"`
  225. UserName string `gorm:"user_name" json:"user_name"`
  226. Mobile string `gorm:"mobile" json:"mobile"`
  227. UserType int `gorm:"user_type" json:"user_type"`
  228. UserTitle int `gorm:"user_title" json:"user_title"`
  229. Intro string `gorm:"intro" json:"intro"`
  230. RoleId int64 `gorm:"role_id" json:"role_id"`
  231. }
  232. func GetGeneralAdminUser(orgID int64, appID int64, user_id int64) (*AdminUserEditViewModel, error) {
  233. rows, err := readUserDb.Raw("SELECT u_a.mobile, u_a_r.admin_user_id, u_a_r.user_name, u_a_r.user_type, u_a_r.user_title, u_a_r.intro, u_a_r.role_id FROM sgj_user_admin AS u_a, sgj_user_admin_role AS u_a_r WHERE u_a.id = u_a_r.admin_user_id AND u_a.id = ? AND u_a_r.status = 1 AND u_a_r.org_id = ? AND u_a_r.app_id = ?;", user_id, orgID, appID).Rows()
  234. defer rows.Close()
  235. if err != nil {
  236. if err == gorm.ErrRecordNotFound {
  237. return nil, nil
  238. } else {
  239. return nil, err
  240. }
  241. }
  242. if rows.Next() {
  243. var viewModel AdminUserEditViewModel
  244. err := readUserDb.ScanRows(rows, &viewModel)
  245. if err != nil {
  246. return nil, err
  247. } else {
  248. return &viewModel, nil
  249. }
  250. }
  251. return nil, nil
  252. }
  253. func SaveAppRole(appRole *models.App_Role) error {
  254. tx := writeUserDb.Begin()
  255. if err := tx.Model(&models.App_Role{}).Save(appRole).Error; err != nil {
  256. tx.Rollback()
  257. return err
  258. }
  259. var tmp models.Org
  260. //根据机构id查询管理员id
  261. tx.Model(&models.Org{}).Where("status = 1 and id = ?", appRole.OrgId).Find(&tmp)
  262. //如果相等则修改管理员的姓名
  263. if tmp.Creator == appRole.AdminUserId {
  264. err = tx.Model(&models.AdminUser{}).Where("id = ?", appRole.AdminUserId).Updates(map[string]interface{}{
  265. "mtime": time.Now().Unix(),
  266. "name": appRole.UserName,
  267. }).Error
  268. if err != nil {
  269. tx.Rollback()
  270. return err
  271. }
  272. }
  273. return tx.Commit().Error
  274. }
  275. func IsMobileDidUsedAtApp(orgID int64, appID int64, mobile string) (bool, error) {
  276. var count int
  277. rows, err := readUserDb.Raw("select count(u_a.id) as count from sgj_user_admin as u_a, sgj_user_admin_role as u_a_r where u_a_r.org_id = ? and u_a_r.app_id = ? and u_a.mobile = ? and u_a.id = u_a_r.admin_user_id;", orgID, appID, mobile).Rows()
  278. defer rows.Close()
  279. if err != nil {
  280. if err == gorm.ErrRecordNotFound {
  281. return false, nil
  282. } else {
  283. return true, err
  284. }
  285. }
  286. if rows.Next() {
  287. rows.Scan(&count)
  288. return count > 0, nil
  289. }
  290. return true, nil
  291. }
  292. func IsUserSuperAdminWithMobile(mobile string) (bool, error) {
  293. var user models.AdminUser
  294. err := readUserDb.Where("mobile = ?", mobile).First(&user).Error
  295. if err != nil {
  296. if err == gorm.ErrRecordNotFound {
  297. return false, nil
  298. } else {
  299. return false, err
  300. }
  301. }
  302. return user.IsSuperAdmin, nil
  303. }
  304. func CreateGeneralAdminUserOne(orgID int64, appID int64, mobile string, name string, userTitle string, roleIds string, user_type int, user_title int, department_id int64, deapartment_name string, sex int64, age int64, nation string, card_type int64, idCard string, education int64, studyMajorName string, workMajorName string, roletype int64, medicalCode string, doctorcode string, licensing int64, jobnumber string, prescriptionQualificationIdentification int64, identificationOutpatients int64, startime int64, medicalRangeCode int64, medicalLevel int64, medicalTypeJob int64, pharmacistRegistrationNumber string, doctorRangeCode int64, doctorLevel int64, doctorTypeJob int64, doctorNumber string, outpatientIllnessCategory string, isActive int64, activeStatus int64) (*models.AdminUser, string, error) {
  305. now := time.Now().Unix()
  306. tx := writeUserDb.Begin()
  307. var adminUser models.AdminUser
  308. err := readUserDb.Where("mobile = ? AND status = 1", mobile).First(&adminUser).Error
  309. password := ""
  310. if err != nil {
  311. if err != gorm.ErrRecordNotFound {
  312. return nil, "", err
  313. } else {
  314. password = utils.RandomNumberString(6)
  315. adminUser.Mobile = mobile
  316. adminUser.Password = utils.String2md5(password)
  317. adminUser.IsSuperAdmin = false
  318. adminUser.Status = 1
  319. adminUser.CreateTime = now
  320. adminUser.ModifyTime = now
  321. if createErr := tx.Create(&adminUser).Error; createErr != nil {
  322. tx.Rollback()
  323. return nil, "", createErr
  324. }
  325. }
  326. }
  327. app_role := models.App_Role{
  328. AdminUserId: adminUser.Id,
  329. OrgId: orgID,
  330. AppId: appID,
  331. Avatar: "",
  332. UserName: name,
  333. UserTitleName: userTitle,
  334. UserTitle: int8(user_title),
  335. UserType: int8(user_type),
  336. Status: 1,
  337. CreateTime: now,
  338. ModifyTime: now,
  339. RoleIds: roleIds,
  340. IsSort: 1,
  341. Department: deapartment_name,
  342. DepartmentId: department_id,
  343. Sex: sex,
  344. Age: age,
  345. Nation: nation,
  346. CardType: card_type,
  347. IdCard: idCard,
  348. Education: education,
  349. StudyMajorName: studyMajorName,
  350. WorkMajorName: workMajorName,
  351. RoleType: roletype,
  352. MedicalCode: medicalCode,
  353. DoctorCode: doctorcode,
  354. Licensing: licensing,
  355. JobNumber: jobnumber,
  356. PharmacistRegistrationNumber: pharmacistRegistrationNumber,
  357. IdentificationOutpatients: identificationOutpatients,
  358. StartTime: startime,
  359. MedicalRangeCode: medicalRangeCode,
  360. MedicalLevel: medicalLevel,
  361. MedicalTypeJob: medicalTypeJob,
  362. DoctorNumber: doctorNumber,
  363. OutpatientIllnesscategory: outpatientIllnessCategory,
  364. IsActive: isActive,
  365. ActiveStatus: activeStatus,
  366. PrescriptionQualificationIdentification: prescriptionQualificationIdentification,
  367. DoctorRangeCode: doctorRangeCode,
  368. DoctorTypeJob: doctorTypeJob,
  369. DoctorLevel: doctorLevel,
  370. }
  371. if createApp_RoleErr := tx.Create(&app_role).Error; createApp_RoleErr != nil {
  372. tx.Rollback()
  373. return nil, "", createApp_RoleErr
  374. }
  375. tx.Commit()
  376. return &adminUser, password, nil
  377. }
  378. func CreateGeneralAdminUser(orgID int64, appID int64, mobile string, name string, userTitle string, roleIds string, user_type int, user_title int, department_id int64, deapartment_name string) (*models.AdminUser, string, error) {
  379. now := time.Now().Unix()
  380. tx := writeUserDb.Begin()
  381. var adminUser models.AdminUser
  382. err := readUserDb.Where("mobile = ? AND status = 1", mobile).First(&adminUser).Error
  383. password := ""
  384. if err != nil {
  385. if err != gorm.ErrRecordNotFound {
  386. return nil, "", err
  387. } else {
  388. password = utils.RandomNumberString(6)
  389. adminUser.Mobile = mobile
  390. adminUser.Password = utils.String2md5(password)
  391. adminUser.IsSuperAdmin = false
  392. adminUser.Status = 1
  393. adminUser.CreateTime = now
  394. adminUser.ModifyTime = now
  395. if createErr := tx.Create(&adminUser).Error; createErr != nil {
  396. tx.Rollback()
  397. return nil, "", createErr
  398. }
  399. }
  400. }
  401. app_role := models.App_Role{
  402. AdminUserId: adminUser.Id,
  403. OrgId: orgID,
  404. AppId: appID,
  405. Avatar: "",
  406. UserName: name,
  407. UserTitleName: userTitle,
  408. UserTitle: int8(user_title),
  409. UserType: int8(user_type),
  410. Status: 1,
  411. CreateTime: now,
  412. ModifyTime: now,
  413. RoleIds: roleIds,
  414. IsSort: 1,
  415. Department: deapartment_name,
  416. DepartmentId: department_id,
  417. }
  418. if createApp_RoleErr := tx.Create(&app_role).Error; createApp_RoleErr != nil {
  419. tx.Rollback()
  420. return nil, "", createApp_RoleErr
  421. }
  422. tx.Commit()
  423. return &adminUser, password, nil
  424. }
  425. type PurviewTreeViewModel struct {
  426. ID int64 `json:"id"`
  427. PID int64 `json:"pid"`
  428. Name string `json:"name"`
  429. Childs []*PurviewTreeViewModel `json:"childs"`
  430. Number int64 `json:"number"`
  431. Url string `json:"url"`
  432. ParentUrl string `json:"parent_url"`
  433. }
  434. func GetAllGeneralPurviewVMsProcessed(module int) ([]*PurviewTreeViewModel, error) {
  435. var originPurviews []*models.Purview
  436. getPurviewErr := readUserDb.Model(models.Purview{}).Where("module = ? AND status = 1", module).Order("listorder asc").Order("id asc").Find(&originPurviews).Error
  437. if getPurviewErr != nil {
  438. return nil, getPurviewErr
  439. }
  440. // 加工这些规则:树形化
  441. purviewVMs := make([]*PurviewTreeViewModel, 0)
  442. pid_childs := make(map[int64][]*PurviewTreeViewModel)
  443. for _, purview := range originPurviews {
  444. // warning:下面这个算法只适用最多两层树形结构的菜单,对于两层以上的会丢失掉第三层及其以下的节点
  445. // 因为取出 originPurviews 的时候已经排过序了,所以顶级节点肯定最先处理,不需要担心子节点比父节点先处理
  446. pvm := &PurviewTreeViewModel{
  447. ID: purview.Id,
  448. PID: purview.Parentid,
  449. Name: purview.Name,
  450. Number: 2,
  451. }
  452. if purview.Parentid == 0 {
  453. purviewVMs = append(purviewVMs, pvm)
  454. } else {
  455. childs := pid_childs[purview.Parentid]
  456. if childs == nil {
  457. childs = make([]*PurviewTreeViewModel, 0)
  458. }
  459. childs = append(childs, pvm)
  460. pid_childs[purview.Parentid] = childs
  461. }
  462. }
  463. for _, vm := range purviewVMs {
  464. vm.Childs = pid_childs[vm.ID]
  465. }
  466. return purviewVMs, nil
  467. }
  468. // 用来处理树形结构
  469. func Totree(map1 map[int64]int64, map2 map[int64]*PurviewTreeViewModel, tmp int64) []*PurviewTreeViewModel {
  470. var j int //用来计数
  471. var tmp_purview []*PurviewTreeViewModel
  472. for k, v := range map1 {
  473. if v == tmp {
  474. tmp_purview = append(tmp_purview, map2[k])
  475. delete(map1, k)
  476. for k1, v1 := range tmp_purview {
  477. if k1 == j {
  478. v1.Childs = Totree(map1, map2, k)
  479. }
  480. }
  481. j++
  482. }
  483. }
  484. return tmp_purview
  485. }
  486. func GetAllGeneralFuncPurviewVMsProcessed() ([]*PurviewTreeViewModel, error) {
  487. var originPurviews []*models.SgjUserOperatePurview
  488. getPurviewErr := readUserDb.Model(models.SgjUserOperatePurview{}).Where(" status = 1").Order("number asc").Find(&originPurviews).Error
  489. if getPurviewErr != nil {
  490. return nil, getPurviewErr
  491. }
  492. // 加工这些规则:树形化
  493. purviewVMs := make([]*PurviewTreeViewModel, 0)
  494. for _, purview := range originPurviews {
  495. // warning:下面这个算法只适用最多两层树形结构的菜单,对于两层以上的会丢失掉第三层及其以下的节点
  496. // 因为取出 originPurviews 的时候已经排过序了,所以顶级节点肯定最先处理,不需要担心子节点比父节点先处理
  497. pvm := &PurviewTreeViewModel{
  498. ID: purview.ID,
  499. PID: purview.Parentid,
  500. Name: purview.Name,
  501. }
  502. purviewVMs = append(purviewVMs, pvm)
  503. }
  504. return purviewVMs, nil
  505. }
  506. func GetRolePurviewIds(roleID int64) (string, error) {
  507. var rolePurview models.RolePurview
  508. err := readUserDb.Where("role_id = ?", roleID).First(&rolePurview).Error
  509. if err != nil {
  510. if err == gorm.ErrRecordNotFound {
  511. return "", nil
  512. } else {
  513. return "", err
  514. }
  515. }
  516. return rolePurview.PurviewIds, nil
  517. }
  518. func SaveRolePurviewIds(orgID int64, appID int64, roleID int64, purviewIds string) error {
  519. var rolePurview models.RolePurview
  520. getRPErr := readUserDb.Where("org_id = ? AND app_id = ? AND role_id = ?", orgID, appID, roleID).First(&rolePurview).Error
  521. if getRPErr != nil {
  522. if getRPErr == gorm.ErrRecordNotFound {
  523. rolePurview = models.RolePurview{
  524. RoleId: roleID,
  525. OrgId: orgID,
  526. AppId: appID,
  527. Status: 1,
  528. CreateTime: time.Now().Unix(),
  529. }
  530. } else {
  531. return getRPErr
  532. }
  533. }
  534. rolePurview.PurviewIds = purviewIds
  535. rolePurview.ModifyTime = time.Now().Unix()
  536. tx := writeUserDb.Begin()
  537. if err := tx.Save(&rolePurview).Error; err != nil {
  538. tx.Rollback()
  539. return err
  540. }
  541. return tx.Commit().Error
  542. }
  543. func SaveFuncRolePurviewIds(orgID int64, appID int64, roleID int64, funcPurviewIds string) error {
  544. var rolePurview models.SgjUserRoleFuncPurview
  545. getRPErr := readUserDb.Where("org_id = ? AND app_id = ? AND role_id = ?", orgID, appID, roleID).First(&rolePurview).Error
  546. if getRPErr != nil {
  547. if getRPErr == gorm.ErrRecordNotFound {
  548. rolePurview = models.SgjUserRoleFuncPurview{
  549. RoleId: roleID,
  550. OrgId: orgID,
  551. AppId: appID,
  552. Status: 1,
  553. Ctime: time.Now().Unix(),
  554. }
  555. } else {
  556. return getRPErr
  557. }
  558. }
  559. rolePurview.PurviewIds = funcPurviewIds
  560. rolePurview.Mtime = time.Now().Unix()
  561. tx := writeUserDb.Begin()
  562. if err := tx.Save(&rolePurview).Error; err != nil {
  563. tx.Rollback()
  564. return err
  565. }
  566. return tx.Commit().Error
  567. }
  568. func ModifyAdminUserInfo(adminUserID int64, orgID int64, appID int64, name string, avatar string, newPassword string) error {
  569. tx := writeUserDb.Begin()
  570. editInfoErr := tx.Exec("update sgj_user_admin_role set user_name = ?, avatar = ?, mtime = ? where admin_user_id = ? and org_id = ?", name, avatar, time.Now().Unix(), adminUserID, orgID).Error
  571. if editInfoErr != nil {
  572. tx.Rollback()
  573. return editInfoErr
  574. }
  575. if len(newPassword) > 0 {
  576. editPwdErr := tx.Exec("update sgj_user_admin set password = ?, mtime = ? where id = ?", newPassword, time.Now().Unix(), adminUserID).Error
  577. if editPwdErr != nil {
  578. tx.Rollback()
  579. return editPwdErr
  580. }
  581. }
  582. //这里加上
  583. err := tx.Model(&models.AdminUser{}).Where("id = ?", adminUserID).Updates(map[string]interface{}{
  584. "mtime": time.Now().Unix(),
  585. "name": name,
  586. }).Error
  587. if err != nil {
  588. tx.Rollback()
  589. return err
  590. }
  591. tx.Commit()
  592. return nil
  593. }
  594. func GetOrgApp(orgID int64, app_type int) (*models.OrgApp, error) {
  595. var apps models.OrgApp
  596. err := readUserDb.Where("app_type = ? AND org_id = ? AND status = 1", app_type, orgID).First(&apps).Error
  597. if err != nil {
  598. return nil, err
  599. }
  600. return &apps, nil
  601. }
  602. func GetAllOrgValidRoles(orgID int64, isSubSuperAdmin bool) ([]*models.Role, error) {
  603. var roles []*models.Role
  604. db := readUserDb.Model(models.Org{})
  605. if isSubSuperAdmin {
  606. db = db.Where("role_name != '子管理员' AND is_system != 1")
  607. }
  608. err := db.Where("org_id = ? AND status = 1", orgID).
  609. Order("number desc,ctime").
  610. Find(&roles).
  611. Error
  612. if err != nil {
  613. if err == gorm.ErrRecordNotFound {
  614. return make([]*models.Role, 0), nil
  615. } else {
  616. return nil, err
  617. }
  618. }
  619. for _, item := range roles {
  620. var total int64
  621. readUserDb.Model(&models.App_Role{}).Where("org_id = ? AND find_in_set(?, role_ids)", orgID, item.Id).Count(&total)
  622. item.StaffNumber = total
  623. }
  624. return roles, nil
  625. }
  626. func CreateUserRole(userRole *models.App_Role) (err error) {
  627. err = writeUserDb.Create(&userRole).Error
  628. return
  629. }
  630. func CreateOrgRole(role *models.Role) (err error) {
  631. err = writeUserDb.Create(&role).Error
  632. return
  633. }
  634. func GetRolePurview(roleID int64) (models.RolePurview, error) {
  635. var rolePurviews models.RolePurview
  636. var err error
  637. err = readUserDb.Where("role_id = ?", roleID).First(&rolePurviews).Error
  638. return rolePurviews, err
  639. }
  640. func GetFuncRolePurview(roleID int64) (models.SgjUserRoleFuncPurview, error) {
  641. var rolePurviews models.SgjUserRoleFuncPurview
  642. var err error
  643. err = readUserDb.Where("role_id = ?", roleID).First(&rolePurviews).Error
  644. return rolePurviews, err
  645. }
  646. func SaveRolePurview(purview *models.RolePurview) (err error) {
  647. err = writeUserDb.Save(&purview).Error
  648. return
  649. }
  650. func CreateRolePurview(purview *models.RolePurview) (err error) {
  651. err = writeUserDb.Create(&purview).Error
  652. return
  653. }
  654. func CreateFuncRolePurview(purview *models.SgjUserRoleFuncPurview) (err error) {
  655. err = writeUserDb.Create(&purview).Error
  656. return
  657. }
  658. func GetAllPurview(module int64, pid int64) ([]*models.Purview, error) {
  659. var originPurviews []*models.Purview
  660. getPurviewErr := readUserDb.Model(models.Purview{}).Preload("Purview", "status = 1").Where("module = ? AND status = 1 AND parentid = ? AND super_admin_exclusive = 0", module, pid).Order("listorder asc").Order("id asc").Find(&originPurviews).Error
  661. return originPurviews, getPurviewErr
  662. }
  663. type NewAdminUserModel struct {
  664. ID int64 `gorm:"id" json:"id"`
  665. AdminUserId int `gorm:"admin_user_id" json:"user_id"`
  666. UserName string `gorm:"user_name" json:"user_name"`
  667. UserTitle int `gorm:"user_title_name" json:"user_title_name"`
  668. Ip string `gorm:"ip" json:"ip"`
  669. Ctime int64 `gorm:"ctime" json:"last_login_time"`
  670. Status int `gorm:"status" json:"status"`
  671. Avatar string `gorm:"avatar" json:"avatar"`
  672. RoleIds string `gorm:"role_ids" json:"role_ids"`
  673. IsSubAdmin bool `gorm:"-" json:"is_sub_admin"`
  674. }
  675. func GetAllAdminUsersAndRole(orgID int64, appID int64, page int, count int) ([]*NewAdminUserModel, int, error) {
  676. var viewModels []*NewAdminUserModel = make([]*NewAdminUserModel, 0)
  677. var rows *sql.Rows
  678. var err error
  679. rows, err = readUserDb.Raw("SELECT u_a_r.id, u_a_r.admin_user_id, u_a_r.user_name, u_a_r.user_title, u_a_r.status,u_a_r.avatar,u_a_r.role_ids FROM sgj_user_admin_role AS u_a_r WHERE org_id = ? AND app_id = ? ORDER BY ctime asc", orgID, appID).Rows()
  680. defer rows.Close()
  681. if err != nil {
  682. if err == gorm.ErrRecordNotFound {
  683. return viewModels, 0, nil
  684. } else {
  685. return nil, 0, err
  686. }
  687. }
  688. for rows.Next() {
  689. var viewModel NewAdminUserModel
  690. readUserDb.ScanRows(rows, &viewModel)
  691. viewModels = append(viewModels, &viewModel)
  692. }
  693. for _, items := range viewModels {
  694. if len(items.RoleIds) > 0 {
  695. ids := strings.Split(items.RoleIds, ",")
  696. for _, ids := range ids {
  697. id, _ := strconv.ParseInt(ids, 10, 64)
  698. if id != 0 {
  699. role, _ := GetRoleByRoleID(id)
  700. if role != nil {
  701. if role.IsSystem == 1 && role.RoleName == "子管理员" {
  702. items.IsSubAdmin = true
  703. }
  704. }
  705. }
  706. }
  707. }
  708. }
  709. total := 0
  710. return viewModels, total, nil
  711. }
  712. func FindAdminUserByID(admin_user_id int64, org_id int64) (total int64, err error) {
  713. err = readUserDb.Model(&models.App_Role{}).Where("admin_user_id = ? AND org_id = ?", admin_user_id, org_id).Count(&total).Error
  714. return
  715. }
  716. func GetRoleAndPurviewById(role_id int64, org_id int64, app_id int64) (rolePurview models.RolePurview, err error) {
  717. err = readUserDb.Model(&models.RolePurview{}).Preload("Role", "status = 1").Where("role_id = ? AND status = 1 AND org_id = ? AND app_id = ?", role_id, org_id, app_id).First(&rolePurview).Error
  718. return
  719. }
  720. func SaveRole(role *models.Role) (err error) {
  721. err = writeUserDb.Save(&role).Error
  722. return
  723. }
  724. // 拥有xx角色的管理员的数量
  725. func RoleAdminUserCountTwo(orgID int64, appID int64, roleID int64) (int, error) {
  726. var count int
  727. err := readUserDb.Model(models.App_Role{}).
  728. Where("org_id = ? AND app_id = ? AND find_in_set(?, role_ids)", orgID, appID, roleID).
  729. Count(&count).
  730. Error
  731. if err != nil {
  732. return 0, err
  733. } else {
  734. return count, nil
  735. }
  736. }
  737. func FindAdminUserID(id int64) (role models.App_Role, err error) {
  738. err = readUserDb.Model(&models.App_Role{}).Where("id = ?", id).First(&role).Error
  739. return
  740. }
  741. func SaveAdminUser(role *models.App_Role) (err error) {
  742. err = writeUserDb.Save(&role).Error
  743. return
  744. }
  745. func GetFunctionPurview(pid int64) (purview []*models.SgjUserOperatePurview, err error) {
  746. err = readUserDb.Model(&models.SgjUserOperatePurview{}).Where("status = 1 AND parentid = ?", pid).Order("number asc").Find(&purview).Error
  747. return
  748. }
  749. func GetRoleFuncPurviewIds(roleID int64) (string, error) {
  750. var rolePurview models.SgjUserRoleFuncPurview
  751. err := readUserDb.Where("role_id = ?", roleID).First(&rolePurview).Error
  752. if err != nil {
  753. if err == gorm.ErrRecordNotFound {
  754. return "", nil
  755. } else {
  756. return "", err
  757. }
  758. }
  759. return rolePurview.PurviewIds, nil
  760. }
  761. func GetRoleFuncPurview(roleID int64) (rolePurviews models.SgjUserRoleFuncPurview, err error) {
  762. err = readUserDb.Where("role_id = ?", roleID).First(&rolePurviews).Error
  763. return
  764. }
  765. func SaveRoleFuncPurview(purview *models.SgjUserRoleFuncPurview) (err error) {
  766. err = writeUserDb.Save(purview).Error
  767. return
  768. }
  769. func GetUserAllRole(org_id int64, admin_user_id int64) (role models.App_Role, err error) {
  770. redis := RedisClient()
  771. defer redis.Close()
  772. // cur_date := time.Now().Format("2006-01-02")
  773. key := "user_all_role:" + strconv.FormatInt(org_id, 10) + ":" + strconv.FormatInt(admin_user_id, 10)
  774. role_str, _ := redis.Get(key).Result()
  775. if len(role_str) == 0 { //没有到缓存数据,从数据库中获取数据,进行缓存到redis
  776. err = readUserDb.Model(&models.App_Role{}).Where("status = 1 AND org_id = ? AND admin_user_id = ?", org_id, admin_user_id).First(&role).Error
  777. if err != nil {
  778. if err == gorm.ErrRecordNotFound {
  779. return role, nil
  780. } else {
  781. return role, err
  782. }
  783. } else {
  784. if role.Id > 0 {
  785. //缓存数据
  786. role_json, err := json.Marshal(role)
  787. if err == nil {
  788. redis.Set(key, role_json, time.Second*60*60*18)
  789. }
  790. }
  791. return role, nil
  792. }
  793. } else { //缓存数据了数据,将redis缓存的json字符串转为map
  794. if err := json.Unmarshal([]byte(role_str), &role); err == nil {
  795. } else {
  796. }
  797. return role, nil
  798. }
  799. }
  800. func GetAllFunctionPurview() (purview []models.SgjUserOperatePurview, err error) {
  801. err = readUserDb.Model(&models.SgjUserOperatePurview{}).Where("status = 1 ").Order("number asc").Find(&purview).Error
  802. return
  803. }
  804. func FindErrorMsgByStr(str string) (string, error) {
  805. var purview models.SgjUserOperatePurview
  806. var err error
  807. err = readUserDb.Model(&models.SgjUserOperatePurview{}).Where("find_in_set(?, urlfor)", str).First(&purview).Error
  808. return purview.ErrorMsg, err
  809. }
  810. func GetNewAllOrgValidRoles(orgID int64) ([]*models.Role, error) {
  811. var roles []*models.Role
  812. db := readUserDb.Model(models.Org{})
  813. err := db.Where("org_id = ? AND status = 1", orgID).
  814. Order("number desc,ctime").
  815. Find(&roles).
  816. Error
  817. if err != nil {
  818. if err == gorm.ErrRecordNotFound {
  819. return make([]*models.Role, 0), nil
  820. } else {
  821. return nil, err
  822. }
  823. }
  824. for _, item := range roles {
  825. var total int64
  826. readUserDb.Model(&models.App_Role{}).Where("org_id = ? AND find_in_set(?, role_ids)", orgID, item.Id).Count(&total)
  827. item.StaffNumber = total
  828. }
  829. return roles, nil
  830. }
  831. func FindRoleRecordByRoleName(name string, org_id int64) (total int64) {
  832. readUserDb.Model(&models.Role{}).Where("status = 1 AND role_name = ? AND org_id = ?", name, org_id).Count(&total)
  833. return
  834. }
  835. func FindAllFuncPurview(ids []string) (purview []*models.SgjUserOperatePurview, err error) {
  836. err = readUserDb.Model(&models.SgjUserOperatePurview{}).Where("status = 1 AND id in (?)", ids).Order("number asc").Find(&purview).Error
  837. return
  838. }
  839. func GetSystemPurview() (purview []*models.Purview, err error) {
  840. err = readUserDb.Model(&models.Purview{}).Where("status = 1 AND module = 3 AND super_admin_exclusive = 1").Find(&purview).Error
  841. return
  842. }
  843. func GetAllSystemPurview() (purview []*models.Purview, err error) {
  844. err = readUserDb.Model(&models.Purview{}).Where("status = 1 AND module = 3 ").Find(&purview).Error
  845. return
  846. }
  847. type Purview struct {
  848. Id int64 `gorm:"PRIMARY_KEY;AUTO_INCREMENT" json:"id"`
  849. Parentid int64 `json:"pid"` // 父级ID
  850. Module int8 `json:"module"` // 所属应用类型 1.病友经营;2.科普号;3.血透经营;4.慢病管理;
  851. Name string `json:"name"` // 规则名称(也是菜单名)
  852. Urlfor string `json:"urlfor"` // 规则唯一英文标识,(Controller.Method)
  853. MenuIconClass string `gorm:"menu_icon_class" json:"menu_icon_class"` // 菜单图标的 css 样式
  854. SuperAdminExclusive int8 `gorm:"super_admin_exclusive" json:"super_admin_exclusive"` // 是否为超级管理员专属 0否1是
  855. Listorder int `json:"-"` // 排序ID
  856. Status int8 `json:"status"` // 状态 0.无效 1.有效 2.禁用
  857. CreateTime int64 `gorm:"column:ctime" json:"-"` // 创建时间
  858. ModifyTime int64 `gorm:"column:mtime" json:"-"` // 修改时间
  859. Purview []*Purview `gorm:"ForeignKey:Parentid;AssociationForeignKey:ID" json:"sub_purview"`
  860. IconUrl string `gorm:"column:icon_url" json:"icon_url" form:"icon_url"`
  861. Desc string `gorm:"column:desc" json:"desc" form:"desc"`
  862. ParentUrl string `gorm:"column:parent_url" json:"parent_url" form:"parent_url"`
  863. Link string `gorm:"-" json:"link"` // urlfor 解析后的链接
  864. Childs []*Purview `gorm:"-" json:"childs"` // 子节点
  865. }
  866. func (Purview) TableName() string {
  867. return "sgj_user_purview"
  868. }
  869. func GetNewAllPurview(url string) ([]*Purview, error) {
  870. var originPurviews []*Purview
  871. getPurviewErr := readUserDb.Model(Purview{}).Preload("Purview", "status = 1").Where("parent_url = ? AND status = 1", url).Order("listorder asc").Order("id asc").Find(&originPurviews).Error
  872. return originPurviews, getPurviewErr
  873. }
  874. func GetOtherNewAllPurview(url string) ([]*Purview, error) {
  875. var originPurviews []*Purview
  876. getPurviewErr := readUserDb.Model(Purview{}).Preload("Purview", func(db *gorm.DB) *gorm.DB {
  877. return db.Preload("Purview", "status = 1").Where("status = 1")
  878. }).Where("parent_url = ? AND status = 1", url).Order("listorder asc").Order("id asc").Find(&originPurviews).Error
  879. return originPurviews, getPurviewErr
  880. }
  881. func GetAllFuncPurview() ([]*models.SgjUserOperatePurview, error) {
  882. var originPurviews []*models.SgjUserOperatePurview
  883. getPurviewErr := readUserDb.Model(&models.SgjUserOperatePurview{}).Where(" status = 1").Error
  884. return originPurviews, getPurviewErr
  885. }
  886. func GetOtherAllGeneralPurviewVMsProcessed(url string) ([]*PurviewTreeViewModel, error, []*models.Purview) {
  887. var originPurviews []*models.Purview
  888. getPurviewErr := readUserDb.Model(Purview{}).Where("status = 1 AND parent_url = ?", url).Order("listorder asc").Order("id asc").Find(&originPurviews).Error
  889. if getPurviewErr != nil {
  890. return nil, getPurviewErr, nil
  891. }
  892. // 加工这些规则:树形化
  893. purviewVMs := make([]*PurviewTreeViewModel, 0)
  894. pid_childs := make(map[int64][]*PurviewTreeViewModel)
  895. fmt.Println(originPurviews)
  896. for _, purview := range originPurviews {
  897. // warning:下面这个算法只适用最多两层树形结构的菜单,对于两层以上的会丢失掉第三层及其以下的节点
  898. // 因为取出 originPurviews 的时候已经排过序了,所以顶级节点肯定最先处理,不需要担心子节点比父节点先处理
  899. pvm := &PurviewTreeViewModel{
  900. ID: purview.Id,
  901. PID: purview.Parentid,
  902. Name: purview.Name,
  903. Number: 2,
  904. ParentUrl: purview.ParentUrl,
  905. Url: purview.Urlfor,
  906. }
  907. if purview.Parentid == 0 {
  908. purviewVMs = append(purviewVMs, pvm)
  909. } else {
  910. childs := pid_childs[purview.Parentid]
  911. if childs == nil {
  912. childs = make([]*PurviewTreeViewModel, 0)
  913. }
  914. childs = append(childs, pvm)
  915. pid_childs[purview.Parentid] = childs
  916. }
  917. }
  918. for _, vm := range purviewVMs {
  919. vm.Childs = pid_childs[vm.ID]
  920. }
  921. return purviewVMs, nil, originPurviews
  922. }