edb_data_ys.go 14 KB

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