edb_data_ys.go 14 KB

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