ymy.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. package ymy
  2. import (
  3. "bytes"
  4. "crypto/tls"
  5. "encoding/json"
  6. "fmt"
  7. "io/ioutil"
  8. "net/http"
  9. "strings"
  10. "time"
  11. "tmr-watch/conf/setting"
  12. "tmr-watch/http/handle/restful"
  13. "tmr-watch/models"
  14. "tmr-watch/pkg/logging"
  15. "github.com/astaxie/beego/logs"
  16. "github.com/xormplus/xorm"
  17. )
  18. func YmyCron(farmId, pastureId string) {
  19. date := time.Now().AddDate(0, 0, -1).Format("2006-01-02")
  20. // date := "2025-05-11"
  21. YmyUtirPush(pastureId, farmId, date)
  22. YmyMaterialIssuePush(pastureId, farmId, date)
  23. YmySyncBar(farmId, pastureId)
  24. YmySyncFeed(pastureId)
  25. YmyFeedtempletPush(pastureId, farmId, date)
  26. }
  27. func YmySyncBar(farmId, pastureId string) {
  28. tx := restful.Engine.NewSession()
  29. defer tx.Close()
  30. reqJson := `{
  31. "methodKey": "getFeedPenList",
  32. "param": {
  33. "farmId": "%s",
  34. "parlorType": "CPT"
  35. },
  36. "platform": "CPT",
  37. "regCode": "cpt180511",
  38. "secret": "67a74fd5748054ac67b6fc433e9249b0"}`
  39. barPull("http://dairy.yimucloud.com/dairy/external/api", fmt.Sprintf(reqJson, farmId), 3, tx, pastureId)
  40. }
  41. func barPull(url, data string, msgtype int, tx *xorm.Session, pastureId string) {
  42. req, err := http.NewRequest("POST", url, bytes.NewBuffer([]byte(data)))
  43. if err != nil {
  44. logs.Error(err)
  45. }
  46. req.Header.Set("Content-Type", "application/json")
  47. // client := &http.Client{}
  48. tr := &http.Transport{
  49. TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
  50. }
  51. client := &http.Client{Transport: tr}
  52. resp, err := client.Do(req)
  53. if err != nil {
  54. logs.Error(err)
  55. return
  56. }
  57. defer resp.Body.Close()
  58. body, _ := ioutil.ReadAll(resp.Body)
  59. respData := new(models.BarResponse)
  60. json.Unmarshal(body, &respData)
  61. tx.Exec(` insert into saplog(pastureId,request,response,status,msgtext,createTime,msgtype,dataDate,url)
  62. values(?,?,?,?,?,now(),?,now(),?)`, pastureId, data, string(body), "", "", msgtype, url)
  63. for _, v := range respData.Result {
  64. fmt.Println(v)
  65. count, _ := tx.Table("bar").Where("pastureId = ? ", pastureId).Count()
  66. tx.Exec(`insert into bar(pastureid,bcode,bname,sort)values(?,?,?,?) ON DUPLICATE KEY UPDATE bname = ? `, pastureId, v.PenId, v.PenName, count+1, v.PenName)
  67. }
  68. }
  69. func YmySyncFeed(pastureId string) {
  70. tx := restful.Engine.NewSession()
  71. defer tx.Close()
  72. reqJson := `{
  73. "data":{
  74. "page": "0",
  75. "size": "1000",
  76. "modifiedAfter":"2025-01-01 00:00:00",
  77. "MATERIAL_BASIC_CLASSIFICATION_CODE":"",
  78. "MATERIAL_CODE": ""
  79. }}`
  80. feedPull("http://219.151.177.119:9000/ierp/kapi/v2/iscb/route/script_cusapi_deepexi_material_query", reqJson, 2, tx, pastureId, getApiToken())
  81. }
  82. type udPastureInfo struct {
  83. Token string `xorm:"token"`
  84. Pastureid string `xorm:"pastureid"`
  85. Werks string `xorm:"werks"`
  86. UpdateDate string `xorm:"updatedate"`
  87. }
  88. func getApiToken() string {
  89. tx := restful.Engine.NewSession()
  90. defer tx.Close()
  91. pastureinfo := new(udPastureInfo)
  92. err := tx.SQL(`SELECT (SELECT pastureid FROM pasture WHERE pastureid = column_default) pastureid,
  93. IF( TIMESTAMPDIFF(MINUTE,
  94. (SELECT updatedate FROM pasture WHERE pastureid = column_default),
  95. NOW()
  96. ) > 60, -- 110分钟 = 1小时50分钟
  97. '', -- 超过时间返回空字符串
  98. (SELECT token FROM pasture WHERE pastureid = column_default) -- 否则返回 pastureid
  99. ) AS token,
  100. (SELECT werks FROM pasture WHERE pastureid = column_default) AS werks,
  101. DATE_FORMAT(
  102. (SELECT updatedate FROM pasture WHERE pastureid = column_default),
  103. '%Y-%m-%d %H:%i:%s'
  104. ) AS updatedate
  105. FROM information_schema.COLUMNS
  106. WHERE table_name = 'recweight'
  107. AND table_schema = ?
  108. AND column_name = 'pastureid' `, setting.DatabaseSetting.Name).GetFirst(pastureinfo).Error
  109. if err != nil {
  110. logs.Error(err)
  111. return pastureinfo.Token
  112. }
  113. if pastureinfo.Token != "" {
  114. return pastureinfo.Token
  115. }
  116. reqJson := `{
  117. "client_id": "Cosmic_deepexi_user",
  118. "client_secret": "Cosmic_zkm_deepexi_openapi@user01",
  119. "username": "dipujiekouyonghu",
  120. "accountId": "1986218827033083904",
  121. "nonce": "a42c1a91-56ad-4c6d-95d1-40bcb8b5ec89",
  122. "timestamp": "%s",
  123. "language": "zh_CN"
  124. }`
  125. reqJson = fmt.Sprintf(reqJson, time.Now().Format("2006-01-02 15:04:05"))
  126. req, err := http.NewRequest("POST", "http://219.151.177.119:9000/ierp/kapi/oauth2/getToken", bytes.NewBuffer([]byte(reqJson)))
  127. if err != nil {
  128. logs.Error(err)
  129. }
  130. req.Header.Set("Content-Type", "application/json")
  131. tr := &http.Transport{
  132. TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
  133. }
  134. client := &http.Client{Transport: tr}
  135. resp, err := client.Do(req)
  136. if err != nil {
  137. logs.Error(err)
  138. return pastureinfo.Token
  139. }
  140. defer resp.Body.Close()
  141. body, _ := ioutil.ReadAll(resp.Body)
  142. fmt.Println(string(body))
  143. token := new(models.TokenResponse)
  144. json.Unmarshal(body, &token)
  145. tx.Exec(" update pasture set token = ?,updatedate = now() where pastureid = ? ", token.Data.AccessToken, pastureinfo.Pastureid)
  146. return token.Data.AccessToken
  147. }
  148. func feedPull(url, data string, msgtype int, tx *xorm.Session, pastureId, token string) {
  149. req, err := http.NewRequest("POST", url, bytes.NewBuffer([]byte(data)))
  150. if err != nil {
  151. logs.Error(err)
  152. }
  153. req.Header.Set("Content-Type", "application/json")
  154. req.Header.Set("access_token", token)
  155. client := &http.Client{}
  156. resp, err := client.Do(req)
  157. if err != nil {
  158. logs.Error(err)
  159. return
  160. }
  161. defer resp.Body.Close()
  162. body, _ := ioutil.ReadAll(resp.Body)
  163. fmt.Println(string(body))
  164. feedData := new(models.FeedResponse)
  165. json.Unmarshal(body, &feedData)
  166. for _, v := range feedData.Data.Content {
  167. feedname := v.MaterialName
  168. feedcode := v.MaterialCode
  169. feedClassExist, err := tx.Table("feedclass").Where("fccode = ? ", v.MaterialClassification).Where(" pastureId = ? ", pastureId).Exist()
  170. fmt.Println(err)
  171. if !feedClassExist {
  172. count, _ := tx.Table("feedclass").Where("pastureId = ? ", pastureId).Count()
  173. ids, err := setting.SnowIds.NextId()
  174. if err != nil {
  175. ids = time.Now().UnixNano()
  176. }
  177. _, err = tx.Exec(`insert into feedclass(id,pastureId,fcname,fccode,bigfeedclassname,sort,bigfeedclassid) values(?,?,?,?,?,?,?)`,
  178. ids, pastureId, v.MaterialClassification, v.MaterialClassification, v.MaterialClassification, count+1, ids)
  179. fmt.Println(err)
  180. }
  181. ids, err := setting.SnowIds.NextId()
  182. if err != nil {
  183. ids = time.Now().UnixNano()
  184. logging.Info("create SnowIds err", err)
  185. }
  186. 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),?) )
  187. ON DUPLICATE KEY UPDATE udname = ? ,fclassid = (select id from feedclass where fccode = ? and pastureId = ? ) ,fclass = ?`,
  188. ids, pastureId, feedcode, feedname, v.MaterialClassification, pastureId, v.MaterialClassification, feedname, feedname, feedname, feedname,
  189. v.MaterialClassification, pastureId, v.MaterialClassification)
  190. }
  191. tx.Exec(` insert into saplog(pastureId,request,response,status,msgtext,createTime,msgtype,dataDate,url)
  192. values(?,?,?,?,?,now(),?,now(),?)`, pastureId, data, string(body), "", "", msgtype, url)
  193. }
  194. func YmyFeedtempletPush(pastureId, farmId, date string) error {
  195. tx := restful.Engine.NewSession()
  196. defer tx.Close()
  197. var now string
  198. if date != "" {
  199. now = date
  200. } else {
  201. now = time.Now().AddDate(0, 0, -1).Format("2006-01-02")
  202. }
  203. dataList, err := tx.SQL(`SELECT
  204. ft.tcode AS recipeId,
  205. ft.TNAME AS recipeName,
  206. ifnull(f.feedcode,f.id) AS ingId,
  207. '' AS feedCode,
  208. ifnull(f.udname,f.fname) AS ingName,
  209. round( fn.dry * ftd.FWEIGHT, 2 ) AS dmQty,
  210. ftd.FWEIGHT AS afQty,
  211. ftd.SORT AS mixNo,
  212. round( f.Uprice * ftd.FWEIGHT, 2 ) AS recipeCost,
  213. ifnull(fc.fcname,'饲料') AS ingType,
  214. f.AllowRatio AS allowableError
  215. FROM
  216. feedtempletdate ft
  217. JOIN ftdetaildate ftd ON ft.id = ftd.FTID and ft.date = ftd.date
  218. JOIN feed f ON ftd.FID = f.id
  219. left join feednur fn on fn.fid = f.id
  220. left JOIN feedclass fc ON f.fclassid = fc.id
  221. WHERE
  222. ft.ENABLE = 1
  223. AND ft.isDelete != 1 and ft.date = ? `, now).Query().List()
  224. if err != nil {
  225. logging.Error(err)
  226. return err
  227. }
  228. dataByte, _ := json.Marshal(&dataList)
  229. reqJson := `
  230. {"param": {
  231. "method": "getfeedtempletinfo",
  232. "resultData": %s,
  233. "farmId": "%s",
  234. "parlorType": "CPT",
  235. "account":"CPT"
  236. },
  237. "platform": "CPT",
  238. "regCode": "cpt180511",
  239. "secret": "67a74fd5748054ac67b6fc433e9249b0",
  240. "methodKey": "pushCptData"}`
  241. reqJson = fmt.Sprintf(reqJson, string(dataByte), farmId)
  242. fmt.Println(reqJson)
  243. postPush(reqJson, 4, tx, pastureId)
  244. return nil
  245. }
  246. //搅拌
  247. func YmyUtirPush(pastureId, farmId, date string) error {
  248. tx := restful.Engine.NewSession()
  249. defer tx.Close()
  250. var now string
  251. if date != "" {
  252. now = date
  253. } else {
  254. now = time.Now().AddDate(0, 0, -1).Format("2006-01-02")
  255. }
  256. dataList, err := tx.SQL(`select MD5(CONCAT(d.pid, d.mydate)) loadId , date_format(d1.date,'%Y-%m-%d') dropDate,date_format(d1.date,'%Y-%m-%d') loadDate,d.times loadShift,d.id tmrNo,ft.tcode recipeId,ft.ccname recipeName,ifnull(f.feedcode,d1.fid) ingId,'' feedCode ,ifnull(f.fname,ftd.fname) ingName,
  257. ifnull(ifnull(fc.fcname,(select fcname from feedclass fc1 join feed f1 on f1.fclassid = fc1.id where f1.id =ftd.fid )),'饲料') ingType,
  258. ifnull(f.dry * d1.actualweightminus,0) dmPct,d1.sort mixNo,ifnull(d1.feedallowratio,0) allowableError , if(f.fname is not null, ifnull(d1.lweight,''), ifnull(ftd.fweight / (select sum(fweight) from ftdetaildate where date = d1.date and ftid = d1.fid ) * d1.lweight,"") ) expWeight,
  259. if(f.fname is not null, ifnull(d1.actualweightminus,''),ifnull(ftd.fweight / (select sum(fweight) from ftdetaildate where date = d1.date and ftid = d1.fid ) * d1.actualweightminus,"") ) actualWeight,
  260. DATE_FORMAT(IFNULL((SELECT MAX(intime) FROM downloadplandtl1 d2
  261. WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid AND d2.intime<d1.intime)
  262. , (SELECT MAX(intime) FROM downloadedplan d2
  263. WHERE d1.date=d2.mydate AND d1.pastureid = d2.pastureid AND d2.id=d1.pid)
  264. ), '%Y-%m-%d %H:%i:%s')
  265. startTime ,
  266. date_format(d1.intime,'%Y-%m-%d %H:%i:%s') endTime, ifnull(driver.drivername,'') tmrName ,d1.feedallowratio allowable_error,d.tmrtname equipmentId
  267. from downloadplandtl1 d1 join downloadedplan d on d.id = d1.pid
  268. left join feedtempletdate ft on ft.id = d.tempid and ft.date = d1.date
  269. left join feed f on f.feedcode = d1.feedcode
  270. left join feedclass fc on fc.id = f.fclassid
  271. left join ftdetaildate ftd on ftd.date = d1.date and ftd.ftid = d1.fid
  272. join tmr t on t.id = d.tmrid
  273. left join driver on driver.drivercode = t.eqcode
  274. where d1.date = ? and d.havebutton = 1 and d1.type = 0 `, now).Query().List()
  275. if err != nil {
  276. logging.Error(err)
  277. return err
  278. }
  279. dataByte, _ := json.Marshal(&dataList)
  280. reqJson := `{"param": {
  281. "method": "uploadadddata",
  282. "resultData": %s,
  283. "farmId": "%s",
  284. "parlorType": "CPT",
  285. "account":"CPT"
  286. },
  287. "platform": "CPT",
  288. "regCode": "cpt180511",
  289. "secret": "67a74fd5748054ac67b6fc433e9249b0",
  290. "methodKey": "pushCptData"} `
  291. reqJson = fmt.Sprintf(reqJson, string(dataByte), farmId)
  292. postPush(reqJson, 0, tx, pastureId)
  293. fmt.Println(reqJson)
  294. return nil
  295. }
  296. func YmyMaterialIssuePush(pastureId, farmId, date string) error {
  297. tx := restful.Engine.NewSession()
  298. defer tx.Close()
  299. var now string
  300. if date != "" {
  301. now = date
  302. } else {
  303. now = time.Now().AddDate(0, 0, -1).Format("2006-01-02")
  304. }
  305. dataList, err := tx.SQL(`SELECT MD5(CONCAT(d.pid, d.mydate)) loadId ,d2.sort feedingNo,ifnull((SELECT dr.driver FROM dutyrecord dr
  306. WHERE dr.pastureid = d.pastureid AND dr.eqid = d.tmrid AND dr.times= d.times AND dr.operatetime <=d.mydate
  307. ORDER BY dr.operatetime DESC LIMIT 1),"") as tmrName,d.tmrtname equipmentId,fp.ccount cowCount,b.bname penName,date_format(d2.date,'%Y-%m-%d') dropDate,d2.lweight expWeight ,d2.actualweightminus actualWeight, ifnull(date_format(timestamp(d2.InTime,CONCAT('-',d2.processTime)),'%Y-%m-%d %H:%i:%s'),d.mydate) as startTime,
  308. ifnull(date_format(d2.InTime,'%Y-%m-%d %H:%i:%s'),d.mydate) as endTime
  309. from downloadedplan d
  310. LEFT JOIN downloadplandtl2 d2 on d.id=d2.PID
  311. left join bar b on b.id = d2.fbarid
  312. left join feedpdate fp on d2.date =fp.date and fp.barid = b.id
  313. where d.mydate= date_format(?,'%Y-%m-%d') and d2.type = 0 and d.havebutton = 1 `, now).Query().List()
  314. if err != nil {
  315. logging.Error(err)
  316. return err
  317. }
  318. dataByte, _ := json.Marshal(&dataList)
  319. reqJson := ` {"param": {
  320. "method": "uploaddiliverdata",
  321. "resultData": %s,
  322. "farmId": "%s",
  323. "parlorType": "CPT",
  324. "account":"CPT"
  325. },
  326. "platform": "CPT",
  327. "regCode": "cpt180511",
  328. "secret": "67a74fd5748054ac67b6fc433e9249b0",
  329. "methodKey": "pushCptData"} `
  330. reqJson = fmt.Sprintf(reqJson, string(dataByte), farmId)
  331. // '0饲喂 1剩料 2原料 3栏舍 4配方 5栏舍牛头数 6库存',
  332. postPush(reqJson, 0, tx, pastureId)
  333. fmt.Println(reqJson)
  334. return nil
  335. }
  336. func postPush(data string, msgtype int, tx *xorm.Session, pastureId string) {
  337. // forwardingReq := new(ForwardingReq)
  338. url := "http://dairy.yimucloud.com/dairy/external/api"
  339. // forwardingReq.Method = "POST"
  340. // forwardingReq.Body = data
  341. // jsonStr, _ := json.Marshal(forwardingReq)
  342. // fmt.Println(setting.ServerSetting.UDForwardingSvc)
  343. // req, err := http.NewRequest("POST", setting.ServerSetting.UDForwardingSvc+":8080/forwarding", bytes.NewBuffer(jsonStr))
  344. req, err := http.NewRequest("POST", url, bytes.NewBuffer([]byte(data)))
  345. if err != nil {
  346. logs.Error(err)
  347. // return nil
  348. }
  349. req.Header.Set("Content-Type", "application/json")
  350. tr := &http.Transport{
  351. // TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
  352. }
  353. client := &http.Client{Transport: tr}
  354. resp, err := client.Do(req)
  355. if err != nil {
  356. logs.Error(err)
  357. return
  358. }
  359. defer resp.Body.Close()
  360. body, _ := ioutil.ReadAll(resp.Body)
  361. fmt.Println(string(body))
  362. if strings.Index(resp.Status, "200") > -1 {
  363. bodyData := make(map[string]string)
  364. json.Unmarshal(body, &bodyData)
  365. if _, ok := bodyData["data"]; ok {
  366. tx.Exec(` insert into saplog(pastureId,request,response,status,msgtext,createTime,msgtype,dataDate,url)
  367. values(?,?,?,?,?,now(),?,now(),?)`, pastureId, data, bodyData["data"], "", "", msgtype, url)
  368. } else {
  369. tx.Exec(` insert into saplog(pastureId,request,response,status,msgtext,createTime,msgtype,dataDate,url)
  370. values(?,?,?,?,?,now(),?,now(),?)`, pastureId, data, string(body), "", "", msgtype, url)
  371. }
  372. } else {
  373. tx.Exec(` insert into saplog(pastureId,request,response,status,msgtext,createTime,msgtype,dataDate,url)
  374. values(?,?,?,?,?,now(),?,now(),?)`, pastureId, data, string(body), "", "", msgtype, url)
  375. }
  376. }