edb_data_ys.go 14 KB

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