company.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. package service
  2. import (
  3. "cold-delivery/common/actions"
  4. cDto "cold-delivery/common/dto"
  5. "cold-delivery/common/global"
  6. "cold-delivery/common/nats/nats_server"
  7. "encoding/json"
  8. "errors"
  9. "fmt"
  10. "gogs.baozhida.cn/zoie/OAuth-core/service"
  11. "gorm.io/gorm"
  12. "gorm.io/gorm/clause"
  13. "cold-delivery/app/admin/model"
  14. "cold-delivery/app/admin/service/dto"
  15. "gogs.baozhida.cn/zoie/OAuth-core/pkg"
  16. )
  17. type Company struct {
  18. service.Service
  19. }
  20. // GetPage 获取Address列表
  21. func (e *Company) GetPage(c *dto.CompanyGetPageReq, list *[]model.SysDept, count *int64) error {
  22. var err error
  23. var data model.SysDept
  24. err = e.Orm.Model(&data).
  25. Scopes(
  26. cDto.MakeCondition(c.GetNeedSearch()),
  27. cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
  28. ).
  29. Find(list).Limit(-1).Offset(-1).
  30. Count(count).Error
  31. if err != nil {
  32. e.Log.Errorf("db error: %s", err)
  33. return global.GetFailedErr
  34. }
  35. return nil
  36. }
  37. func CompanyIdScopes(id int) func(db *gorm.DB) *gorm.DB {
  38. return func(db *gorm.DB) *gorm.DB {
  39. if id == 0 {
  40. return db
  41. }
  42. return db.Where("id = ? ", id)
  43. }
  44. }
  45. func (e *Company) GetAll(c *dto.CompanyGetAllReq, list *[]model.SysDept, count *int64, p *actions.DataPermission) error {
  46. var err error
  47. var data model.SysDept
  48. err = e.Orm.Model(&data).
  49. Scopes(
  50. CompanyIdScopes(p.DeptId),
  51. cDto.MakeCondition(c.GetNeedSearch()),
  52. ).
  53. Find(list).Limit(-1).Offset(-1).
  54. Count(count).Error
  55. if err != nil {
  56. e.Log.Errorf("db error: %s", err)
  57. return global.GetFailedErr
  58. }
  59. return nil
  60. }
  61. // Get 获取SysDept对象
  62. func (e *Company) Get(d *dto.CompanyGetReq, deptModel *model.SysDept) error {
  63. err := e.Orm.
  64. First(deptModel, d.GetId()).Error
  65. if err != nil {
  66. e.Log.Errorf("db error: %s", err)
  67. if errors.Is(err, gorm.ErrRecordNotFound) {
  68. return global.GetNotFoundOrNoPermissionErr
  69. }
  70. return global.GetFailedErr
  71. }
  72. return nil
  73. }
  74. // Insert 创建SysDept对象
  75. func (e *Company) Insert(c *dto.CompanyInsertReq) error {
  76. var err error
  77. var data model.SysDept
  78. tx := e.Orm.Debug().Begin()
  79. defer func() {
  80. if err != nil {
  81. tx.Rollback()
  82. } else {
  83. tx.Commit()
  84. }
  85. }()
  86. var i int64
  87. err = e.Orm.Model(&data).Where("name = ?", c.Name).Count(&i).Error
  88. if err != nil {
  89. e.Log.Errorf("db error: %s", err)
  90. return global.CreateFailedErr
  91. }
  92. if i > 0 {
  93. err = errors.New("公司名称已存在!")
  94. e.Log.Errorf("db error: %s", err)
  95. return err
  96. }
  97. var coldCompany nats_server.Company_R
  98. coldCompany, err = nats_server.Cold_ReadCompanyByT_key(c.ColdKey)
  99. if err != nil {
  100. e.Log.Errorf("获取3.0秘钥失败: %s", err)
  101. err = errors.New("冷链3.0公司秘钥错误!")
  102. return err
  103. }
  104. data.ColdPid = coldCompany.Id
  105. c.Generate(&data)
  106. err = tx.Create(&data).Error
  107. if err != nil {
  108. e.Log.Errorf("db error: %s", err)
  109. return global.CreateFailedErr
  110. }
  111. c.Id = data.Id
  112. deptPath := pkg.IntToString(data.Id) + "/"
  113. if data.ParentId != 0 {
  114. var deptP model.SysDept
  115. tx.First(&deptP, data.ParentId)
  116. deptPath = deptP.Path + deptPath
  117. } else {
  118. deptPath = "/0/" + deptPath
  119. }
  120. var mp = map[string]string{}
  121. mp["path"] = deptPath
  122. err = tx.Model(&data).Update("path", deptPath).Error
  123. if err != nil {
  124. e.Log.Errorf("db error: %s", err)
  125. return global.CreateFailedErr
  126. }
  127. return nil
  128. }
  129. // Update 修改SysDept对象
  130. func (e *Company) Update(c *dto.CompanyUpdateReq) error {
  131. var err error
  132. var deptModel = model.SysDept{}
  133. tx := e.Orm.Debug().Begin()
  134. defer func() {
  135. if err != nil {
  136. tx.Rollback()
  137. } else {
  138. tx.Commit()
  139. }
  140. }()
  141. err = tx.First(&deptModel, c.GetId()).Error
  142. if err != nil {
  143. e.Log.Errorf("db error: %s", err)
  144. if errors.Is(err, gorm.ErrRecordNotFound) {
  145. return global.UpdateNotFoundOrNoPermissionErr
  146. }
  147. return global.UpdateFailedErr
  148. }
  149. if c.ColdKey != deptModel.ColdKey {
  150. var coldCompany nats_server.Company_R
  151. coldCompany, err = nats_server.Cold_ReadCompanyByT_key(c.ColdKey)
  152. if err != nil {
  153. e.Log.Errorf("获取3.0秘钥失败: %s", err)
  154. err = errors.New("冷链3.0公司秘钥错误!")
  155. return err
  156. }
  157. deptModel.ColdPid = coldCompany.Id
  158. }
  159. c.Generate(&deptModel)
  160. DeptPath := pkg.IntToString(deptModel.Id) + "/"
  161. if deptModel.ParentId != 0 {
  162. var DeptP model.SysDept
  163. tx.First(&DeptP, deptModel.ParentId)
  164. DeptPath = DeptP.Path + DeptPath
  165. } else {
  166. DeptPath = "/0/" + DeptPath
  167. }
  168. deptModel.Path = DeptPath
  169. db := tx.Save(&deptModel)
  170. if err = db.Error; err != nil {
  171. e.Log.Errorf("UpdateSysDept error: %s", err)
  172. return err
  173. }
  174. return nil
  175. }
  176. // Remove 删除SysDept
  177. // 删除部门 同时删除其子部门、部门下的用户
  178. func (e *Company) Remove(d *dto.CompanyDeleteReq, p *actions.DataPermission) error {
  179. var err error
  180. tx := e.Orm.Begin()
  181. defer func() {
  182. if err != nil {
  183. tx.Rollback()
  184. } else {
  185. tx.Commit()
  186. }
  187. }()
  188. var dept model.SysDept
  189. err = e.Orm.
  190. First(&dept, d.GetId()).Error
  191. if err != nil {
  192. e.Log.Errorf("db error: %s", err)
  193. if errors.Is(err, gorm.ErrRecordNotFound) {
  194. return global.GetNotFoundOrNoPermissionErr
  195. }
  196. return global.DeleteFailedErr
  197. }
  198. var deptList = make([]model.SysDept, 0)
  199. var deptIds = make([]int, 0)
  200. tx.Where("path like ?", dept.Path+"%").Find(&deptList)
  201. // 获取部门及其子部门下ID
  202. for _, v := range deptList {
  203. deptIds = append(deptIds, v.Id)
  204. }
  205. db := tx.Select(clause.Associations).Delete(&deptList)
  206. if err = db.Error; err != nil {
  207. e.Log.Errorf("Delete error: %s", err)
  208. return global.DeleteFailedErr
  209. }
  210. if db.RowsAffected == 0 {
  211. return global.DeleteNotFoundOrNoPermissionErr
  212. }
  213. // 删除部门下的用户
  214. dbUser := tx.Where("dept_id in (?)", deptIds).Delete(&model.SysUser{})
  215. if err = dbUser.Error; err != nil {
  216. e.Log.Errorf("Delete User error: %s", err)
  217. return global.DeleteFailedErr
  218. }
  219. return nil
  220. }
  221. // SetDeptPage 设置Dept页面数据
  222. func (e *Company) SetDeptPage(c *dto.CompanyGetPageReq, p *actions.DataPermission) (m []model.SysDept, err error) {
  223. var list []model.SysDept
  224. err = e.getList(c, &list, p)
  225. for i := 0; i < len(list); i++ {
  226. if list[i].ParentId != 0 {
  227. continue
  228. }
  229. info := e.DeptPageCall(&list, list[i])
  230. m = append(m, info)
  231. }
  232. if len(m) == 0 {
  233. parentMap, flag := getDeptParent(list)
  234. if flag {
  235. for i := 0; i < len(list); i++ {
  236. if parentMap[list[i].ParentId] {
  237. continue
  238. }
  239. info := e.DeptPageCall(&list, list[i])
  240. m = append(m, info)
  241. }
  242. } else {
  243. for i := 0; i < len(list); i++ {
  244. info := e.DeptPageCall(&list, list[i])
  245. m = append(m, info)
  246. }
  247. }
  248. }
  249. return
  250. }
  251. func getDeptParent(deptList []model.SysDept) (map[int]bool, bool) {
  252. list := deptList
  253. var flag = false
  254. var parentMap = map[int]bool{}
  255. for j := 0; j < len(list); j++ {
  256. parentMap[list[j].ParentId] = false
  257. }
  258. for j := 0; j < len(list); j++ {
  259. if _, ok := parentMap[list[j].Id]; !ok {
  260. continue
  261. }
  262. parentMap[list[j].Id] = true
  263. flag = true
  264. }
  265. return parentMap, flag
  266. }
  267. // getList 获取组织数据
  268. func (e *Company) getList(c *dto.CompanyGetPageReq, list *[]model.SysDept, p *actions.DataPermission) error {
  269. var err error
  270. var data model.SysDept
  271. if len(c.Name) == 0 && p.DeptId == 0 {
  272. err = e.Orm.Model(&data).
  273. Scopes(
  274. cDto.MakeCondition(c.GetNeedSearch()),
  275. ).
  276. Find(list).Error
  277. if err != nil {
  278. e.Log.Errorf("db error:%s", err)
  279. return err
  280. }
  281. return nil
  282. }
  283. var tempList []model.SysDept
  284. err = e.Orm.Model(&data).Where("id in (select id from sys_dept where dept_path like ? )", "%/"+pkg.IntToString(p.DeptId)+"/%").
  285. Scopes(
  286. cDto.MakeCondition(c.GetNeedSearch()),
  287. ).
  288. Order("id desc").
  289. Find(&tempList).Error
  290. if err != nil {
  291. e.Log.Errorf("db error: %s", err)
  292. return global.GetFailedErr
  293. }
  294. // 获取部门及其子部门下ID
  295. for _, dept := range tempList {
  296. var deptList = make([]model.SysDept, 0)
  297. err = e.Orm.Where("dept_path like ?", dept.Path+"%").Order(fmt.Sprintf("sort %s", c.SortOrder)).Find(&deptList).Error
  298. *list = append(*list, deptList...)
  299. }
  300. if err != nil {
  301. e.Log.Errorf("db error: %s", err)
  302. return global.GetFailedErr
  303. }
  304. *list = DeduplicateDept(*list)
  305. return nil
  306. }
  307. func (e *Company) DeptPageCall(deptList *[]model.SysDept, menu model.SysDept) model.SysDept {
  308. list := *deptList
  309. min := make([]model.SysDept, 0)
  310. for j := 0; j < len(list); j++ {
  311. if menu.Id != list[j].ParentId {
  312. continue
  313. }
  314. mi := model.SysDept{}
  315. mi.Id = list[j].Id
  316. mi.ParentId = list[j].ParentId
  317. mi.ColdKey = list[j].ColdKey
  318. mi.Path = list[j].Path
  319. mi.Name = list[j].Name
  320. mi.Sort = list[j].Sort
  321. mi.Status = list[j].Status
  322. mi.Remark = list[j].Remark
  323. mi.CreatedAt = list[j].CreatedAt
  324. mi.Children = []model.SysDept{}
  325. ms := e.DeptPageCall(deptList, mi)
  326. min = append(min, ms)
  327. }
  328. menu.Children = min
  329. return menu
  330. }
  331. func DeduplicateDept(list []model.SysDept) []model.SysDept {
  332. seen := make(map[string]bool)
  333. deduplicated := []model.SysDept{}
  334. for _, v := range list {
  335. // 将结构体编码为 JSON 字符串
  336. key, err := json.Marshal(v)
  337. if err != nil {
  338. // 处理错误
  339. continue
  340. }
  341. // 将 JSON 字符串作为键插入到 map 中
  342. if _, ok := seen[string(key)]; !ok {
  343. seen[string(key)] = true
  344. deduplicated = append(deduplicated, v)
  345. }
  346. }
  347. return deduplicated
  348. }