report_v2.go 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843
  1. package services
  2. import (
  3. "archive/zip"
  4. "encoding/json"
  5. "errors"
  6. "eta/eta_mobile/models"
  7. "eta/eta_mobile/models/report"
  8. "eta/eta_mobile/models/report_approve"
  9. "eta/eta_mobile/models/system"
  10. "eta/eta_mobile/utils"
  11. "fmt"
  12. "github.com/rdlucklib/rdluck_tools/file"
  13. "github.com/rdlucklib/rdluck_tools/http"
  14. html2 "golang.org/x/net/html"
  15. "net/url"
  16. "os"
  17. "path"
  18. "strconv"
  19. "strings"
  20. "time"
  21. "github.com/beego/beego/v2/server/web"
  22. "github.com/beego/beego/v2/server/web/context"
  23. "github.com/go-redis/redis/v8"
  24. )
  25. // AddReportAndChapter
  26. // @Description: 新增报告(包含章节)
  27. // @author: Roc
  28. // @datetime 2024-06-04 11:23:20
  29. // @param reportInfo *models.Report
  30. // @param inheritReportId int
  31. // @return err error
  32. // @return errMsg string
  33. func AddReportAndChapter(reportInfo *models.Report, inheritReportId int, grantAdminIdList []int, reportDate time.Time) (err error, errMsg string) {
  34. // 根据审批开关及审批流判断当前报告状态
  35. state, e := CheckReportCurrState(report_approve.FlowReportTypeChinese, reportInfo.ClassifyIdFirst, reportInfo.ClassifyIdSecond, reportInfo.ClassifyIdThird, models.ReportOperateAdd)
  36. if e != nil {
  37. //errMsg = "操作失败"
  38. err = errors.New("校验报告当前状态失败, Err: " + e.Error())
  39. return
  40. }
  41. // 报告状态
  42. reportInfo.State = state
  43. // 获取最小分类id
  44. minClassifyId := reportInfo.ClassifyIdThird
  45. if minClassifyId <= 0 {
  46. minClassifyId = reportInfo.ClassifyIdSecond
  47. }
  48. if minClassifyId <= 0 {
  49. minClassifyId = reportInfo.ClassifyIdFirst
  50. }
  51. if minClassifyId <= 0 {
  52. errMsg = "分类异常"
  53. err = errors.New(errMsg)
  54. return
  55. }
  56. errMsg = "生成报告失败"
  57. // 报告继承
  58. if inheritReportId > 0 {
  59. inheritReport, tmpErr := models.GetReportByReportId(inheritReportId)
  60. if tmpErr != nil && tmpErr.Error() != utils.ErrNoRow() {
  61. errMsg = "获取待继承的报告失败"
  62. err = tmpErr
  63. return
  64. }
  65. if inheritReport != nil {
  66. // 判断当前的报告分类与继承的报告分类是否一致
  67. if inheritReport.ClassifyIdFirst != reportInfo.ClassifyIdFirst || inheritReport.ClassifyIdSecond != reportInfo.ClassifyIdSecond || inheritReport.ClassifyIdThird != reportInfo.ClassifyIdThird {
  68. errMsg = "分类异常,与继承的报告分类不一致"
  69. err = errors.New(errMsg)
  70. return
  71. }
  72. reportInfo.ChapterType = inheritReport.ChapterType
  73. reportInfo.Content = inheritReport.Content
  74. reportInfo.ContentSub = inheritReport.ContentSub
  75. reportInfo.ContentStruct = inheritReport.ContentStruct
  76. reportInfo.CanvasColor = inheritReport.CanvasColor
  77. //reportInfo.NeedSplice = inheritReport.NeedSplice
  78. reportInfo.NeedSplice = 1
  79. reportInfo.HeadResourceId = inheritReport.HeadResourceId
  80. //reportInfo.HeadImg = inheritReport.HeadImg
  81. //reportInfo.EndImg = inheritReport.EndImg
  82. reportInfo.HeadImg = ``
  83. reportInfo.EndImg = ``
  84. reportInfo.EndResourceId = inheritReport.EndResourceId
  85. if inheritReport.HeadResourceId > 0 {
  86. reportInfo.HeadImg = inheritReport.HeadImg
  87. }
  88. if inheritReport.EndResourceId > 0 {
  89. reportInfo.EndImg = inheritReport.EndImg
  90. }
  91. reportInfo.InheritReportId = inheritReport.Id
  92. }
  93. }
  94. // 获取待生成的报告章节
  95. addChapterList, allGrantUserList, err, errMsg := getAddChapter(reportInfo, minClassifyId, inheritReportId, grantAdminIdList, reportDate)
  96. // 新增报告及章节
  97. var reportId int64
  98. reportId, err = models.AddReportAndChapter(reportInfo, allGrantUserList, addChapterList)
  99. if err != nil {
  100. err = errors.New("新增报告及章节失败, Err: " + err.Error())
  101. return
  102. }
  103. reportCode := utils.MD5(strconv.Itoa(reportInfo.Id))
  104. reportInfo.ReportCode = reportCode
  105. // 修改唯一编码
  106. {
  107. go models.ModifyReportCode(reportId, reportCode)
  108. }
  109. // 报告权限处理
  110. go handleReportPermission(reportId, minClassifyId)
  111. return
  112. }
  113. // EditReport
  114. // @Description: 修改报告的基础信息、授权用户权限
  115. // @author: Roc
  116. // @datetime 2024-06-06 17:16:58
  117. // @param reportInfo *models.Report
  118. // @param req models.EditReq
  119. // @param sysUser *system.Admin
  120. // @return err error
  121. // @return errMsg string
  122. func EditReport(reportInfo *models.Report, req models.EditReq, sysUser *system.Admin) (err error, errMsg string) {
  123. errMsg = `保存失败`
  124. oldIsPublicPublish := reportInfo.IsPublicPublish
  125. //var stage int
  126. //if reportInfo.ClassifyNameFirst != req.ClassifyNameFirst || reportInfo.ClassifyNameSecond != req.ClassifyNameSecond {
  127. // // 报告期数
  128. // maxStage, _ := models.GetReportStageEdit(req.ClassifyIdFirst, req.ClassifyIdSecond, req.ClassifyIdThird, int(req.ReportId))
  129. // maxStage = maxStage + 1
  130. // stage = maxStage
  131. //} else {
  132. // stage = reportInfo.Stage
  133. //}
  134. //if req.State != reportInfo.State {
  135. // recordItem := &models.ReportStateRecord{
  136. // ReportId: int(req.ReportId),
  137. // ReportType: 1,
  138. // State: req.State,
  139. // AdminId: this.SysUser.AdminId,
  140. // AdminName: this.SysUser.AdminName,
  141. // CreateTime: time.Now(),
  142. // }
  143. // go func() {
  144. // _, _ = models.AddReportStateRecord(recordItem)
  145. // }()
  146. //}
  147. //item := new(models.Report)
  148. //reportInfo.ClassifyIdFirst = req.ClassifyIdFirst
  149. //reportInfo.ClassifyNameFirst = req.ClassifyNameFirst
  150. //reportInfo.ClassifyIdSecond = req.ClassifyIdSecond
  151. //reportInfo.ClassifyNameSecond = req.ClassifyNameSecond
  152. //reportInfo.ClassifyIdThird = req.ClassifyIdThird
  153. //reportInfo.ClassifyNameThird = req.ClassifyNameThird
  154. reportInfo.Title = req.Title
  155. reportInfo.Abstract = req.Abstract
  156. reportInfo.Author = req.Author
  157. reportInfo.Frequency = req.Frequency
  158. //reportInfo.State = reportInfo.State // 编辑不变更状态
  159. //reportInfo.Stage = stage // 编辑不变更期数
  160. //reportInfo.Content = html.EscapeString(req.Content) // 编辑不变更具体内容
  161. //reportInfo.ContentSub = html.EscapeString(contentSub) // 编辑不变更具体内容
  162. reportInfo.CreateTime = req.CreateTime
  163. //reportInfo.CollaborateType = req.CollaborateType
  164. //reportInfo.ReportLayout = req.ReportLayout
  165. if req.IsPublicPublish <= 0 {
  166. req.IsPublicPublish = 1
  167. }
  168. reportInfo.IsPublicPublish = req.IsPublicPublish
  169. reportInfo.LastModifyAdminId = sysUser.AdminId
  170. reportInfo.LastModifyAdminName = sysUser.RealName
  171. reportInfo.ModifyTime = time.Now()
  172. state, e := CheckReportCurrState(report_approve.FlowReportTypeChinese, reportInfo.ClassifyIdFirst, reportInfo.ClassifyIdSecond, reportInfo.ClassifyIdThird, models.ReportOperateEdit)
  173. if e != nil {
  174. //errMsg = "操作失败"
  175. err = errors.New("校验报告当前状态失败, Err: " + e.Error())
  176. return
  177. }
  178. // 报告状态
  179. reportInfo.State = state
  180. //updateCols := []string{"ClassifyIdFirst", "ClassifyNameFirst", "ClassifyIdSecond", "ClassifyNameSecond", "ClassifyIdThird", "ClassifyNameThird", "Title", "Abstract", "Author", "Frequency", "Stage", "CreateTime", "IsPublicPublish", "LastModifyAdminId", "LastModifyAdminName", "ModifyTime"}
  181. updateCols := []string{"Title", "Abstract", "Author", "Frequency", "CreateTime", "IsPublicPublish", "LastModifyAdminId", "LastModifyAdminName", "ModifyTime", "State"}
  182. if req.HeadResourceId > 0 {
  183. reportInfo.HeadResourceId = req.HeadResourceId
  184. updateCols = append(updateCols, "HeadResourceId")
  185. }
  186. if req.EndResourceId > 0 {
  187. reportInfo.EndResourceId = req.EndResourceId
  188. updateCols = append(updateCols, "EndResourceId")
  189. }
  190. // 需要添加的报告授权数据
  191. addReportAdminList := make([]*report.ReportGrant, 0)
  192. // 待移除的报告授权数据id
  193. delReportGrantIdList := make([]int, 0)
  194. // 处理当前报告需要新增/移除的授权信息
  195. {
  196. reportGrantObj := report.ReportGrant{}
  197. // 获取当前报告已经授权的用户信息
  198. reportGrantList, tmpErr := reportGrantObj.GetGrantListById(reportInfo.Id)
  199. if tmpErr != nil {
  200. err = tmpErr
  201. return
  202. }
  203. // 当前报告已经授权的用户信息
  204. currReportAdminMap := make(map[int]*report.ReportGrant)
  205. // 需要删除的报告授权数据
  206. delReportAdminMap := make(map[int]*report.ReportGrant)
  207. for _, v := range reportGrantList {
  208. currReportAdminMap[v.AdminId] = v
  209. delReportAdminMap[v.AdminId] = v
  210. }
  211. // 先看需要新增哪些用户
  212. for _, tmpAdminId := range req.GrantAdminIdList {
  213. _, ok := currReportAdminMap[tmpAdminId]
  214. // 如果章节中需要新增的用户 已经在 报告授权用户里面,那么就忽略,可以不用新增了
  215. if ok {
  216. delete(delReportAdminMap, tmpAdminId)
  217. continue
  218. }
  219. // 如果不存在,那么就新增授权
  220. addReportAdminList = append(addReportAdminList, &report.ReportGrant{
  221. //GrantId: 0,
  222. ReportId: reportInfo.Id,
  223. AdminId: tmpAdminId,
  224. CreateTime: time.Now(),
  225. })
  226. }
  227. // 查出需要移除的授权id
  228. for _, v := range delReportAdminMap {
  229. delReportGrantIdList = append(delReportGrantIdList, v.GrantId)
  230. }
  231. }
  232. // 修改报告的基本信息,以及报告的授权用户
  233. err = models.EditReportAndPermission(reportInfo, updateCols, addReportAdminList, delReportGrantIdList)
  234. if err != nil {
  235. return
  236. }
  237. // 报告权限处理
  238. {
  239. minClassifyId, _, tmpErr := getMinClassify(reportInfo)
  240. if tmpErr != nil {
  241. return
  242. }
  243. go handleReportPermission(int64(reportInfo.Id), minClassifyId)
  244. }
  245. // 更新es里的章节数据
  246. if oldIsPublicPublish != reportInfo.IsPublicPublish {
  247. if reportInfo.HasChapter == 1 {
  248. // 晨周报
  249. chapterList, tmpErr := models.GetPublishedChapterListByReportId(reportInfo.Id)
  250. if tmpErr != nil {
  251. return
  252. }
  253. if len(chapterList) > 0 {
  254. // 更新章节的es数据
  255. for _, chapterInfo := range chapterList {
  256. err = updateReportChapterEsByChapter(chapterInfo, reportInfo.IsPublicPublish)
  257. if err != nil {
  258. return
  259. }
  260. }
  261. }
  262. }
  263. }
  264. return
  265. }
  266. // getAddChapter
  267. // @Description: 获取待新增的报告章节列表
  268. // @author: Roc
  269. // @datetime 2024-06-04 13:10:58
  270. // @param reportInfo *models.Report
  271. // @param minClassifyId int
  272. // @param inheritReportId int
  273. // @param grantAdminIdList []int
  274. // @return chapterList []*models.ReportChapter
  275. // @return err error
  276. // @return errMsg string
  277. func getAddChapter(reportInfo *models.Report, minClassifyId, inheritReportId int, grantAdminIdList []int, reportDate time.Time) (chapterList []models.AddReportChapter, allGrantUserList []*report.ReportGrant, err error, errMsg string) {
  278. // 待生成的报告章节内容
  279. chapterList = make([]models.AddReportChapter, 0)
  280. // 所有的授权用户
  281. allGrantUserList = make([]*report.ReportGrant, 0)
  282. // 报告授权的用户ID
  283. needAdminIdMap := make(map[int]bool)
  284. for _, adminId := range grantAdminIdList {
  285. needAdminIdMap[adminId] = true
  286. allGrantUserList = append(allGrantUserList, &report.ReportGrant{
  287. //GrantId: 0,
  288. //ReportId: 0,
  289. AdminId: adminId,
  290. CreateTime: time.Now(),
  291. })
  292. }
  293. if reportInfo.HasChapter != 1 {
  294. return
  295. }
  296. // 最小单元的分类
  297. var minClassifyName string
  298. if reportInfo.ClassifyIdThird == minClassifyId {
  299. minClassifyName = reportInfo.ClassifyNameThird
  300. } else if reportInfo.ClassifyIdSecond == minClassifyId {
  301. minClassifyName = reportInfo.ClassifyNameSecond
  302. } else {
  303. minClassifyName = reportInfo.ClassifyNameFirst
  304. }
  305. errMsg = "生成报告章节失败"
  306. // 章节类型列表
  307. allTypeList, err := models.GetReportChapterTypeListByClassifyId(minClassifyId)
  308. if err != nil {
  309. err = errors.New(errMsg)
  310. return
  311. }
  312. // 待添加的章节
  313. chapterTypeList := make([]*models.ReportChapterType, 0)
  314. // 待添加的章节类型id列表
  315. chapterTypeIdList := make([]int, 0)
  316. //nowTime := time.Now().Local()
  317. for _, chapterType := range allTypeList {
  318. // 如果被永久暂停更新了
  319. if chapterType.Enabled == 0 { //该章节已被永久禁用,那么就不允许继承或者新增该章节
  320. continue
  321. }
  322. if chapterType.PauseStartTime != "" && chapterType.PauseEndTime != "" && chapterType.PauseStartTime != utils.EmptyDateStr && chapterType.PauseEndTime != utils.EmptyDateStr {
  323. startTime, timeErr := time.ParseInLocation(utils.FormatDate, chapterType.PauseStartTime, time.Local)
  324. if timeErr != nil {
  325. utils.FileLog.Error("更新规则时间转换失败4001, Err: " + timeErr.Error())
  326. continue
  327. }
  328. endTime, timeErr := time.ParseInLocation(utils.FormatDate, chapterType.PauseEndTime, time.Local)
  329. if timeErr != nil {
  330. utils.FileLog.Error("更新规则时间转换失败4002, Err: " + timeErr.Error())
  331. continue
  332. }
  333. // 暂停更新(此处用报告日期去判断是否需要停更,而不是报告创建日期)
  334. if !reportDate.Before(startTime) && !reportDate.After(endTime) {
  335. continue
  336. }
  337. }
  338. // 正常的章节类型状态,那么应该自动创建该章节
  339. chapterTypeList = append(chapterTypeList, chapterType)
  340. chapterTypeIdList = append(chapterTypeIdList, chapterType.ReportChapterTypeId)
  341. }
  342. // 待继承的章节类id的授权用户
  343. oldChapterIdGrantListMap := make(map[int][]*report.ReportChapterGrant)
  344. // 待继承的章节类id关联的品种列表
  345. oldChapterPermissionListMap := make(map[int][]*report.ReportChapterPermissionMapping)
  346. // 自定义章节列表
  347. customAddChapterList := make([]models.AddReportChapter, 0)
  348. // 报告继承
  349. inheritChapterMap := make(map[int]*models.ReportChapter)
  350. // 当前分类下配置的章节类型id所关联的品种列表(默认配置,不是从继承报告里面获取的,如果有继承章节,那么需要从继承报告里面获取)
  351. currChapterTypePermissionListMap := make(map[int][]*report.ReportChapterPermissionMapping)
  352. if len(chapterTypeIdList) > 0 {
  353. mappingList, e := models.GetChapterTypePermissionByChapterTypeIdList(chapterTypeIdList)
  354. if e != nil {
  355. err = fmt.Errorf("获取章节类型权限列表失败, Err: " + e.Error())
  356. return
  357. }
  358. hasPermissionMap := make(map[string]bool)
  359. for _, v := range mappingList {
  360. tmpChapterTypePermissionList, ok := currChapterTypePermissionListMap[v.ReportChapterTypeId]
  361. if !ok {
  362. tmpChapterTypePermissionList = make([]*report.ReportChapterPermissionMapping, 0)
  363. }
  364. key := fmt.Sprint(v.ReportChapterTypeId, "-", v.ChartPermissionId)
  365. if _, has := hasPermissionMap[key]; !has {
  366. hasPermissionMap[key] = true
  367. currChapterTypePermissionListMap[v.ReportChapterTypeId] = append(tmpChapterTypePermissionList, &report.ReportChapterPermissionMapping{
  368. ReportChapterPermissionMappingId: 0,
  369. ReportChapterId: 0,
  370. ChartPermissionId: v.ChartPermissionId,
  371. CreateTime: time.Now(),
  372. })
  373. }
  374. }
  375. }
  376. if inheritReportId > 0 {
  377. // 继承待继承的报告章节内容
  378. inheritReportChapters, tmpErr := models.GetChapterListByReportId(inheritReportId)
  379. if tmpErr != nil {
  380. errMsg = "获取待继承的报告章节失败"
  381. err = tmpErr
  382. return
  383. }
  384. reportChaptersIdList := make([]int, 0)
  385. for _, v := range inheritReportChapters {
  386. reportChaptersIdList = append(reportChaptersIdList, v.ReportChapterId)
  387. }
  388. // 继承的报告章节用户map
  389. grantListMap := make(map[int][]*report.ReportChapterGrant)
  390. // 继承的报告章节的关联品种map
  391. chapterPermissionListMap := make(map[int][]*report.ReportChapterPermissionMapping)
  392. // 授权数据列表
  393. if len(reportChaptersIdList) > 0 {
  394. // 授权用户数据
  395. obj := report.ReportChapterGrant{}
  396. grantList, tmpErr := obj.GetGrantListByIdList(reportChaptersIdList)
  397. if tmpErr != nil {
  398. errMsg = "获取待继承的报告章节的授权用户列表失败"
  399. err = tmpErr
  400. return
  401. }
  402. for _, v := range grantList {
  403. // 如果不在报告授权的用户ID里面,那么该章节就不继承该授权用户
  404. if _, ok := needAdminIdMap[v.AdminId]; !ok {
  405. continue
  406. }
  407. currReportChapterId := v.ReportChapterId
  408. tmpGrantList, ok := grantListMap[currReportChapterId]
  409. if !ok {
  410. tmpGrantList = make([]*report.ReportChapterGrant, 0)
  411. }
  412. v.ReportChapterId = 0
  413. v.GrantId = 0
  414. tmpGrantList = append(tmpGrantList, v)
  415. grantListMap[currReportChapterId] = tmpGrantList
  416. }
  417. // 授权关联品种数据
  418. permissionObj := report.ReportChapterPermissionMapping{}
  419. permissionList, tmpErr := permissionObj.GetPermissionListByIdList(reportChaptersIdList)
  420. if tmpErr != nil {
  421. errMsg = "获取待继承的报告章节的授权用户列表失败"
  422. err = tmpErr
  423. return
  424. }
  425. for _, v := range permissionList {
  426. currReportChapterId := v.ReportChapterId
  427. tmpPermissionList, ok := chapterPermissionListMap[currReportChapterId]
  428. if !ok {
  429. tmpPermissionList = make([]*report.ReportChapterPermissionMapping, 0)
  430. }
  431. v.ReportChapterId = 0
  432. v.ReportChapterPermissionMappingId = 0
  433. tmpPermissionList = append(tmpPermissionList, v)
  434. chapterPermissionListMap[currReportChapterId] = tmpPermissionList
  435. }
  436. }
  437. // 继承的报告章节内容
  438. for i := 0; i < len(inheritReportChapters); i++ {
  439. customChapter := inheritReportChapters[i]
  440. // 授权用户列表
  441. tmpGrantList, ok := grantListMap[customChapter.ReportChapterId]
  442. if !ok {
  443. tmpGrantList = make([]*report.ReportChapterGrant, 0)
  444. }
  445. oldChapterIdGrantListMap[customChapter.ReportChapterId] = tmpGrantList
  446. // 关联品种列表
  447. chapterPermissionList, ok := chapterPermissionListMap[customChapter.ReportChapterId]
  448. if !ok {
  449. chapterPermissionList = make([]*report.ReportChapterPermissionMapping, 0)
  450. }
  451. oldChapterPermissionListMap[customChapter.ReportChapterId] = chapterPermissionList
  452. // 判断该章节是否是系统章节,如果是的话,那就是需要额外创建的
  453. if customChapter.TypeId > 0 {
  454. inheritChapterMap[customChapter.TypeId] = customChapter
  455. continue
  456. }
  457. // 自定义的报告内容
  458. customChapter.ReportId = reportInfo.Id
  459. customChapter.ReportChapterId = 0
  460. customChapter.ClassifyIdFirst = minClassifyId
  461. customChapter.ClassifyNameFirst = minClassifyName
  462. customChapter.Stage = reportInfo.Stage
  463. customChapter.PublishState = 1
  464. customChapter.CreateTime = reportInfo.CreateTime
  465. customChapter.ModifyTime = time.Now()
  466. customChapter.LastModifyAdminId = reportInfo.LastModifyAdminId
  467. customChapter.LastModifyAdminName = reportInfo.LastModifyAdminName
  468. customChapter.ContentModifyTime = time.Now()
  469. customAddChapter := models.AddReportChapter{
  470. ReportChapter: customChapter,
  471. GrantList: tmpGrantList,
  472. GrantPermissionList: chapterPermissionList,
  473. }
  474. customAddChapterList = append(customAddChapterList, customAddChapter)
  475. }
  476. }
  477. // 最大排序
  478. var maxSort int
  479. for _, typeItem := range chapterTypeList {
  480. v, ok := inheritChapterMap[typeItem.ReportChapterTypeId]
  481. // 章节授权用户
  482. var tmpGrantList []*report.ReportChapterGrant
  483. // 章节关联品种
  484. var tmpChapterPermissionList []*report.ReportChapterPermissionMapping
  485. chapterItem := new(models.ReportChapter)
  486. if ok && v != nil {
  487. // 如果存在继承的章节,那么就从继承的章节内容中获取
  488. chapterItem.AddType = 2
  489. chapterItem.Title = v.Title
  490. chapterItem.ReportType = v.ReportType
  491. chapterItem.ClassifyIdFirst = minClassifyId
  492. chapterItem.ClassifyNameFirst = minClassifyName
  493. chapterItem.TypeId = typeItem.ReportChapterTypeId
  494. chapterItem.TypeName = typeItem.ReportChapterTypeName
  495. chapterItem.Content = v.Content
  496. chapterItem.ContentSub = v.ContentSub
  497. chapterItem.Stage = reportInfo.Stage
  498. chapterItem.PublishState = 1
  499. chapterItem.Sort = typeItem.Sort
  500. chapterItem.CreateTime = reportInfo.CreateTime
  501. chapterItem.ModifyTime = time.Now()
  502. chapterItem.LastModifyAdminId = reportInfo.LastModifyAdminId
  503. chapterItem.LastModifyAdminName = reportInfo.LastModifyAdminName
  504. chapterItem.ContentModifyTime = time.Now()
  505. chapterItem.ContentStruct = v.ContentStruct
  506. chapterItem.ReportLayout = v.ReportLayout
  507. chapterItem.ReportCreateTime = time.Now()
  508. // 继承历史章节中的授权用户列表
  509. tmpGrantList, ok = oldChapterIdGrantListMap[v.ReportChapterId]
  510. if !ok {
  511. tmpGrantList = make([]*report.ReportChapterGrant, 0)
  512. }
  513. // 继承历史章节中的关联品种列表
  514. tmpChapterPermissionList, ok = oldChapterPermissionListMap[v.ReportChapterId]
  515. if !ok {
  516. tmpChapterPermissionList = make([]*report.ReportChapterPermissionMapping, 0)
  517. }
  518. } else {
  519. // 如果系统章节未从继承的报告中找到,那么获取往期中最新版本的此章节内容
  520. var findChapter bool
  521. if inheritReportId > 0 {
  522. chapterNewest, e := models.GetNewestPreReportChapterByClassifyIdAndTypeId(minClassifyId, typeItem.ReportChapterTypeId)
  523. if e != nil && e.Error() == utils.ErrNoRow() {
  524. errMsg = "继承最新内容的章节失败"
  525. err = fmt.Errorf("获取最新内容的章节失败, %v", e)
  526. return
  527. }
  528. if chapterNewest != nil {
  529. chapterItem.AddType = 2
  530. chapterItem.Title = chapterNewest.Title
  531. chapterItem.ReportType = chapterNewest.ReportType
  532. chapterItem.ClassifyIdFirst = minClassifyId
  533. chapterItem.ClassifyNameFirst = minClassifyName
  534. chapterItem.TypeId = typeItem.ReportChapterTypeId
  535. chapterItem.TypeName = typeItem.ReportChapterTypeName
  536. chapterItem.Content = chapterNewest.Content
  537. chapterItem.ContentSub = chapterNewest.ContentSub
  538. chapterItem.Stage = reportInfo.Stage
  539. chapterItem.PublishState = 1
  540. chapterItem.Sort = typeItem.Sort
  541. chapterItem.CreateTime = reportInfo.CreateTime
  542. chapterItem.ModifyTime = time.Now()
  543. chapterItem.LastModifyAdminId = reportInfo.LastModifyAdminId
  544. chapterItem.LastModifyAdminName = reportInfo.LastModifyAdminName
  545. chapterItem.ContentModifyTime = time.Now()
  546. chapterItem.ContentStruct = chapterNewest.ContentStruct
  547. chapterItem.ReportLayout = chapterNewest.ReportLayout
  548. chapterItem.ReportCreateTime = time.Now()
  549. // 这里的授权和品种权限需要额外查询
  550. tmpGrantList = make([]*report.ReportChapterGrant, 0)
  551. tmpChapterPermissionList = make([]*report.ReportChapterPermissionMapping, 0)
  552. {
  553. grantOb := report.ReportChapterGrant{}
  554. chapterGrant, e := grantOb.GetGrantListById(chapterNewest.ReportChapterId)
  555. if e != nil {
  556. errMsg = "获取待继承的报告章节的授权用户列表失败"
  557. err = fmt.Errorf("获取待继承的报告章节的授权用户列表失败, ChapterId: %d, Err: %v", chapterNewest.ReportChapterId, e)
  558. return
  559. }
  560. for _, cg := range chapterGrant {
  561. // 如果不在报告授权的用户ID里面,那么该章节就不继承该授权用户
  562. if _, ok := needAdminIdMap[cg.AdminId]; !ok {
  563. continue
  564. }
  565. cg.ReportChapterId = 0
  566. cg.GrantId = 0
  567. tmpGrantList = append(tmpGrantList, cg)
  568. }
  569. permissionOb := report.ReportChapterPermissionMapping{}
  570. permissions, e := permissionOb.GetPermissionListById(chapterNewest.ReportChapterId)
  571. if e != nil {
  572. errMsg = "获取待继承的报告章节的品种权限失败"
  573. err = fmt.Errorf("获取待继承的报告章节的品种权限失败, ChapterId: %d, Err: %v", chapterNewest.ReportChapterId, e)
  574. return
  575. }
  576. for _, ps := range permissions {
  577. ps.ReportChapterId = 0
  578. ps.ReportChapterPermissionMappingId = 0
  579. tmpChapterPermissionList = append(tmpChapterPermissionList, ps)
  580. }
  581. }
  582. findChapter = true
  583. }
  584. }
  585. // 没找到那就新增一篇空白的
  586. if !findChapter {
  587. chapterItem.AddType = 1
  588. chapterItem.Title = typeItem.ReportChapterTypeName
  589. chapterItem.ReportType = typeItem.ResearchType
  590. chapterItem.ClassifyIdFirst = minClassifyId
  591. chapterItem.ClassifyNameFirst = minClassifyName
  592. chapterItem.TypeId = typeItem.ReportChapterTypeId
  593. chapterItem.TypeName = typeItem.ReportChapterTypeName
  594. chapterItem.Stage = reportInfo.Stage
  595. chapterItem.PublishState = 1
  596. chapterItem.Sort = typeItem.Sort
  597. chapterItem.CreateTime = reportInfo.CreateTime
  598. chapterItem.ModifyTime = time.Now()
  599. chapterItem.LastModifyAdminId = reportInfo.LastModifyAdminId
  600. chapterItem.LastModifyAdminName = reportInfo.LastModifyAdminName
  601. chapterItem.ContentModifyTime = time.Now()
  602. //chapterItem.ContentStruct = v.ContentStruct
  603. chapterItem.ReportLayout = reportInfo.ReportLayout
  604. chapterItem.ReportCreateTime = time.Now()
  605. // 默认配置:从当前分类下配置的章节类型id所关联的品种列表
  606. tmpChapterPermissionList, ok = currChapterTypePermissionListMap[typeItem.ReportChapterTypeId]
  607. if !ok {
  608. tmpChapterPermissionList = make([]*report.ReportChapterPermissionMapping, 0)
  609. }
  610. }
  611. }
  612. if typeItem.Sort > maxSort {
  613. maxSort = typeItem.Sort
  614. }
  615. addChapter := models.AddReportChapter{
  616. ReportChapter: chapterItem,
  617. GrantList: tmpGrantList,
  618. GrantPermissionList: tmpChapterPermissionList,
  619. }
  620. chapterList = append(chapterList, addChapter)
  621. }
  622. // 将自定义的章节内容添加到待生成的章节内容中
  623. for _, addChapterItem := range customAddChapterList {
  624. maxSort++
  625. addChapterItem.ReportChapter.Sort = maxSort
  626. chapterList = append(chapterList, addChapterItem)
  627. }
  628. //hasGrantUserMap := make(map[int]bool)
  629. //for _, grantList := range typeGrantListMap {
  630. // for _, grant := range grantList {
  631. // if _, ok := hasGrantUserMap[grant.AdminId]; !ok {
  632. // allGrantUserList = append(allGrantUserList, &report.ReportGrant{
  633. // //GrantId: 0,
  634. // //ReportId: 0,
  635. // AdminId: grant.AdminId,
  636. // CreateTime: time.Now(),
  637. // })
  638. // }
  639. // }
  640. //}
  641. return
  642. }
  643. // AddChapterBaseInfoAndPermission
  644. // @Description: 添加章节基本信息及权限
  645. // @author: Roc
  646. // @datetime 2024-06-11 15:35:23
  647. // @param reportInfo *models.Report
  648. // @param reportChapterInfo *models.ReportChapter
  649. // @param permissionIdList []int
  650. // @param adminIdList []int
  651. // @return err error
  652. // @return errMsg string
  653. func AddChapterBaseInfoAndPermission(reportInfo *models.Report, reportChapterInfo *models.ReportChapter, permissionIdList []int, adminIdList []int) (err error, errMsg string) {
  654. errMsg = "新增失败"
  655. if reportInfo.State == 2 {
  656. errMsg = "该报告已发布,不允许编辑"
  657. err = errors.New(errMsg)
  658. return
  659. }
  660. // 需要添加的报告章节授权数据
  661. addChapterAdminList := make([]*report.ReportChapterGrant, 0)
  662. for _, adminId := range adminIdList {
  663. //新增授权
  664. addChapterAdminList = append(addChapterAdminList, &report.ReportChapterGrant{
  665. //GrantId: 0,
  666. //ReportChapterId: reportChapterInfo.ReportChapterId,
  667. AdminId: adminId,
  668. CreateTime: time.Now(),
  669. })
  670. }
  671. // 需要添加的报告章节品种权限数据
  672. addChapterPermissionList := make([]*report.ReportChapterPermissionMapping, 0)
  673. // 品种权限
  674. for _, permissionId := range permissionIdList {
  675. // 如果不存在,那么就新增品种权限配置
  676. addChapterPermissionList = append(addChapterPermissionList, &report.ReportChapterPermissionMapping{
  677. //ReportChapterPermissionMappingId: 0,
  678. //ReportChapterId: reportChapterInfo.ReportChapterId,
  679. ChartPermissionId: permissionId,
  680. CreateTime: time.Now(),
  681. })
  682. }
  683. err = models.AddChapterBaseInfoAndPermission(reportChapterInfo, addChapterAdminList, addChapterPermissionList)
  684. return
  685. }
  686. // EditChapterBaseInfoAndPermission
  687. // @Description: 修改报告章节的基础信息、授权用户权限、品种权限
  688. // @author: Roc
  689. // @datetime 2024-06-05 11:49:11
  690. // @param reportInfo *models.Report
  691. // @param reportChapterInfo *models.ReportChapter
  692. // @param title string
  693. // @param permissionIdList []int
  694. // @param adminIdList []int
  695. // @return err error
  696. // @return errMsg string
  697. func EditChapterBaseInfoAndPermission(reportInfo *models.Report, reportChapterInfo *models.ReportChapter, title string, permissionIdList []int, adminIdList []int) (err error, errMsg string) {
  698. errMsg = "修改失败"
  699. if reportInfo.State == 2 {
  700. errMsg = "该报告已发布,不允许编辑"
  701. err = errors.New(errMsg)
  702. return
  703. }
  704. updateCols := make([]string, 0)
  705. // 如果标题内容,那么就修改
  706. if title != `` {
  707. reportChapterInfo.Title = title
  708. reportChapterInfo.ModifyTime = time.Now()
  709. updateCols = append(updateCols, "Title", "ModifyTime")
  710. reportChapterInfo.UpdateChapter(updateCols)
  711. }
  712. reportGrantObj := report.ReportGrant{}
  713. chapterGrantObj := report.ReportChapterGrant{}
  714. chapterPermissionObj := report.ReportChapterPermissionMapping{}
  715. // 报告授权的用户map
  716. reportGrantAdminIdMap := make(map[int]bool)
  717. // 获取报告授权的用户信息
  718. {
  719. // 获取当前报告已经授权的用户信息
  720. reportGrantList, tmpErr := reportGrantObj.GetGrantListById(reportInfo.Id)
  721. if tmpErr != nil {
  722. err = tmpErr
  723. return
  724. }
  725. for _, v := range reportGrantList {
  726. reportGrantAdminIdMap[v.AdminId] = true
  727. }
  728. }
  729. // 需要添加的报告章节授权数据
  730. addChapterAdminList := make([]*report.ReportChapterGrant, 0)
  731. // 待移除的报告章节授权数据id
  732. delReportChapterGrantIdList := make([]int, 0)
  733. // 处理当前报告章节需要新增/移除的授权信息
  734. {
  735. // 获取当前章节已经授权的用户信息
  736. chapterGrantList, tmpErr := chapterGrantObj.GetGrantListById(reportChapterInfo.ReportChapterId)
  737. if tmpErr != nil {
  738. err = tmpErr
  739. return
  740. }
  741. // 当前章节已经授权的用户信息
  742. currChapterAdminMap := make(map[int]*report.ReportChapterGrant)
  743. // 需要删除的报告章节授权数据
  744. delChapterAdminMap := make(map[int]*report.ReportChapterGrant)
  745. for _, v := range chapterGrantList {
  746. currChapterAdminMap[v.AdminId] = v
  747. delChapterAdminMap[v.AdminId] = v
  748. }
  749. for _, adminId := range adminIdList {
  750. // 如果该用户 不在 报告授权的用户map 里面,说明这个用户是要移除的
  751. if _, ok := reportGrantAdminIdMap[adminId]; !ok {
  752. continue
  753. }
  754. _, ok := currChapterAdminMap[adminId]
  755. // 如果存在,那么从 “需要删除的报告章节授权数据” 的map中移除
  756. if ok {
  757. delete(delChapterAdminMap, adminId)
  758. continue
  759. }
  760. // 如果不存在,那么就新增授权
  761. addChapterAdminList = append(addChapterAdminList, &report.ReportChapterGrant{
  762. //GrantId: 0,
  763. ReportChapterId: reportChapterInfo.ReportChapterId,
  764. AdminId: adminId,
  765. CreateTime: time.Now(),
  766. })
  767. }
  768. // 查出需要移除的授权id
  769. for _, v := range delChapterAdminMap {
  770. delReportChapterGrantIdList = append(delReportChapterGrantIdList, v.GrantId)
  771. }
  772. }
  773. // 其他章节授权的用户
  774. otherChapterAdminMap := make(map[int]bool)
  775. {
  776. // 获取报告所有的章节id
  777. reportChapterIdList, tmpErr := models.GetReportChapterIdList(reportInfo.Id)
  778. if tmpErr != nil {
  779. err = tmpErr
  780. return
  781. }
  782. if len(reportChapterIdList) > 0 {
  783. list, tmpErr := chapterGrantObj.GetGrantListByIdList(reportChapterIdList)
  784. if tmpErr != nil {
  785. err = tmpErr
  786. return
  787. }
  788. for _, v := range list {
  789. // 如果是当前章节,因为涉及到重新授权,所以得过滤
  790. if v.ReportChapterId == reportChapterInfo.ReportChapterId {
  791. continue
  792. }
  793. otherChapterAdminMap[v.AdminId] = true
  794. }
  795. }
  796. }
  797. // 需要添加的报告章节品种权限数据
  798. addChapterPermissionList := make([]*report.ReportChapterPermissionMapping, 0)
  799. // 待移除的报告章节品种权限数据id
  800. delChapterPermissionMappingIdList := make([]int, 0)
  801. // 处理当前报告章节需要新增/移除的品种权限信息
  802. {
  803. // 获取当前章节已经配置的品种权限信息
  804. chapterPermissionList, tmpErr := chapterPermissionObj.GetPermissionListById(reportChapterInfo.ReportChapterId)
  805. if tmpErr != nil {
  806. err = tmpErr
  807. return
  808. }
  809. // 当前章节已经配置的品种权限信息
  810. currChapterPermissionMap := make(map[int]*report.ReportChapterPermissionMapping)
  811. // 需要删除的报告章节品种权限配置
  812. delChapterPermissionMap := make(map[int]*report.ReportChapterPermissionMapping)
  813. for _, v := range chapterPermissionList {
  814. currChapterPermissionMap[v.ChartPermissionId] = v
  815. delChapterPermissionMap[v.ChartPermissionId] = v
  816. }
  817. for _, permissionId := range permissionIdList {
  818. _, ok := currChapterPermissionMap[permissionId]
  819. // 如果存在,那么从 “需要删除的报告章节品种权限配置” 的map中移除
  820. if ok {
  821. delete(delChapterPermissionMap, permissionId)
  822. continue
  823. }
  824. // 如果不存在,那么就新增品种权限配置
  825. addChapterPermissionList = append(addChapterPermissionList, &report.ReportChapterPermissionMapping{
  826. //ReportChapterPermissionMappingId: 0,
  827. ReportChapterId: reportChapterInfo.ReportChapterId,
  828. ChartPermissionId: permissionId,
  829. CreateTime: time.Now(),
  830. })
  831. }
  832. // 查出需要移除的品种权限配置
  833. for _, v := range delChapterPermissionMap {
  834. delChapterPermissionMappingIdList = append(delChapterPermissionMappingIdList, v.ReportChapterPermissionMappingId)
  835. }
  836. }
  837. err = models.EditChapterBaseInfoAndPermission(reportInfo, reportChapterInfo, updateCols, addChapterAdminList, addChapterPermissionList, delReportChapterGrantIdList, delChapterPermissionMappingIdList)
  838. return
  839. }
  840. // DelChapter
  841. // @Description: 删除报告章节、授权用户权限、品种权限
  842. // @author: Roc
  843. // @datetime 2024-06-06 17:28:37
  844. // @param reportInfo *models.Report
  845. // @param reportChapterInfo *models.ReportChapter
  846. // @param sysUser *system.Admin
  847. // @return err error
  848. // @return errMsg string
  849. func DelChapter(reportInfo *models.Report, reportChapterInfo *models.ReportChapter, sysUser *system.Admin) (err error, errMsg string) {
  850. errMsg = "删除失败"
  851. if reportInfo.State == 2 {
  852. errMsg = "该报告已发布,不允许删除"
  853. err = errors.New(errMsg)
  854. return
  855. }
  856. reportInfo.LastModifyAdminId = sysUser.AdminId
  857. reportInfo.LastModifyAdminName = sysUser.RealName
  858. reportInfo.ModifyTime = time.Now()
  859. updateReportCols := []string{"LastModifyAdminId", "LastModifyAdminName", "ModifyTime"}
  860. err = models.DelChapterAndPermission(reportInfo, updateReportCols, reportChapterInfo)
  861. return
  862. }
  863. // DownloadVoice
  864. // @Description: 下载报告音频文件
  865. // @author: Roc
  866. // @datetime 2024-06-13 15:36:46
  867. // @param reportInfo *models.ReportDetail
  868. // @return savePath string
  869. // @return fileName string
  870. // @return err error
  871. // @return errMsg string
  872. func DownloadVoice(reportInfo *models.ReportDetail) (savePath, fileName string, err error, errMsg string) {
  873. errMsg = `下载失败`
  874. // 如果报告有音频,那么下载音频
  875. if reportInfo.VideoUrl != `` {
  876. savePath = time.Now().Format(utils.FormatDateTimeUnSpace) + utils.GetRandString(5) + ".mp3"
  877. fileName = reportInfo.VideoName + ".mp3"
  878. fileBody, tmpErr := http.Get(reportInfo.VideoUrl)
  879. if tmpErr != nil {
  880. err = tmpErr
  881. errMsg = "音频下载失败"
  882. return
  883. }
  884. err = file.SaveFile(fileBody, savePath)
  885. if err != nil {
  886. errMsg = "音频保存失败"
  887. return
  888. }
  889. }
  890. // 如果是章节报告,那么就下载压缩包
  891. if reportInfo.HasChapter == 1 {
  892. videoList, tmpErr := models.GetReportChapterVideoList(reportInfo.Id)
  893. if tmpErr != nil {
  894. err = tmpErr
  895. errMsg = "获取音频列表失败"
  896. return
  897. }
  898. if len(videoList) > 0 {
  899. // 创建zip
  900. savePath = time.Now().Format(utils.FormatDateTimeUnSpace) + utils.GetRandString(5) + ".zip"
  901. fileName = reportInfo.VideoName + ".zip"
  902. zipFile, tmpErr := os.Create(savePath)
  903. if tmpErr != nil {
  904. err = tmpErr
  905. return
  906. }
  907. zipWriter := zip.NewWriter(zipFile)
  908. // 生成zip过程中报错关闭
  909. defer func() {
  910. if err != nil {
  911. zipWriter.Close()
  912. zipFile.Close()
  913. }
  914. }()
  915. // 获取音频,写入zip
  916. for i := 0; i < len(videoList); i++ {
  917. item := videoList[i]
  918. if item.VideoName == "" || item.VideoUrl == "" {
  919. continue
  920. }
  921. // 音频文件后缀
  922. ext := path.Ext(item.VideoUrl)
  923. ioWriter, tmpErr := zipWriter.Create(fmt.Sprintf("%s%s", item.VideoName, ext))
  924. if tmpErr != nil {
  925. err = tmpErr
  926. if os.IsPermission(err) {
  927. fmt.Println("权限不足: ", err)
  928. return
  929. }
  930. return
  931. }
  932. var content []byte
  933. content, err = http.Get(item.VideoUrl)
  934. if err != nil {
  935. content = []byte("")
  936. }
  937. ioWriter.Write(content)
  938. }
  939. // 生成zip后关闭,否则下载文件会损坏
  940. zipWriter.Close()
  941. zipFile.Close()
  942. }
  943. }
  944. return
  945. }
  946. // CheckReportAuthByAdminIdList
  947. // @Description: 根据管理员id列表,判断当前用户是否有报告权限
  948. // @author: Roc
  949. // @datetime 2024-06-13 11:03:10
  950. // @param adminId int
  951. // @param createAdminId int
  952. // @param grantAdminIdList []int
  953. // @return isAuth bool
  954. func CheckReportAuthByAdminIdList(adminId, createAdminId int, grantAdminIdList []int) (isAuth bool) {
  955. // 如果是自己创建的报告,那么就有权限
  956. if adminId == createAdminId {
  957. isAuth = true
  958. return
  959. }
  960. // 如果是授权用户,那么就有权限
  961. if utils.IsCheckInList(grantAdminIdList, adminId) {
  962. isAuth = true
  963. return
  964. }
  965. return
  966. }
  967. // CheckReportAuthByReportId
  968. // @Description: 根据报告ID,判断当前用户是否有报告权限
  969. // @author: Roc
  970. // @datetime 2024-06-13 16:21:28
  971. // @param adminId int
  972. // @param reportInfoId int
  973. // @return isAuth bool
  974. // @return err error
  975. func CheckReportAuthByReportId(sysUser *system.Admin, createAdminId int, reportInfoId int) (isAuth bool, err error) {
  976. // 如果是自己创建的报告,那么就有权限
  977. if sysUser.AdminId == createAdminId {
  978. isAuth = true
  979. return
  980. }
  981. // 如果本人是超管,那么就有权限
  982. if utils.IsAdminRole(sysUser.RoleTypeCode) {
  983. isAuth = true
  984. return
  985. }
  986. obj := report.ReportGrant{}
  987. item, err := obj.GetGrantByIdAndAdmin(reportInfoId, sysUser.AdminId)
  988. if err != nil {
  989. // 如果是没找到数据,那么就是无权限
  990. if err.Error() == utils.ErrNoRow() {
  991. err = nil
  992. return
  993. }
  994. // sql报错了
  995. return
  996. }
  997. // 用户id一致就有权限
  998. if item.AdminId == sysUser.AdminId {
  999. isAuth = true
  1000. }
  1001. return
  1002. }
  1003. // EditReportLayoutImg
  1004. // @Description: 修改报告的版图信息
  1005. // @author: Roc
  1006. // @datetime 2024-06-18 11:35:00
  1007. // @param reportInfo *models.Report
  1008. // @param req models.EditLayoutImgReq
  1009. // @param sysUser *system.Admin
  1010. // @return err error
  1011. // @return errMsg string
  1012. func EditReportLayoutImg(reportInfo *models.Report, req models.EditLayoutImgReq, sysUser *system.Admin) (err error, errMsg string) {
  1013. errMsg = `保存失败`
  1014. reportInfo.HeadResourceId = req.HeadResourceId
  1015. reportInfo.HeadImg = req.HeadImg
  1016. reportInfo.EndResourceId = req.EndResourceId
  1017. reportInfo.EndImg = req.EndImg
  1018. reportInfo.CanvasColor = req.CanvasColor
  1019. reportInfo.LastModifyAdminId = sysUser.AdminId
  1020. reportInfo.LastModifyAdminName = sysUser.RealName
  1021. reportInfo.ModifyTime = time.Now()
  1022. updateCols := []string{"HeadResourceId", "HeadImg", "EndResourceId", "EndImg", "CanvasColor", "LastModifyAdminId", "LastModifyAdminName", "ModifyTime"}
  1023. err = reportInfo.UpdateReport(updateCols)
  1024. if err != nil {
  1025. return
  1026. }
  1027. return
  1028. }
  1029. // PublishReport
  1030. // @Description: 报告发布
  1031. // @author: Roc
  1032. // @datetime 2024-06-20 09:44:13
  1033. // @param reportId int
  1034. // @param reportUrl string
  1035. // @param sysUser *system.Admin
  1036. // @return tips string
  1037. // @return err error
  1038. // @return errMsg string
  1039. func PublishReport(reportId int, reportUrl string, sysUser *system.Admin) (tips string, err error, errMsg string) {
  1040. errMsg = `报告发布失败`
  1041. reportInfo, err := models.GetReportByReportId(reportId)
  1042. if err != nil {
  1043. errMsg = "获取报告信息失败"
  1044. return
  1045. }
  1046. if reportInfo == nil {
  1047. errMsg = "获取报告信息失败"
  1048. err = errors.New(errMsg)
  1049. return
  1050. }
  1051. var publishTime time.Time
  1052. if reportInfo.MsgIsSend == 1 && reportInfo.PublishTime.IsZero() { //如果报告曾经发布过,并且已经发送过模版消息,则章节的发布时间为报告的发布时间
  1053. publishTime = reportInfo.PublishTime
  1054. } else {
  1055. publishTime = time.Now()
  1056. }
  1057. var tmpErr error
  1058. // 章节类型的报告(原来的晨周报)
  1059. if reportInfo.HasChapter == 1 {
  1060. tips, tmpErr, errMsg = PublishChapterReport(reportInfo, reportUrl, sysUser)
  1061. if tmpErr != nil {
  1062. err = errors.New("晨周报发布失败, Err:" + tmpErr.Error() + ", report_id:" + strconv.Itoa(reportId))
  1063. }
  1064. return
  1065. }
  1066. // 普通报告
  1067. if reportInfo.Content == "" {
  1068. errMsg = `报告内容为空,不可发布`
  1069. err = errors.New("报告内容为空,不需要生成,report_id:" + strconv.Itoa(reportId))
  1070. return
  1071. }
  1072. // 根据审批开关及审批流判断当前报告状态
  1073. state, e := CheckReportCurrState(report_approve.FlowReportTypeChinese, reportInfo.ClassifyIdFirst, reportInfo.ClassifyIdSecond, reportInfo.ClassifyIdThird, models.ReportOperatePublish)
  1074. if e != nil {
  1075. errMsg = "操作失败"
  1076. err = errors.New("校验报告当前状态失败, Err: " + e.Error())
  1077. return
  1078. }
  1079. if state == models.ReportStatePublished {
  1080. // 发布报告
  1081. if tmpErr = models.PublishReportById(reportId, publishTime, sysUser.AdminId, sysUser.RealName); tmpErr != nil {
  1082. err = errors.New("报告发布失败, Err:" + tmpErr.Error() + ", report_id:" + strconv.Itoa(reportId))
  1083. return
  1084. }
  1085. go func() {
  1086. // 生成音频
  1087. if reportInfo.VideoUrl == "" {
  1088. go UpdateReportVideo(reportInfo)
  1089. }
  1090. // 更新报告Es
  1091. _ = UpdateReportEs(reportId, 2)
  1092. }()
  1093. } else {
  1094. // 从无审批切换为有审批, 状态重置
  1095. if e = models.ResetReportById(reportId, state, sysUser.AdminId, sysUser.RealName); e != nil {
  1096. errMsg = "操作失败"
  1097. err = fmt.Errorf("重置报告状态失败, Err: %s, ReportId: %d", e.Error(), reportId)
  1098. return
  1099. }
  1100. }
  1101. recordItem := &models.ReportStateRecord{
  1102. ReportId: reportId,
  1103. ReportType: 1,
  1104. State: state,
  1105. AdminId: sysUser.AdminId,
  1106. AdminName: sysUser.AdminName,
  1107. CreateTime: time.Now(),
  1108. }
  1109. go func() {
  1110. _, _ = models.AddReportStateRecord(recordItem)
  1111. }()
  1112. // 生成报告pdf和长图
  1113. {
  1114. reportPdfUrl := GetGeneralPdfUrl(reportInfo.ReportCode, reportInfo.ReportLayout)
  1115. go Report2pdfAndJpeg(reportPdfUrl, reportId, 1)
  1116. }
  1117. // 报告权限处理
  1118. {
  1119. minClassifyId, _, tmpErr := getMinClassify(reportInfo)
  1120. if tmpErr != nil {
  1121. return
  1122. }
  1123. go handleReportPermission(int64(reportInfo.Id), minClassifyId)
  1124. }
  1125. return
  1126. }
  1127. // PublishChapterReport
  1128. // @Description: 发布章节类型的报告
  1129. // @author: Roc
  1130. // @datetime 2024-06-28 10:38:50
  1131. // @param reportInfo *models.Report
  1132. // @param reportUrl string
  1133. // @return tips string
  1134. // @return err error
  1135. // @return errMsg string
  1136. func PublishChapterReport(reportInfo *models.Report, reportUrl string, sysUser *system.Admin) (tips string, err error, errMsg string) {
  1137. reportId := reportInfo.Id
  1138. if reportInfo.State == 2 {
  1139. return
  1140. }
  1141. // 获取所有章节列表
  1142. chapters, err := models.GetChapterListByReportId(reportId)
  1143. if err != nil {
  1144. return
  1145. }
  1146. chapterLen := len(chapters)
  1147. if chapterLen <= 0 {
  1148. tips = "报告章节为空,不可发布"
  1149. errMsg = tips
  1150. err = errors.New(tips)
  1151. return
  1152. }
  1153. // 获取报告中的所有章节列表
  1154. chapterList, err := models.GetChapterListByReportId(reportId)
  1155. if err != nil {
  1156. return
  1157. }
  1158. for _, chapter := range chapterList {
  1159. if chapter.PublishState == 1 {
  1160. tips = "还存在未发布的章节"
  1161. errMsg = tips
  1162. err = errors.New(tips)
  1163. return
  1164. }
  1165. }
  1166. // 根据审批开关及审批流判断当前报告状态
  1167. state, e := CheckReportCurrState(report_approve.FlowReportTypeChinese, reportInfo.ClassifyIdFirst, reportInfo.ClassifyIdSecond, reportInfo.ClassifyIdThird, models.ReportOperatePublish)
  1168. if e != nil {
  1169. //errMsg = "操作失败"
  1170. err = errors.New("校验报告当前状态失败, Err: " + e.Error())
  1171. return
  1172. }
  1173. // 如果状态不是已发布,那么就重置状态
  1174. if state != models.ReportStatePublished {
  1175. // 从无审批切换为有审批, 状态重置
  1176. if e = models.ResetReportById(reportId, state, sysUser.AdminId, sysUser.RealName); e != nil {
  1177. //errMsg = "操作失败"
  1178. err = fmt.Errorf("重置报告状态失败, Err: %s, ReportId: %d", e.Error(), reportId)
  1179. return
  1180. }
  1181. return
  1182. }
  1183. // 需发布整期
  1184. updateCols := make([]string, 0)
  1185. reportInfo.LastModifyAdminId = sysUser.AdminId
  1186. reportInfo.LastModifyAdminName = sysUser.RealName
  1187. updateCols = append(updateCols, "LastModifyAdminId", "LastModifyAdminName", "Title", "State", "ModifyTime")
  1188. // 发布后标题调整
  1189. //title := reportInfo.Title
  1190. //title = strings.ReplaceAll(title, "【弘则FICC晨报】", "")
  1191. //title = strings.ReplaceAll(title, "【弘则FICC周报】", "")
  1192. //if title == "" {
  1193. // // 取第一个需发布章节的标题
  1194. // firstId := publishIdArr[0]
  1195. // firstTitle := ""
  1196. // for i := 0; i < chapterLen; i++ {
  1197. // if chapters[i].ReportChapterId == firstId {
  1198. // firstTitle = chapters[i].Title
  1199. // break
  1200. // }
  1201. // }
  1202. // title = firstTitle
  1203. //}
  1204. //report.Title = title
  1205. reportInfo.State = state
  1206. // 研报后台4.4 只在没有发布过时更新发布时间,其余均按模版消息发送时间当作发布时间
  1207. if reportInfo.MsgIsSend == 0 || reportInfo.PublishTime.IsZero() {
  1208. reportInfo.PublishTime = time.Now().Local()
  1209. updateCols = append(updateCols, "PublishTime")
  1210. }
  1211. reportInfo.ModifyTime = time.Now().Local()
  1212. if e := models.PublishReportAndChapter(reportInfo, true, updateCols); e != nil {
  1213. err = errors.New("发布报告及章节失败")
  1214. return
  1215. }
  1216. // 生成章节音频
  1217. go UpdateReportVideo(reportInfo)
  1218. // 更新报告ES
  1219. go func() {
  1220. _ = UpdateReportEs(reportInfo.Id, 2)
  1221. }()
  1222. // 发布时备份内容
  1223. go SaveReportLogs(reportInfo, chapters, reportInfo.AdminId, reportInfo.AdminRealName)
  1224. // 生成报告pdf和长图
  1225. {
  1226. reportPdfUrl := GetGeneralPdfUrl(reportInfo.ReportCode, reportInfo.ReportLayout)
  1227. go Report2pdfAndJpeg(reportPdfUrl, reportId, 1)
  1228. }
  1229. return
  1230. }
  1231. // DeleteReportAndChapter 删除报告及章节
  1232. func DeleteReportAndChapter(reportId int) (err error) {
  1233. reportInfo, err := models.GetReportByReportId(reportId)
  1234. if err != nil {
  1235. err = errors.New("报告信息有误, Err: " + err.Error())
  1236. return
  1237. }
  1238. if reportInfo.State == 2 {
  1239. err = errors.New("报告已发布,不可删除")
  1240. return
  1241. }
  1242. // 更新ES
  1243. _ = UpdateReportEs(reportId, 1)
  1244. // 删除
  1245. if reportInfo.HasChapter == 1 {
  1246. err = models.DeleteDayWeekReportAndChapter(reportId)
  1247. } else {
  1248. err = models.DeleteReport(reportId)
  1249. }
  1250. if err != nil {
  1251. err = errors.New("删除失败, Err: " + err.Error())
  1252. return
  1253. }
  1254. // 重置PPT关联报告
  1255. go func() {
  1256. _ = ResetPPTReport(reportId, false)
  1257. }()
  1258. return
  1259. }
  1260. // getMinClassify
  1261. // @Description: 获取最小分类ID
  1262. // @author: Roc
  1263. // @datetime 2024-06-20 09:23:19
  1264. // @param reportInfo *models.Report
  1265. // @return minClassifyId int
  1266. // @return minClassifyName string
  1267. // @return err error
  1268. func getMinClassify(reportInfo *models.Report) (minClassifyId int, minClassifyName string, err error) {
  1269. defer func() {
  1270. if err != nil {
  1271. utils.FileLog.Error("获取最小分类ID失败,报告ID:%d,Err:%s", reportInfo.Id, err.Error())
  1272. }
  1273. }()
  1274. minClassifyId = reportInfo.ClassifyIdThird
  1275. minClassifyName = reportInfo.ClassifyNameThird
  1276. if minClassifyId <= 0 {
  1277. minClassifyId = reportInfo.ClassifyIdSecond
  1278. minClassifyName = reportInfo.ClassifyNameSecond
  1279. }
  1280. if minClassifyId <= 0 {
  1281. minClassifyId = reportInfo.ClassifyIdFirst
  1282. minClassifyName = reportInfo.ClassifyNameFirst
  1283. }
  1284. if minClassifyId <= 0 {
  1285. err = errors.New("分类异常")
  1286. }
  1287. return
  1288. }
  1289. // handleReportPermission
  1290. // @Description: 报告权限处理
  1291. // @author: Roc
  1292. // @datetime 2024-06-19 18:00:51
  1293. // @param reportId int64
  1294. // @param minClassifyId int
  1295. func handleReportPermission(reportId int64, minClassifyId int) {
  1296. // TODO 报告权限处理
  1297. var err error
  1298. defer func() {
  1299. if err != nil {
  1300. utils.FileLog.Error("报告权限处理失败,报告ID:%d,分类ID:%d,Err:%s", reportId, minClassifyId, err.Error())
  1301. //alarm_msg.SendAlarmMsg("修改删除报告权限失败,Err:"+err.Error(), 3)
  1302. }
  1303. }()
  1304. err = models.RemoveChartPermissionChapterMapping(reportId)
  1305. if err != nil {
  1306. err = errors.New("修改删除报告权限失败,Err:" + err.Error())
  1307. return
  1308. }
  1309. permissionItems, err := models.GetPermission(minClassifyId)
  1310. if err != nil {
  1311. err = errors.New("获取权限失败,Err:" + err.Error())
  1312. return
  1313. }
  1314. for _, v := range permissionItems {
  1315. err = models.AddChartPermissionChapterMapping(v.ChartPermissionId, reportId)
  1316. if err != nil {
  1317. err = errors.New("新增权限失败,Err:" + err.Error())
  1318. return
  1319. }
  1320. }
  1321. // 同步crm权限
  1322. _ = EditReportPermissionSync(reportId, minClassifyId)
  1323. return
  1324. }
  1325. // HandleReportPermission
  1326. // @Description: 报告权限处理
  1327. // @author: Roc
  1328. // @datetime 2024-07-12 11:17:49
  1329. // @param reportInfo *models.Report
  1330. func HandleReportPermission(reportInfo *models.Report) {
  1331. minClassifyId, _, tmpErr := getMinClassify(reportInfo)
  1332. if tmpErr != nil {
  1333. return
  1334. }
  1335. handleReportPermission(int64(reportInfo.Id), minClassifyId)
  1336. }
  1337. // UpdateReportVideo
  1338. // @Description: 更新报告音频
  1339. // @author: Roc
  1340. // @datetime 2024-07-17 18:11:10
  1341. // @param reportInfo *models.Report
  1342. func UpdateReportVideo(reportInfo *models.Report) {
  1343. if reportInfo.HasChapter == 1 {
  1344. reportChapterIdList := make([]int, 0)
  1345. // 获取报告中的所有章节列表
  1346. chapterList, err := models.GetChapterListByReportId(reportInfo.Id)
  1347. if err != nil {
  1348. return
  1349. }
  1350. for _, chapter := range chapterList {
  1351. if chapter.PublishState == 2 {
  1352. reportChapterIdList = append(reportChapterIdList, chapter.ReportChapterId)
  1353. }
  1354. }
  1355. if len(reportChapterIdList) > 0 {
  1356. err = UpdateChaptersVideo(reportChapterIdList)
  1357. if err != nil {
  1358. utils.FileLog.Info(fmt.Sprintf("%d报告音频生产失败:%s", reportInfo.Id, err.Error()))
  1359. }
  1360. }
  1361. } else {
  1362. err := CreateVideo(reportInfo)
  1363. if err != nil {
  1364. utils.FileLog.Info(fmt.Sprintf("%d报告音频生产失败:%s", reportInfo.Id, err.Error()))
  1365. }
  1366. }
  1367. }
  1368. // GetGeneralPdfUrl
  1369. // @Description: 获取生成pdf的地址
  1370. // @author: Roc
  1371. // @datetime 2024-07-19 14:09:28
  1372. // @param reportCode string
  1373. // @param reportLayout int8
  1374. // @return pdfUrl string
  1375. func GetGeneralPdfUrl(reportCode string, reportLayout int8) (pdfUrl string) {
  1376. conf, e := models.GetBusinessConfByKey("ReportViewUrl")
  1377. if e != nil {
  1378. return
  1379. }
  1380. switch reportLayout {
  1381. case 1:
  1382. // 普通布局
  1383. pdfUrl = fmt.Sprintf("%s/reportshare_pdf?code=%s", conf.ConfVal, reportCode)
  1384. case 2:
  1385. // 智能布局
  1386. pdfUrl = fmt.Sprintf("%s/reportshare_smart_pdf?code=%s", conf.ConfVal, reportCode)
  1387. }
  1388. return
  1389. }
  1390. // GetReportShareUrlToken 获取报告分享链接token
  1391. func GetReportShareUrlToken(req models.ReportShartUrlReq, adminId int) (linkToken string, err error) {
  1392. cacheLinkKey := utils.CACHE_REPORT_SHARE_SHORT_Url + strconv.Itoa(req.ReportId) + "userId:" + strconv.Itoa(adminId)
  1393. linkToken, _ = utils.Rc.RedisString(cacheLinkKey)
  1394. if linkToken != "" && utils.Rc.IsExist(utils.CACHE_REPORT_SHARE_ORIGIN_Url+linkToken) {
  1395. return
  1396. }
  1397. var ok bool
  1398. // 冲突检测
  1399. for i := 0; i < 3; i++ {
  1400. linkToken = req.Url
  1401. if i > 0 {
  1402. linkToken += "_" + utils.GetRandDigit(3)
  1403. }
  1404. hashUrl := utils.MurmurHash64([]byte(linkToken))
  1405. linkToken = utils.ConvertNumToBase62(hashUrl)
  1406. ok = utils.Rc.IsExist(utils.CACHE_REPORT_SHARE_ORIGIN_Url + linkToken)
  1407. if !ok {
  1408. break
  1409. }
  1410. }
  1411. if !ok {
  1412. after := time.Now().AddDate(0, 0, 7)
  1413. err = utils.Rc.Put(cacheLinkKey, linkToken, time.Until(after))
  1414. if err != nil {
  1415. return
  1416. }
  1417. err = utils.Rc.Put(utils.CACHE_REPORT_SHARE_ORIGIN_Url+linkToken, req.Url, time.Until(after))
  1418. if err != nil {
  1419. return
  1420. }
  1421. } else {
  1422. linkToken = ""
  1423. err = errors.New("生成链接失败")
  1424. }
  1425. return
  1426. }
  1427. func TransfromToOriginUrl(linkToken string) (originLink string, msg string, err error) {
  1428. cacheLinkKey := utils.CACHE_REPORT_SHARE_ORIGIN_Url + linkToken
  1429. originLink, err = utils.Rc.RedisString(cacheLinkKey)
  1430. if err != nil {
  1431. if err == redis.Nil {
  1432. msg = "链接已失效, 请重新获取"
  1433. return
  1434. }
  1435. msg = "获取链接失败"
  1436. return
  1437. }
  1438. if originLink == "" {
  1439. msg = "链接已失效, 请重新获取"
  1440. return
  1441. }
  1442. return
  1443. }
  1444. func FilterShareUrl() web.FilterFunc {
  1445. return func(c *context.Context) {
  1446. path := c.Input.Context.Request.URL.Path
  1447. tokenArr := strings.Split(path, "/")
  1448. token := tokenArr[len(tokenArr)-1]
  1449. newPath := "/v1/report/share/link"
  1450. q := c.Input.Context.Request.URL.Query()
  1451. q.Add("Token", token)
  1452. c.Input.Context.Request.URL.Path = newPath
  1453. c.Input.Context.Request.URL.RawQuery = q.Encode()
  1454. utils.ApiLog.Info(fmt.Sprintf("原始请求为:%s, 已修改请求路径为:%s?%s", path, newPath, q.Encode()))
  1455. }
  1456. }
  1457. // HandleReportContent
  1458. // @Description: 处理报告内容(动态图表/表格添加授权token)
  1459. // @author: Roc
  1460. // @datetime 2025-01-07 10:03:15
  1461. // @param body string
  1462. // @return newBody string
  1463. func HandleReportContent(body string, opType string, tokenMap map[string]string) (newBody string) {
  1464. if body == `` {
  1465. return
  1466. }
  1467. newBody = body
  1468. // 解析HTML
  1469. doc, err := html2.Parse(strings.NewReader(body))
  1470. if err != nil {
  1471. fmt.Println("Error parsing HTML:", err)
  1472. return
  1473. }
  1474. replaceIframeSrc(doc, opType, tokenMap)
  1475. // 输出修改后的HTML
  1476. var modifiedHtml strings.Builder
  1477. err = html2.Render(&modifiedHtml, doc)
  1478. if err != nil {
  1479. fmt.Println("Error rendering HTML:", err)
  1480. return
  1481. }
  1482. newBody = modifiedHtml.String()
  1483. fmt.Println(newBody)
  1484. return
  1485. }
  1486. // replaceIframeSrc 遍历HTML节点,替换iframe的src属性
  1487. func replaceIframeSrc(n *html2.Node, opType string, tokenMap map[string]string) {
  1488. if n.Type == html2.ElementNode && n.Data == "iframe" {
  1489. for i, attr := range n.Attr {
  1490. if attr.Key == "src" {
  1491. newLink := attr.Val
  1492. // 处理链接
  1493. switch opType {
  1494. case `add`:
  1495. newLink = linkAddToken(attr.Val, tokenMap)
  1496. case `del`:
  1497. newLink = linkDelToken(attr.Val)
  1498. }
  1499. // 替换原来的链接
  1500. n.Attr[i].Val = newLink
  1501. break
  1502. }
  1503. }
  1504. }
  1505. // 递归处理子节点
  1506. for c := n.FirstChild; c != nil; c = c.NextSibling {
  1507. replaceIframeSrc(c, opType, tokenMap)
  1508. }
  1509. }
  1510. // linkAddToken 链接添加token
  1511. func linkAddToken(link string, tokenMap map[string]string) string {
  1512. var err error
  1513. defer func() {
  1514. if err != nil {
  1515. utils.FileLog.Info("处理链接失败,ERR:" + err.Error())
  1516. }
  1517. }()
  1518. parsedURL, err := url.Parse(link)
  1519. if err != nil {
  1520. return link
  1521. }
  1522. // 获取查询参数
  1523. queryParams := parsedURL.Query()
  1524. // 先移除authToken参数,避免莫名其妙的这个值入库了
  1525. queryParams.Del("authToken")
  1526. // 获取code参数
  1527. code := queryParams.Get("code")
  1528. if code == "" {
  1529. return link
  1530. }
  1531. showType := `chart`
  1532. if strings.Contains(parsedURL.Path, "sheetshow") {
  1533. showType = `excel`
  1534. }
  1535. // 避免报告里面一个图表/表格重复生成token
  1536. key := fmt.Sprint(showType, `:`, code)
  1537. if tokenMap != nil {
  1538. if token, ok := tokenMap[key]; ok {
  1539. // 在链接后面添加一个token值
  1540. return link + "&authToken=" + token
  1541. }
  1542. }
  1543. token, err := GeneralChartToken(showType, code, 30*time.Minute)
  1544. if err != nil {
  1545. return link
  1546. }
  1547. if tokenMap != nil {
  1548. tokenMap[key] = token
  1549. }
  1550. // 在链接后面添加一个token值
  1551. return link + "&authToken=" + token
  1552. }
  1553. // linkDelToken 链接添加token
  1554. func linkDelToken(link string) string {
  1555. var err error
  1556. defer func() {
  1557. if err != nil {
  1558. utils.FileLog.Info("处理链接失败,ERR:" + err.Error())
  1559. }
  1560. }()
  1561. parsedURL, err := url.Parse(link)
  1562. if err != nil {
  1563. return link
  1564. }
  1565. // 获取查询参数
  1566. queryParams := parsedURL.Query()
  1567. // 移除authToken参数
  1568. queryParams.Del("authToken")
  1569. // 更新URL的查询参数
  1570. parsedURL.RawQuery = queryParams.Encode()
  1571. return parsedURL.String()
  1572. }
  1573. // GeneralChartToken
  1574. // @Description: 生产图表/表格授权token
  1575. // @author: Roc
  1576. // @datetime 2025-01-07 10:41:36
  1577. // @param showType string
  1578. // @param uniqueCode string
  1579. // @param expireTime time.Duration
  1580. // @return token string
  1581. // @return err error
  1582. func GeneralChartToken(showType, uniqueCode string, expireTime time.Duration) (token string, err error) {
  1583. // 缓存key
  1584. token = utils.MD5(fmt.Sprint(showType+`:`, uniqueCode, time.Now().UnixNano()/1e6))
  1585. key := fmt.Sprint(utils.CACHE_CHART_AUTH, token)
  1586. err = utils.Rc.Put(key, uniqueCode, expireTime)
  1587. return
  1588. }
  1589. // HandleReportContentStruct
  1590. // @Description: 处理内容组件的链接
  1591. // @author: Roc
  1592. // @datetime 2025-01-07 13:38:39
  1593. // @param body string
  1594. // @param opType string
  1595. // @return newBody string
  1596. func HandleReportContentStruct(body string, opType string, tokenMap map[string]string) (newBody string) {
  1597. if body == `` {
  1598. return
  1599. }
  1600. newBody = body
  1601. // 解析JSON数据到map[string]interface{}
  1602. var jsonData []map[string]interface{}
  1603. if err := json.Unmarshal([]byte(body), &jsonData); err != nil {
  1604. fmt.Println("Error parsing JSON:", err)
  1605. return
  1606. }
  1607. // 处理每个组件
  1608. for i := range jsonData {
  1609. if err := processMap(jsonData[i], opType, tokenMap); err != nil {
  1610. fmt.Println("Error processing component:", err)
  1611. return
  1612. }
  1613. }
  1614. // 将处理后的数据转换回JSON字符串
  1615. modifiedJSON, err := json.MarshalIndent(jsonData, "", " ")
  1616. if err != nil {
  1617. fmt.Println("Error marshaling JSON:", err)
  1618. return
  1619. }
  1620. newBody = string(modifiedJSON)
  1621. return
  1622. }
  1623. // processMap 递归处理map中的content字段
  1624. func processMap(data map[string]interface{}, opType string, tokenMap map[string]string) error {
  1625. for key, value := range data {
  1626. switch v := value.(type) {
  1627. case string:
  1628. if key == "content" {
  1629. newContent := v
  1630. // 处理链接
  1631. switch opType {
  1632. case `add`:
  1633. newContent = linkAddToken(v, tokenMap)
  1634. case `del`:
  1635. newContent = linkDelToken(v)
  1636. }
  1637. data[key] = newContent
  1638. }
  1639. case map[string]interface{}:
  1640. if err := processMap(v, opType, tokenMap); err != nil {
  1641. return err
  1642. }
  1643. case []interface{}:
  1644. for i := range v {
  1645. if m, ok := v[i].(map[string]interface{}); ok {
  1646. if err := processMap(m, opType, tokenMap); err != nil {
  1647. return err
  1648. }
  1649. }
  1650. }
  1651. }
  1652. }
  1653. return nil
  1654. }