company.go 9.8 KB

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