123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426 |
- package ymy
- import (
- "bytes"
- "crypto/tls"
- "encoding/json"
- "fmt"
- "io/ioutil"
- "net/http"
- "strings"
- "time"
- "tmr-watch/conf/setting"
- "tmr-watch/http/handle/restful"
- "tmr-watch/models"
- "tmr-watch/pkg/logging"
- "github.com/astaxie/beego/logs"
- "github.com/xormplus/xorm"
- )
- func YmyCron(farmId, pastureId string) {
- date := time.Now().AddDate(0, 0, -1).Format("2006-01-02")
- // date := "2025-05-11"
- YmyUtirPush(pastureId, farmId, date)
- YmyMaterialIssuePush(pastureId, farmId, date)
- YmySyncBar(farmId, pastureId)
- YmySyncFeed(pastureId)
- YmyFeedtempletPush(pastureId, farmId, date)
- }
- func YmySyncBar(farmId, pastureId string) {
- tx := restful.Engine.NewSession()
- defer tx.Close()
- reqJson := `{
- "methodKey": "getFeedPenList",
- "param": {
- "farmId": "%s",
- "parlorType": "CPT"
- },
- "platform": "CPT",
- "regCode": "cpt180511",
- "secret": "67a74fd5748054ac67b6fc433e9249b0"}`
- barPull("http://dairy.yimucloud.com/dairy/external/api", fmt.Sprintf(reqJson, farmId), 3, tx, pastureId)
- }
- func barPull(url, data string, msgtype int, tx *xorm.Session, pastureId string) {
- req, err := http.NewRequest("POST", url, bytes.NewBuffer([]byte(data)))
- if err != nil {
- logs.Error(err)
- }
- req.Header.Set("Content-Type", "application/json")
- // client := &http.Client{}
- tr := &http.Transport{
- TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
- }
- client := &http.Client{Transport: tr}
- resp, err := client.Do(req)
- if err != nil {
- logs.Error(err)
- return
- }
- defer resp.Body.Close()
- body, _ := ioutil.ReadAll(resp.Body)
- respData := new(models.BarResponse)
- json.Unmarshal(body, &respData)
- tx.Exec(` insert into saplog(pastureId,request,response,status,msgtext,createTime,msgtype,dataDate,url)
- values(?,?,?,?,?,now(),?,now(),?)`, pastureId, data, string(body), "", "", msgtype, url)
- for _, v := range respData.Result {
- fmt.Println(v)
- count, _ := tx.Table("bar").Where("pastureId = ? ", pastureId).Count()
- tx.Exec(`insert into bar(pastureid,bcode,bname,sort)values(?,?,?,?) ON DUPLICATE KEY UPDATE bname = ? `, pastureId, v.PenId, v.PenName, count+1, v.PenName)
- }
- }
- func YmySyncFeed(pastureId string) {
- tx := restful.Engine.NewSession()
- defer tx.Close()
- reqJson := `{
- "data":{
- "page": "0",
- "size": "1000",
- "modifiedAfter":"2025-01-01 00:00:00",
- "MATERIAL_BASIC_CLASSIFICATION_CODE":"",
- "MATERIAL_CODE": ""
- }}`
- feedPull("http://219.151.177.119:9000/ierp/kapi/v2/iscb/route/script_cusapi_deepexi_material_query", reqJson, 2, tx, pastureId, getApiToken())
- }
- type udPastureInfo struct {
- Token string `xorm:"token"`
- Pastureid string `xorm:"pastureid"`
- Werks string `xorm:"werks"`
- UpdateDate string `xorm:"updatedate"`
- }
- func getApiToken() string {
- tx := restful.Engine.NewSession()
- defer tx.Close()
- pastureinfo := new(udPastureInfo)
- err := tx.SQL(`SELECT (SELECT pastureid FROM pasture WHERE pastureid = column_default) pastureid,
- IF( TIMESTAMPDIFF(MINUTE,
- (SELECT updatedate FROM pasture WHERE pastureid = column_default),
- NOW()
- ) > 60, -- 110分钟 = 1小时50分钟
- '', -- 超过时间返回空字符串
- (SELECT token FROM pasture WHERE pastureid = column_default) -- 否则返回 pastureid
- ) AS token,
- (SELECT werks FROM pasture WHERE pastureid = column_default) AS werks,
- DATE_FORMAT(
- (SELECT updatedate FROM pasture WHERE pastureid = column_default),
- '%Y-%m-%d %H:%i:%s'
- ) AS updatedate
- FROM information_schema.COLUMNS
- WHERE table_name = 'recweight'
- AND table_schema = ?
- AND column_name = 'pastureid' `, setting.DatabaseSetting.Name).GetFirst(pastureinfo).Error
- if err != nil {
- logs.Error(err)
- return pastureinfo.Token
- }
- if pastureinfo.Token != "" {
- return pastureinfo.Token
- }
- reqJson := `{
- "client_id": "Cosmic_deepexi_user",
- "client_secret": "Cosmic_zkm_deepexi_openapi@user01",
- "username": "dipujiekouyonghu",
- "accountId": "1986218827033083904",
- "nonce": "a42c1a91-56ad-4c6d-95d1-40bcb8b5ec89",
- "timestamp": "%s",
- "language": "zh_CN"
- }`
- reqJson = fmt.Sprintf(reqJson, time.Now().Format("2006-01-02 15:04:05"))
- req, err := http.NewRequest("POST", "http://219.151.177.119:9000/ierp/kapi/oauth2/getToken", bytes.NewBuffer([]byte(reqJson)))
- if err != nil {
- logs.Error(err)
- }
- req.Header.Set("Content-Type", "application/json")
- tr := &http.Transport{
- TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
- }
- client := &http.Client{Transport: tr}
- resp, err := client.Do(req)
- if err != nil {
- logs.Error(err)
- return pastureinfo.Token
- }
- defer resp.Body.Close()
- body, _ := ioutil.ReadAll(resp.Body)
- fmt.Println(string(body))
- token := new(models.TokenResponse)
- json.Unmarshal(body, &token)
- tx.Exec(" update pasture set token = ?,updatedate = now() where pastureid = ? ", token.Data.AccessToken, pastureinfo.Pastureid)
- return token.Data.AccessToken
- }
- func feedPull(url, data string, msgtype int, tx *xorm.Session, pastureId, token string) {
- req, err := http.NewRequest("POST", url, bytes.NewBuffer([]byte(data)))
- if err != nil {
- logs.Error(err)
- }
- req.Header.Set("Content-Type", "application/json")
- req.Header.Set("access_token", token)
- client := &http.Client{}
- resp, err := client.Do(req)
- if err != nil {
- logs.Error(err)
- return
- }
- defer resp.Body.Close()
- body, _ := ioutil.ReadAll(resp.Body)
- fmt.Println(string(body))
- feedData := new(models.FeedResponse)
- json.Unmarshal(body, &feedData)
- for _, v := range feedData.Data.Content {
- feedname := v.MaterialName
- feedcode := v.MaterialCode
- feedClassExist, err := tx.Table("feedclass").Where("fccode = ? ", v.MaterialClassification).Where(" pastureId = ? ", pastureId).Exist()
- fmt.Println(err)
- if !feedClassExist {
- count, _ := tx.Table("feedclass").Where("pastureId = ? ", pastureId).Count()
- ids, err := setting.SnowIds.NextId()
- if err != nil {
- ids = time.Now().UnixNano()
- }
- _, err = tx.Exec(`insert into feedclass(id,pastureId,fcname,fccode,bigfeedclassname,sort,bigfeedclassid) values(?,?,?,?,?,?,?)`,
- ids, pastureId, v.MaterialClassification, v.MaterialClassification, v.MaterialClassification, count+1, ids)
- fmt.Println(err)
- }
- ids, err := setting.SnowIds.NextId()
- if err != nil {
- ids = time.Now().UnixNano()
- logging.Info("create SnowIds err", err)
- }
- 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),?) )
- ON DUPLICATE KEY UPDATE udname = ? ,fclassid = (select id from feedclass where fccode = ? and pastureId = ? ) ,fclass = ?`,
- ids, pastureId, feedcode, feedname, v.MaterialClassification, pastureId, v.MaterialClassification, feedname, feedname, feedname, feedname,
- v.MaterialClassification, pastureId, v.MaterialClassification)
- }
- tx.Exec(` insert into saplog(pastureId,request,response,status,msgtext,createTime,msgtype,dataDate,url)
- values(?,?,?,?,?,now(),?,now(),?)`, pastureId, data, string(body), "", "", msgtype, url)
- }
- func YmyFeedtempletPush(pastureId, farmId, date string) error {
- tx := restful.Engine.NewSession()
- defer tx.Close()
- var now string
- if date != "" {
- now = date
- } else {
- now = time.Now().AddDate(0, 0, -1).Format("2006-01-02")
- }
- dataList, err := tx.SQL(`SELECT
- ft.tcode AS recipeId,
- ft.TNAME AS recipeName,
- ifnull(f.feedcode,f.id) AS ingId,
- '' AS feedCode,
- ifnull(f.udname,f.fname) AS ingName,
- round( fn.dry * ftd.FWEIGHT, 2 ) AS dmQty,
- ftd.FWEIGHT AS afQty,
- ftd.SORT AS mixNo,
- round( f.Uprice * ftd.FWEIGHT, 2 ) AS recipeCost,
- ifnull(fc.fcname,'饲料') AS ingType,
- f.AllowRatio AS allowableError
- FROM
- feedtempletdate ft
- JOIN ftdetaildate ftd ON ft.id = ftd.FTID and ft.date = ftd.date
- JOIN feed f ON ftd.FID = f.id
- left join feednur fn on fn.fid = f.id
- left JOIN feedclass fc ON f.fclassid = fc.id
- WHERE
- ft.ENABLE = 1
- AND ft.isDelete != 1 and ft.date = ? `, now).Query().List()
- if err != nil {
- logging.Error(err)
- return err
- }
- dataByte, _ := json.Marshal(&dataList)
- reqJson := `
- {"param": {
- "method": "getfeedtempletinfo",
- "resultData": %s,
- "farmId": "%s",
- "parlorType": "CPT",
- "account":"CPT"
- },
- "platform": "CPT",
- "regCode": "cpt180511",
- "secret": "67a74fd5748054ac67b6fc433e9249b0",
- "methodKey": "pushCptData"}`
- reqJson = fmt.Sprintf(reqJson, string(dataByte), farmId)
- fmt.Println(reqJson)
- postPush(reqJson, 4, tx, pastureId)
- return nil
- }
- //搅拌
- func YmyUtirPush(pastureId, farmId, date string) error {
- tx := restful.Engine.NewSession()
- defer tx.Close()
- var now string
- if date != "" {
- now = date
- } else {
- now = time.Now().AddDate(0, 0, -1).Format("2006-01-02")
- }
- 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,
- ifnull(ifnull(fc.fcname,(select fcname from feedclass fc1 join feed f1 on f1.fclassid = fc1.id where f1.id =ftd.fid )),'饲料') ingType,
- 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,
-
- 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,
- DATE_FORMAT(IFNULL((SELECT MAX(intime) FROM downloadplandtl1 d2
- WHERE d1.pid=d2.pid AND d1.pastureid = d2.pastureid AND d2.intime<d1.intime)
- , (SELECT MAX(intime) FROM downloadedplan d2
- WHERE d1.date=d2.mydate AND d1.pastureid = d2.pastureid AND d2.id=d1.pid)
- ), '%Y-%m-%d %H:%i:%s')
- startTime ,
- date_format(d1.intime,'%Y-%m-%d %H:%i:%s') endTime, ifnull(driver.drivername,'') tmrName ,d1.feedallowratio allowable_error,d.tmrtname equipmentId
- from downloadplandtl1 d1 join downloadedplan d on d.id = d1.pid
- left join feedtempletdate ft on ft.id = d.tempid and ft.date = d1.date
- left join feed f on f.feedcode = d1.feedcode
- left join feedclass fc on fc.id = f.fclassid
- left join ftdetaildate ftd on ftd.date = d1.date and ftd.ftid = d1.fid
- join tmr t on t.id = d.tmrid
- left join driver on driver.drivercode = t.eqcode
- where d1.date = ? and d.havebutton = 1 and d1.type = 0 `, now).Query().List()
- if err != nil {
- logging.Error(err)
- return err
- }
- dataByte, _ := json.Marshal(&dataList)
- reqJson := `{"param": {
- "method": "uploadadddata",
- "resultData": %s,
- "farmId": "%s",
- "parlorType": "CPT",
- "account":"CPT"
- },
- "platform": "CPT",
- "regCode": "cpt180511",
- "secret": "67a74fd5748054ac67b6fc433e9249b0",
- "methodKey": "pushCptData"} `
- reqJson = fmt.Sprintf(reqJson, string(dataByte), farmId)
- postPush(reqJson, 0, tx, pastureId)
- fmt.Println(reqJson)
- return nil
- }
- func YmyMaterialIssuePush(pastureId, farmId, date string) error {
- tx := restful.Engine.NewSession()
- defer tx.Close()
- var now string
- if date != "" {
- now = date
- } else {
- now = time.Now().AddDate(0, 0, -1).Format("2006-01-02")
- }
- dataList, err := tx.SQL(`SELECT MD5(CONCAT(d.pid, d.mydate)) loadId ,d2.sort feedingNo,ifnull((SELECT dr.driver FROM dutyrecord dr
- WHERE dr.pastureid = d.pastureid AND dr.eqid = d.tmrid AND dr.times= d.times AND dr.operatetime <=d.mydate
- 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,
- ifnull(date_format(d2.InTime,'%Y-%m-%d %H:%i:%s'),d.mydate) as endTime
- from downloadedplan d
- LEFT JOIN downloadplandtl2 d2 on d.id=d2.PID
- left join bar b on b.id = d2.fbarid
- left join feedpdate fp on d2.date =fp.date and fp.barid = b.id
- where d.mydate= date_format(?,'%Y-%m-%d') and d2.type = 0 and d.havebutton = 1 `, now).Query().List()
- if err != nil {
- logging.Error(err)
- return err
- }
- dataByte, _ := json.Marshal(&dataList)
- reqJson := ` {"param": {
- "method": "uploaddiliverdata",
- "resultData": %s,
- "farmId": "%s",
- "parlorType": "CPT",
- "account":"CPT"
- },
- "platform": "CPT",
- "regCode": "cpt180511",
- "secret": "67a74fd5748054ac67b6fc433e9249b0",
- "methodKey": "pushCptData"} `
- reqJson = fmt.Sprintf(reqJson, string(dataByte), farmId)
- // '0饲喂 1剩料 2原料 3栏舍 4配方 5栏舍牛头数 6库存',
- postPush(reqJson, 0, tx, pastureId)
- fmt.Println(reqJson)
- return nil
- }
- func postPush(data string, msgtype int, tx *xorm.Session, pastureId string) {
- // forwardingReq := new(ForwardingReq)
- url := "http://dairy.yimucloud.com/dairy/external/api"
- // forwardingReq.Method = "POST"
- // forwardingReq.Body = data
- // jsonStr, _ := json.Marshal(forwardingReq)
- // fmt.Println(setting.ServerSetting.UDForwardingSvc)
- // req, err := http.NewRequest("POST", setting.ServerSetting.UDForwardingSvc+":8080/forwarding", bytes.NewBuffer(jsonStr))
- req, err := http.NewRequest("POST", url, bytes.NewBuffer([]byte(data)))
- if err != nil {
- logs.Error(err)
- // return nil
- }
- req.Header.Set("Content-Type", "application/json")
- tr := &http.Transport{
- // TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
- }
- client := &http.Client{Transport: tr}
- resp, err := client.Do(req)
- if err != nil {
- logs.Error(err)
- return
- }
- defer resp.Body.Close()
- body, _ := ioutil.ReadAll(resp.Body)
- fmt.Println(string(body))
- if strings.Index(resp.Status, "200") > -1 {
- bodyData := make(map[string]string)
- json.Unmarshal(body, &bodyData)
- if _, ok := bodyData["data"]; ok {
- tx.Exec(` insert into saplog(pastureId,request,response,status,msgtext,createTime,msgtype,dataDate,url)
- values(?,?,?,?,?,now(),?,now(),?)`, pastureId, data, bodyData["data"], "", "", msgtype, url)
- } else {
- tx.Exec(` insert into saplog(pastureId,request,response,status,msgtext,createTime,msgtype,dataDate,url)
- values(?,?,?,?,?,now(),?,now(),?)`, pastureId, data, string(body), "", "", msgtype, url)
- }
- } else {
- tx.Exec(` insert into saplog(pastureId,request,response,status,msgtext,createTime,msgtype,dataDate,url)
- values(?,?,?,?,?,now(),?,now(),?)`, pastureId, data, string(body), "", "", msgtype, url)
- }
- }
|