role_service.go 32KB

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