report_v2.go 67 KB

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