edb_data_ys.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. /**
  2. * @Author: jgl
  3. * @Date: 2021/9/15 10:15
  4. */
  5. package data_manage
  6. import (
  7. "crypto/md5"
  8. "encoding/hex"
  9. "encoding/json"
  10. "errors"
  11. "eta_gn/eta_task/global"
  12. "eta_gn/eta_task/utils"
  13. "fmt"
  14. "io/ioutil"
  15. "net/http"
  16. "net/url"
  17. "strconv"
  18. "time"
  19. )
  20. type EdbDataYs struct {
  21. EdbDataId int `gorm:"column:edb_data_id;primaryKey"` // `orm:"column(edb_data_id);pk"`
  22. EdbInfoId int
  23. EdbCode string
  24. DataTime string
  25. Value float64
  26. Status int
  27. CreateTime time.Time
  28. ModifyTime time.Time
  29. DataTimestamp int64
  30. }
  31. func AddEdbDataSmm(items []*EdbDataYs) (err error) {
  32. //o := orm.NewOrm()
  33. //_, err = o.InsertMulti(1, items)
  34. err = global.DEFAULT_DmSQL.CreateInBatches(items, utils.MultiAddNum).Error
  35. return
  36. }
  37. func ModifyEdbDataSmm(edbCode, dataTime string, value float64) (err error) {
  38. //o := orm.NewOrm()
  39. sql := ` UPDATE edb_data_ys SET value=?,status=1,modify_time=NOW() WHERE edb_code=? AND data_time=? `
  40. //_, err = o.Raw(sql, value, edbCode, dataTime).Exec()
  41. err = global.DEFAULT_DmSQL.Exec(sql, value, edbCode, dataTime).Error
  42. return
  43. }
  44. /*
  45. //有色基础指标同步
  46. func SyncSmmIndexDataBase() {
  47. utils.FileLog.Info("start:" + time.Now().Format(utils.FormatDateTime))
  48. list, err := data_manage.GetBaseFromSmmList()
  49. if err != nil {
  50. fmt.Println("GetBaseFromSmmList Err:" + err.Error())
  51. return
  52. }
  53. token, err := getToken("pqian@hzinsights.com", "hz123456")
  54. if err != nil {
  55. fmt.Println(err)
  56. return
  57. }
  58. endDate := time.Now().Format(utils.FormatDate)
  59. smmIndexAll, err := data_manage.GetBaseFromSmmIndex()
  60. if err != nil {
  61. fmt.Println("GetBaseFromSmmIndex Err:" + err.Error())
  62. return
  63. }
  64. existIndexMap := make(map[string]*data_manage.BaseFromSmmIndex)
  65. for _, item := range smmIndexAll {
  66. existIndexMap[item.IndexCode] = item
  67. }
  68. for k, v := range list {
  69. edbCode := v.Interface
  70. var startDate string
  71. if v.EndDate == "" || v.EndDate == "0000-00-00" {
  72. startDate = v.ApiStartTime
  73. } else {
  74. if v.EndDate != "" {
  75. dateFormate, _ := time.Parse(utils.FormatDate, v.EndDate)
  76. var syncDay int
  77. if v.ApiUpdateType == "day" {
  78. syncDay = utils.DATA_REFRESH
  79. } else if v.ApiUpdateType == "month" {
  80. syncDay = utils.DATA_REFRESH * 30
  81. } else if v.ApiUpdateType == "week" {
  82. syncDay = utils.DATA_REFRESH * 7
  83. } else if v.ApiUpdateType == "year" {
  84. syncDay = utils.DATA_REFRESH * 365
  85. }
  86. startDate = dateFormate.AddDate(0, 0, -syncDay).Format(utils.FormatDate)
  87. }
  88. }
  89. ysItem, err := getApiData(token, edbCode, startDate, endDate)
  90. if err != nil {
  91. fmt.Println(err)
  92. return
  93. }
  94. if ysItem != nil && ysItem.Code == 200 {
  95. frequency := ysItem.Data.Frequency
  96. indexMap := make(map[string]int)
  97. smmIndexIdMap := make(map[int]int)
  98. indexCodeMap := make(map[int]string)
  99. indexKey := 0
  100. var isDateIndex int
  101. for fk, fv := range ysItem.Data.Field {
  102. if fv.IsDate == "1" {
  103. isDateIndex = fk
  104. } else {
  105. if !strings.Contains(fv.Name, "产品名称") &&
  106. !strings.Contains(fv.Name, "单位") &&
  107. !strings.Contains(fv.Name, "时间") &&
  108. !strings.Contains(fv.Name, "备注") {
  109. indexMap[fv.DBColName] = fk
  110. indexKey += 1
  111. indexCode := v.Interface + "#" + strconv.Itoa(indexKey)
  112. if findItem, ok := existIndexMap[indexCode]; !ok {
  113. ssmIndex := new(data_manage.BaseFromSmmIndex)
  114. ssmIndex.Interface = v.Interface
  115. ssmIndex.Name = v.Name
  116. ssmIndex.IndexCode = indexCode
  117. ssmIndex.IndexName = v.Name + "_" + fv.Name
  118. ssmIndex.Type1 = v.Type1
  119. ssmIndex.Type2 = v.Type2
  120. ssmIndex.Type3 = v.Type3
  121. ssmIndex.Frequency = frequency
  122. ssmIndex.Unit = fv.Unit
  123. ssmIndex.ApiStartTime = v.ApiStartTime
  124. ssmIndex.ApiUpdateTime = v.ApiUpdateTime
  125. ssmIndex.StartTime = v.StartTime
  126. ssmIndex.FinishTime = v.FinishTime
  127. ssmIndex.CreateTime = time.Now()
  128. ssmIndex.ModifyTime = time.Now()
  129. lastIndexId, err := data_manage.AddBaseFromSmmIndex(ssmIndex)
  130. if err != nil {
  131. return
  132. }
  133. smmIndexIdMap[fk] = int(lastIndexId)
  134. indexCodeMap[fk] = indexCode
  135. } else {
  136. smmIndexIdMap[fk] = findItem.BaseFromSmmIndexId
  137. indexCodeMap[fk] = findItem.IndexCode
  138. }
  139. }
  140. }
  141. }
  142. existDataMap := make(map[string]*data_manage.BaseFromSmmData)
  143. for _, mv := range indexCodeMap {
  144. indexCode := mv
  145. dataAllList, err := data_manage.GetBaseFromSmmDataAll(indexCode)
  146. if err != nil {
  147. fmt.Println("GetBaseFromSmmData Err:" + err.Error())
  148. return
  149. }
  150. for _, item := range dataAllList {
  151. key := item.IndexCode + item.DataTime
  152. existDataMap[key] = item
  153. }
  154. }
  155. addExistDataMap := make(map[string]string)
  156. for _, dv := range ysItem.Data.Content {
  157. var dataTime string
  158. dataTime = dv[isDateIndex]
  159. if strings.Contains(dataTime, "Q1") {
  160. dataTime = strings.Replace(dataTime, "Q1", "-01", -1)
  161. dataTime += "-31"
  162. }
  163. if strings.Contains(dataTime, "Q2") {
  164. dataTime = strings.Replace(dataTime, "Q2", "-06", -1)
  165. dataTime += "-30"
  166. }
  167. if strings.Contains(dataTime, "Q3") {
  168. dataTime = strings.Replace(dataTime, "Q3", "-09", -1)
  169. dataTime += "-30"
  170. }
  171. if strings.Contains(dataTime, "Q4") {
  172. dataTime = strings.Replace(dataTime, "Q4", "-12", -1)
  173. dataTime += "-31"
  174. }
  175. if strings.Contains(dataTime, "H1") {
  176. dataTime = strings.Replace(dataTime, "H1", "-06", -1)
  177. dataTime += "-30"
  178. }
  179. if strings.Contains(dataTime, "H2") {
  180. dataTime = strings.Replace(dataTime, "H2", "-12", -1)
  181. dataTime += "-31"
  182. }
  183. if frequency == "月" {
  184. monthDate, err := time.Parse("2006-01", dataTime)
  185. if err != nil {
  186. fmt.Println("time.Parse:" + err.Error())
  187. }
  188. lastTime := monthDate.AddDate(0, 1, -1)
  189. lastYear, lastMonth, lastDay := lastTime.Date()
  190. var lastDate string
  191. if int(lastMonth) < 10 {
  192. lastDate = strconv.Itoa(lastYear) + "-" + "0" + strconv.Itoa(int(lastMonth)) + "-" + strconv.Itoa(lastDay)
  193. } else {
  194. lastDate = strconv.Itoa(lastYear) + "-" + strconv.Itoa(int(lastMonth)) + "-" + strconv.Itoa(lastDay)
  195. }
  196. dataTime = lastDate
  197. } else if frequency == "年" {
  198. dataTime = dataTime + "-12-31"
  199. }
  200. saveDataTime, err := time.Parse(utils.FormatDate, dataTime)
  201. if err != nil {
  202. fmt.Println("saveDataTime parse err:" + err.Error() + " dataTime:" + dataTime)
  203. panic(err)
  204. }
  205. timestamp := saveDataTime.UnixNano() / 1e6
  206. //循环指标
  207. for _, v := range indexMap {
  208. indexCode := indexCodeMap[v]
  209. smmIndexId := smmIndexIdMap[v]
  210. dataVal := dv[v]
  211. if indexCode != "" {
  212. key := indexCode + dataTime
  213. val := strings.Replace(dataVal, ",", "", -1)
  214. if findData, dataOk := existDataMap[key]; !dataOk {
  215. if _, addOK := addExistDataMap[key]; !addOK {
  216. if val != "" && val != "-" {
  217. dataItem := new(data_manage.BaseFromSmmData)
  218. dataItem.BaseFromSmmIndexId = int(smmIndexId)
  219. dataItem.IndexCode = indexCode
  220. dataItem.DataTime = dataTime
  221. dataItem.Value = val
  222. dataItem.CreateTime = time.Now()
  223. dataItem.ModifyTime = time.Now()
  224. dataItem.DataTimestamp = timestamp
  225. _, err = data_manage.AddBaseFromSmmData(dataItem)
  226. if err != nil && !strings.Contains(err.Error(), "idx_index_code_date") {
  227. fmt.Println("AddBaseFromSmmData Err:" + err.Error())
  228. return
  229. }
  230. }
  231. }
  232. } else {
  233. if findData != nil && findData.Value != val { //修改
  234. if _, addOK := addExistDataMap[key]; !addOK {
  235. if val != "" && val != "-" {
  236. err = data_manage.ModifyBaseFromSmmData(findData.SmmDataId, val)
  237. if err != nil {
  238. fmt.Println("ModifyBaseFromSmmData Err:" + err.Error())
  239. return
  240. }
  241. }
  242. }
  243. }
  244. }
  245. addExistDataMap[key] = key
  246. }
  247. }
  248. }
  249. //修改数据开始,结束日期
  250. {
  251. indexList, err := data_manage.GetBaseFromSmmIndexByCode(v.Interface)
  252. if err != nil {
  253. fmt.Println("GetBaseFromSmmIndexByCode Err:" + err.Error())
  254. }
  255. for _, sv := range indexList {
  256. minDate, maxDate, err := data_manage.GetBaseFromSmmMaxOrMinDate(sv.IndexCode)
  257. if err != nil {
  258. fmt.Println("GetEdbDataSmmMaxOrMinDate Err:" + err.Error())
  259. } else {
  260. err = data_manage.ModifyBaseFromSmmMinDateAndMaxDate(sv.BaseFromSmmIndexId, v.BaseFromSmmId, minDate, maxDate)
  261. if err != nil {
  262. fmt.Println("ModifyBaseFromSmmMinDateAndMaxDate Err:" + err.Error())
  263. }
  264. }
  265. }
  266. }
  267. }
  268. fmt.Println(v.Interface, v.Name, k)
  269. time.Sleep(1 * time.Second)
  270. }
  271. utils.FileLog.Info("end:" + time.Now().Format(utils.FormatDateTime))
  272. }
  273. */
  274. const (
  275. dataUrl = "https://dataapi.smm.cn/GetData/" //data url (中文)
  276. //dataUrl = "https://dataapi.smm.cn/GetDataEn/" //data url (english edition)
  277. authUrl = "https://platform.smm.cn/usercenter/auth" // auth url (for all)
  278. )
  279. type TokenResp struct {
  280. Code int `json:"Code"`
  281. Msg string `json:"Msg"`
  282. Data TokenData `json:"Data"`
  283. }
  284. type TokenData struct {
  285. Token string `json:"Token"`
  286. }
  287. // 获取token
  288. func getToken(userName string, password string) (string, error) {
  289. encryptAuth := md5.New()
  290. encryptAuth.Write([]byte(password)) //encrypt password with md5
  291. newPassword := hex.EncodeToString(encryptAuth.Sum(nil))
  292. resp, err := http.PostForm(authUrl, url.Values{"user_name": {userName}, "password": {newPassword}})
  293. if err != nil {
  294. return "", err
  295. }
  296. defer resp.Body.Close()
  297. body, err := ioutil.ReadAll(resp.Body)
  298. if err != nil {
  299. fmt.Println("reponse error", err)
  300. return "", err
  301. }
  302. var bodyJsonContent TokenResp
  303. if err = json.Unmarshal([]byte(body), &bodyJsonContent); err != nil {
  304. fmt.Println(err, "unmarsal failure")
  305. return "", err
  306. }
  307. var token string
  308. if bodyJsonContent.Code == 0 {
  309. token = bodyJsonContent.Data.Token
  310. }
  311. //print(token)
  312. return token, nil
  313. }
  314. // request response
  315. type DataResp struct {
  316. Code int `json:"Code"`
  317. Msg string `json:"Msg"`
  318. Data *ApiData `json:"Data"`
  319. }
  320. // api data response
  321. type ApiData struct {
  322. Status int `json:"Status"` //0 no permission,1 ok
  323. Field []ApiField `json:"Field"`
  324. Content [][]string `json:"Content"`
  325. }
  326. // api title
  327. type ApiField struct {
  328. Unit string `json:"Unit"`
  329. Info string `json:"Info"`
  330. Name string `json:"Name"`
  331. ColumnType string `json:"ColumnType"`
  332. ColIndex uint `json:"ColIndex"`
  333. IsDate string `json:"IsDate"`
  334. }
  335. type YsResult struct {
  336. Code int64 `json:"Code"`
  337. Data struct {
  338. CompanyList []interface{} `json:"CompanyList"`
  339. Content [][]string `json:"Content"`
  340. Field []struct {
  341. ColIndex int64 `json:"ColIndex"`
  342. ColumnType string `json:"ColumnType"`
  343. Info string `json:"Info"`
  344. IsDate string `json:"IsDate"`
  345. Name string `json:"Name"`
  346. Unit string `json:"Unit"`
  347. DBColName string `json:"db_col_name"`
  348. } `json:"Field"`
  349. CountPage int64 `json:"count_page"`
  350. CurrentPage int64 `json:"current_page"`
  351. Frequency string `json:"frequency"`
  352. Mindate string `json:"mindate"`
  353. PageNum int64 `json:"page_num"`
  354. Status int64 `json:"status"`
  355. TotalNum int64 `json:"total_num"`
  356. } `json:"Data"`
  357. Msg string `json:"Msg"`
  358. }
  359. /*
  360. * request data
  361. * sdatetime,edatetime ==>format:yyyy-mm-dd,
  362. * apiName ==> data.metal.com(for english)/data.smm.cn (for chinese)
  363. */
  364. func getApiData(token string, apiName string, sdatetime string, edatetime string) (item *YsResult, err error) {
  365. reqUrl := dataUrl + apiName
  366. resp, err := http.PostForm(reqUrl, url.Values{"token": {token}, "sdatetime": {sdatetime}, "edatetime": {edatetime}})
  367. if err != nil {
  368. return nil, err
  369. }
  370. defer resp.Body.Close()
  371. body, err := ioutil.ReadAll(resp.Body)
  372. if err != nil {
  373. fmt.Println("response error")
  374. return nil, err
  375. }
  376. utils.FileLog.Info("ys result:" + string(body))
  377. dataJsonContent := new(YsResult)
  378. if err = json.Unmarshal([]byte(body), &dataJsonContent); err != nil {
  379. fmt.Println(err, "data unmarshal failure")
  380. return nil, err
  381. }
  382. if dataJsonContent.Code == 200 && len(dataJsonContent.Data.Content) > 0 {
  383. return dataJsonContent, nil
  384. } else {
  385. err = errors.New("code:" + strconv.Itoa(int(dataJsonContent.Code)) + "msg:" + dataJsonContent.Msg)
  386. }
  387. return nil, nil
  388. }