Forráskód Böngészése

获取汇率、货币单位接口

hsun 2 éve
szülő
commit
76a09e593a
3 módosított fájl, 98 hozzáadás és 19 törlés
  1. 33 4
      controller/contract/register.go
  2. 62 13
      services/fms/currency_rate.go
  3. 3 2
      utils/constants.go

+ 33 - 4
controller/contract/register.go

@@ -2,10 +2,12 @@ package contract
 
 import (
 	"bytes"
+	"context"
 	"encoding/json"
 	"fmt"
 	"github.com/gin-gonic/gin"
 	"github.com/go-playground/validator/v10"
+	jsoniter "github.com/json-iterator/go"
 	"github.com/shopspring/decimal"
 	"github.com/tealeg/xlsx"
 	"hongze/fms_api/controller/resp"
@@ -1993,7 +1995,7 @@ func (rg *RegisterController) Import(c *gin.Context) {
 // CurrencyList
 // @Title 货币单位列表
 // @Description 货币单位列表
-// @Success 200 {object} fms.ContractRegisterItem
+// @Success 200 {object} fms.CurrencyUnitItem
 // @router /contract/register/currency_list [get]
 func (rg *RegisterController) CurrencyList(c *gin.Context) {
 	// 货币列表
@@ -2007,10 +2009,37 @@ func (rg *RegisterController) CurrencyList(c *gin.Context) {
 	}
 
 	rateMap := make(map[string]float64)
+	rateList := make([]*fmsService.CurrencyRateItem, 0)
+	
+	// 读取缓存
+	cacheJson, _ := global.Redis.Get(context.TODO(), utils.CURRENCY_RMB_RATE).Result()
+	if cacheJson != "" {
+		if e = jsoniter.UnmarshalFromString(cacheJson, &rateList); e != nil {
+			resp.FailData("获取失败", "读取汇率缓存失败, Err: "+e.Error(), c)
+			return
+		}
+	}
 
-	// TODO:从缓存中读取汇率
-
-	// TODO:请求汇率接口
+	// 请求汇率接口
+	if cacheJson == "" {
+		rateList, e = fmsService.CurlRateApi()
+		if e != nil {
+			resp.FailData("获取失败", "请求汇率接口失败, Err: "+e.Error(), c)
+			return
+		}
+		newCache, e := jsoniter.MarshalToString(rateList)
+		if e != nil {
+			resp.FailData("获取失败", "写入汇率缓存失败, Err: "+e.Error(), c)
+			return
+		}
+		now := time.Now()
+		todayLast := time.Date(now.Year(), now.Month(), now.Day(), 23, 59, 59, 0, time.Local)
+		sub := todayLast.Sub(now)
+		_ = global.Redis.SetEX(context.TODO(), utils.CURRENCY_RMB_RATE, newCache, sub)
+	}
+	for i := range rateList {
+		rateMap[rateList[i].Code] = rateList[i].Rate
+	}
 
 	respList := make([]*fms.CurrencyUnitItem, 0)
 	for i := range list {

+ 62 - 13
services/fms/currency_rate.go

@@ -1,15 +1,20 @@
 package fms
 
-import "time"
-
-// TODO:汇率
+import (
+	"encoding/json"
+	"fmt"
+	"hongze/fms_api/services/alarm_msg"
+	"hongze/fms_api/utils"
+	"strconv"
+	"time"
+)
 
 const CurrencyRateApiAppCode = "ABC123"
 
 type CurrencyRateApiResp struct {
-	Status int                         `json:"status" description:"状态码"`
-	Msg    string                      `json:"msg" description:"响应信息"`
-	Result []CurrencyRateApiRespResult `json:"result" description:"响应数据"`
+	Status string                    `json:"status" description:"状态码"`
+	Msg    string                    `json:"msg" description:"响应信息"`
+	Result CurrencyRateApiRespResult `json:"result" description:"响应数据"`
 }
 
 type CurrencyRateApiRespResult struct {
@@ -19,16 +24,60 @@ type CurrencyRateApiRespResult struct {
 }
 
 type CurrencyRateApiRespResultList struct {
-	Name       string    `json:"name"`
-	Rate       string    `json:"rate"`
-	UpdateTime time.Time `json:"updatetime"`
+	Name       string `json:"name"`
+	Rate       string `json:"rate"`
+	UpdateTime string `json:"updatetime"`
 }
 
-func CurlRateApi() {
-
+type CurrencyRateItem struct {
+	Name       string    `json:"name"`
+	Code       string    `json:"code"`
+	Rate       float64   `json:"rate"`
+	UpdateTime time.Time `json:"update_time"`
 }
 
-// GetRMBRate 获取人民币汇率
-func GetRMBRate() (err error) {
+func CurlRateApi() (resList []*CurrencyRateItem, err error) {
+	defer func() {
+		if err != nil {
+			go alarm_msg.SendAlarmMsg("请求汇率接口失败, Err: "+err.Error(), 3)
+		}
+	}()
+	// TODO:请求接口
+
+	// 汇率结果
+	resultJson := `{"status":"0","msg":"ok","result":{"currency":"CNY","name":"人民币","list":{"HKD":{"name":"港币","rate":"1.2198","updatetime":"2015-10-26 16:56:22"},"USD":{"name":"美元","rate":"0.1574","updatetime":"2015-10-26 16:56:22"},"EUR":{"name":"欧元","rate":"0.1426","updatetime":"2015-10-26 16:56:22"}}}}`
+	results := new(CurrencyRateApiResp)
+	if e := json.Unmarshal([]byte(resultJson), &results); e != nil {
+		err = fmt.Errorf("rate api result unmarshal err: %s", results.Msg)
+		return
+	}
+	if results.Status != "0" {
+		err = fmt.Errorf("curl rate api errMsg: %s", results.Msg)
+		return
+	}
+	list := results.Result.List
+	if list == nil {
+		err = fmt.Errorf("rate api list is empty")
+		return
+	}
+	resList = make([]*CurrencyRateItem, 0)
+	for k, v := range list {
+		item := new(CurrencyRateItem)
+		item.Code = k
+		item.Name = v.Name
+		f, e := strconv.ParseFloat(v.Rate, 64)
+		if e != nil {
+			err = fmt.Errorf("rate api rate parse err: %v", e)
+			return
+		}
+		item.Rate = f
+		t, e := time.ParseInLocation(utils.FormatDateTime, v.UpdateTime, time.Local)
+		if e != nil {
+			err = fmt.Errorf("rate api time parse err: %v", e)
+			return
+		}
+		item.UpdateTime = t
+		resList = append(resList, item)
+	}
 	return
 }

+ 3 - 2
utils/constants.go

@@ -1,6 +1,6 @@
 package utils
 
-//常量定义
+// 常量定义
 const (
 	FormatTime            = "15:04:05"                //时间格式
 	FormatDate            = "2006-01-02"              //日期格式
@@ -17,7 +17,7 @@ const (
 	PageSize30            = 30
 )
 
-//手机号,电子邮箱正则
+// 手机号,电子邮箱正则
 const (
 	RegularMobile = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0-9])|(17[0-9])|(16[0-9])|(19[0-9]))\\d{8}$" //手机号码
 	RegularEmail  = `\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*`                                             //匹配电子邮箱
@@ -34,6 +34,7 @@ const (
 	SYSTEM_LOGIN_TOKEN          = "fms:login:token:"
 	SYSTEM_LOGIN_TOKEN_NO_TRUST = "fms:login:no_trust:" //管理后台登录(不可信登录态)
 	SYSTEM_LOGIN_ADMINID_IP     = "fms:login:admin_id:"
+	CURRENCY_RMB_RATE           = "fms:currency:rmb:rate" // 汇率接口
 )
 
 // OSS