add
This commit is contained in:
@@ -2,8 +2,6 @@
|
||||
//
|
||||
// go run ./cmd/qygl_report_preview -in resources/dev-report/built.json
|
||||
// go run ./cmd/qygl_report_preview -in built.json -addr :8899 -watch
|
||||
//
|
||||
// 每次打开/刷新页面都会重新读取 -in 文件;加 -watch 后保存 JSON 会自动刷新浏览器。
|
||||
package main
|
||||
|
||||
import (
|
||||
@@ -16,6 +14,8 @@ import (
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"hyapi-server/internal/shared/qyglreport"
|
||||
)
|
||||
|
||||
func parseBuiltReport(data []byte) (map[string]interface{}, error) {
|
||||
@@ -56,9 +56,7 @@ func renderPage(tmpl *template.Template, report map[string]interface{}, injectLi
|
||||
return nil, err
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
if err := tmpl.Execute(&buf, map[string]interface{}{
|
||||
"ReportJSON": template.JS(reportBytes),
|
||||
}); err != nil {
|
||||
if err := tmpl.Execute(&buf, qyglreport.PageTemplateData(template.JS(reportBytes))); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
b := buf.Bytes()
|
||||
@@ -114,6 +112,9 @@ func main() {
|
||||
log.Fatalf("解析模板: %v", err)
|
||||
}
|
||||
|
||||
mediaDir := filepath.Join(rootAbs, "resources", "qygl-media")
|
||||
http.Handle("/reports/qygl/media/", http.StripPrefix("/reports/qygl/media/", http.FileServer(http.Dir(mediaDir))))
|
||||
|
||||
http.HandleFunc("/__version", func(w http.ResponseWriter, r *http.Request) {
|
||||
tag, err := fileVersionTag(inAbs)
|
||||
if err != nil {
|
||||
|
||||
@@ -1049,6 +1049,16 @@ type YYSYP7PLReq struct {
|
||||
DateRange string `json:"date_range" validate:"required,validDateRange"`
|
||||
}
|
||||
|
||||
// YYSY2M8QReq 手机消费区间验证
|
||||
type YYSY2M8QReq struct {
|
||||
MobileNo string `json:"mobile_no" validate:"required,min=11,max=11,validMobileNo"`
|
||||
}
|
||||
|
||||
// YYSY7R4VReq 手机停机验证
|
||||
type YYSY7R4VReq struct {
|
||||
MobileNo string `json:"mobile_no" validate:"required,min=11,max=11,validMobileNo"`
|
||||
}
|
||||
|
||||
type QYGL5S1IReq struct {
|
||||
EntCode string `json:"ent_code" validate:"omitempty,validUSCI"`
|
||||
EntName string `json:"ent_name" validate:"required,min=1,validEnterpriseName"`
|
||||
|
||||
@@ -214,7 +214,8 @@ func registerAllProcessors(combService *comb.CombService) {
|
||||
"YYSYXHHO": yysy.ProcessYYSYXHHORequest, //运营商三要素即时版查询
|
||||
"YYSYGLSF": yysy.ProcessYYSYGLSFRequest, //全网手机三要素验证1979周更新版
|
||||
"YYSYP7PL": yysy.ProcessYYSYP7PLRequest, //手机二次放号检测查询
|
||||
"YYSYS7Y1": yysy.ProcessYYSYS7Y1Request, //移动手机号易诉分
|
||||
"YYSY2M8Q": yysy.ProcessYYSY2M8QRequest, //手机消费区间验证
|
||||
"YYSY7R4V": yysy.ProcessYYSY7R4VRequest, //手机停机验证
|
||||
|
||||
// IVYZ系列处理器
|
||||
"IVYZSQ0E": ivyz.ProcessIVYZSQ0ERequest, //身份证实名认证即时版
|
||||
|
||||
@@ -252,6 +252,8 @@ func (s *FormConfigServiceImpl) getDTOStruct(ctx context.Context, apiCode string
|
||||
"QCXG521L": &dto.QCXG521LReq{}, //车辆静态信息查询 10479
|
||||
"QCXGY7F2": &dto.QCXGY7F2Req{}, //二手车VIN估值 10443
|
||||
"YYSYGLSF": &dto.YYSYGLSFReq{}, //全网手机三要素验证1979周更新版
|
||||
"YYSY2M8Q": &dto.YYSY2M8QReq{}, //手机消费区间验证
|
||||
"YYSY7R4V": &dto.YYSY7R4VReq{}, //手机停机验证
|
||||
"QCXG3M7Z": &dto.QCXG3M7ZReq{}, //人车关系核验(ETC)10093 月更
|
||||
"JRZQ1P5G": &dto.JRZQ1P5GReq{}, //全国自然人借贷压力指数查询(2)
|
||||
"IVYZ9OHN": &dto.IVYZ9OHNReq{}, //身份证OCR
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
package yysy
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"hyapi-server/internal/domains/api/dto"
|
||||
"hyapi-server/internal/domains/api/services/processors"
|
||||
)
|
||||
|
||||
// ProcessYYSY2M8QRequest YYSYXF7J 手机消费区间验证(天远中转)
|
||||
func ProcessYYSY2M8QRequest(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
|
||||
var paramsDto dto.YYSY2M8QReq
|
||||
return processors.ValidateParamsAndCallTianyuan(ctx, deps, "YYSYXF7J", params, ¶msDto)
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package yysy
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"hyapi-server/internal/domains/api/dto"
|
||||
"hyapi-server/internal/domains/api/services/processors"
|
||||
)
|
||||
|
||||
// ProcessYYSY7R4VRequest YYSYT7C4 手机停机验证(天远中转)
|
||||
func ProcessYYSY7R4VRequest(ctx context.Context, params []byte, deps *processors.ProcessorDependencies) ([]byte, error) {
|
||||
var paramsDto dto.YYSY7R4VReq
|
||||
return processors.ValidateParamsAndCallTianyuan(ctx, deps, "YYSYT7C4", params, ¶msDto)
|
||||
}
|
||||
@@ -19,10 +19,11 @@ import (
|
||||
"hyapi-server/internal/domains/api/services/processors"
|
||||
"hyapi-server/internal/domains/api/services/processors/qygl/reportstore"
|
||||
"hyapi-server/internal/shared/pdf"
|
||||
"hyapi-server/internal/shared/qyglreport"
|
||||
)
|
||||
|
||||
// QYGLReportHandler 企业全景报告页面渲染处理器
|
||||
// 使用 QYGLJ1U9 聚合接口生成企业报告数据,并通过模板引擎渲染 qiye.html
|
||||
// 使用 QYGL7HBN 聚合接口生成企业报告数据,并通过模板引擎渲染 qiye.html
|
||||
type QYGLReportHandler struct {
|
||||
apiRequestService *api_services.ApiRequestService
|
||||
logger *zap.Logger
|
||||
@@ -95,12 +96,9 @@ func (h *QYGLReportHandler) GetQYGLReportPage(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// 使用 template.JS 避免在脚本中被转义,直接作为 JS 对象字面量注入
|
||||
reportJSON := template.JS(reportJSONBytes)
|
||||
|
||||
c.HTML(http.StatusOK, "qiye.html", gin.H{
|
||||
"ReportJSON": reportJSON,
|
||||
})
|
||||
c.HTML(http.StatusOK, "qiye.html", qyglreport.PageTemplateData(reportJSON))
|
||||
}
|
||||
|
||||
// GetQYGLReportPageByID 通过编号查看企业全景报告页面
|
||||
@@ -116,10 +114,7 @@ func (h *QYGLReportHandler) GetQYGLReportPageByID(c *gin.Context) {
|
||||
if h.reportRepo != nil {
|
||||
if entity, err := h.reportRepo.FindByReportID(c.Request.Context(), id); err == nil && entity != nil {
|
||||
h.maybeScheduleQYGLPDFPregen(c.Request.Context(), id)
|
||||
reportJSON := template.JS(entity.ReportData)
|
||||
c.HTML(http.StatusOK, "qiye.html", gin.H{
|
||||
"ReportJSON": reportJSON,
|
||||
})
|
||||
c.HTML(http.StatusOK, "qiye.html", qyglreport.PageTemplateData(template.JS(entity.ReportData)))
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -138,13 +133,11 @@ func (h *QYGLReportHandler) GetQYGLReportPageByID(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
reportJSON := template.JS(reportJSONBytes)
|
||||
|
||||
h.maybeScheduleQYGLPDFPregen(c.Request.Context(), id)
|
||||
|
||||
c.HTML(http.StatusOK, "qiye.html", gin.H{
|
||||
"ReportJSON": reportJSON,
|
||||
})
|
||||
reportJSON := template.JS(reportJSONBytes)
|
||||
|
||||
c.HTML(http.StatusOK, "qiye.html", qyglreport.PageTemplateData(reportJSON))
|
||||
}
|
||||
|
||||
// qyglReportExists 报告是否仍在库或本进程内存中(用于决定是否补开预生成)
|
||||
|
||||
@@ -23,6 +23,9 @@ func NewQYGLReportRoutes(
|
||||
func (r *QYGLReportRoutes) Register(router *sharedhttp.GinRouter) {
|
||||
engine := router.GetEngine()
|
||||
|
||||
// 报告头图/页脚(qiye.html 样式引用)
|
||||
engine.Static("/reports/qygl/media", "resources/qygl-media")
|
||||
|
||||
// 企业全景报告页面(实时生成)
|
||||
engine.GET("/reports/qygl", r.handler.GetQYGLReportPage)
|
||||
|
||||
|
||||
@@ -10,6 +10,12 @@ import (
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// A4 纵向 @ 96dpi,与 CSS @page / 报告页 max-width 对齐
|
||||
const (
|
||||
htmlPDFViewportWidth = 794
|
||||
htmlPDFViewportHeight = 1123
|
||||
)
|
||||
|
||||
// HTMLPDFGenerator 使用 headless Chrome 将 HTML 页面渲染为 PDF
|
||||
type HTMLPDFGenerator struct {
|
||||
logger *zap.Logger
|
||||
@@ -26,41 +32,54 @@ func NewHTMLPDFGenerator(logger *zap.Logger) *HTMLPDFGenerator {
|
||||
}
|
||||
|
||||
// GenerateFromURL 使用 headless Chrome 打开指定 URL,并导出为 PDF 字节流
|
||||
// 这里固定使用 A4 纵向纸张,开启背景打印
|
||||
// 流程:A4 视口渲染 → 等待报告 DOM → 滚动触发展开 → 切换 print 媒体 → PrintToPDF(边距由 CSS @page 控制)
|
||||
func (g *HTMLPDFGenerator) GenerateFromURL(ctx context.Context, url string) ([]byte, error) {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
|
||||
// 整个生成过程增加超时时间,避免长时间卡死
|
||||
timeoutCtx, cancel := context.WithTimeout(ctx, 60*time.Second)
|
||||
timeoutCtx, cancel := context.WithTimeout(ctx, 90*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// 创建 Chrome 上下文(使用系统默认的 headless Chrome/Chromium)
|
||||
chromeCtx, cancelChrome := chromedp.NewContext(timeoutCtx)
|
||||
opts := append(chromedp.DefaultExecAllocatorOptions[:],
|
||||
chromedp.Flag("headless", true),
|
||||
chromedp.Flag("disable-gpu", true),
|
||||
chromedp.Flag("no-sandbox", true),
|
||||
chromedp.Flag("disable-dev-shm-usage", true),
|
||||
)
|
||||
allocCtx, allocCancel := chromedp.NewExecAllocator(timeoutCtx, opts...)
|
||||
defer allocCancel()
|
||||
|
||||
chromeCtx, cancelChrome := chromedp.NewContext(allocCtx)
|
||||
defer cancelChrome()
|
||||
|
||||
var pdfBuf []byte
|
||||
|
||||
tasks := chromedp.Tasks{
|
||||
chromedp.EmulateViewport(htmlPDFViewportWidth, htmlPDFViewportHeight),
|
||||
chromedp.Navigate(url),
|
||||
// 等待页面主体和报告容器就绪,确保数据渲染完成
|
||||
chromedp.WaitReady("body", chromedp.ByQuery),
|
||||
chromedp.WaitVisible(".page", chromedp.ByQuery),
|
||||
waitReportReadyForPDF(),
|
||||
waitReportPosterImages(),
|
||||
scrollPageForPrintLayout(),
|
||||
chromedp.ActionFunc(func(ctx context.Context) error {
|
||||
return chromedp.Evaluate(`document.body.classList.add('pdf-export')`, nil).Do(ctx)
|
||||
}),
|
||||
chromedp.ActionFunc(func(ctx context.Context) error {
|
||||
time.Sleep(150 * time.Millisecond)
|
||||
return nil
|
||||
}),
|
||||
chromedp.ActionFunc(func(ctx context.Context) error {
|
||||
g.logger.Info("开始通过 headless Chrome 生成企业报告 PDF", zap.String("url", url))
|
||||
var (
|
||||
buf []byte
|
||||
err error
|
||||
)
|
||||
buf, _, err = page.PrintToPDF().
|
||||
buf, _, err := page.PrintToPDF().
|
||||
WithPrintBackground(true).
|
||||
WithPaperWidth(8.27). // A4 宽度(英寸 -> 约 210mm)
|
||||
WithPaperHeight(11.69). // A4 高度(英寸 -> 约 297mm)
|
||||
WithMarginTop(0.4).
|
||||
WithMarginBottom(0.4).
|
||||
WithMarginLeft(0.4).
|
||||
WithMarginRight(0.4).
|
||||
WithPaperWidth(8.27).
|
||||
WithPaperHeight(11.69).
|
||||
WithMarginTop(0.39).
|
||||
WithMarginBottom(0.39).
|
||||
WithMarginLeft(0.47).
|
||||
WithMarginRight(0.47).
|
||||
Do(ctx)
|
||||
if err == nil {
|
||||
pdfBuf = buf
|
||||
@@ -86,3 +105,87 @@ func (g *HTMLPDFGenerator) GenerateFromURL(ctx context.Context, url string) ([]b
|
||||
return pdfBuf, nil
|
||||
}
|
||||
|
||||
// waitReportReadyForPDF 等待企业报告脚本渲染完成(qiye.html 设置 data-qygl-report-ready)
|
||||
func waitReportReadyForPDF() chromedp.Action {
|
||||
return chromedp.ActionFunc(func(ctx context.Context) error {
|
||||
deadline := time.Now().Add(45 * time.Second)
|
||||
for {
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
var ready string
|
||||
_ = chromedp.Evaluate(`document.body && document.body.dataset.qyglReportReady || ''`, &ready).Do(ctx)
|
||||
if ready == "1" {
|
||||
return nil
|
||||
}
|
||||
var sectionCount float64
|
||||
_ = chromedp.Evaluate(`document.querySelectorAll('#reportSections .section-card, .report-sections .section-block').length`, §ionCount).Do(ctx)
|
||||
if sectionCount > 0 {
|
||||
return nil
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
return fmt.Errorf("等待报告内容渲染超时")
|
||||
}
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func waitReportPosterImages() chromedp.Action {
|
||||
return chromedp.ActionFunc(func(ctx context.Context) error {
|
||||
deadline := time.Now().Add(20 * time.Second)
|
||||
for {
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
var pending float64
|
||||
js := `(function(){
|
||||
var imgs = document.querySelectorAll('img.header-poster, img.footer-poster');
|
||||
if (!imgs.length) return 0;
|
||||
for (var i = 0; i < imgs.length; i++) {
|
||||
var img = imgs[i];
|
||||
if (!img.complete || img.naturalWidth === 0) return 1;
|
||||
}
|
||||
return 0;
|
||||
})()`
|
||||
if err := chromedp.Evaluate(js, &pending).Do(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
if pending == 0 {
|
||||
return nil
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
return fmt.Errorf("等待报告海报图片加载超时")
|
||||
}
|
||||
time.Sleep(150 * time.Millisecond)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func scrollPageForPrintLayout() chromedp.Action {
|
||||
return chromedp.ActionFunc(func(ctx context.Context) error {
|
||||
var height float64
|
||||
if err := chromedp.Evaluate(`Math.max(document.body.scrollHeight, document.documentElement.scrollHeight)`, &height).Do(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
step := float64(900)
|
||||
if height < step {
|
||||
step = height
|
||||
}
|
||||
if step <= 0 {
|
||||
return nil
|
||||
}
|
||||
for y := float64(0); y <= height; y += step {
|
||||
js := fmt.Sprintf(`window.scrollTo(0, %f);`, y)
|
||||
if err := chromedp.Evaluate(js, nil).Do(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
time.Sleep(120 * time.Millisecond)
|
||||
}
|
||||
if err := chromedp.Evaluate(`window.scrollTo(0, 0);`, nil).Do(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
time.Sleep(300 * time.Millisecond)
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
77
internal/shared/qyglreport/poster_assets.go
Normal file
77
internal/shared/qyglreport/poster_assets.go
Normal file
@@ -0,0 +1,77 @@
|
||||
package qyglreport
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"html/template"
|
||||
"mime"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultBannerRel = "resources/qygl-media/banner.jpg"
|
||||
defaultFooterRel = "resources/qygl-media/footer.png"
|
||||
)
|
||||
|
||||
var (
|
||||
loadOnce sync.Once
|
||||
bannerURL template.URL
|
||||
footerURL template.URL
|
||||
)
|
||||
|
||||
func loadPosterAssets() {
|
||||
bannerURL = dataURLFromFile(resolveMediaFile([]string{
|
||||
defaultBannerRel,
|
||||
"resources/qygl-media/banner.png",
|
||||
}), "/reports/qygl/media/banner.jpg")
|
||||
footerURL = dataURLFromFile(defaultFooterRel, "/reports/qygl/media/footer.png")
|
||||
}
|
||||
|
||||
func resolveMediaFile(candidates []string) string {
|
||||
for _, p := range candidates {
|
||||
if _, err := os.Stat(p); err == nil {
|
||||
return p
|
||||
}
|
||||
}
|
||||
if len(candidates) > 0 {
|
||||
return candidates[0]
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func dataURLFromFile(path string, httpFallback string) template.URL {
|
||||
if path == "" {
|
||||
return template.URL(httpFallback)
|
||||
}
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return template.URL(httpFallback)
|
||||
}
|
||||
ext := filepath.Ext(path)
|
||||
mimeType := mime.TypeByExtension(ext)
|
||||
if mimeType == "" {
|
||||
switch ext {
|
||||
case ".jpg", ".jpeg":
|
||||
mimeType = "image/jpeg"
|
||||
case ".png":
|
||||
mimeType = "image/png"
|
||||
default:
|
||||
mimeType = "application/octet-stream"
|
||||
}
|
||||
}
|
||||
encoded := base64.StdEncoding.EncodeToString(data)
|
||||
return template.URL("data:" + mimeType + ";base64," + encoded)
|
||||
}
|
||||
|
||||
// PageTemplateData 企业报告 HTML 模板数据(海报内嵌 data URL,PDF 生成不依赖外链)
|
||||
func PageTemplateData(reportJSON template.JS) gin.H {
|
||||
loadOnce.Do(loadPosterAssets)
|
||||
return gin.H{
|
||||
"ReportJSON": reportJSON,
|
||||
"BannerPosterURL": bannerURL,
|
||||
"FooterPosterURL": footerURL,
|
||||
}
|
||||
}
|
||||
1681
resources/qiye.html
1681
resources/qiye.html
File diff suppressed because it is too large
Load Diff
BIN
resources/qygl-media/banner.jpg
Normal file
BIN
resources/qygl-media/banner.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 49 KiB |
BIN
resources/qygl-media/banner.png
Normal file
BIN
resources/qygl-media/banner.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 541 KiB |
BIN
resources/qygl-media/footer.png
Normal file
BIN
resources/qygl-media/footer.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 295 KiB |
Reference in New Issue
Block a user