Bläddra i källkod

Merge branch 'feature/customer-eta-mini-ht-api' into debug

kobe6258 2 månader sedan
förälder
incheckning
479ef1343d

+ 63 - 8
controllers/chart.go

@@ -2,10 +2,12 @@ package controllers
 
 import (
 	"encoding/json"
+	"eta/eta_chart_lib/facade"
 	"eta/eta_chart_lib/models"
 	"eta/eta_chart_lib/models/data_manage"
 	"eta/eta_chart_lib/models/data_manage/cross_variety/request"
 	"eta/eta_chart_lib/models/data_manage/excel"
+	requestDTO "eta/eta_chart_lib/models/request"
 	"eta/eta_chart_lib/services/data"
 	"eta/eta_chart_lib/services/data/cross_variety"
 	"eta/eta_chart_lib/services/data/range_analysis"
@@ -37,6 +39,7 @@ func (this *ChartController) ChartInfoDetail() {
 	uniqueCode := this.GetString("UniqueCode")
 	token := this.GetString("Token")
 	source, _ := this.GetInt("Source")
+	miniSource := this.GetString("MiniSource")
 	if uniqueCode == "" {
 		br.Msg = "参数错误"
 		br.ErrMsg = "参数错误,uniqueCode is empty"
@@ -53,16 +56,24 @@ func (this *ChartController) ChartInfoDetail() {
 		return
 	}
 	var isCollect bool
-	if source == utils.CHART_SOURCE_DW && token != "" {
-		tmpIsCollect, err := dwmini.GetMyChartIsCollect(token, uniqueCode)
-		if err != nil {
-			br.Msg = "获取失败"
-			br.ErrMsg = "获取收藏状态失败,Err:" + err.Error()
-			return
+	if miniSource != "" {
+		auth := this.Ctx.Request.Header.Get("Authorization")
+		param := facade.BaseRequest{
+			Auth:       auth,
+			UniqueCode: uniqueCode,
+		}
+		isCollect = facade.FacadeClient.Deal(param).IsCollect(facade.GetInstance(miniSource))
+	} else {
+		if source == utils.CHART_SOURCE_DW && token != "" {
+			tmpIsCollect, err := dwmini.GetMyChartIsCollect(token, uniqueCode)
+			if err != nil {
+				br.Msg = "获取失败"
+				br.ErrMsg = "获取收藏状态失败,Err:" + err.Error()
+				return
+			}
+			isCollect = tmpIsCollect
 		}
-		isCollect = tmpIsCollect
 	}
-
 	//判断是否有缓存
 	if utils.Re == nil {
 		if utils.Re == nil && utils.Rc.IsExist(key) {
@@ -255,6 +266,50 @@ func (this *ChartController) ChartInfoRefresh() {
 	br.Msg = "刷新成功"
 }
 
+// MiniBookMark
+// @Title 小程序收藏/取消收藏通用接口
+// @Description 小程序收藏/取消收藏通用接口
+// @Param	request	body models.ChartCollectReq true "type json string"
+// @Success Ret=200 取消收藏成功
+// @router /mini/bookMark [post]
+func (this *ChartController) MiniBookMark() {
+	br := new(models.BaseResponse).Init()
+	defer func() {
+		this.Data["json"] = br
+		this.ServeJSON()
+	}()
+	var req requestDTO.ChartCollectReq
+	if err := json.Unmarshal(this.Ctx.Input.RequestBody, &req); err != nil {
+		br.Msg = "参数错误"
+		br.ErrMsg = "参数错误,Err:" + err.Error()
+		return
+	}
+	if req.UniqueCode == "" {
+		br.Msg = "参数错误"
+		br.ErrMsg = "参数错误,UniqueCode is empty"
+		return
+	}
+	if req.Source == "" {
+		br.Msg = "参数错误"
+		br.ErrMsg = "参数错误,Source is empty"
+		return
+	}
+	auth := this.Ctx.Request.Header.Get("Authorization")
+	param := facade.BaseRequest{
+		Auth:       auth,
+		UniqueCode: req.UniqueCode,
+	}
+	action, err := facade.FacadeClient.Deal(param).HandleAction(req.Action, facade.GetInstance(req.Source))
+	if err != nil {
+		br.Msg = action + "失败"
+		br.ErrMsg = action + "失败,Err:" + err.Error()
+		return
+	}
+	br.Ret = 200
+	br.Success = true
+	br.Msg = action + "成功"
+}
+
 // CollectCancel
 // @Title 东吴小程序图表取消收藏接口
 // @Description 东吴小程序图表取消收藏接口

+ 143 - 0
facade/instance/ht_mini_facade.go

@@ -0,0 +1,143 @@
+package instance
+
+import (
+	"encoding/json"
+	"errors"
+	"eta/eta_chart_lib/facade"
+	"eta/eta_chart_lib/models"
+	"eta/eta_chart_lib/utils"
+	"fmt"
+)
+
+const (
+	bookMarkUrl      = "user/bookMark"
+	unBookMarkUrl    = "user/unBookMark"
+	checkBookMarkUrl = "user/checkBookMark"
+	target           = "ht"
+)
+
+type HTCollectionReq struct {
+	UniqueCode string `json:"uniqueCode"`
+}
+type HTMiniFacade struct {
+	facade.BaseMiniFacade
+}
+type HTResponse struct {
+	Ret     int
+	Msg     string
+	Data    interface{} `json:"data"`
+	ErrMsg  string
+	ErrCode int
+	Success bool
+}
+type HTRequest struct {
+	facade.BaseRequest
+	ChartInfoId int
+	ChartName   string
+	ChartImage  string
+	SourceType  string
+	SourceId    int
+}
+
+func dealChartInfo(baseReq facade.BaseRequest) (request HTRequest, err error) {
+	chartInfo, err := models.GetChartInfoByUniqueCode(baseReq.UniqueCode)
+	if err != nil {
+		utils.FileLog.Error("收藏失败,获取图表信息失败:%v", err.Error())
+		return
+	}
+	request = HTRequest{
+		BaseRequest: baseReq,
+		ChartImage:  chartInfo.ChartImage,
+		ChartInfoId: chartInfo.ChartInfoId,
+		ChartName:   chartInfo.ChartName,
+		SourceType:  "chart",
+		SourceId:    chartInfo.ChartInfoId,
+	}
+	return
+}
+func parseResult(resp string) (response HTResponse, err error) {
+	err = json.Unmarshal([]byte(resp), &response)
+	if err != nil {
+		utils.FileLog.Error("收藏失败,解析应答失败:%v,应答结果:%s", err.Error(), resp)
+	}
+	if !response.Success {
+		utils.FileLog.Error("收藏失败,应答结果:%d[%s]", response.ErrCode, response.ErrMsg)
+		err = errors.New(response.ErrMsg)
+	}
+	return
+}
+func (ht *HTMiniFacade) Collect(req facade.BaseRequest) (err error) {
+	param, err := dealChartInfo(req)
+	if err != nil {
+		utils.FileLog.Error("收藏失败,获取图表信息失败:%v", err.Error())
+		return err
+	}
+	url, err := generateUrl(bookMarkUrl)
+	if err != nil {
+		return
+	}
+	resp, err := ht.Post(url, param, req.Auth)
+	if err != nil {
+		utils.FileLog.Error("收藏失败,err:%v,resp:%v", err, resp)
+	}
+	_, err = parseResult(resp)
+	return
+}
+func (ht *HTMiniFacade) UnCollect(req facade.BaseRequest) (err error) {
+	param, err := dealChartInfo(req)
+	if err != nil {
+		utils.FileLog.Error("收藏失败,获取图表信息失败:%v", err.Error())
+		return err
+	}
+	url, err := generateUrl(unBookMarkUrl)
+	if err != nil {
+		return
+	}
+	resp, err := ht.Post(url, param, req.Auth)
+	if err != nil {
+		utils.FileLog.Error("取消收藏失败,err:%v,resp:%v", err, resp)
+	}
+	_, err = parseResult(resp)
+	return
+}
+func generateUrl(path string) (url string, err error) {
+	configPath := utils.GetMiniUrl(target)
+	if url == "" {
+		utils.FileLog.Error("获取mini接口地址失败", err)
+		err = errors.New("获取mini接口地址失败")
+		return
+	}
+	url = fmt.Sprintf("%s%s", configPath, path)
+	return
+}
+func (ht *HTMiniFacade) IsCollect(req facade.BaseRequest) bool {
+	param, err := dealChartInfo(req)
+	if err != nil {
+		utils.FileLog.Error("获取是否收藏失败,获取图表信息失败:%v", err.Error())
+		return false
+	}
+	url, err := generateUrl(checkBookMarkUrl)
+	if err != nil {
+		return false
+	}
+	resp, err := ht.Post(url, param, req.Auth)
+	if err != nil {
+		utils.FileLog.Error("获取是否收藏失败,err:%v,resp:%v", err, resp)
+	}
+	response, err := parseResult(resp)
+	if err != nil {
+		utils.FileLog.Error("获取是否收藏失败,解析应答失败:%v,应答结果:%s", err, resp)
+		return false
+	}
+	var resMap = response.Data.(map[string]interface{})
+	bookMarked := resMap["isBookMarked"]
+	if bookMarked == nil {
+		return false
+	}
+	return bookMarked.(bool)
+}
+func init() {
+	facade.RegisterMiniFacade(target, &HTMiniFacade{
+		BaseMiniFacade: facade.FacadeClient,
+	})
+}

+ 234 - 0
facade/mini_facde.go

@@ -0,0 +1,234 @@
+package facade
+
+import (
+	"context"
+	"encoding/json"
+	"errors"
+	"eta/eta_chart_lib/utils"
+	"fmt"
+	"io"
+	"net/http"
+	"strings"
+	"sync"
+	"time"
+)
+
+var (
+	once          sync.Once
+	miniFacadeMap = make(map[string]ChartCollect)
+
+	FacadeClient = BaseMiniFacade{
+		client: DefaultClient(),
+	}
+)
+
+const (
+	bookMark   = "bookMark"
+	unBookMark = "unBookMark"
+)
+
+func GetInstance(name string) ChartCollect {
+	return miniFacadeMap[name]
+}
+
+type ChartCollect interface {
+	Collect(data BaseRequest) (err error)
+	UnCollect(data BaseRequest) (err error)
+	IsCollect(data BaseRequest) bool
+}
+
+type BaseRequest struct {
+	Auth       string `json:"auth"`
+	UniqueCode string `json:"uniqueCode"`
+}
+
+func (bm *BaseMiniFacade) GetData() interface{} {
+	return bm.data
+}
+
+func (bm *BaseMiniFacade) Post(url string, data interface{}, auth string) (result string, err error) {
+	resp, err := bm.client.Post(url, data, auth)
+	if err != nil {
+		return
+	}
+	respBody, respErr := io.ReadAll(resp.Body)
+	if respErr != nil {
+		utils.FileLog.Error("读取body失败,err:%v", err)
+		return
+	}
+	result = string(respBody)
+	return
+}
+func (bm *BaseMiniFacade) Deal(data BaseRequest) *BaseMiniFacade {
+	bm.data = data
+	return bm
+}
+func (bm *BaseMiniFacade) HandleAction(action string, handler ChartCollect) (actionMsg string, err error) {
+	if handler == nil {
+		return "", errors.New("不支持的操作类型")
+	}
+	switch action {
+	case bookMark:
+		err = handler.Collect(bm.data)
+		actionMsg = "收藏"
+	case unBookMark:
+		err = handler.UnCollect(bm.data)
+		actionMsg = "取消收藏"
+	default:
+		err = errors.New("不支持的操作")
+	}
+	return
+}
+
+func (bm *BaseMiniFacade) IsCollect(handler ChartCollect) bool {
+	return handler.IsCollect(bm.data)
+}
+
+type BaseMiniFacade struct {
+	client *HttpClient
+	data   BaseRequest //返回参数
+}
+
+type HttpClient struct {
+	*http.Client
+	maxRetries     int
+	retryDelayFunc RetryDelayFunc
+}
+
+// NewClient 构造函数,其中 delayFunc 参数是可选的
+func NewClient(timeout time.Duration, maxRetries int, delayFunc ...RetryDelayFunc) *HttpClient {
+	var df RetryDelayFunc
+	if len(delayFunc) > 0 {
+		df = delayFunc[0]
+	} else {
+		df = defaultRetryDelayFunc
+	}
+	return &HttpClient{
+		Client:         &http.Client{Timeout: timeout},
+		maxRetries:     maxRetries,
+		retryDelayFunc: df,
+	}
+}
+
+func DefaultClient() *HttpClient {
+	return NewClient(time.Second*10, 3)
+}
+func defaultRetryDelayFunc(attempt int) time.Duration {
+	delay := time.Duration(attempt) * time.Second
+	if attempt > 0 {
+		delay *= 2
+	}
+	return delay
+}
+
+type RetryDelayFunc func(attempt int) time.Duration
+
+func retryErr(err error) bool {
+	return errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled)
+}
+
+// DoWithRetry 发送带有重试机制的HTTP请求,允许用户自定义重试延迟逻辑
+func (hc *HttpClient) DoWithRetry(ctx context.Context, req *http.Request) (resp *http.Response, err error) {
+	attempt := 0
+	for {
+		resp, err = hc.Do(req.WithContext(ctx))
+		if err != nil && retryErr(err) {
+			if attempt >= hc.maxRetries {
+
+				return nil, fmt.Errorf("请求失败: %w", err)
+			}
+			attempt++
+			delay := hc.retryDelayFunc(attempt)
+			time.Sleep(delay)
+			continue
+		}
+		return
+	}
+}
+
+func (hc *HttpClient) Post(url string, data interface{}, auth string) (resp *http.Response, err error) {
+	dataStr, err := json.Marshal(data)
+	if err != nil {
+		utils.FileLog.Error("请求data json序列化失败,err:" + err.Error())
+	}
+	body := io.NopCloser(strings.NewReader(string(dataStr)))
+	req, err := http.NewRequest(http.MethodPost, url, body)
+	req.Header.Set("Content-Type", "application/json")
+	req.Header.Set("Authorization", auth)
+	if err != nil {
+		utils.FileLog.Error("创建POST请求失败: %v", err.Error())
+	}
+	resp, err = hc.DoWithRetry(req.Context(), req)
+	if err == nil {
+		code := resp.StatusCode
+		if code != 200 {
+			utils.FileLog.Error("请求错误应答,状态码:%d", code)
+			errMsg := fmt.Sprintf("请求状态码异常,StatusCode:[%d]", code)
+			respBody, respErr := io.ReadAll(resp.Body)
+			if respErr != nil {
+				utils.FileLog.Error("读取body失败,err:%v", err)
+				err = errors.New(errMsg)
+				return
+			}
+			utils.FileLog.Error("请求错误应答,body:%s", string(respBody))
+			errMsg = fmt.Sprintf("%s,body:%s", errMsg, string(respBody))
+			err = errors.New(errMsg)
+			return
+		}
+	} else {
+		utils.FileLog.Error("未知的应答错误,获取第三方授权信息失败", err.Error())
+	}
+	return
+}
+func (hc *HttpClient) PostWithAuth(url string, data interface{}, token string) (resp *http.Response, err error) {
+	dataStr, err := json.Marshal(data)
+	if err != nil {
+		utils.FileLog.Error("请求data json序列化失败,err:" + err.Error())
+	}
+	body := io.NopCloser(strings.NewReader(string(dataStr)))
+	req, err := http.NewRequest(http.MethodPost, url, body)
+	req.Header.Set("Content-Type", "application/json")
+	req.Header.Set("Authorization", token)
+	if err != nil {
+		utils.FileLog.Error("创建POST请求失败: %v", err)
+	}
+	resp, err = hc.DoWithRetry(req.Context(), req)
+	code := resp.StatusCode
+	if code != 200 {
+		utils.FileLog.Error("请求错误应答,状态码:%d", code)
+		errMsg := fmt.Sprintf("请求状态码异常,StatusCode:[%d]", code)
+		respBody, respErr := io.ReadAll(resp.Body)
+		if respErr != nil {
+			utils.FileLog.Error("读取body失败,err:%v", err)
+			err = errors.New(errMsg)
+			return
+		}
+		utils.FileLog.Error("请求错误应答,body:%s", string(respBody))
+		errMsg = fmt.Sprintf("%s,body:%s", errMsg, string(respBody))
+		err = errors.New(errMsg)
+		return
+	}
+	return
+}
+func (hc *HttpClient) Get(url string) (resp *http.Response, err error) {
+	req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, url, nil)
+	if err != nil {
+		utils.FileLog.Error("创建请求失败: %v", err)
+	}
+	resp, err = hc.DoWithRetry(req.Context(), req)
+	return
+}
+
+func RegisterMiniFacade(name string, facade ChartCollect) {
+	if facade == nil {
+		panic("实例不存在,无法注册")
+	}
+	if _, ok := miniFacadeMap[name]; ok {
+		utils.FileLog.Error("请勿重复注册小程序插件:" + name)
+	}
+	miniFacadeMap[name] = facade
+}
+
+func init() {
+
+}

+ 3 - 3
main.go

@@ -2,16 +2,16 @@ package main
 
 import (
 	"eta/eta_chart_lib/controllers"
+	_ "eta/eta_chart_lib/facade/instance"
 	_ "eta/eta_chart_lib/routers"
 	"eta/eta_chart_lib/services/alarm_msg"
 	"eta/eta_chart_lib/utils"
 	"fmt"
-	"runtime"
-	"time"
-
 	"github.com/beego/beego/v2/adapter/logs"
 	beego "github.com/beego/beego/v2/server/web"
 	"github.com/beego/beego/v2/server/web/context"
+	"runtime"
+	"time"
 )
 
 func main() {

+ 8 - 0
models/request/mini.go

@@ -0,0 +1,8 @@
+package request
+
+type ChartCollectReq struct {
+	UniqueCode string `json:"uniqueCode"`
+	Source     string `json:"source"`
+	Action     string `json:"action"`
+	ExtraInfo  string `json:"extraInfo"` //通用额外信息传输需要的扩展信息
+}

+ 9 - 0
routers/commentsRouter.go

@@ -70,6 +70,15 @@ func init() {
             Filters: nil,
             Params: nil})
 
+    beego.GlobalControllerRouter["eta/eta_chart_lib/controllers:ChartController"] = append(beego.GlobalControllerRouter["eta/eta_chart_lib/controllers:ChartController"],
+        beego.ControllerComments{
+            Method: "MiniBookMark",
+            Router: `/mini/bookMark`,
+            AllowHTTPMethods: []string{"post"},
+            MethodParams: param.Make(),
+            Filters: nil,
+            Params: nil})
+
     beego.GlobalControllerRouter["eta/eta_chart_lib/controllers:ChartController"] = append(beego.GlobalControllerRouter["eta/eta_chart_lib/controllers:ChartController"],
         beego.ControllerComments{
             Method: "ChartInfoRefresh",

+ 2 - 2
services/excel/lucky_sheet.go

@@ -196,7 +196,7 @@ type LuckySheetDataValue struct {
 	VerticalType   int                    ` description:"垂直对齐,	0 中间、1 上、2下"`
 	Fs             interface{}            `json:"fs" description:"字体大小,14"`
 	Cl             interface{}            `json:"cl" description:"删除线,	0 常规 、 1 删除线"`
-	Ht             interface{}            `json:"ht" description:"水平对齐,	0 居中、1 左、2右"`
+	Ht             interface{}            `json:"instance" description:"水平对齐,	0 居中、1 左、2右"`
 	Vt             interface{}            `json:"vt" description:"垂直对齐,	0 中间、1 上、2下"`
 	//TextRotate     string                    `json:"tr" description:"竖排文字,	3"`
 	//RotateText     string                    `json:"rt" description:"文字旋转角度,	介于0~180之间的整数,包含0和180"`
@@ -221,7 +221,7 @@ type LuckySheetDataCellType struct {
 		VerticalType   int         `description:"垂直对齐,	0 中间、1 上、2下"`
 		Fs             interface{} `json:"fs" description:"字体大小,14"`
 		Cl             interface{} `json:"cl" description:"删除线,	0 常规 、 1 删除线"`
-		Ht             interface{} `json:"ht" description:"水平对齐,	0 居中、1 左、2右"`
+		Ht             interface{} `json:"instance" description:"水平对齐,	0 居中、1 左、2右"`
 		Vt             interface{} `json:"vt" description:"垂直对齐,	0 中间、1 上、2下"`
 		Un             interface{} `json:"un" description:""`
 		Bold           interface{} `json:"bl" description:"粗体,0 常规 、 1加粗	"`

+ 9 - 0
utils/config.go

@@ -231,3 +231,12 @@ func FormatTableDataShowValue(x float64) (res string) {
 	}
 	return
 }
+
+func GetMiniUrl(source string) string {
+	config, err := web.AppConfig.GetSection(RunMode)
+	if err != nil {
+		panic("配置文件读取错误 " + err.Error())
+	}
+	urlName := fmt.Sprintf("mini_url_%s", source)
+	return config[urlName]
+}