浏览代码

Merge branch 'feature/eta_2.6.9'

hsun 1 周之前
父节点
当前提交
9475bb221f
共有 7 个文件被更改,包括 108 次插入52 次删除
  1. 1 0
      controllers/report_chapter.go
  2. 1 0
      controllers/report_v2.go
  3. 8 3
      models/report.go
  4. 1 0
      models/report_chapter.go
  5. 1 1
      models/report_v2.go
  6. 2 1
      services/report_v2.go
  7. 94 47
      services/smart_report.go

+ 1 - 0
controllers/report_chapter.go

@@ -832,6 +832,7 @@ func (this *ReportController) GetDayWeekChapter() {
 		ReportChapterItem: *chapterItem,
 		GrandAdminIdList:  chapterGrantIdList,
 		PermissionIdList:  chapterPermissionIdList,
+		FreeReportRatio:   reportInfo.FreeReportRatio,
 	}
 
 	// 获取当前编辑状态

+ 1 - 0
controllers/report_v2.go

@@ -475,6 +475,7 @@ func (this *ReportController) Add() {
 
 	item.ClassifyIdThird = req.ClassifyIdThird
 	item.ClassifyNameThird = classifyMap[req.ClassifyIdThird]
+	item.FreeReportRatio = req.FreeReportRatio
 
 	// 产品要求,如果是多人协作,那么就是章节类型的报告
 	if req.CollaborateType == 2 {

+ 8 - 3
models/report.go

@@ -93,6 +93,7 @@ type Report struct {
 	VoiceGenerateType   int       `description:"音频生成方式,0:系统生成,1:人工上传"`
 	RaiReportId         int       `description:"RAI报告ID"`
 	MiniShow            int       `description:"是否在C端展示:0-否;1-是"`
+	FreeReportRatio     string    `description:"自由布局页面比例:A4; 16:9; 4:3; 10:7"`
 }
 
 type ReportList struct {
@@ -160,6 +161,7 @@ type ReportList struct {
 	IsCollect           int       `description:"是否收藏"`
 	RaiReportId         int       `description:"RAI报告ID"`
 	MiniShow            int       `description:"是否在C端展示:0-否;1-是"`
+	FreeReportRatio     string    `description:"自由布局页面比例:A4; 16:9; 4:3; 10:7"`
 }
 
 type ReportListResp struct {
@@ -385,6 +387,7 @@ type ReportDetail struct {
 	FreeLayoutConfig    string    `description:"自由布局配置"`
 	RaiReportId         int       `description:"RAI报告ID"`
 	MiniShow            int       `description:"是否在C端展示:0-否;1-是"`
+	FreeReportRatio     string    `description:"自由布局页面比例:A4; 16:9; 4:3; 10:7"`
 }
 
 func GetReportById(reportId int) (item *ReportDetail, err error) {
@@ -530,6 +533,7 @@ type AddReq struct {
 	InheritReportId    int    `description:"待继承的报告ID"`
 	GrantAdminIdList   []int  `description:"授权用户id列表"`
 	MiniShow           int    `description:"是否在C端展示:0-否;1-是"`
+	FreeReportRatio    string `description:"自由布局页面比例:A4; 16:9; 4:3; 10:7"`
 }
 
 type PrePublishReq struct {
@@ -574,9 +578,10 @@ type EditReq struct {
 	EndResourceId      int    `description:"版尾资源ID"`
 	//CollaborateType    int8   `description:"协作方式,1:个人,2:多人协作。默认:1"`
 	//ReportLayout       int8   `description:"报告布局,1:常规布局,2:智能布局。默认:1"`
-	IsPublicPublish  int8  `description:"是否公开发布,1:是,2:否"`
-	GrantAdminIdList []int `description:"授权用户id列表"`
-	MiniShow         int   `description:"是否在C端展示:0-否;1-是"`
+	IsPublicPublish  int8   `description:"是否公开发布,1:是,2:否"`
+	GrantAdminIdList []int  `description:"授权用户id列表"`
+	MiniShow         int    `description:"是否在C端展示:0-否;1-是"`
+	FreeReportRatio  string `description:"自由布局页面比例:A4; 16:9; 4:3; 10:7"`
 }
 
 type EditResp struct {

+ 1 - 0
models/report_chapter.go

@@ -94,6 +94,7 @@ type ReportChapterItemResp struct {
 	EndImg           string `description:"报告尾图地址"`
 	HeadStyle        string `description:"版头样式"`
 	EndStyle         string `description:"版尾样式"`
+	FreeReportRatio  string `description:"自由布局页面比例:A4; 16:9; 4:3; 10:7"`
 }
 
 type ReportChapterResp struct {

+ 1 - 1
models/report_v2.go

@@ -393,7 +393,7 @@ func GetReportListCountByAuthorized(condition string, pars []interface{}) (count
 func GetReportListByAuthorized(condition string, pars []interface{}, startSize, pageSize int) (items []*ReportList, err error) {
 	o := orm.NewOrmUsingDB("rddp")
 
-	sql := `SELECT id,classify_id_first,classify_name_first,classify_id_second,classify_name_second,classify_id_third,classify_name_third,title,stage,create_time,author,report_layout,collaborate_type,is_public_publish,abstract,has_chapter,publish_time,mini_show FROM report as a WHERE 1=1  `
+	sql := `SELECT id,classify_id_first,classify_name_first,classify_id_second,classify_name_second,classify_id_third,classify_name_third,title,stage,create_time,author,report_layout,collaborate_type,is_public_publish,abstract,has_chapter,publish_time,mini_show,free_report_ratio FROM report as a WHERE 1=1  `
 	if condition != "" {
 		sql += condition
 	}

+ 2 - 1
services/report_v2.go

@@ -217,7 +217,7 @@ func EditReport(reportInfo *models.Report, req models.EditReq, sysUser *system.A
 	reportInfo.State = state
 
 	//updateCols := []string{"ClassifyIdFirst", "ClassifyNameFirst", "ClassifyIdSecond", "ClassifyNameSecond", "ClassifyIdThird", "ClassifyNameThird", "Title", "Abstract", "Author", "Frequency", "Stage", "CreateTime", "IsPublicPublish", "LastModifyAdminId", "LastModifyAdminName", "ModifyTime"}
-	updateCols := []string{"Title", "Abstract", "Author", "Frequency", "CreateTime", "IsPublicPublish", "LastModifyAdminId", "LastModifyAdminName", "ModifyTime", "State", "MiniShow"}
+	updateCols := []string{"Title", "Abstract", "Author", "Frequency", "CreateTime", "IsPublicPublish", "LastModifyAdminId", "LastModifyAdminName", "ModifyTime", "State", "MiniShow", "FreeReportRatio"}
 
 	if req.HeadResourceId > 0 {
 		reportInfo.HeadResourceId = req.HeadResourceId
@@ -228,6 +228,7 @@ func EditReport(reportInfo *models.Report, req models.EditReq, sysUser *system.A
 		updateCols = append(updateCols, "EndResourceId")
 	}
 	reportInfo.MiniShow = req.MiniShow
+	reportInfo.FreeReportRatio = req.FreeReportRatio
 
 	// 需要添加的报告授权数据
 	addReportAdminList := make([]*report.ReportGrant, 0)

+ 94 - 47
services/smart_report.go

@@ -8,10 +8,12 @@ import (
 	"eta/eta_mobile/utils"
 	"fmt"
 	"html"
+	"math"
 	"os"
 	"os/exec"
 	"path"
 	"strconv"
+	"strings"
 	"time"
 )
 
@@ -136,11 +138,12 @@ func SmartReportElasticUpsert(smartReportId int, state int) (err error) {
 	return
 }
 
-func ReportToPdf(width int, reportUrl, filePath string, top, bottom, left, right int) (err error) {
+func ReportToPdf(width, height int, reportUrl, filePath string, top, bottom, left, right int) (err error) {
 	pyCode := `
 import asyncio
 from pyppeteer import launch
 
+@asyncio.coroutine
 async def main():
     # 异步代码
     browser = await launch({
@@ -151,7 +154,7 @@ async def main():
     page = await browser.newPage()
     await page.setViewport({
         'width': %d,
-        'height': 1697
+        'height': %d
     })
     await page.goto('%s', {
         'waitUntil': 'networkidle0',
@@ -163,7 +166,7 @@ async def main():
 
     await page.pdf({
 		'width': %d,
-        'height': 1697,
+        'height': %d,
         'path': "%s",
         'printBackground': True,
         'margin': {
@@ -186,7 +189,7 @@ finally:
     loop.close()
 `
 
-	pyCode = fmt.Sprintf(pyCode, utils.ChromePath, width+left+right, reportUrl, width, filePath, top, bottom, left, right)
+	pyCode = fmt.Sprintf(pyCode, utils.ChromePath, width, height, reportUrl, width+left+right, height+top+bottom, filePath, top, bottom, left, right)
 	utils.FileLog.Info("pdf pyCode: \n" + pyCode)
 	cmd := exec.Command("python3", "-c", pyCode)
 	output, e := cmd.CombinedOutput()
@@ -203,7 +206,7 @@ finally:
 	return
 }
 
-func ReportToJpeg(width int, reportUrl, filePath string) (err error) {
+func ReportToJpeg(width, height int, reportUrl, filePath string) (err error) {
 	pyCode := `
 import asyncio
 from pyppeteer import launch, errors
@@ -223,23 +226,23 @@ async def main():
         # 设置视口大小
         await page.setViewport({
             'width': %d,
-            'height': 1080
+            'height': %d
         })
         
         # 导航到页面
         await page.goto('%s', {
             'waitUntil': 'networkidle0',
-            'timeout': 1000000  # 设置超时时间为 100 秒
+            'timeout': 3000000  # 设置超时时间为 100 秒
         })
         # Customizing footer for page numbers starting from page 2
 
         # 在这里添加两秒的等待
-        await asyncio.sleep(2)
+        await asyncio.sleep(5)
 
         await page.screenshot({
             'path': "%s",
             'fullPage': True,
-			'quality':100
+			'quality':80
         })
         
     except errors.BrowserError as e:
@@ -264,10 +267,9 @@ finally:
     loop.close()
 `
 
-	pyCode = fmt.Sprintf(pyCode, utils.ChromePath, width, reportUrl, filePath)
+	pyCode = fmt.Sprintf(pyCode, utils.ChromePath, width, height, reportUrl, filePath)
 	utils.FileLog.Info("jpeg pyCode: \n" + pyCode)
 	cmd := exec.Command("python3", "-c", pyCode)
-
 	output, e := cmd.CombinedOutput()
 	if e != nil {
 		err = e
@@ -304,6 +306,13 @@ func Report2pdfAndJpeg(reportUrl string, reportId, reportType int) {
 	}
 	var report *models.ReportDetail
 
+	// 默认宽高,自由布局需要根据比例重新计算
+	var freeRatio string
+	pcWidth := 1200
+	pcHeight := 1697
+	mobileWidth := 600
+	mobileHeight := 1697
+
 	// 先清空字段
 	if reportType == 1 {
 		report, err = models.GetReportById(reportId)
@@ -315,6 +324,9 @@ func Report2pdfAndJpeg(reportUrl string, reportId, reportType int) {
 			utils.FileLog.Info("清空pdf长图字段失败, Err: \n" + err.Error())
 			return
 		}
+		if report.ReportLayout == 3 {
+			freeRatio = report.FreeReportRatio
+		}
 	} else if reportType == 2 {
 		err = models.UpdatePdfUrlEnglishReportById(reportId)
 		if err != nil {
@@ -329,21 +341,41 @@ func Report2pdfAndJpeg(reportUrl string, reportId, reportType int) {
 		}
 	}
 
+	// 重新计算比例
+	if freeRatio != "" {
+		h, e := calculateReportPdfHeight(pcWidth, freeRatio)
+		if e != nil {
+			err = fmt.Errorf("重新计算PDF生成高度失败, %v", e)
+			return
+		}
+		pcHeight = h
+
+		hm, e := calculateReportPdfHeight(mobileWidth, freeRatio)
+		if e != nil {
+			err = fmt.Errorf("重新计算移动端PDF生成高度失败, %v", e)
+			return
+		}
+		mobileHeight = hm
+	}
+
 	reportCode := utils.MD5(strconv.Itoa(reportId))
 
 	// pc端
-	pdfPath := `./static/` + reportCode + "_1200.pdf"
-	jpegPath := `./static/` + reportCode + "_1200.jpeg"
-
 	go func() {
-		width := 1200
+		pdfPath := `./static/` + reportCode + "_1200.pdf"
+		jpegPath := `./static/` + reportCode + "_1200.jpg"
+
+		//width := 1200
 		top, bottom, left, right := 20, 20, 20, 20
 		if reportType == 1 {
 			if report != nil && report.ReportLayout == 3 {
 				top, bottom, left, right = 0, 0, 0, 0
 			}
 		}
-		err := ReportToPdf(width, reportUrl, pdfPath, top, bottom, left, right)
+		//if reportType == 3 {
+		//	width = 800
+		//}
+		err = ReportToPdf(pcWidth, pcHeight, reportUrl, pdfPath, top, bottom, left, right)
 		if err != nil {
 			utils.FileLog.Info("ReportToPdf failed: , error: \n" + err.Error())
 			go alarm_msg.SendAlarmMsg("ReportToPdf failed:"+err.Error(), 3)
@@ -401,31 +433,26 @@ func Report2pdfAndJpeg(reportUrl string, reportId, reportType int) {
 			}
 		}
 
-	}()
+		time.Sleep(1 * time.Minute)
 
-	go func() {
-		width := 1200
-		/*if reportType == 3 {
-			width = 800
-		}*/
-		err := ReportToJpeg(width, reportUrl, jpegPath)
+		err = ReportToJpeg(pcWidth, pcHeight, reportUrl, jpegPath)
 		if err != nil {
 			utils.FileLog.Info("ReportToJpeg failed: , error: \n" + err.Error())
 		}
-		file, err := os.Open(jpegPath)
+		file, err = os.Open(jpegPath)
 		if err != nil {
 			utils.FileLog.Info("open file failed: , error: \n" + err.Error())
 			return
 		}
 
-		ext := path.Ext(file.Name())
+		ext = path.Ext(file.Name())
 
-		randStr := utils.GetRandStringNoSpecialChar(28)
-		fileName := randStr + ext
+		randStr = utils.GetRandStringNoSpecialChar(28)
+		fileName = randStr + ext
 		defer file.Close() //关闭上传文件
 
-		resourceUrl := ``
-		ossClient := NewOssClient()
+		resourceUrl = ``
+		ossClient = NewOssClient()
 		if ossClient == nil {
 			utils.FileLog.Info("初始化OSS服务失败")
 			return
@@ -461,12 +488,7 @@ func Report2pdfAndJpeg(reportUrl string, reportId, reportType int) {
 				return
 			}
 		}
-
 	}()
-
-	// 移动端
-	pdfPathMobile := `./static/` + reportCode + "_600.pdf"
-	jpegPathMobile := `./static/` + reportCode + "_600.jpeg"
 	var mobilePdf = true
 	if reportType == 1 && report != nil {
 		if report.ReportLayout == 3 {
@@ -474,10 +496,13 @@ func Report2pdfAndJpeg(reportUrl string, reportId, reportType int) {
 		}
 	}
 	if mobilePdf {
+		// 移动端
 		go func() {
-			width := 600
+			pdfPathMobile := `./static/` + reportCode + "_600.pdf"
+			jpegPathMobile := `./static/` + reportCode + "_600.jpg"
 			top, bottom, left, right := 20, 20, 20, 20
-			err := ReportToPdf(width, reportUrl, pdfPathMobile, top, bottom, left, right)
+			//width := 600
+			err = ReportToPdf(mobileWidth, mobileHeight, reportUrl, pdfPathMobile, top, bottom, left, right)
 			if err != nil {
 				utils.FileLog.Info("ReportToPdf failed: , error: \n" + err.Error())
 				go alarm_msg.SendAlarmMsg("ReportToPdf failed:"+err.Error(), 3)
@@ -535,28 +560,26 @@ func Report2pdfAndJpeg(reportUrl string, reportId, reportType int) {
 				}
 			}
 
-		}()
+			time.Sleep(1 * time.Minute)
 
-		go func() {
-			width := 600
-			err := ReportToJpeg(width, reportUrl, jpegPathMobile)
+			err = ReportToJpeg(mobileWidth, mobileHeight, reportUrl, jpegPathMobile)
 			if err != nil {
 				utils.FileLog.Info("ReportToJpeg failed: , error: \n" + err.Error())
 			}
-			file, err := os.Open(jpegPathMobile)
+			file, err = os.Open(jpegPathMobile)
 			if err != nil {
 				utils.FileLog.Info("open file failed: , error: \n" + err.Error())
 				return
 			}
 
-			ext := path.Ext(file.Name())
+			ext = path.Ext(file.Name())
 
-			randStr := utils.GetRandStringNoSpecialChar(28)
-			fileName := randStr + ext
+			randStr = utils.GetRandStringNoSpecialChar(28)
+			fileName = randStr + ext
 			defer file.Close() //关闭上传文件
 
-			resourceUrl := ``
-			ossClient := NewOssClient()
+			resourceUrl = ``
+			ossClient = NewOssClient()
 			if ossClient == nil {
 				utils.FileLog.Info("初始化OSS服务失败")
 				return
@@ -592,7 +615,31 @@ func Report2pdfAndJpeg(reportUrl string, reportId, reportType int) {
 					return
 				}
 			}
-
 		}()
 	}
 }
+
+// calculateReportPdfHeight 自由布局-根据宽度和布局比例计算高度
+func calculateReportPdfHeight(width int, freeRatio string) (height int, err error) {
+	ratioArr := strings.Split(freeRatio, "/")
+	if len(ratioArr) != 2 {
+		err = fmt.Errorf("布局比例有误, %s", freeRatio)
+		return
+	}
+	m, e := strconv.ParseFloat(ratioArr[0], 64)
+	if e != nil {
+		err = fmt.Errorf("布局比例有误, %s", freeRatio)
+		return
+	}
+	n, e := strconv.ParseFloat(ratioArr[1], 64)
+	if e != nil {
+		err = fmt.Errorf("布局比例有误, %s", freeRatio)
+		return
+	}
+	if m <= 0 {
+		err = fmt.Errorf("布局比例有误, %s", freeRatio)
+		return
+	}
+	height = int(math.Round(float64(width) * n / m))
+	return
+}