edb_data_ys.go 12 KB

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