ymy.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. package ymy
  2. import (
  3. "bytes"
  4. "crypto/tls"
  5. "encoding/json"
  6. "fmt"
  7. "io/ioutil"
  8. "net/http"
  9. "time"
  10. "tmr-watch/conf/setting"
  11. "tmr-watch/http/handle/restful"
  12. "tmr-watch/models"
  13. "tmr-watch/pkg/logging"
  14. "github.com/astaxie/beego/logs"
  15. "github.com/xormplus/xorm"
  16. )
  17. func YmyCron() {
  18. // pastureinfo := new(udPastureInfo)
  19. // err := tx.SQL(`select column_default as pastureid from information_schema.COLUMNS
  20. // WHERE table_name = 'recweight' AND table_schema = ? AND column_name = 'pastureid'`, setting.DatabaseSetting.Name).GetFirst(pastureinfo).Error
  21. // if err != nil {
  22. // logs.Error(err)
  23. // return err
  24. // }
  25. }
  26. func YmySyncBar(farmId, pastureId string) {
  27. tx := restful.Engine.NewSession()
  28. defer tx.Close()
  29. reqJson := `{
  30. "methodKey": "getFeedPenList",
  31. "param": {
  32. "farmId": "%s",
  33. "parlorType": "CPT"
  34. },
  35. "platform": "CPT",
  36. "regCode": "cpt180511",
  37. "secret": "67a74fd5748054ac67b6fc433e9249b0"}`
  38. barPull("http://dairy.yimucloud.com/dairy/external/api", fmt.Sprintf(reqJson, farmId), 3, tx, pastureId)
  39. }
  40. func barPull(url, data string, msgtype int, tx *xorm.Session, pastureId string) {
  41. req, err := http.NewRequest("POST", url, bytes.NewBuffer([]byte(data)))
  42. if err != nil {
  43. logs.Error(err)
  44. }
  45. req.Header.Set("Content-Type", "application/json")
  46. // client := &http.Client{}
  47. tr := &http.Transport{
  48. TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
  49. }
  50. client := &http.Client{Transport: tr}
  51. resp, err := client.Do(req)
  52. if err != nil {
  53. logs.Error(err)
  54. return
  55. }
  56. defer resp.Body.Close()
  57. body, _ := ioutil.ReadAll(resp.Body)
  58. respData := new(models.BarResponse)
  59. json.Unmarshal(body, &respData)
  60. tx.Exec(` insert into saplog(pastureId,request,response,status,msgtext,createTime,msgtype,dataDate,url)
  61. values(?,?,?,?,?,now(),?,now(),?)`, pastureId, data, string(body), "", "", msgtype, url)
  62. for _, v := range respData.Result {
  63. count, _ := tx.Table("bar").Where("pastureId = ? ", pastureId).Count()
  64. tx.Exec(`insert into bar(pastureid,bcode,bname,sort)values(?,?,?,?) ON DUPLICATE KEY UPDATE bname = ? `, pastureId, v.PenId, v.PenName, count+1, v.PenName)
  65. }
  66. }
  67. func YmySyncFeed(farmId, pastureId string) {
  68. tx := restful.Engine.NewSession()
  69. defer tx.Close()
  70. reqJson := `{
  71. "data":{
  72. "page": "0",
  73. "size": "1000",
  74. "modifiedAfter":"2025-01-01 00:00:00",
  75. "MATERIAL_BASIC_CLASSIFICATION_CODE":"",
  76. "MATERIAL_CODE": ""
  77. }}`
  78. // reqJson = fmt.Sprintf(reqJson, time.Now().Format("2006-01-02 15:04:05"))
  79. feedPull("http://113.250.182.238:9000/ierp/kapi/v2/iscb/route/script_cusapi_deepexi_material_query", reqJson, 2, tx, pastureId, getApiToken())
  80. }
  81. type udPastureInfo struct {
  82. Token string `xorm:"token"`
  83. Pastureid string `xorm:"pastureid"`
  84. Werks string `xorm:"werks"`
  85. UpdateDate string `xorm:"updatedate"`
  86. }
  87. func getApiToken() string {
  88. tx := restful.Engine.NewSession()
  89. defer tx.Close()
  90. pastureinfo := new(udPastureInfo)
  91. err := tx.SQL(`SELECT (SELECT pastureid FROM pasture WHERE pastureid = column_default) pastureid,
  92. IF( TIMESTAMPDIFF(MINUTE,
  93. (SELECT updatedate FROM pasture WHERE pastureid = column_default),
  94. NOW()
  95. ) > 60, -- 110分钟 = 1小时50分钟
  96. '', -- 超过时间返回空字符串
  97. (SELECT token FROM pasture WHERE pastureid = column_default) -- 否则返回 pastureid
  98. ) AS token,
  99. (SELECT werks FROM pasture WHERE pastureid = column_default) AS werks,
  100. DATE_FORMAT(
  101. (SELECT updatedate FROM pasture WHERE pastureid = column_default),
  102. '%Y-%m-%d %H:%i:%s'
  103. ) AS updatedate
  104. FROM information_schema.COLUMNS
  105. WHERE table_name = 'recweight'
  106. AND table_schema = ?
  107. AND column_name = 'pastureid' `, setting.DatabaseSetting.Name).GetFirst(pastureinfo).Error
  108. if err != nil {
  109. logs.Error(err)
  110. return pastureinfo.Token
  111. }
  112. if pastureinfo.Token != "" {
  113. return pastureinfo.Token
  114. }
  115. reqJson := `{
  116. "client_id": "Cosmic_deepexi_user",
  117. "client_secret": "Cosmic_zkm_deepexi_openapi@user01",
  118. "username": "dipujiekouyonghu",
  119. "accountId": "2174058657413595136",
  120. "nonce": "a42c1a91-56ad-4c6d-95d1-40bcb8b5ec89",
  121. "timestamp": "%s",
  122. "language": "zh_CN"
  123. }`
  124. reqJson = fmt.Sprintf(reqJson, time.Now().Format("2006-01-02 15:04:05"))
  125. req, err := http.NewRequest("POST", "http://113.250.182.238:9000/ierp/kapi/oauth2/getToken", bytes.NewBuffer([]byte(reqJson)))
  126. if err != nil {
  127. logs.Error(err)
  128. }
  129. req.Header.Set("Content-Type", "application/json")
  130. tr := &http.Transport{
  131. TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
  132. }
  133. client := &http.Client{Transport: tr}
  134. resp, err := client.Do(req)
  135. if err != nil {
  136. logs.Error(err)
  137. return pastureinfo.Token
  138. }
  139. defer resp.Body.Close()
  140. body, _ := ioutil.ReadAll(resp.Body)
  141. fmt.Println(string(body))
  142. token := new(models.TokenResponse)
  143. json.Unmarshal(body, &token)
  144. tx.Exec(" update pasture set token = ?,updatedate = now() where pastureid = ? ", token.Data.AccessToken, pastureinfo.Pastureid)
  145. return token.Data.AccessToken
  146. }
  147. func feedPull(url, data string, msgtype int, tx *xorm.Session, pastureId, token string) {
  148. req, err := http.NewRequest("POST", url, bytes.NewBuffer([]byte(data)))
  149. if err != nil {
  150. logs.Error(err)
  151. }
  152. req.Header.Set("Content-Type", "application/json")
  153. req.Header.Set("access_token", token)
  154. client := &http.Client{}
  155. resp, err := client.Do(req)
  156. if err != nil {
  157. logs.Error(err)
  158. return
  159. }
  160. defer resp.Body.Close()
  161. body, _ := ioutil.ReadAll(resp.Body)
  162. fmt.Println(string(body))
  163. feedData := new(models.FeedResponse)
  164. json.Unmarshal(body, &feedData)
  165. for _, v := range feedData.Data.Content {
  166. feedname := v.MaterialName
  167. feedcode := v.MaterialCode
  168. feedClassExist, err := tx.Table("feedclass").Where("fccode = ? ", v.MaterialClassification).Where(" pastureId = ? ", pastureId).Exist()
  169. fmt.Println(err)
  170. if !feedClassExist {
  171. count, _ := tx.Table("feedclass").Where("pastureId = ? ", pastureId).Count()
  172. ids, err := setting.SnowIds.NextId()
  173. if err != nil {
  174. ids = time.Now().UnixNano()
  175. }
  176. _, err = tx.Exec(`insert into feedclass(id,pastureId,fcname,fccode,bigfeedclassname,sort,bigfeedclassid) values(?,?,?,?,?,?,?)`,
  177. ids, pastureId, v.MaterialClassification, v.MaterialClassification, v.MaterialClassification, count+1, ids)
  178. fmt.Println(err)
  179. }
  180. ids, err := setting.SnowIds.NextId()
  181. if err != nil {
  182. ids = time.Now().UnixNano()
  183. logging.Info("create SnowIds err", err)
  184. }
  185. tx.Exec(`insert into feed(id,pastureId,feedcode,udname,fclassid,fclass,fname) values(?,?,?,?,(select id from feedclass where fccode = ? and pastureId = ? ),?,if(char_length(?) > 7, left(?,7),?) )
  186. ON DUPLICATE KEY UPDATE udname = ? ,fclassid = (select id from feedclass where fccode = ? and pastureId = ? ) ,fclass = ?`,
  187. ids, pastureId, feedcode, feedname, v.MaterialClassification, pastureId, v.MaterialClassification, feedname, feedname, feedname, feedname,
  188. v.MaterialClassification, pastureId, v.MaterialClassification)
  189. }
  190. tx.Exec(` insert into saplog(pastureId,request,response,status,msgtext,createTime,msgtype,dataDate,url)
  191. values(?,?,?,?,?,now(),?,now(),?)`, pastureId, data, string(body), "", "", msgtype, url)
  192. }