init_calculate_index.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. package services
  2. import (
  3. "bytes"
  4. "crypto/md5"
  5. "encoding/json"
  6. "errors"
  7. "eta/eta_data_init/models"
  8. "eta/eta_data_init/utils"
  9. "fmt"
  10. "github.com/shopspring/decimal"
  11. "github.com/xuri/excelize/v2"
  12. "io/ioutil"
  13. "net/http"
  14. "os"
  15. "path/filepath"
  16. "reflect"
  17. "sort"
  18. "strconv"
  19. "strings"
  20. "time"
  21. )
  22. //初始化计算指标数据
  23. //classifyId:=685
  24. const (
  25. HZ_DATA_API = "https://hzdataapi.hzinsights.com/hzdataapi/"
  26. ClassifyId = 685
  27. )
  28. func InitCalculateIndex() {
  29. //读取基础指标
  30. var err error
  31. defer func() {
  32. if err != nil {
  33. fmt.Println("InitBaseIndexData Err:" + err.Error())
  34. }
  35. }()
  36. //读取excel
  37. path, err := filepath.Abs(os.Args[0])
  38. if err != nil {
  39. fmt.Println(err)
  40. }
  41. dir := filepath.Dir(path)
  42. fmt.Println("dir:" + dir)
  43. dataPath := dir + "/docs/逸诺指标库(基础).xlsx"
  44. fmt.Println("dataPath:" + dataPath)
  45. f, err := excelize.OpenFile(dataPath)
  46. if err != nil {
  47. fmt.Println(err)
  48. return
  49. }
  50. defer func() {
  51. // Close the spreadsheet.
  52. if err := f.Close(); err != nil {
  53. fmt.Println(err)
  54. }
  55. }()
  56. rows, err := f.GetRows("edb_info")
  57. if err != nil {
  58. fmt.Println(err)
  59. return
  60. }
  61. hzMethod := "edb_index/detail"
  62. edbLibIndexMethod := "/edb_info/detail"
  63. var needAddIndexArr []string
  64. needAddIndexMap := make(map[string]string)
  65. edbLibIndexMap := make(map[string]int)
  66. for rk, row := range rows {
  67. if rk <= 0 {
  68. continue
  69. }
  70. if rk%10 == 0 {
  71. time.Sleep(3 * time.Second)
  72. }
  73. var indexCode string
  74. for ck, colCell := range row {
  75. switch ck {
  76. case 0:
  77. indexCode = colCell
  78. }
  79. }
  80. fmt.Println(rk, indexCode)
  81. if indexCode == "" {
  82. fmt.Println("指标编码不能为空")
  83. return
  84. }
  85. params := make(map[string]interface{})
  86. params["EdbCode"] = indexCode
  87. result, err := hzDataHttpPost(hzMethod, params)
  88. if err != nil {
  89. fmt.Println("hzDataHttpPost Err:" + err.Error())
  90. return
  91. }
  92. utils.FileLog.Info("hzDataHttpPost:" + string(result))
  93. resp := new(models.EdbInfoResp)
  94. err = json.Unmarshal([]byte(result), &resp)
  95. if err != nil {
  96. fmt.Println("json.Unmarshal Err:" + err.Error())
  97. return
  98. }
  99. if resp.Ret != 200 && !strings.Contains(resp.ErrMsg, "QuerySeter") {
  100. fmt.Println("resp Err:" + resp.ErrMsg)
  101. return
  102. }
  103. //指标信息不存在
  104. if resp.Data.EdbInfoId <= 0 {
  105. fmt.Println("指标:" + indexCode + ";不存在")
  106. f.SetCellStr("edb_info", "H"+strconv.Itoa(rk+1), "不存在")
  107. continue
  108. }
  109. //判断是否存在计算指标
  110. if len(resp.Data.CalculateList) <= 0 {
  111. f.SetCellStr("edb_info", "H"+strconv.Itoa(rk+1), "不存在")
  112. continue
  113. }
  114. //存在计算指标
  115. for _, cv := range resp.Data.CalculateList {
  116. //计算指标所依赖的基础指标
  117. var total int
  118. for _, bv := range cv.BaseEdbInfoCode {
  119. //判断基础指标是否存在
  120. indexMap := make(map[string]interface{})
  121. indexMap["EdbCode"] = bv.FromEdbCode
  122. result, err := PostEdbLib(indexMap, edbLibIndexMethod)
  123. if err != nil {
  124. utils.FileLog.Info("获取计算指标所依赖的基础指标失败:" + err.Error() + " result:" + string(result))
  125. return
  126. }
  127. indexResp := new(models.EdbInfoResp)
  128. err = json.Unmarshal(result, &indexResp)
  129. if err != nil {
  130. utils.FileLog.Info("json.Unmarshal 获取计算指标所依赖的基础指标失败:" + err.Error())
  131. return
  132. }
  133. if indexResp.Ret != 200 && indexResp.ErrCode != "400" {
  134. fmt.Println("获取计算指标所依赖的基础指标失败 Err:" + indexResp.Msg)
  135. return
  136. }
  137. if indexResp.Data.EdbInfoId > 0 {
  138. edbLibIndexMap[bv.FromEdbCode] = indexResp.Data.EdbInfoId
  139. total++
  140. }
  141. }
  142. if total == len(cv.BaseEdbInfoCode) {
  143. if _, ok := needAddIndexMap[cv.EdbCode]; !ok {
  144. needAddIndexArr = append(needAddIndexArr, cv.EdbCode)
  145. needAddIndexMap[cv.EdbCode] = cv.EdbCode
  146. }
  147. }
  148. }
  149. }
  150. f.Save()
  151. fmt.Println("calculate len:", len(needAddIndexArr))
  152. time.Sleep(30 * time.Second)
  153. hzIndexMethod := "edb_index/item"
  154. hzCalculateIndexMethod := "edb_info_calculate/item"
  155. edbLibIndexMethod = "edb_info/copy/from/hz"
  156. edbLibCalculateIndexMethod := "edb_info/copy/calculate/from/hz"
  157. for k, v := range needAddIndexArr { //需要同步的计算指标
  158. fmt.Println(k, v)
  159. params := make(map[string]interface{})
  160. params["EdbCode"] = v
  161. hzResult, err := hzDataHttpPost(hzIndexMethod, params)
  162. if err != nil {
  163. fmt.Println("hzDataHttpPost Err:" + err.Error())
  164. return
  165. }
  166. hzResp := new(models.EdbInfoItemResp)
  167. err = json.Unmarshal([]byte(hzResult), &hzResp)
  168. if err != nil {
  169. fmt.Println("json.Unmarshal Err:" + err.Error())
  170. return
  171. }
  172. if hzResp.Ret != 200 {
  173. fmt.Println("resp Err:" + hzResp.ErrMsg)
  174. return
  175. }
  176. edbInfo := hzResp.Data
  177. //新增指标信息
  178. indexMap := make(map[string]interface{})
  179. indexMap["EdbInfoType"] = edbInfo.EdbInfoType
  180. indexMap["SourceName"] = edbInfo.SourceName
  181. indexMap["Source"] = edbInfo.Source
  182. indexMap["EdbCode"] = edbInfo.EdbCode
  183. indexMap["EdbName"] = edbInfo.EdbName
  184. indexMap["EdbNameEn"] = edbInfo.EdbNameEn
  185. indexMap["EdbNameSource"] = edbInfo.EdbNameSource
  186. indexMap["Frequency"] = edbInfo.Frequency
  187. indexMap["Unit"] = edbInfo.Unit
  188. indexMap["UnitEn"] = edbInfo.UnitEn
  189. indexMap["StartDate"] = edbInfo.StartDate
  190. indexMap["EndDate"] = edbInfo.EndDate
  191. indexMap["ClassifyId"] = ClassifyId
  192. indexMap["SysUserId"] = 0
  193. indexMap["SysUserRealName"] = ""
  194. indexMap["UniqueCode"] = edbInfo.UniqueCode
  195. indexMap["CreateTime"] = time.Now()
  196. indexMap["ModifyTime"] = time.Now()
  197. indexMap["MinValue"] = edbInfo.MinValue
  198. indexMap["MaxValue"] = edbInfo.MaxValue
  199. indexMap["CalculateFormula"] = edbInfo.CalculateFormula
  200. indexMap["EdbType"] = edbInfo.EdbType
  201. indexMap["IsUpdate"] = 1
  202. indexMap["Sort"] = edbInfo.Sort
  203. indexMap["LatestDate"] = edbInfo.LatestDate
  204. indexMap["LatestValue"] = edbInfo.LatestValue
  205. indexMap["MoveType"] = edbInfo.MoveType
  206. indexMap["MoveFrequency"] = edbInfo.MoveFrequency
  207. indexMap["NoUpdate"] = edbInfo.NoUpdate
  208. indexMap["ServerUrl"] = edbInfo.ServerUrl
  209. indexMap["ChartImage"] = edbInfo.ChartImage
  210. indexMap["Calendar"] = edbInfo.Calendar
  211. indexMap["DataDateType"] = edbInfo.DataDateType
  212. edbLibResult, err := PostEdbLib(indexMap, edbLibIndexMethod)
  213. if err != nil {
  214. utils.FileLog.Info("新增计算指标失败:" + err.Error() + " result:" + string(edbLibResult))
  215. return
  216. }
  217. indexBaseResp := new(models.EdbInfoResp)
  218. err = json.Unmarshal(edbLibResult, &indexBaseResp)
  219. if err != nil {
  220. fmt.Println("edbLibResult json.Unmarshal Err:" + err.Error())
  221. return
  222. }
  223. if indexBaseResp.Ret != 200 {
  224. fmt.Println("PostEdbLib resp Err:" + hzResp.ErrMsg)
  225. return
  226. }
  227. //新增计算指标映射关系
  228. calculateParams := make(map[string]interface{})
  229. calculateParams["EdbCode"] = v
  230. hzResult, err = hzDataHttpPost(hzCalculateIndexMethod, calculateParams)
  231. if err != nil {
  232. fmt.Println("hzDataHttpPost calculate Err:" + err.Error())
  233. return
  234. }
  235. hzCalculateResp := new(models.EdbInfoCalculateMappingResp)
  236. err = json.Unmarshal([]byte(hzResult), &hzCalculateResp)
  237. if err != nil {
  238. fmt.Println("calculate json.Unmarshal Err:" + err.Error())
  239. return
  240. }
  241. if hzResp.Ret != 200 {
  242. fmt.Println("calculate resp Err:" + hzResp.ErrMsg)
  243. return
  244. }
  245. for _, cv := range hzCalculateResp.Data {
  246. //获取FromIndex
  247. var fromEdbInfoId int
  248. fromEdbInfoId = edbLibIndexMap[cv.FromEdbCode]
  249. //新增指标信息
  250. indexCalculateMap := make(map[string]interface{})
  251. indexCalculateMap["EdbInfoId"] = indexBaseResp.Data.EdbInfoId
  252. indexCalculateMap["Source"] = cv.Source
  253. indexCalculateMap["SourceName"] = cv.SourceName
  254. indexCalculateMap["EdbCode"] = cv.EdbCode
  255. indexCalculateMap["FromEdbInfoId"] = fromEdbInfoId
  256. indexCalculateMap["FromEdbCode"] = cv.FromEdbCode
  257. indexCalculateMap["FromEdbName"] = cv.FromEdbName
  258. indexCalculateMap["FromSource"] = cv.FromSource
  259. indexCalculateMap["FromSourceName"] = cv.FromSourceName
  260. indexCalculateMap["MoveValue"] = cv.MoveValue
  261. indexCalculateMap["Sort"] = cv.Sort
  262. indexCalculateMap["CreateTime"] = time.Now()
  263. indexCalculateMap["ModifyTime"] = time.Now()
  264. indexCalculateMap["FromTag"] = cv.FromTag
  265. edbLibResult, err := PostEdbLib(indexCalculateMap, edbLibCalculateIndexMethod)
  266. if err != nil {
  267. utils.FileLog.Info("新增计算指标映射关系失败:" + err.Error() + " result:" + string(edbLibResult))
  268. return
  269. }
  270. baseResp := new(models.BaseResponse)
  271. err = json.Unmarshal([]byte(edbLibResult), &baseResp)
  272. if err != nil {
  273. fmt.Println("edbLibResult mapping json.Unmarshal Err:" + err.Error())
  274. return
  275. }
  276. if baseResp.Ret != 200 {
  277. fmt.Println("PostEdbLib mapping resp Err:" + hzResp.ErrMsg)
  278. return
  279. }
  280. }
  281. time.Sleep(1 * time.Second)
  282. }
  283. }
  284. func hzDataHttpPost(method string, postDataMap map[string]interface{}) (result string, err error) {
  285. bytesData, err := handlePostData(postDataMap)
  286. if err != nil {
  287. return
  288. }
  289. client := &http.Client{}
  290. req, err := http.NewRequest("POST", HZ_DATA_API+method, bytes.NewReader(bytesData))
  291. if err != nil {
  292. return "", err
  293. }
  294. req.Header.Set("content-type", "application/json")
  295. resp, err := client.Do(req)
  296. if err != nil {
  297. return "", err
  298. }
  299. body, err := ioutil.ReadAll(resp.Body)
  300. if err != nil {
  301. return "", err
  302. }
  303. result = string(body)
  304. return
  305. }
  306. // handlePostData 处理post请求数据
  307. func handlePostData(postDataMap map[string]interface{}) (bytesData []byte, err error) {
  308. postDataMap["nonce_str"] = utils.GetRandString(16) // 随机字符串
  309. postDataMap["timestamp"] = time.Now().Unix() //当前格林威治时间,int64类型
  310. postDataMap["appid"] = utils.APPID //当前格林威治时间,int64类型
  311. // 待签名数据
  312. signData := convertParamInterface(postDataMap)
  313. sign, err := getSignData(signData)
  314. if err != nil {
  315. return
  316. }
  317. postDataMap["sign"] = sign //签名
  318. bytesData, err = json.Marshal(postDataMap)
  319. return
  320. }
  321. // 将请求传入的数据格式转换成签名需要的格式(目前只能处理简单的类型,数组、对象暂不支持)
  322. func convertParamInterface(params map[string]interface{}) (signData map[string]string) {
  323. signData = make(map[string]string)
  324. for key := range params {
  325. val := ``
  326. //fmt.Println("key", key, ";val:", params[key], ";type:", reflect.TypeOf(params[key]))
  327. //signData[key] = params[key][0]
  328. tmpVal := params[key]
  329. switch reflect.TypeOf(tmpVal).Kind() {
  330. case reflect.String:
  331. val = fmt.Sprint(tmpVal)
  332. case reflect.Int, reflect.Int16, reflect.Int64, reflect.Int32, reflect.Int8:
  333. val = fmt.Sprint(tmpVal)
  334. case reflect.Uint, reflect.Uint32, reflect.Uint16, reflect.Uint8, reflect.Uint64:
  335. val = fmt.Sprint(tmpVal)
  336. case reflect.Bool:
  337. val = fmt.Sprint(tmpVal)
  338. case reflect.Float64:
  339. decimalNum := decimal.NewFromFloat(tmpVal.(float64))
  340. val = decimalNum.String()
  341. //val = strconv.FormatFloat(tmpVal.(float64), 'E', -1, 64) //float64
  342. case reflect.Float32:
  343. decimalNum := decimal.NewFromFloat32(tmpVal.(float32))
  344. val = decimalNum.String()
  345. }
  346. signData[key] = val
  347. }
  348. return signData
  349. }
  350. // getSignData 获取参数签名
  351. func getSignData(postData map[string]string) (sign string, err error) {
  352. appid := utils.APPID
  353. if appid == "" {
  354. err = errors.New("参数异常,缺少appid")
  355. return
  356. }
  357. secret := utils.SECRET
  358. if secret == "" {
  359. err = errors.New("参数异常,缺少secret")
  360. return
  361. }
  362. if postData["nonce_str"] == "" {
  363. err = errors.New("参数异常,缺少随机字符串")
  364. return
  365. }
  366. if postData["timestamp"] == "" {
  367. err = errors.New("参数异常,缺少时间戳")
  368. return
  369. }
  370. //先取出除sign外的所有的提交的参数key
  371. var keys []string
  372. for k := range postData {
  373. if k != "sign" {
  374. keys = append(keys, k)
  375. }
  376. }
  377. //1,根据参数名称的ASCII码表的顺序排序
  378. sort.Strings(keys)
  379. //2 根据排序后的参数名称,取出对应的值,并拼接字符串
  380. var signStr string
  381. for _, v := range keys {
  382. signStr += v + "=" + postData[v] + "&"
  383. }
  384. //3,全转小写(md5(拼装的字符串后+分配给你的app_secret))
  385. //sign := strings.ToLower(fmt.Sprintf("%x", md5.Sum([]byte(strings.Trim(signStr, "&")+key))))
  386. //md5.Sum([]byte(signStr+"key="+key)) 这是md5加密出来后的每个字符的ascall码,需要再转换成对应的字符
  387. //3,全转大写(md5(拼装的字符串后+分配给你的app_secret))
  388. sign = strings.ToUpper(fmt.Sprintf("%x", md5.Sum([]byte(signStr+"secret="+secret))))
  389. return
  390. }