gpr_risk.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. package services
  2. import (
  3. "context"
  4. "encoding/json"
  5. "eta/eta_crawler/services/alarm_msg"
  6. "eta/eta_crawler/utils"
  7. "fmt"
  8. "github.com/xuri/excelize/v2"
  9. "io"
  10. "net/http"
  11. "os"
  12. "path/filepath"
  13. "strconv"
  14. "time"
  15. )
  16. // GprRiskIndex 美国农业部指标数据
  17. type GprRiskIndex struct {
  18. ClassifyName string `description:"指标目录"`
  19. ParentClassifyName string `description:"父级指标目录"`
  20. ClassifySort int `description:"指标目录排序号"`
  21. IndexName string `description:"指标名称"`
  22. IndexCode string `description:"指标编码"`
  23. Unit string `description:"单位"`
  24. Sort int `description:"排序号"`
  25. Frequency string `description:"频度"`
  26. TerminalCode string `description:"编码"`
  27. ExcelDataMap map[string]string
  28. }
  29. func DownloadGprRiskFile() (err error) {
  30. // todo 设置下载频率, 如果有正在处理中的,则暂停下载
  31. defer func() {
  32. if err != nil {
  33. msg := "失败提醒" + "DownloadGprRiskFile ErrMsg:" + err.Error()
  34. fmt.Println("msg:", msg)
  35. utils.FileLog.Info(msg)
  36. go alarm_msg.SendAlarmMsg(msg, 3)
  37. }
  38. }()
  39. url := "https://www.matteoiacoviello.com/gpr_files/data_gpr_daily_recent.xls"
  40. destDir := "static"
  41. fileName := fmt.Sprintf("data_gpr_daily_recent_%s.xls", time.Now().Format(utils.FormatDateTimeUnSpace))
  42. //fileName := filepath.Base(url)
  43. destPath := filepath.Join(destDir, fileName)
  44. fmt.Println(destPath)
  45. //创建文件
  46. out, err := os.Create(destPath)
  47. if err != nil {
  48. err = fmt.Errorf("failed to create file: %w", err)
  49. return
  50. }
  51. defer out.Close()
  52. // 发起下载请求
  53. resp, err := http.Get(url)
  54. if err != nil {
  55. err = fmt.Errorf("failed to make request: %w", err)
  56. return
  57. }
  58. defer resp.Body.Close()
  59. // 检查HTTP状态码
  60. if resp.StatusCode != http.StatusOK {
  61. err = fmt.Errorf("bad status: %s", resp.Status)
  62. return
  63. }
  64. // 将内容写入文件
  65. _, err = io.Copy(out, resp.Body)
  66. if err != nil {
  67. err = fmt.Errorf("failed to copy content: %w", err)
  68. return
  69. }
  70. // 转换文件格式
  71. downloadFileXlsx := destPath + "x"
  72. err = ConvertXlsToXlsx(destPath, downloadFileXlsx)
  73. if err != nil {
  74. err = fmt.Errorf("文件格式转换失败 convert excel, Err:%w", err)
  75. return
  76. }
  77. // 使用通道等待解析完成
  78. done := make(chan error)
  79. go func() {
  80. done <- ParseGprRiskExcel(downloadFileXlsx)
  81. }()
  82. // 等待解析完成或超时
  83. select {
  84. case err = <-done:
  85. if err != nil {
  86. err = fmt.Errorf("parse excel, Err:%w", err)
  87. return
  88. }
  89. }
  90. // 删除临时文件
  91. defer func() {
  92. os.Remove(destPath)
  93. }()
  94. fmt.Printf(" GPR地缘风险指数 File downloaded successfully: %s\n", destPath)
  95. return
  96. }
  97. func DownloadGPRRiskTask(cont context.Context) (err error) {
  98. err = DownloadGprRiskFile()
  99. return
  100. }
  101. func ParseGprRiskExcel(path string) (err error) {
  102. defer func() {
  103. if err != nil {
  104. msg := "失败提醒" + "ParseGprRiskExcel ErrMsg:" + err.Error()
  105. fmt.Println("msg:", msg)
  106. utils.FileLog.Info(msg)
  107. go alarm_msg.SendAlarmMsg(msg, 3)
  108. }
  109. }()
  110. //var xlFile *xlsx.File
  111. exist, err := PathExists(path)
  112. if err != nil {
  113. fmt.Println(err)
  114. err = fmt.Errorf("文件地址不存在 err:%s", err.Error())
  115. return
  116. }
  117. if !exist {
  118. err = fmt.Errorf("文件地址不存在")
  119. return
  120. }
  121. //xlFile, err = xlsx.OpenFile(path)
  122. xlFile, err := excelize.OpenFile(path)
  123. if err != nil {
  124. fmt.Println("OpenFile err:", err)
  125. err = fmt.Errorf("打开文件失败 err:%s", err.Error())
  126. return
  127. }
  128. defer func() {
  129. // 关闭工作簿
  130. if err = xlFile.Close(); err != nil {
  131. fmt.Println(err)
  132. }
  133. os.Remove(path)
  134. }()
  135. sheetName := xlFile.GetSheetName(0)
  136. fmt.Println("Sheet Name:", sheetName)
  137. //解析出表头第7行
  138. //拼接指标名称
  139. // 指标名称
  140. indexMap := make(map[string]*GprRiskIndex)
  141. indexList := make([]*GprRiskIndex, 0)
  142. sort := 0
  143. rows, err := xlFile.GetRows(sheetName)
  144. dataK := 0
  145. unit := "无"
  146. indexName := "GPR地缘风险指数"
  147. inCode := "gprdyfxzs"
  148. classifyName := "GPR地缘风险指数"
  149. //for _, sheet := range xlFile.Sheets {
  150. //遍历行读取
  151. for i, row := range rows {
  152. if i == 0 {
  153. for k, text := range row {
  154. if text == "GPRD" {
  155. dataK = k
  156. break
  157. }
  158. }
  159. } else {
  160. dateStr := ""
  161. for k, text := range row {
  162. if k == 0 {
  163. dateT, e := time.ParseInLocation("20060102", text, time.Local)
  164. if e != nil {
  165. utils.FileLog.Info("日期格式转换失败 err:%s", err.Error())
  166. continue
  167. }
  168. dateStr = dateT.Format(utils.FormatDate)
  169. } else if k == dataK {
  170. date := dateStr
  171. dataVal := text
  172. indexItem, okIndex := indexMap[indexName]
  173. if !okIndex {
  174. // 新增指标
  175. indexItem = new(GprRiskIndex)
  176. indexItem.IndexName = indexName
  177. indexItem.ClassifyName = classifyName
  178. indexItem.ParentClassifyName = ""
  179. indexItem.ClassifySort = 0
  180. indexItem.IndexCode = inCode
  181. indexItem.Frequency = "日度"
  182. indexItem.Sort = sort
  183. indexItem.Unit = unit
  184. indexItem.ExcelDataMap = make(map[string]string)
  185. sort++
  186. }
  187. val, e := strconv.ParseFloat(dataVal, 64)
  188. if e != nil {
  189. utils.FileLog.Info("数据转换失败 err:%s", e.Error())
  190. continue
  191. }
  192. indexItem.ExcelDataMap[date] = fmt.Sprintf("%.2f", utils.FloatFormatRound(val, 2))
  193. indexMap[indexName] = indexItem
  194. }
  195. }
  196. }
  197. }
  198. //}
  199. for _, v := range indexMap {
  200. //fmt.Printf("IndexName: %s \n", v.IndexName)
  201. //fmt.Printf("IndexCode: %s \n", v.IndexCode)
  202. indexList = append(indexList, v)
  203. if len(indexList) > 100 {
  204. err = addGprRiskData(indexList)
  205. if err != nil {
  206. return
  207. }
  208. indexList = []*GprRiskIndex{}
  209. }
  210. }
  211. if len(indexList) > 0 {
  212. err = addGprRiskData(indexList)
  213. if err != nil {
  214. return
  215. }
  216. }
  217. fmt.Println("GPR地缘风险指数 执行成功")
  218. return
  219. }
  220. func addGprRiskData(indexList []*GprRiskIndex) (err error) {
  221. sheetName := "GPR地缘风险指数"
  222. if len(indexList) > 0 {
  223. params := make(map[string]interface{})
  224. params["List"] = indexList
  225. params["TerminalCode"] = ""
  226. result, e := utils.PostEdbLib(params, "gpr_risk/handle/excel_data")
  227. if e != nil {
  228. err = fmt.Errorf("sheet :%s PostEdbLib err: %s", sheetName, e.Error())
  229. b, _ := json.Marshal(params)
  230. utils.FileLog.Info(fmt.Sprintf("sheet :%s PostEdbLib err: %s, params: %s", sheetName, e.Error(), string(b)))
  231. return
  232. }
  233. resp := new(utils.BaseEdbLibResponse)
  234. if e := json.Unmarshal(result, &resp); e != nil {
  235. err = fmt.Errorf("sheet :%s json.Unmarshal err: %s", sheetName, e)
  236. utils.FileLog.Info(fmt.Sprintf("sheet :%s json.Unmarshal err: %s", sheetName, e))
  237. return
  238. }
  239. if resp.Ret != 200 {
  240. err = fmt.Errorf("sheet :%s Msg: %s, ErrMsg: %s", sheetName, resp.Msg, resp.ErrMsg)
  241. utils.FileLog.Info(fmt.Sprintf("sheet :%s Msg: %s, ErrMsg: %s", sheetName, resp.Msg, resp.ErrMsg))
  242. return
  243. }
  244. }
  245. return
  246. }